Skip to main content

ghast_entity/
store.rs

1//! Version-independent entity store shared by the per-version trackers.
2
3use std::collections::HashMap;
4use std::hash::{BuildHasherDefault, Hasher};
5
6use uuid::Uuid;
7
8use crate::entity::{Entity, EntityType, MetaValue};
9
10/// What the tracker keeps. Everything off costs nothing beyond position tracking; packets for a
11/// disabled part are not parsed (and the client should not even decode them, see the version
12/// modules' packet id lists).
13///
14/// `#[non_exhaustive]`: build it from [`Config::default`] with the `with_*` methods:
15///
16/// ```
17/// let c = ghast_entity::Config::default().with_equipment(false).with_skins(true);
18/// assert!(c.metadata && !c.equipment && c.skins);
19/// ```
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct Config {
23    /// Entity metadata (flags, health, item of item entities, names, ...). Default `true`.
24    pub metadata: bool,
25    /// Equipment. Default `true`.
26    pub equipment: bool,
27    /// Status effects. Default `true`.
28    pub effects: bool,
29    /// Tab list (`player_info`). Default `true`.
30    pub player_list: bool,
31    /// Queue [`Event`]s for [`Entities::drain_events`]. Default `false`.
32    pub events: bool,
33    /// Keep the base64 `"textures"` profile property (skin / cape URLs) of tab-list entries in
34    /// [`PlayerInfo::textures`]. Default `false`: properties are skipped without allocating.
35    pub skins: bool,
36    /// With [`Config::player_list`] off: still read the tab list, but keep only each entry's
37    /// profile name and game mode (inline, about 50 bytes per entry; no [`PlayerInfo`]). That is
38    /// what vanilla needs from it for entities: [`Entities::player_name`] (team rules use the
39    /// scoreboard name), spectators (not pickable, not pushed, never on the ground) and, on
40    /// 26.x, refusing a player spawn whose profile is not in the tab list. Ignored when
41    /// [`Config::player_list`] is on (the full list answers the same questions). Default `false`.
42    pub player_names: bool,
43    /// The client view of the other entities: what the vanilla client draws and picks
44    /// ([`Entity::drawn_position`], [`Entity::drawn_bounding_box`]) and the per-entity clocks
45    /// ([`Entity::position_tick`], [`Entity::spawn_tick`], [`Entity::last_hurt_tick`],
46    /// [`Entity::estimated_velocity`]); the same switch as each tracker's
47    /// `track_client_motion`. One small heap block per living entity. Default `false`.
48    pub client_motion: bool,
49    /// Entity types (`minecraft:entity_type` registry ids of the tracker's version) whose
50    /// equipment and status effects are kept even with [`Config::equipment`] /
51    /// [`Config::effects`] off: the packets of other types are dropped after their entity id
52    /// (one map lookup). Modern (26.x) trackers only; the older ones ignore it. Default empty.
53    pub kept_types: &'static [u16],
54    /// Entity types (`minecraft:entity_type` registry ids of the tracker's version) whose client
55    /// copy keeps its own motion between the server's packets ([`Entities::client_motion`]):
56    /// set by the spawn, `set_entity_motion` and teleport packets, slowed by 0.98 on each tick
57    /// without a running interpolation and cut under 0.003 per axis (`LivingEntity.aiStep`),
58    /// pushed by the local player (`Tracker::push_motion` of the modern trackers). What a mount carries into the
59    /// first tick the bot rides it. Modern (26.x) trackers only. Default empty.
60    pub motion_types: &'static [u16],
61}
62
63impl Config {
64    /// Sets [`Config::client_motion`].
65    #[must_use]
66    pub const fn with_client_motion(mut self, on: bool) -> Self {
67        self.client_motion = on;
68        self
69    }
70
71    /// Sets [`Config::metadata`].
72    #[must_use]
73    pub const fn with_metadata(mut self, on: bool) -> Self {
74        self.metadata = on;
75        self
76    }
77
78    /// Sets [`Config::equipment`].
79    #[must_use]
80    pub const fn with_equipment(mut self, on: bool) -> Self {
81        self.equipment = on;
82        self
83    }
84
85    /// Sets [`Config::effects`].
86    #[must_use]
87    pub const fn with_effects(mut self, on: bool) -> Self {
88        self.effects = on;
89        self
90    }
91
92    /// Sets [`Config::player_list`].
93    #[must_use]
94    pub const fn with_player_list(mut self, on: bool) -> Self {
95        self.player_list = on;
96        self
97    }
98
99    /// Sets [`Config::events`].
100    #[must_use]
101    pub const fn with_events(mut self, on: bool) -> Self {
102        self.events = on;
103        self
104    }
105
106    /// Sets [`Config::skins`].
107    #[must_use]
108    pub const fn with_skins(mut self, on: bool) -> Self {
109        self.skins = on;
110        self
111    }
112
113    /// Sets [`Config::kept_types`].
114    #[must_use]
115    pub const fn with_kept_types(mut self, types: &'static [u16]) -> Self {
116        self.kept_types = types;
117        self
118    }
119
120    /// Sets [`Config::motion_types`].
121    #[must_use]
122    pub const fn with_motion_types(mut self, types: &'static [u16]) -> Self {
123        self.motion_types = types;
124        self
125    }
126
127    /// Sets [`Config::player_names`].
128    #[must_use]
129    pub const fn with_player_names(mut self, on: bool) -> Self {
130        self.player_names = on;
131        self
132    }
133
134    /// `true` when the tracker reads the tab list (full or names only): its packets
135    /// (`PLAYER_LIST_IDS` of the version module) must reach the tracker.
136    #[must_use]
137    pub const fn reads_tab_list(&self) -> bool {
138        self.player_list || self.player_names
139    }
140}
141
142impl Default for Config {
143    fn default() -> Self {
144        Config {
145            metadata: true,
146            equipment: true,
147            effects: true,
148            player_list: true,
149            events: false,
150            skins: false,
151            player_names: false,
152            client_motion: false,
153            kept_types: &[],
154            motion_types: &[],
155        }
156    }
157}
158
159/// A change notification (only queued with [`Config::events`]).
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
161#[non_exhaustive]
162pub enum Event {
163    /// A new entity (or a replacement for an existing id).
164    Spawned(i32),
165    /// An entity was removed (destroy, pickup, world change).
166    Removed {
167        /// Id.
168        id: i32,
169        /// Its type.
170        ty: EntityType,
171    },
172    /// Server position or rotation changed (movement, teleport).
173    Moved(i32),
174    /// Velocity changed.
175    Velocity(i32),
176    /// `entity_status` (e.g. 2 hurt, 3 death).
177    Status {
178        /// Id.
179        id: i32,
180        /// Status byte.
181        status: i8,
182    },
183    /// Metadata changed.
184    Metadata(i32),
185    /// An entity was hurt: 1.8 – 1.16.5 the hurt statuses (2; 1.12+ also 33 thorns, 36
186    /// drowning, 37 burning; 1.16 44 sweet berry bush, each also queued as [`Event::Status`]),
187    /// 26.x a living entity's `damage_event`. The bot's own entity included.
188    Hurt {
189        /// Id.
190        id: i32,
191        /// 26.x: the entity that caused the damage (the shooter for projectiles), if any;
192        /// always `None` before 26.x (the status carries no source).
193        attacker: Option<i32>,
194    },
195    /// Equipment changed.
196    Equipment(i32),
197    /// Effects changed.
198    Effects(i32),
199    /// Riding changed: `id` now rides `vehicle`.
200    Mounted {
201        /// Rider.
202        id: i32,
203        /// Vehicle (`None` = dismounted).
204        vehicle: Option<i32>,
205    },
206    /// An item / orb / arrow was picked up (`collector` may be the bot).
207    Collected {
208        /// Picked-up entity.
209        collected: i32,
210        /// Collector.
211        collector: i32,
212    },
213    /// The tab list changed.
214    PlayerList,
215    /// A tracked entity swung its arm (`animation` / `animate`: 1.8 action 0; 1.9+ action 0
216    /// the main hand, 3 the off hand) — the server's echo of an attack, a dig or a use.
217    Swing {
218        /// Id.
219        id: i32,
220        /// The off hand's swing (1.9+).
221        off_hand: bool,
222    },
223}
224
225/// A tab-list entry (`#[non_exhaustive]`: read-only for callers, fields may be added).
226#[derive(Clone, Debug, PartialEq, Eq)]
227#[non_exhaustive]
228pub struct PlayerInfo {
229    /// Profile name.
230    pub name: Box<str>,
231    /// Game mode.
232    pub game_mode: i32,
233    /// Latency in ms.
234    pub ping: i32,
235    /// Display name (raw chat JSON), if set (1.8 – 1.16; see
236    /// [`PlayerInfo::display_name_nbt`] for 26.1).
237    pub display_name: Option<Box<str>>,
238    /// The base64 `"textures"` profile property as sent (only with [`Config::skins`]; its
239    /// signature is not kept). Decoded it is JSON with the skin and cape URLs.
240    pub textures: Option<Box<str>>,
241    /// 26.1: the display name as its raw network NBT text component, if set.
242    pub display_name_nbt: Option<bytes::Bytes>,
243    /// Shown in the tab list (26.1 `UPDATE_LISTED`; always `true` before 26.1).
244    pub listed: bool,
245    /// 26.1 tab list order (`UPDATE_LIST_ORDER`; 0 before).
246    pub list_order: i32,
247    /// Which tab list object this is (26.1 player entities keep the one they first saw).
248    pub(crate) generation: u32,
249}
250
251#[derive(Default, Clone, Copy)]
252pub(crate) struct IdHasher(u64);
253
254impl Hasher for IdHasher {
255    #[inline]
256    fn finish(&self) -> u64 {
257        let h = self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15);
258        h ^ (h >> 29)
259    }
260
261    #[inline]
262    fn write(&mut self, bytes: &[u8]) {
263        for &b in bytes {
264            self.0 = (self.0 << 8) | u64::from(b);
265        }
266    }
267
268    #[inline]
269    fn write_i32(&mut self, v: i32) {
270        self.0 = u64::from(v as u32);
271    }
272
273    #[inline]
274    fn write_u64(&mut self, v: u64) {
275        self.0 = v;
276    }
277
278    #[inline]
279    fn write_u128(&mut self, v: u128) {
280        self.0 = (v as u64) ^ ((v >> 64) as u64);
281    }
282}
283
284pub(crate) type Fast<K, V> = HashMap<K, V, BuildHasherDefault<IdHasher>>;
285
286/// Gives memory back once a map holds less than a quarter of its capacity (a crowd left):
287/// shrinks to twice the live entries, so it neither keeps a peak's table forever nor rehashes
288/// back and forth around one size. Small maps are left alone.
289#[inline]
290pub(crate) fn shrink_map<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
291    let cap = m.capacity();
292    if cap > 64 && m.len() * 4 < cap {
293        m.shrink_to(m.len() * 2);
294    }
295}
296
297/// Call after an insert into `m`, with its `capacity()` before the insert (or after the last
298/// insert). hashbrown grows a table whose free slots ran out even when many of them are only
299/// deletion markers (ids that came and went), so a steady crowd with fresh ids doubles the
300/// table. A growth at least doubles `capacity()`; a real one leaves the table just over half
301/// full, one that leaves it at most half full was forced by markers and is undone at once: the
302/// table is rebuilt at its live size, which also drops the markers.
303#[inline]
304pub(crate) fn after_insert<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>, old_cap: usize) {
305    let cap = m.capacity();
306    if cap >= 2 * old_cap.max(1) && m.len() * 2 <= cap {
307        compact(m);
308    }
309}
310
311#[cold]
312#[inline(never)]
313fn compact<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
314    m.shrink_to(m.len());
315}
316
317/// A tab-list entry as [`Config::player_names`] keeps it: the profile name inline (a name longer
318/// than [`TabLite::INLINE`] bytes lives in `Entities::long_names`), the game mode and the tab
319/// list object generation (26.x).
320#[derive(Clone, Copy, Debug)]
321pub(crate) struct TabLite {
322    name: [u8; TabLite::INLINE],
323    /// Name length, or [`TabLite::LONG`].
324    len: u8,
325    pub(crate) game_mode: i32,
326    pub(crate) generation: u32,
327}
328
329impl TabLite {
330    /// Inline name bytes (vanilla profile names are at most 16 characters).
331    const INLINE: usize = 23;
332    const LONG: u8 = u8::MAX;
333}
334
335/// What the tab list says about one profile (full or names-only list).
336#[derive(Clone, Copy, Debug)]
337pub(crate) struct TabRef<'a> {
338    pub(crate) name: &'a str,
339    pub(crate) game_mode: i32,
340    pub(crate) generation: u32,
341}
342
343/// The tab lists of an [`Entities`] (borrowed field by field, so a caller can hold them while
344/// it changes entities).
345#[derive(Clone, Copy)]
346pub(crate) struct Tabs<'a> {
347    pub(crate) players: &'a Fast<Uuid, PlayerInfo>,
348    pub(crate) lite: &'a Fast<Uuid, TabLite>,
349    pub(crate) long_names: &'a Fast<Uuid, Box<str>>,
350}
351
352impl<'a> Tabs<'a> {
353    /// The entry of `uuid`.
354    #[inline]
355    pub(crate) fn get(self, uuid: &Uuid) -> Option<TabRef<'a>> {
356        if let Some(p) = self.players.get(uuid) {
357            return Some(TabRef {
358                name: &p.name,
359                game_mode: p.game_mode,
360                generation: p.generation,
361            });
362        }
363        if self.lite.is_empty() {
364            return None;
365        }
366        let t = self.lite.get(uuid)?;
367        let name = if t.len == TabLite::LONG {
368            self.long_names.get(uuid).map_or("", |n| &**n)
369        } else {
370            std::str::from_utf8(&t.name[..usize::from(t.len)]).unwrap_or("")
371        };
372        Some(TabRef {
373            name,
374            game_mode: t.game_mode,
375            generation: t.generation,
376        })
377    }
378}
379
380/// The tracked entities and tab list (queries are the same for every version).
381#[derive(Clone, Debug, Default)]
382pub struct Entities {
383    pub(crate) map: Fast<i32, Entity>,
384    pub(crate) self_id: Option<i32>,
385    pub(crate) config: Config,
386    pub(crate) events: Vec<Event>,
387    pub(crate) players: Fast<Uuid, PlayerInfo>,
388    /// The names-only tab list ([`Config::player_names`] without [`Config::player_list`]).
389    pub(crate) lite: Fast<Uuid, TabLite>,
390    /// Names-only entries whose name does not fit inline.
391    pub(crate) long_names: Fast<Uuid, Box<str>>,
392    pub(crate) scratch: Vec<(u8, MetaValue)>,
393    /// Set once any leash link exists (skips the leash scan on removal otherwise).
394    pub(crate) any_leash: bool,
395    /// The tracker's protocol family (selects the vanilla size table).
396    pub(crate) era: crate::entity::Era,
397    /// Modern trackers: a living mount the bot steers (the client set it; vanilla moves it
398    /// itself and ignores the server's relative moves of it).
399    pub(crate) steered: Option<i32>,
400    /// Last tab list object generation handed out.
401    pub(crate) generations: u32,
402    /// The client's tick clock ([`Entities::set_tick`]).
403    pub(crate) now: u64,
404    /// The client view is on (`track_client_motion`): living entities carry their drawn state
405    /// and clocks.
406    pub(crate) client_motion: bool,
407    /// Entities whose drawn state still changes on the next client tick (interpolation steps
408    /// left): a tick without any visits nothing.
409    pub(crate) lerping: u32,
410    /// The client view's chunk-section list counter (spawns and section changes).
411    pub(crate) order_seq: u32,
412    /// Scratch for the entities that changed sections in a tick.
413    pub(crate) order_scratch: Vec<(u32, i32, [i32; 3])>,
414    /// 26.3: the stepped interpolations of living entities, by id (empty for other versions).
415    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
416    pub(crate) stepped: Fast<i32, crate::modern_state::Stepped>,
417    /// 26.3: the sleeping positions of living entities, by id (only kept until the entity's
418    /// first tick checks its bed; empty for other versions).
419    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
420    pub(crate) sleeping: Fast<i32, [i32; 3]>,
421    /// The client copies' own motion of the [`Config::motion_types`] entities, by id (only
422    /// non-zero ones are kept).
423    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
424    pub(crate) motions: Fast<i32, [f64; 3]>,
425}
426
427impl Entities {
428    pub(crate) fn new(config: Config) -> Self {
429        Entities {
430            config,
431            client_motion: config.client_motion,
432            ..Default::default()
433        }
434    }
435
436    /// The entity with this id (including the bot's own entry, see [`Entities::self_id`]).
437    #[inline]
438    #[must_use]
439    pub fn get(&self, id: i32) -> Option<&Entity> {
440        self.map.get(&id)
441    }
442
443    /// Number of tracked entities (including the bot's own entry).
444    #[must_use]
445    pub fn len(&self) -> usize {
446        self.map.len()
447    }
448
449    /// `true` when nothing is tracked.
450    #[must_use]
451    pub fn is_empty(&self) -> bool {
452        self.map.is_empty()
453    }
454
455    /// Other entities (the bot's own entry is skipped), arbitrary order.
456    pub fn iter(&self) -> impl Iterator<Item = &Entity> {
457        let me = self.self_id;
458        self.map.values().filter(move |e| Some(e.id) != me)
459    }
460
461    /// The bot's own entity id (from `login`). Its entry carries metadata, equipment, riding
462    /// state and effects as far as the [`Config`] keeps them, but **no position**: the client
463    /// owns its own position. The ghast client tracks entities with [`Config::effects`] and
464    /// [`Config::equipment`] off: use `TickContext::effects` for the bot's own effects.
465    #[must_use]
466    pub fn self_id(&self) -> Option<i32> {
467        self.self_id
468    }
469
470    /// The bot's own entry (see [`Entities::self_id`] for what it carries).
471    #[must_use]
472    pub fn me(&self) -> Option<&Entity> {
473        self.map.get(&self.self_id?)
474    }
475
476    /// Entities whose server position is within `radius` of `p` (linear scan).
477    pub fn within(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
478        let r2 = radius * radius;
479        self.iter().filter(move |e| {
480            let d = [e.pos[0] - p[0], e.pos[1] - p[1], e.pos[2] - p[2]];
481            d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= r2
482        })
483    }
484
485    /// Alias of [`Entities::within`].
486    pub fn near(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
487        self.within(p, radius)
488    }
489
490    /// The tab list.
491    #[must_use]
492    pub fn player_info(&self, uuid: &Uuid) -> Option<&PlayerInfo> {
493        self.players.get(uuid)
494    }
495
496    /// All tab-list entries.
497    pub fn players(&self) -> impl Iterator<Item = (&Uuid, &PlayerInfo)> {
498        self.players.iter()
499    }
500
501    /// Name of a player entity (from the tab list: the full one, or the names-only one of
502    /// [`Config::player_names`]).
503    #[must_use]
504    pub fn player_name(&self, id: i32) -> Option<&str> {
505        let e = self.map.get(&id)?;
506        e.is_player()
507            .then(|| self.tab(&e.uuid).map(|t| t.name))
508            .flatten()
509    }
510
511    /// Profile name of a tab-list entry (full list or names only).
512    #[must_use]
513    pub fn tab_name(&self, uuid: &Uuid) -> Option<&str> {
514        self.tab(uuid).map(|t| t.name)
515    }
516
517    /// The motion (`getDeltaMovement`) of the client copy of entity `id` when its type is one of
518    /// [`Config::motion_types`]: zero once it has run out (or was never set), `None` for other
519    /// types and unknown ids. Modern (26.x) trackers only.
520    #[must_use]
521    pub fn client_motion(&self, id: i32) -> Option<[f64; 3]> {
522        let e = self.map.get(&id)?;
523        let EntityType::Registry(t) = e.ty else {
524            return None;
525        };
526        if !self.config.motion_types.contains(&t) {
527            return None;
528        }
529        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
530        if let Some(v) = self.motions.get(&id) {
531            return Some(*v);
532        }
533        Some([0.0; 3])
534    }
535
536    /// The local player pushed entity `id`: `delta` (x, z) is added to its client motion, for
537    /// a [`Config::motion_types`] entity (others: nothing).
538    pub(crate) fn push_motion(&mut self, id: i32, delta: [f64; 2]) {
539        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
540        if self.client_motion(id).is_some() {
541            let v = self.motions.entry(id).or_insert([0.0; 3]);
542            let n = [v[0] + delta[0], v[1], v[2] + delta[1]];
543            if n.iter().all(|c| c.is_finite()) {
544                *v = n;
545            }
546            if let Some(e) = self.map.get_mut(&id) {
547                e.m.set_flag(crate::modern_state::st::SETTLED, false);
548            }
549        }
550        #[cfg(not(any(feature = "v26_1", feature = "v26_2", feature = "v26_3")))]
551        let _ = (id, delta);
552    }
553
554    /// Sets the client motion of a [`Config::motion_types`] entity (`setDeltaMovement`).
555    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
556    pub(crate) fn set_motion(&mut self, id: i32, ty: EntityType, v: [f64; 3]) {
557        let EntityType::Registry(t) = ty else {
558            return;
559        };
560        if !self.config.motion_types.contains(&t) {
561            return;
562        }
563        if v.iter().all(|c| c.to_bits() == 0) {
564            self.motions.remove(&id);
565        } else {
566            self.motions.insert(id, v);
567        }
568    }
569
570    /// The uuid of the tab-list entry (full list or names only) with profile name `name`.
571    #[must_use]
572    pub fn tab_uuid(&self, name: &str) -> Option<Uuid> {
573        let tabs = self.tabs();
574        self.players
575            .keys()
576            .chain(self.lite.keys())
577            .find(|u| tabs.get(u).is_some_and(|t| t.name == name))
578            .copied()
579    }
580
581    /// Game mode of a tab-list entry (full list or names only).
582    #[must_use]
583    pub fn tab_game_mode(&self, uuid: &Uuid) -> Option<i32> {
584        self.tab(uuid).map(|t| t.game_mode)
585    }
586
587    /// 26.x: the generation of `uuid`'s tab-list object (a new number each time the server
588    /// adds the entry): a player entity that looked its entry up keeps reading that object
589    /// (`v26_x::tab_generation`) while it is in the list.
590    #[must_use]
591    pub fn tab_generation(&self, uuid: &Uuid) -> Option<u32> {
592        self.tab(uuid).map(|t| t.generation)
593    }
594
595    /// Number of tab-list entries kept (full list or names only).
596    #[must_use]
597    pub fn tab_len(&self) -> usize {
598        self.players.len() + self.lite.len()
599    }
600
601    /// The names-only list is in use.
602    #[inline]
603    pub(crate) fn lite_mode(&self) -> bool {
604        !self.config.player_list && self.config.player_names
605    }
606
607    /// The tab-list entry of `uuid` (full or names only).
608    #[inline]
609    pub(crate) fn tab(&self, uuid: &Uuid) -> Option<TabRef<'_>> {
610        self.tabs().get(uuid)
611    }
612
613    /// The tab lists, borrowed apart from the entity map.
614    #[inline]
615    pub(crate) fn tabs(&self) -> Tabs<'_> {
616        Tabs {
617            players: &self.players,
618            lite: &self.lite,
619            long_names: &self.long_names,
620        }
621    }
622
623    /// `true` when the tab list (full or names only) has `uuid`.
624    #[inline]
625    pub(crate) fn tab_has(&self, uuid: &Uuid) -> bool {
626        self.players.contains_key(uuid) || self.lite.contains_key(uuid)
627    }
628
629    /// Adds a names-only entry unless `uuid` has one (vanilla's `putIfAbsent`; 1.8 – 1.16
630    /// replace, `replace` = true). Returns `true` when an entry was added.
631    pub(crate) fn lite_add(
632        &mut self,
633        uuid: Uuid,
634        name: &str,
635        game_mode: i32,
636        generation: u32,
637        replace: bool,
638    ) -> bool {
639        if !replace && self.lite.contains_key(&uuid) {
640            return false;
641        }
642        let mut t = TabLite {
643            name: [0; TabLite::INLINE],
644            len: TabLite::LONG,
645            game_mode,
646            generation,
647        };
648        if name.len() <= TabLite::INLINE {
649            t.name[..name.len()].copy_from_slice(name.as_bytes());
650            t.len = name.len() as u8;
651            if self.long_names.remove(&uuid).is_some() {
652                shrink_map(&mut self.long_names);
653            }
654        } else {
655            self.long_names.insert(uuid, Box::from(name));
656        }
657        let cap = self.lite.capacity();
658        self.lite.insert(uuid, t);
659        after_insert(&mut self.lite, cap);
660        true
661    }
662
663    /// Removes `uuid` from the tab list (full or names only): its game mode and generation.
664    pub(crate) fn tab_remove(&mut self, uuid: &Uuid) -> Option<(i32, u32)> {
665        if let Some(p) = self.players.remove(uuid) {
666            shrink_map(&mut self.players);
667            return Some((p.game_mode, p.generation));
668        }
669        let t = self.lite.remove(uuid)?;
670        if t.len == TabLite::LONG && self.long_names.remove(uuid).is_some() {
671            shrink_map(&mut self.long_names);
672        }
673        shrink_map(&mut self.lite);
674        Some((t.game_mode, t.generation))
675    }
676
677    /// Sets the game mode of a names-only entry.
678    #[inline]
679    pub(crate) fn lite_game_mode(&mut self, uuid: &Uuid, game_mode: i32) {
680        if let Some(t) = self.lite.get_mut(uuid) {
681            t.game_mode = game_mode;
682        }
683    }
684
685    /// The configuration.
686    #[must_use]
687    pub fn config(&self) -> Config {
688        self.config
689    }
690
691    /// Takes the queued events (keeps the buffer's capacity).
692    pub fn drain_events(&mut self) -> std::vec::Drain<'_, Event> {
693        self.events.drain(..)
694    }
695
696    /// Removes every entity (keeps the tab list and the bot's id).
697    pub fn clear(&mut self) {
698        if self.config.events {
699            let me = self.self_id;
700            self.events.extend(
701                self.map
702                    .values()
703                    .filter(|e| Some(e.id) != me)
704                    .map(|e| Event::Removed { id: e.id, ty: e.ty }),
705            );
706        }
707        let me = self.self_id.and_then(|id| self.map.remove(&id));
708        self.map.clear();
709        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
710        {
711            self.stepped.clear();
712            shrink_map(&mut self.stepped);
713            self.sleeping.clear();
714            shrink_map(&mut self.sleeping);
715            self.motions.clear();
716            shrink_map(&mut self.motions);
717        }
718        self.lerping = 0;
719        shrink_map(&mut self.map);
720        if let Some(mut me) = me {
721            me.set_vehicle(None);
722            if let Some(l) = &mut me.links {
723                l.passengers.clear();
724                l.leash_holder = None;
725            }
726            me.tidy_links();
727            self.map.insert(me.id, me);
728        }
729    }
730
731    #[inline]
732    pub(crate) fn event(&mut self, e: Event) {
733        if self.config.events {
734            self.events.push(e);
735        }
736    }
737
738    pub(crate) fn set_self(&mut self, id: i32) {
739        if let Some(old) = self.self_id {
740            self.map.remove(&old);
741        }
742        self.self_id = Some(id);
743        let mut me = Entity::new(id, EntityType::Player);
744        self.resolve(&mut me);
745        self.map.insert(id, me);
746    }
747
748    /// Stamps the protocol family and resolves the vanilla size entry.
749    fn resolve(&self, e: &mut Entity) {
750        use crate::entity::Era;
751        e.era = self.era;
752        e.sizer = match self.era {
753            #[cfg(feature = "v1_8")]
754            Era::V1_8 => crate::v1_8::vanilla_size(e),
755            #[cfg(feature = "v1_12")]
756            Era::V1_12 => crate::v1_12::vanilla_size(e),
757            #[cfg(feature = "v1_16_5")]
758            Era::V1_16 => crate::v1_16_5::vanilla_size(e),
759            #[cfg(feature = "v26_1")]
760            Era::V26 => crate::v26_1::vanilla_size(e),
761            #[cfg(feature = "v26_2")]
762            Era::V26_2 => crate::v26_2::vanilla_size(e),
763            #[cfg(feature = "v26_3")]
764            Era::V26_3 => crate::v26_3::vanilla_size(e),
765            #[allow(unreachable_patterns)]
766            _ => None,
767        };
768    }
769
770    /// Sets the clock that stamps [`Entity::position_tick`], [`Entity::spawn_tick`] and
771    /// [`Entity::last_hurt_tick`] (the ghast client sets it to the tick in which the behaviour
772    /// first sees the packets that follow).
773    pub fn set_tick(&mut self, now: u64) {
774        self.now = now;
775    }
776
777    /// The clock set with [`Entities::set_tick`].
778    #[must_use]
779    pub fn tick(&self) -> u64 {
780        self.now
781    }
782
783    /// Attaches the client view's state to a spawning entity (living entities, with the view on).
784    #[inline]
785    fn attach_client(&mut self, e: &mut Entity) {
786        use crate::drawn::{Client, Lerp, legacy_lerp};
787        use crate::entity::Era;
788        let lerp = match e.era {
789            Era::V1_8 | Era::V1_12 => legacy_lerp(e),
790            _ if e.living => Some(Lerp::External),
791            // 1.16.5 boats (registry id 6), armor stands (1, living, spawned as objects) and
792            // minecarts interpolate in the client view.
793            Era::V1_16
794                if matches!(e.ty, EntityType::Registry(6 | 1))
795                    || e.sizer.is_some_and(|s| s.name.ends_with("minecart")) =>
796            {
797                Some(Lerp::External)
798            }
799            _ => None,
800        };
801        if let Some(l) = lerp {
802            self.order_seq = self.order_seq.wrapping_add(1);
803            let c = Client::new(e, l, self.now, self.order_seq);
804            // A 1.12 shulker starts busy (its first tick turns it).
805            self.lerping += u32::from(c.busy());
806            e.client = Some(Box::new(c));
807        }
808    }
809
810    /// Turns the client view on or off for every tracked entity (on: drawn where the server has
811    /// them now).
812    pub(crate) fn set_client_motion(&mut self, on: bool) {
813        if on == self.client_motion {
814            return;
815        }
816        self.client_motion = on;
817        self.lerping = 0;
818        let mut map = std::mem::take(&mut self.map);
819        for e in map.values_mut() {
820            if on && Some(e.id) != self.self_id {
821                self.attach_client(e);
822            } else {
823                e.client = None;
824            }
825        }
826        self.map = map;
827    }
828
829    /// One client tick of the legacy (1.8 / 1.12) drawn positions.
830    pub(crate) fn step_drawn(&mut self) {
831        if self.lerping == 0 {
832            return;
833        }
834        let mut ended = 0;
835        let mut moved = std::mem::take(&mut self.order_scratch);
836        for e in self.map.values_mut() {
837            let on_ground = e.on_ground;
838            if let Some(c) = e.client.as_deref_mut()
839                && c.busy()
840            {
841                ended += u32::from(c.step(on_ground));
842                // World.checkChunk after the entity's tick: another section's list takes it.
843                let sec = crate::drawn::section_of(c.pos);
844                if sec != c.section {
845                    moved.push((c.spawn_seq, e.id, sec));
846                }
847            }
848        }
849        self.lerping -= ended;
850        if matches!(
851            self.era,
852            crate::entity::Era::V1_8 | crate::entity::Era::V1_12
853        ) && self.map.values().any(Entity::rides)
854        {
855            self.seat_riders(&mut moved);
856        }
857        if !moved.is_empty() {
858            self.resection(&mut moved);
859        }
860        self.order_scratch = moved;
861    }
862
863    /// 1.8 `tickRiding`: after its vehicle's tick a rider sits where the vehicle's
864    /// `updatePassengerPosition` puts it, then its own chunk check follows its vehicle's.
865    #[cold]
866    #[inline(never)]
867    fn seat_riders(&mut self, moved: &mut Vec<(u32, i32, [i32; 3])>) {
868        let riders: Vec<(i32, i32)> = self
869            .map
870            .values()
871            .filter_map(|e| e.vehicle().map(|v| (e.id, v)))
872            .collect();
873        for (rid, vid) in riders {
874            let Some(v) = self.map.get(&vid) else {
875                continue;
876            };
877            let Some(vc) = v.client.as_deref() else {
878                continue;
879            };
880            let Some(r) = self.map.get(&rid) else {
881                continue;
882            };
883            let seat = if self.era == crate::entity::Era::V1_8 {
884                crate::drawn::seat_1_8(v, vc, r).map(|p| (p, None))
885            } else {
886                crate::drawn::seat_1_12(v, vc, r)
887            };
888            let Some((seat, yaw)) = seat else {
889                continue;
890            };
891            let vseq = vc.spawn_seq;
892            if let Some(rc) = self.map.get_mut(&rid).and_then(|e| e.client.as_deref_mut()) {
893                rc.pos = seat;
894                rc.bb = None;
895                if let Some(y) = yaw {
896                    rc.rot[0] = y;
897                }
898                let sec = crate::drawn::section_of(seat);
899                if sec != rc.section {
900                    // The rider's check runs right after its vehicle's.
901                    moved.retain(|m| m.1 != rid);
902                    moved.push((vseq, rid, sec));
903                }
904            }
905        }
906    }
907
908    /// The entities that changed sections in this tick join their new lists in the world's
909    /// tick order (spawn order).
910    #[cold]
911    #[inline(never)]
912    fn resection(&mut self, moved: &mut Vec<(u32, i32, [i32; 3])>) {
913        // Spawn order; a rider (keyed by its vehicle's) after its vehicle.
914        let riders: Vec<i32> = moved
915            .iter()
916            .filter(|m| self.map.get(&m.1).is_some_and(Entity::rides))
917            .map(|m| m.1)
918            .collect();
919        moved.sort_by_key(|m| (m.0, riders.contains(&m.1)));
920        for &(_, id, sec) in moved.iter() {
921            self.order_seq = self.order_seq.wrapping_add(1);
922            if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
923                c.section = sec;
924                c.seq = self.order_seq;
925            }
926        }
927        moved.clear();
928    }
929
930    /// The count of interpolating entities changed by `d` ([`crate::drawn::relative`] /
931    /// `teleport`).
932    #[inline]
933    pub(crate) fn lerp_changed(&mut self, d: i32) {
934        self.lerping = self.lerping.wrapping_add_signed(d);
935    }
936
937    /// An entity left the store: it no longer counts as interpolating.
938    #[inline]
939    fn forget_lerp(&mut self, e: &Entity) {
940        if e.client.as_ref().is_some_and(|c| c.busy()) {
941            self.lerping -= 1;
942        }
943    }
944
945    /// 1.8.9 / 1.12.2: a moving piston moved entity `id` on the client (`Entity.move`): the
946    /// client view draws it at `pos` with box `bb` (`[min_x, min_y, min_z, max_x, max_y,
947    /// max_z]`) until its next interpolation step, and keeps its ground and web state. `false`
948    /// when the client view does not keep the entity.
949    pub(crate) fn legacy_pushed(
950        &mut self,
951        id: i32,
952        pos: [f64; 3],
953        bb: [f64; 6],
954        on_ground: bool,
955        in_web: bool,
956    ) -> bool {
957        let Some(e) = self.map.get_mut(&id) else {
958            return false;
959        };
960        let Some(c) = e.client.as_deref_mut() else {
961            return false;
962        };
963        // A 1.12 shulker on its attached block.
964        let attached = c.shulker.as_ref().is_some_and(|s| s.attached.is_some());
965        if c.lerp == crate::drawn::Lerp::External {
966            return false;
967        }
968        let d = c.legacy_pushed(pos, bb, on_ground, in_web, attached);
969        self.lerp_changed(d);
970        true
971    }
972
973    /// The client's own hit on entity `id` pushed it (`Entity.addVelocity` after an attack the
974    /// client counts as landed): a 1.8 boat drifts by it in the client view.
975    pub(crate) fn knock(&mut self, id: i32, d: [f64; 3]) {
976        if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
977            let x = c.add_velocity(d);
978            self.lerp_changed(x);
979        }
980    }
981
982    /// A hurt (status or damage event) of entity `id`: stamps it and queues [`Event::Hurt`].
983    #[inline]
984    pub(crate) fn hurt(&mut self, id: i32, attacker: Option<i32>) {
985        let now = self.now;
986        if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
987            c.hurt = Some(now);
988        }
989        self.event(Event::Hurt { id, attacker });
990    }
991
992    /// Adds an entity, replacing (and unlinking) any entity with the same id, as vanilla does.
993    pub(crate) fn spawn(&mut self, mut e: Entity) {
994        let id = e.id;
995        self.resolve(&mut e);
996        if Some(id) == self.self_id {
997            return;
998        }
999        if self.client_motion {
1000            self.attach_client(&mut e);
1001        }
1002        if self.map.contains_key(&id) {
1003            self.unlink(id);
1004        }
1005        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1006        if !self.stepped.is_empty() {
1007            self.stepped.remove(&id);
1008        }
1009        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1010        if !self.sleeping.is_empty() {
1011            self.sleeping.remove(&id);
1012        }
1013        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1014        if !self.motions.is_empty() {
1015            self.motions.remove(&id);
1016        }
1017        let cap = self.map.capacity();
1018        if let Some(old) = self.map.insert(id, e) {
1019            self.forget_lerp(&old);
1020        }
1021        after_insert(&mut self.map, cap);
1022        self.event(Event::Spawned(id));
1023    }
1024
1025    pub(crate) fn remove(&mut self, id: i32) -> bool {
1026        if Some(id) == self.self_id || !self.map.contains_key(&id) {
1027            return false;
1028        }
1029        self.unlink(id);
1030        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1031        if !self.stepped.is_empty() {
1032            self.stepped.remove(&id);
1033        }
1034        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1035        if !self.sleeping.is_empty() {
1036            self.sleeping.remove(&id);
1037        }
1038        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1039        if !self.motions.is_empty() {
1040            self.motions.remove(&id);
1041        }
1042        if let Some(e) = self.map.remove(&id) {
1043            self.forget_lerp(&e);
1044            self.event(Event::Removed { id, ty: e.ty });
1045        }
1046        shrink_map(&mut self.map);
1047        true
1048    }
1049
1050    /// Detaches `id` from its vehicle, passengers and leash links.
1051    fn unlink(&mut self, id: i32) {
1052        let Some(e) = self.map.get_mut(&id) else {
1053            return;
1054        };
1055        if e.links.is_none() && !e.rides() && !self.any_leash {
1056            return;
1057        }
1058        let vehicle = e.take_vehicle();
1059        let passengers = e.take_passengers();
1060        if let Some(v) = vehicle
1061            && let Some(v) = self.map.get_mut(&v)
1062        {
1063            v.remove_passenger(id);
1064        }
1065        for p in passengers {
1066            if let Some(p) = self.map.get_mut(&p)
1067                && p.vehicle() == Some(id)
1068            {
1069                p.set_vehicle(None);
1070            }
1071        }
1072        if self.any_leash {
1073            for other in self.map.values_mut() {
1074                if other.leash_holder() == Some(id) {
1075                    other.set_leash_holder(None);
1076                }
1077            }
1078        }
1079    }
1080
1081    /// `startRiding` in the client view: a 1.8 dismount puts the rider on top of its old
1082    /// vehicle (`refreshPositionAndAngles(x, minY + height, z)`); a mount seats it at the next
1083    /// tick (`updatePassengerPosition`).
1084    #[cold]
1085    #[inline(never)]
1086    fn seat_change(&mut self, rider: i32, old: Option<i32>, vehicle: Option<i32>) {
1087        let top = match (vehicle, old.and_then(|o| self.map.get(&o))) {
1088            // 1.12's client moves nothing at a dismount.
1089            (None, Some(o)) if self.era == crate::entity::Era::V1_8 => {
1090                o.client.as_deref().and_then(|c| {
1091                    let h = o.sizer.and_then(|s| s.registered).map(|(_, h)| h)?;
1092                    Some([c.pos[0], c.pos[1] + f64::from(h), c.pos[2]])
1093                })
1094            }
1095            _ => None,
1096        };
1097        let Some(c) = self
1098            .map
1099            .get_mut(&rider)
1100            .and_then(|e| e.client.as_deref_mut())
1101        else {
1102            return;
1103        };
1104        let idle = !c.busy();
1105        if let Some(p) = top {
1106            c.pos = p;
1107            c.bb = None;
1108        }
1109        c.order_pending = true;
1110        let d = i32::from(c.busy()) - i32::from(!idle);
1111        self.lerp_changed(d);
1112    }
1113
1114    /// `true` when `vehicle` is `rider` or (indirectly) rides `rider`.
1115    fn rides(&self, vehicle: i32, rider: i32) -> bool {
1116        let mut cur = Some(vehicle);
1117        let mut guard = 0;
1118        while let Some(c) = cur {
1119            if c == rider {
1120                return true;
1121            }
1122            guard += 1;
1123            if guard > 64 {
1124                return true;
1125            }
1126            cur = self.map.get(&c).and_then(Entity::vehicle);
1127        }
1128        false
1129    }
1130
1131    /// Makes `rider` ride `vehicle` (or dismount with `None`). `single` = 1.8 semantics (one
1132    /// rider per vehicle: a previous rider is dismounted). Returns `false` when ignored.
1133    pub(crate) fn mount(&mut self, rider: i32, vehicle: Option<i32>, single: bool) -> bool {
1134        if !self.map.contains_key(&rider) {
1135            return false;
1136        }
1137        if let Some(v) = vehicle
1138            && (!self.map.contains_key(&v) || self.rides(v, rider))
1139        {
1140            return false;
1141        }
1142        // Leave the old vehicle.
1143        let old = self.map.get_mut(&rider).and_then(Entity::take_vehicle);
1144        if let Some(o) = old
1145            && let Some(o) = self.map.get_mut(&o)
1146        {
1147            o.remove_passenger(rider);
1148        }
1149        if self.client_motion
1150            && matches!(
1151                self.era,
1152                crate::entity::Era::V1_8 | crate::entity::Era::V1_12
1153            )
1154        {
1155            self.seat_change(rider, old, vehicle);
1156        }
1157        if let Some(v) = vehicle {
1158            let prev: Vec<i32> = if single {
1159                self.map
1160                    .get_mut(&v)
1161                    .map(Entity::take_passengers)
1162                    .unwrap_or_default()
1163            } else {
1164                Vec::new()
1165            };
1166            for p in prev {
1167                if let Some(p) = self.map.get_mut(&p) {
1168                    p.set_vehicle(None);
1169                }
1170            }
1171            if let Some(ve) = self.map.get_mut(&v) {
1172                ve.push_passenger(rider);
1173            }
1174            if let Some(r) = self.map.get_mut(&rider) {
1175                r.set_vehicle(Some(v));
1176            }
1177        }
1178        self.event(Event::Mounted { id: rider, vehicle });
1179        true
1180    }
1181
1182    /// 1.16 `set_passengers`: ejects every current passenger of `vehicle`, then mounts `ids`.
1183    pub(crate) fn set_passengers(&mut self, vehicle: i32, ids: impl Iterator<Item = i32>) -> bool {
1184        let Some(v) = self.map.get_mut(&vehicle) else {
1185            return false;
1186        };
1187        let old = v.take_passengers();
1188        for p in &old {
1189            if let Some(p) = self.map.get_mut(p)
1190                && p.vehicle() == Some(vehicle)
1191            {
1192                p.set_vehicle(None);
1193            }
1194        }
1195        // Reuse the old buffer for the new list (no allocation in steady state).
1196        let mut old = old;
1197        old.clear();
1198        if let Some(v) = self.map.get_mut(&vehicle) {
1199            v.set_passengers(old);
1200        }
1201        for id in ids {
1202            self.mount(id, Some(vehicle), false);
1203        }
1204        true
1205    }
1206
1207    pub(crate) fn leash(&mut self, id: i32, holder: Option<i32>) -> bool {
1208        match self.map.get_mut(&id) {
1209            Some(e) => {
1210                e.set_leash_holder(holder);
1211                self.any_leash |= holder.is_some();
1212                true
1213            }
1214            None => false,
1215        }
1216    }
1217}
1218
1219#[cfg(test)]
1220mod tests {
1221    use super::*;
1222
1223    fn store() -> Entities {
1224        let mut s = Entities::new(Config {
1225            events: true,
1226            ..Config::default()
1227        });
1228        for id in 1..=4 {
1229            s.spawn(Entity::new(id, EntityType::Registry(6)));
1230        }
1231        s
1232    }
1233
1234    /// Bytes per tracked entity (the map slot adds the 4-byte key, padded).
1235    #[test]
1236    fn entity_size() {
1237        let n = std::mem::size_of::<Entity>();
1238        eprintln!("size_of::<Entity>() = {n}");
1239        // 0.3.0 – 0.4.3: 232 bytes. Riding, leash and effects sit behind one pointer, the
1240        // metadata is an exact-size block (pointer + length); the 26.x state is boxed.
1241        // 0.4.8: + 8 bytes, the pointer to the client view's drawn state and clocks.
1242        let modern = cfg!(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"));
1243        assert!(n <= if modern { 176 } else { 168 }, "{n}");
1244        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1245        {
1246            let b = std::mem::size_of::<crate::modern_state::State>();
1247            eprintln!("size_of::<modern_state::State>() = {b} (heap, 26.x entities only)");
1248            assert!(b <= 120, "{b}");
1249        }
1250    }
1251
1252    #[test]
1253    fn mount_single_and_multi() {
1254        let mut s = store();
1255        assert!(s.mount(1, Some(2), true));
1256        assert!(s.mount(3, Some(2), true)); // 1.8: replaces rider 1
1257        assert_eq!(s.get(2).unwrap().passengers(), &[3]);
1258        assert_eq!(s.get(1).unwrap().vehicle(), None);
1259        assert!(!s.mount(2, Some(3), true), "cycle");
1260        assert!(s.set_passengers(4, [1, 3].into_iter()));
1261        assert_eq!(s.get(4).unwrap().passengers(), &[1, 3]);
1262        assert_eq!(s.get(2).unwrap().passengers(), &[] as &[i32]);
1263        assert_eq!(s.get(3).unwrap().vehicle(), Some(4));
1264        s.remove(4);
1265        assert_eq!(s.get(1).unwrap().vehicle(), None);
1266        assert_eq!(s.get(3).unwrap().vehicle(), None);
1267    }
1268
1269    #[test]
1270    fn self_entry_survives_clear() {
1271        let mut s = store();
1272        s.set_self(9);
1273        s.spawn(Entity::new(9, EntityType::Registry(1))); // ignored: own id
1274        assert_eq!(s.get(9).unwrap().entity_type(), EntityType::Player);
1275        assert!(!s.remove(9));
1276        s.drain_events().for_each(drop);
1277        s.clear();
1278        assert_eq!(s.len(), 1);
1279        assert!(s.me().is_some());
1280        assert_eq!(s.drain_events().count(), 4);
1281        assert_eq!(s.iter().count(), 0);
1282    }
1283}