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). The pairs live in one exact-size heap
148/// block (no spare capacity): an entity typically has a handful of entries, set once at spawn.
149#[derive(Clone, Debug, Default, PartialEq)]
150pub struct Metadata {
151    entries: Box<[(u8, MetaValue)]>,
152}
153
154impl Metadata {
155    /// The value at `index`.
156    #[must_use]
157    pub fn get(&self, index: u8) -> Option<&MetaValue> {
158        self.entries
159            .iter()
160            .find(|(i, _)| *i == index)
161            .map(|(_, v)| v)
162    }
163
164    /// Sets the value at `index`.
165    pub fn set(&mut self, index: u8, value: MetaValue) {
166        match self.entries.iter_mut().find(|(i, _)| *i == index) {
167            Some(slot) => slot.1 = value,
168            None => self.push_new(index, value),
169        }
170    }
171
172    /// Appends a new index (the block grows by exactly one entry).
173    #[cold]
174    #[inline(never)]
175    fn push_new(&mut self, index: u8, value: MetaValue) {
176        let mut v = Vec::with_capacity(self.entries.len() + 1);
177        v.extend(std::mem::take(&mut self.entries));
178        v.push((index, value));
179        self.entries = v.into_boxed_slice();
180    }
181
182    /// Applies `src` (drained) in order, as [`Metadata::set`] would one by one, skipping indices
183    /// `keep` refuses; grows the block at most once, to the exact size.
184    #[inline]
185    pub(crate) fn set_from(&mut self, src: &mut Vec<(u8, MetaValue)>, keep: impl Fn(u8) -> bool) {
186        let mut it = src.drain(..);
187        // Overwrites in place until the first index this entity does not have yet.
188        while let Some((i, v)) = it.next() {
189            if !keep(i) {
190                continue;
191            }
192            match self.entries.iter_mut().find(|(k, _)| *k == i) {
193                Some(slot) => slot.1 = v,
194                None => return self.grow_from((i, v), it, keep),
195            }
196        }
197    }
198
199    /// The rest of [`Metadata::set_from`] once a new index occurs: one exact-size block.
200    #[cold]
201    #[inline(never)]
202    fn grow_from(
203        &mut self,
204        first: (u8, MetaValue),
205        rest: std::vec::Drain<'_, (u8, MetaValue)>,
206        keep: impl Fn(u8) -> bool,
207    ) {
208        let tail = rest.as_slice();
209        let mut new = 1;
210        for (j, (i, _)) in tail.iter().enumerate() {
211            if keep(*i)
212                && *i != first.0
213                && !self.entries.iter().any(|(k, _)| k == i)
214                && !tail[..j].iter().any(|(k, _)| k == i)
215            {
216                new += 1;
217            }
218        }
219        let mut out = Vec::with_capacity(self.entries.len() + new);
220        out.extend(std::mem::take(&mut self.entries));
221        out.push(first);
222        for (i, v) in rest {
223            if !keep(i) {
224                continue;
225            }
226            match out.iter_mut().find(|(k, _)| *k == i) {
227                Some(slot) => slot.1 = v,
228                None => out.push((i, v)),
229            }
230        }
231        debug_assert_eq!(out.len(), out.capacity());
232        self.entries = out.into_boxed_slice();
233    }
234
235    /// All entries.
236    pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
237        self.entries.iter().map(|(i, v)| (*i, v))
238    }
239
240    /// Number of entries.
241    #[must_use]
242    pub fn len(&self) -> usize {
243        self.entries.len()
244    }
245
246    /// `true` when nothing has been received.
247    #[must_use]
248    pub fn is_empty(&self) -> bool {
249        self.entries.is_empty()
250    }
251
252    /// Byte at `index` (`Byte` values only).
253    #[must_use]
254    pub fn byte(&self, index: u8) -> Option<i8> {
255        match self.get(index)? {
256            MetaValue::Byte(b) => Some(*b),
257            _ => None,
258        }
259    }
260
261    /// Float at `index`.
262    #[must_use]
263    pub fn float(&self, index: u8) -> Option<f32> {
264        match self.get(index)? {
265            MetaValue::Float(f) => Some(*f),
266            _ => None,
267        }
268    }
269
270    /// Item at `index` (`Some(None)` = an empty stack was sent).
271    #[must_use]
272    pub fn item(&self, index: u8) -> Option<Option<&Item>> {
273        match self.get(index)? {
274            MetaValue::Item(i) => Some(i.as_ref()),
275            _ => None,
276        }
277    }
278
279    pub(crate) fn clear(&mut self) {
280        self.entries = Box::default();
281    }
282
283    pub(crate) fn entries_mut(&mut self) -> impl Iterator<Item = &mut (u8, MetaValue)> {
284        self.entries.iter_mut()
285    }
286
287    /// Heap bytes held (for the size tests).
288    #[cfg(test)]
289    pub(crate) fn heap_bytes(&self) -> usize {
290        std::mem::size_of_val::<[(u8, MetaValue)]>(&self.entries)
291    }
292}
293
294/// The rarely set parts of an entity (passengers, leash, effects), behind one pointer: most
295/// entities never have any of them.
296#[derive(Clone, Debug, Default, PartialEq)]
297pub(crate) struct Links {
298    /// 26.x players: the profile name the entity was created with, once its tab-list entry is
299    /// gone (vanilla's player keeps its `GameProfile`).
300    pub(crate) profile_name: Option<Box<str>>,
301    pub(crate) leash_holder: Option<i32>,
302    pub(crate) passengers: Vec<i32>,
303    pub(crate) effects: Vec<Effect>,
304}
305
306/// The protocol family an entity was tracked with (selects metadata indices and size rules).
307#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
308pub(crate) enum Era {
309    /// 1.8.x.
310    #[default]
311    V1_8,
312    /// 1.9 – 1.12 (implemented: 1.12.2).
313    V1_12,
314    /// 1.16.5.
315    V1_16,
316    /// 26.1.
317    V26,
318    /// 26.2 (the same modern state as 26.1, with 26.2's ids and sizes).
319    V26_2,
320}
321
322/// 1.16 registry ids used by [`Entity::class`].
323const ITEM_1_16: u16 = 37;
324const XP_ORB_1_16: u16 = 24;
325const PAINTING_1_16: u16 = 55;
326
327/// Number of equipment slots kept (1.16: main hand, off hand, feet, legs, chest, head;
328/// 1.8: held, boots, leggings, chestplate, helmet in slots 0..=4).
329pub const EQUIPMENT_SLOTS: usize = 6;
330
331/// A tracked entity, as the vanilla client knows it from the server's packets.
332#[derive(Clone, Debug)]
333pub struct Entity {
334    pub(crate) id: i32,
335    pub(crate) uuid: Uuid,
336    pub(crate) ty: EntityType,
337    pub(crate) living: bool,
338    /// The tracker's protocol family.
339    pub(crate) era: Era,
340    /// Vanilla size table entry (resolved at spawn).
341    pub(crate) sizer: Option<&'static ghast_data::VanillaEntitySize>,
342    pub(crate) pos: [f64; 3],
343    /// Per version: 1.8 the server position in 1/32 blocks (`serverPos`, i32 values); 1.9 – 1.12
344    /// the tracked position in 1/4096 blocks (`lfloor(x * 4096)`, plus moves); 26.1 the
345    /// `VecDeltaCodec` base (`f64` bits).
346    pub(crate) traced: [i64; 3],
347    pub(crate) yaw: f32,
348    pub(crate) pitch: f32,
349    pub(crate) head_yaw: f32,
350    pub(crate) velocity: [f64; 3],
351    pub(crate) on_ground: bool,
352    pub(crate) data: i32,
353    pub(crate) meta: Metadata,
354    pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
355    /// The vehicle's id (valid with `rides`; an `Option<i32>` would take 8 bytes here).
356    pub(crate) vehicle_id: i32,
357    pub(crate) rides: bool,
358    /// Passengers, leash and effects (`None` = none of them).
359    pub(crate) links: Option<Box<Links>>,
360    /// 26.1 client state (codec base, interpolation, size keys), boxed: one pointer for the
361    /// other versions.
362    #[cfg(any(feature = "v26_1", feature = "v26_2"))]
363    pub(crate) m: crate::modern_state::Ext,
364}
365
366impl Entity {
367    pub(crate) fn new(id: i32, ty: EntityType) -> Self {
368        Entity {
369            id,
370            uuid: Uuid::nil(),
371            ty,
372            living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
373            era: Era::V1_8,
374            sizer: None,
375            pos: [0.0; 3],
376            traced: [0; 3],
377            yaw: 0.0,
378            pitch: 0.0,
379            head_yaw: 0.0,
380            velocity: [0.0; 3],
381            on_ground: false,
382            data: 0,
383            meta: Metadata::default(),
384            equipment: None,
385            links: None,
386            vehicle_id: 0,
387            rides: false,
388            #[cfg(any(feature = "v26_1", feature = "v26_2"))]
389            m: crate::modern_state::Ext::default(),
390        }
391    }
392
393    /// The links, allocated on first use.
394    #[inline]
395    pub(crate) fn links_mut(&mut self) -> &mut Links {
396        self.links.get_or_insert_with(Box::default)
397    }
398
399    /// Sets the vehicle (dismounting allocates nothing).
400    #[inline]
401    pub(crate) fn set_vehicle(&mut self, v: Option<i32>) {
402        self.rides = v.is_some();
403        self.vehicle_id = v.unwrap_or(0);
404    }
405
406    /// Takes the vehicle.
407    #[inline]
408    pub(crate) fn take_vehicle(&mut self) -> Option<i32> {
409        let v = self.vehicle();
410        self.set_vehicle(None);
411        v
412    }
413
414    /// Sets the leash holder.
415    #[inline]
416    pub(crate) fn set_leash_holder(&mut self, h: Option<i32>) {
417        match (&mut self.links, h) {
418            (Some(l), h) => l.leash_holder = h,
419            (None, None) => {}
420            (None, Some(_)) => self.links_mut().leash_holder = h,
421        }
422        self.tidy_links();
423    }
424
425    /// Takes the passenger list (no allocation when there is none).
426    #[inline]
427    pub(crate) fn take_passengers(&mut self) -> Vec<i32> {
428        let p = self
429            .links
430            .as_mut()
431            .map(|l| std::mem::take(&mut l.passengers))
432            .unwrap_or_default();
433        self.tidy_links();
434        p
435    }
436
437    /// Removes `id` from the passengers.
438    #[inline]
439    pub(crate) fn remove_passenger(&mut self, id: i32) {
440        if let Some(l) = &mut self.links {
441            l.passengers.retain(|&p| p != id);
442        }
443        self.tidy_links();
444    }
445
446    /// Replaces the passenger list.
447    #[inline]
448    pub(crate) fn set_passengers(&mut self, p: Vec<i32>) {
449        if !p.is_empty() || self.links.is_some() {
450            self.links_mut().passengers = p;
451        }
452        self.tidy_links();
453    }
454
455    /// Adds a passenger.
456    #[inline]
457    pub(crate) fn push_passenger(&mut self, id: i32) {
458        self.links_mut().passengers.push(id);
459    }
460
461    /// Clears the effects.
462    #[inline]
463    pub(crate) fn clear_effects(&mut self) {
464        if let Some(l) = &mut self.links {
465            l.effects = Vec::new();
466        }
467        self.tidy_links();
468    }
469
470    /// Frees the links once they are all empty.
471    #[inline]
472    pub(crate) fn tidy_links(&mut self) {
473        if self.links.as_ref().is_some_and(|l| {
474            l.leash_holder.is_none()
475                && l.profile_name.is_none()
476                && l.passengers.is_empty()
477                && l.effects.is_empty()
478        }) {
479            self.links = None;
480        }
481    }
482
483    /// Heap bytes this entity holds (metadata block, equipment, links with their buffers, the
484    /// modern state; for the size tests).
485    #[cfg(test)]
486    pub(crate) fn heap_bytes(&self) -> usize {
487        let mut n = self.meta.heap_bytes();
488        if self.equipment.is_some() {
489            n += std::mem::size_of::<[Option<Item>; EQUIPMENT_SLOTS]>();
490        }
491        if let Some(l) = &self.links {
492            n += std::mem::size_of::<Links>()
493                + l.passengers.capacity() * 4
494                + l.effects.capacity() * std::mem::size_of::<Effect>();
495        }
496        #[cfg(any(feature = "v26_1", feature = "v26_2"))]
497        if self.m.0.is_some() {
498            n += std::mem::size_of::<crate::modern_state::State>();
499        }
500        n
501    }
502
503    /// Network entity id.
504    #[must_use]
505    pub fn id(&self) -> i32 {
506        self.id
507    }
508
509    /// UUID (nil for 1.8 entities other than players).
510    #[must_use]
511    pub fn uuid(&self) -> Uuid {
512        self.uuid
513    }
514
515    /// Type.
516    #[must_use]
517    pub fn entity_type(&self) -> EntityType {
518        self.ty
519    }
520
521    /// Version-independent class.
522    #[must_use]
523    pub fn class(&self) -> EntityClass {
524        #[cfg(feature = "v26_1")]
525        if self.era == Era::V26 {
526            return crate::v26_1::class(self);
527        }
528        #[cfg(feature = "v26_2")]
529        if self.era == Era::V26_2 {
530            return crate::v26_2::class(self);
531        }
532        match self.ty {
533            EntityType::Player => EntityClass::Player,
534            EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
535            EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
536                EntityClass::ExperienceOrb
537            }
538            EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
539            _ if self.living => EntityClass::Mob,
540            _ => EntityClass::Object,
541        }
542    }
543
544    /// The stack of an item entity (from metadata; `None` before the server sent it or when
545    /// metadata is not tracked; 1.16 always keeps it for item entities). Always `None` on 26.1,
546    /// whose stacks carry data components: see `v26_1::item_stack` / `v26_1::item_count`.
547    #[must_use]
548    pub fn item(&self) -> Option<&Item> {
549        if matches!(self.era, Era::V26 | Era::V26_2) {
550            return None;
551        }
552        let index = match self.ty {
553            EntityType::LegacyObject(2) if self.era == Era::V1_12 => 6,
554            EntityType::LegacyObject(2) => 10,
555            EntityType::Registry(ITEM_1_16) => 7,
556            _ => return None,
557        };
558        self.meta.item(index).flatten()
559    }
560
561    /// Vanilla client-side dimensions: the type's size from ghast-data (checked against the
562    /// oracle), with the variant the client applies from metadata (baby, slime size, wither
563    /// skeleton, elder guardian, small / marker armor stand, 1.16 player pose). `None` for
564    /// hanging entities (paintings, item frames, leash knots), whose box comes from facing.
565    ///
566    /// Variants vanilla applies on the entity's next client tick are applied immediately, and
567    /// the old-min-corner quirk after a resize is not modelled.
568    #[must_use]
569    pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
570        let vs = self.sizer?;
571        match self.era {
572            #[cfg(feature = "v1_8")]
573            Era::V1_8 => crate::v1_8::dimensions(self, vs),
574            #[cfg(feature = "v1_12")]
575            Era::V1_12 => crate::v1_12::dimensions(self, vs),
576            #[cfg(feature = "v1_16_5")]
577            Era::V1_16 => crate::v1_16_5::dimensions(self, vs),
578            #[cfg(feature = "v26_1")]
579            Era::V26 => {
580                let _ = vs;
581                crate::v26_1::dimensions(self)
582            }
583            #[cfg(feature = "v26_2")]
584            Era::V26_2 => {
585                let _ = vs;
586                crate::v26_2::dimensions(self)
587            }
588            // A tracker only stamps eras of versions compiled in.
589            #[allow(unreachable_patterns)]
590            _ => None,
591        }
592    }
593
594    /// How much the crosshair pick grows this entity's box (vanilla `getCollisionBorderSize` /
595    /// `getTargetingMargin`, from the type's size table: 0.1 for most 1.8 types, 0 since 1.9,
596    /// 1.0 for fireballs); 0 when the type has no size entry.
597    #[must_use]
598    pub fn targeting_margin(&self) -> f32 {
599        self.sizer.map_or(0.0, |s| s.targeting_margin)
600    }
601
602    /// `(width, height)` of [`Entity::dimensions`].
603    #[must_use]
604    pub fn size(&self) -> Option<(f32, f32)> {
605        self.dimensions().map(|d| (d.width, d.height))
606    }
607
608    /// Vanilla bounding box at the server position, `[min_x, min_y, min_z, max_x, max_y,
609    /// max_z]` (bit-exact `EntityDimensions::bounding_box`).
610    #[must_use]
611    pub fn bounding_box(&self) -> Option<[f64; 6]> {
612        let [x, y, z] = self.pos;
613        let b = self.dimensions()?.bounding_box(x, y, z);
614        Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
615    }
616
617    /// `true` for players.
618    #[must_use]
619    pub fn is_player(&self) -> bool {
620        self.ty == EntityType::Player
621    }
622
623    /// The **server position**: exactly the coordinates the vanilla client tracks from the
624    /// packets (1.8: `serverPos / 32.0`; 1.12: spawn / teleport coordinates, after a relative
625    /// move the tracked 1/4096 position; 1.16: the packet coordinates, rel moves applied in
626    /// 1/4096 fixed point). The rendered position interpolates towards this over 3 ticks in
627    /// vanilla; a bot does not need that.
628    ///
629    /// **26.1** is different: this is the entity's *current* position as the client holds it
630    /// (`Entity.position()`): position packets of interpolated entities (living entities, boats,
631    /// minecarts) set a target the entity reaches over 3 calls of `v26_1::Tracker::tick`, others
632    /// move at once. That is the position vanilla's crosshair pick reads at tick time (with
633    /// [`Entity::bounding_box`]); the packet coordinates are `v26_1::server_position`.
634    #[must_use]
635    pub fn position(&self) -> [f64; 3] {
636        self.pos
637    }
638
639    /// 1.8 only: the raw server position in 1/32 blocks (`[0; 3]` in 1.12 and 1.16).
640    #[must_use]
641    pub fn fixed_position(&self) -> [i32; 3] {
642        if self.era == Era::V1_8 {
643            self.traced.map(|t| t as i32)
644        } else {
645            [0; 3]
646        }
647    }
648
649    /// Body yaw in degrees as vanilla computes it from the angle byte (`b * 360 / 256f`).
650    #[must_use]
651    pub fn yaw(&self) -> f32 {
652        self.yaw
653    }
654
655    /// Pitch in degrees.
656    #[must_use]
657    pub fn pitch(&self) -> f32 {
658        self.pitch
659    }
660
661    /// Head yaw in degrees (from `entity_head_rotation`; mobs also at spawn).
662    #[must_use]
663    pub fn head_yaw(&self) -> f32 {
664        self.head_yaw
665    }
666
667    /// Last velocity the server sent (blocks per tick), from the spawn packet or
668    /// `entity_velocity`. Not integrated over time.
669    #[must_use]
670    pub fn velocity(&self) -> [f64; 3] {
671        self.velocity
672    }
673
674    /// On-ground flag of the last movement packet.
675    #[must_use]
676    pub fn on_ground(&self) -> bool {
677        self.on_ground
678    }
679
680    /// Spawn data: object data (1.8 objects / 1.16 `spawn_entity`), experience orb value,
681    /// painting direction.
682    #[must_use]
683    pub fn data(&self) -> i32 {
684        self.data
685    }
686
687    /// Entity this one rides.
688    #[must_use]
689    pub fn vehicle(&self) -> Option<i32> {
690        self.rides.then_some(self.vehicle_id)
691    }
692
693    /// Entities riding this one (1.8: at most one).
694    #[must_use]
695    pub fn passengers(&self) -> &[i32] {
696        self.links.as_ref().map_or(&[], |l| &l.passengers)
697    }
698
699    /// Entity holding this one's leash.
700    #[must_use]
701    pub fn leash_holder(&self) -> Option<i32> {
702        self.links.as_ref().and_then(|l| l.leash_holder)
703    }
704
705    /// Metadata (empty unless metadata tracking is enabled).
706    #[must_use]
707    pub fn metadata(&self) -> &Metadata {
708        &self.meta
709    }
710
711    /// Equipment slot (see [`EQUIPMENT_SLOTS`]); `None` if never sent or empty.
712    #[must_use]
713    pub fn equipment(&self, slot: usize) -> Option<&Item> {
714        self.equipment.as_ref()?.get(slot)?.as_ref()
715    }
716
717    /// Active effects as last reported.
718    #[must_use]
719    pub fn effects(&self) -> &[Effect] {
720        self.links.as_ref().map_or(&[], |l| &l.effects)
721    }
722
723    /// The effect with this id, if active.
724    #[must_use]
725    pub fn effect(&self, id: u8) -> Option<&Effect> {
726        self.effects().iter().find(|e| e.id == id)
727    }
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733
734    /// `set_from` is `set` applied in order: overwrites, new indices appended once, the last
735    /// duplicate wins, refused indices are skipped; the block is exact-size.
736    #[test]
737    fn metadata_set_from_matches_set() {
738        let batches: [&[(u8, i8)]; 4] = [
739            &[(0, 1), (9, 2), (0, 3)],
740            &[(9, 4)],
741            &[(5, 5), (2, 6), (5, 7), (9, 8)],
742            &[(7, 9), (3, 10)],
743        ];
744        let keep = |i: u8| i != 3;
745        let (mut a, mut b) = (Metadata::default(), Metadata::default());
746        for batch in batches {
747            let mut src: Vec<(u8, MetaValue)> = batch
748                .iter()
749                .map(|&(i, v)| (i, MetaValue::Byte(v)))
750                .collect();
751            for (i, v) in src.clone() {
752                if keep(i) {
753                    a.set(i, v);
754                }
755            }
756            b.set_from(&mut src, keep);
757            assert!(src.is_empty());
758            assert_eq!(a, b);
759        }
760        let got: Vec<(u8, i8)> = b
761            .iter()
762            .map(|(i, v)| match v {
763                MetaValue::Byte(x) => (i, *x),
764                _ => unreachable!(),
765            })
766            .collect();
767        assert_eq!(got, [(0, 3), (9, 8), (5, 7), (2, 6), (7, 9)]);
768        assert_eq!(b.heap_bytes(), 5 * std::mem::size_of::<(u8, MetaValue)>());
769        b.clear();
770        assert!(b.is_empty() && b.heap_bytes() == 0);
771    }
772
773    #[test]
774    fn links_are_freed_when_empty() {
775        let mut e = Entity::new(1, EntityType::Player);
776        e.set_vehicle(None);
777        e.set_leash_holder(None);
778        e.clear_effects();
779        assert!(e.links.is_none());
780        e.set_vehicle(Some(2));
781        e.push_passenger(3);
782        assert_eq!((e.vehicle(), e.passengers()), (Some(2), &[3][..]));
783        e.set_vehicle(None);
784        e.remove_passenger(3);
785        assert!(e.links.is_none());
786        assert_eq!(e.take_passengers(), Vec::<i32>::new());
787    }
788}