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}
44
45impl Config {
46    /// Sets [`Config::metadata`].
47    #[must_use]
48    pub const fn with_metadata(mut self, on: bool) -> Self {
49        self.metadata = on;
50        self
51    }
52
53    /// Sets [`Config::equipment`].
54    #[must_use]
55    pub const fn with_equipment(mut self, on: bool) -> Self {
56        self.equipment = on;
57        self
58    }
59
60    /// Sets [`Config::effects`].
61    #[must_use]
62    pub const fn with_effects(mut self, on: bool) -> Self {
63        self.effects = on;
64        self
65    }
66
67    /// Sets [`Config::player_list`].
68    #[must_use]
69    pub const fn with_player_list(mut self, on: bool) -> Self {
70        self.player_list = on;
71        self
72    }
73
74    /// Sets [`Config::events`].
75    #[must_use]
76    pub const fn with_events(mut self, on: bool) -> Self {
77        self.events = on;
78        self
79    }
80
81    /// Sets [`Config::skins`].
82    #[must_use]
83    pub const fn with_skins(mut self, on: bool) -> Self {
84        self.skins = on;
85        self
86    }
87
88    /// Sets [`Config::player_names`].
89    #[must_use]
90    pub const fn with_player_names(mut self, on: bool) -> Self {
91        self.player_names = on;
92        self
93    }
94
95    /// `true` when the tracker reads the tab list (full or names only): its packets
96    /// (`PLAYER_LIST_IDS` of the version module) must reach the tracker.
97    #[must_use]
98    pub const fn reads_tab_list(&self) -> bool {
99        self.player_list || self.player_names
100    }
101}
102
103impl Default for Config {
104    fn default() -> Self {
105        Config {
106            metadata: true,
107            equipment: true,
108            effects: true,
109            player_list: true,
110            events: false,
111            skins: false,
112            player_names: false,
113        }
114    }
115}
116
117/// A change notification (only queued with [`Config::events`]).
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum Event {
121    /// A new entity (or a replacement for an existing id).
122    Spawned(i32),
123    /// An entity was removed (destroy, pickup, world change).
124    Removed {
125        /// Id.
126        id: i32,
127        /// Its type.
128        ty: EntityType,
129    },
130    /// Server position or rotation changed (movement, teleport).
131    Moved(i32),
132    /// Velocity changed.
133    Velocity(i32),
134    /// `entity_status` (e.g. 2 hurt, 3 death).
135    Status {
136        /// Id.
137        id: i32,
138        /// Status byte.
139        status: i8,
140    },
141    /// Metadata changed.
142    Metadata(i32),
143    /// Equipment changed.
144    Equipment(i32),
145    /// Effects changed.
146    Effects(i32),
147    /// Riding changed: `id` now rides `vehicle`.
148    Mounted {
149        /// Rider.
150        id: i32,
151        /// Vehicle (`None` = dismounted).
152        vehicle: Option<i32>,
153    },
154    /// An item / orb / arrow was picked up (`collector` may be the bot).
155    Collected {
156        /// Picked-up entity.
157        collected: i32,
158        /// Collector.
159        collector: i32,
160    },
161    /// The tab list changed.
162    PlayerList,
163}
164
165/// A tab-list entry (`#[non_exhaustive]`: read-only for callers, fields may be added).
166#[derive(Clone, Debug, PartialEq, Eq)]
167#[non_exhaustive]
168pub struct PlayerInfo {
169    /// Profile name.
170    pub name: Box<str>,
171    /// Game mode.
172    pub game_mode: i32,
173    /// Latency in ms.
174    pub ping: i32,
175    /// Display name (raw chat JSON), if set (1.8 – 1.16; see
176    /// [`PlayerInfo::display_name_nbt`] for 26.1).
177    pub display_name: Option<Box<str>>,
178    /// The base64 `"textures"` profile property as sent (only with [`Config::skins`]; its
179    /// signature is not kept). Decoded it is JSON with the skin and cape URLs.
180    pub textures: Option<Box<str>>,
181    /// 26.1: the display name as its raw network NBT text component, if set.
182    pub display_name_nbt: Option<bytes::Bytes>,
183    /// Shown in the tab list (26.1 `UPDATE_LISTED`; always `true` before 26.1).
184    pub listed: bool,
185    /// 26.1 tab list order (`UPDATE_LIST_ORDER`; 0 before).
186    pub list_order: i32,
187    /// Which tab list object this is (26.1 player entities keep the one they first saw).
188    pub(crate) generation: u32,
189}
190
191#[derive(Default, Clone, Copy)]
192pub(crate) struct IdHasher(u64);
193
194impl Hasher for IdHasher {
195    #[inline]
196    fn finish(&self) -> u64 {
197        let h = self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15);
198        h ^ (h >> 29)
199    }
200
201    #[inline]
202    fn write(&mut self, bytes: &[u8]) {
203        for &b in bytes {
204            self.0 = (self.0 << 8) | u64::from(b);
205        }
206    }
207
208    #[inline]
209    fn write_i32(&mut self, v: i32) {
210        self.0 = u64::from(v as u32);
211    }
212
213    #[inline]
214    fn write_u64(&mut self, v: u64) {
215        self.0 = v;
216    }
217
218    #[inline]
219    fn write_u128(&mut self, v: u128) {
220        self.0 = (v as u64) ^ ((v >> 64) as u64);
221    }
222}
223
224pub(crate) type Fast<K, V> = HashMap<K, V, BuildHasherDefault<IdHasher>>;
225
226/// Gives memory back once a map holds less than a quarter of its capacity (a crowd left):
227/// shrinks to twice the live entries, so it neither keeps a peak's table forever nor rehashes
228/// back and forth around one size. Small maps are left alone.
229#[inline]
230pub(crate) fn shrink_map<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
231    let cap = m.capacity();
232    if cap > 64 && m.len() * 4 < cap {
233        m.shrink_to(m.len() * 2);
234    }
235}
236
237/// Call after an insert into `m`, with its `capacity()` before the insert (or after the last
238/// insert). hashbrown grows a table whose free slots ran out even when many of them are only
239/// deletion markers (ids that came and went), so a steady crowd with fresh ids doubles the
240/// table. A growth at least doubles `capacity()`; a real one leaves the table just over half
241/// full, one that leaves it at most half full was forced by markers and is undone at once: the
242/// table is rebuilt at its live size, which also drops the markers.
243#[inline]
244pub(crate) fn after_insert<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>, old_cap: usize) {
245    let cap = m.capacity();
246    if cap >= 2 * old_cap.max(1) && m.len() * 2 <= cap {
247        compact(m);
248    }
249}
250
251#[cold]
252#[inline(never)]
253fn compact<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
254    m.shrink_to(m.len());
255}
256
257/// A tab-list entry as [`Config::player_names`] keeps it: the profile name inline (a name longer
258/// than [`TabLite::INLINE`] bytes lives in `Entities::long_names`), the game mode and the tab
259/// list object generation (26.x).
260#[derive(Clone, Copy, Debug)]
261pub(crate) struct TabLite {
262    name: [u8; TabLite::INLINE],
263    /// Name length, or [`TabLite::LONG`].
264    len: u8,
265    pub(crate) game_mode: i32,
266    pub(crate) generation: u32,
267}
268
269impl TabLite {
270    /// Inline name bytes (vanilla profile names are at most 16 characters).
271    const INLINE: usize = 23;
272    const LONG: u8 = u8::MAX;
273}
274
275/// What the tab list says about one profile (full or names-only list).
276#[derive(Clone, Copy, Debug)]
277pub(crate) struct TabRef<'a> {
278    pub(crate) name: &'a str,
279    pub(crate) game_mode: i32,
280    pub(crate) generation: u32,
281}
282
283/// The tab lists of an [`Entities`] (borrowed field by field, so a caller can hold them while
284/// it changes entities).
285#[derive(Clone, Copy)]
286pub(crate) struct Tabs<'a> {
287    pub(crate) players: &'a Fast<Uuid, PlayerInfo>,
288    pub(crate) lite: &'a Fast<Uuid, TabLite>,
289    pub(crate) long_names: &'a Fast<Uuid, Box<str>>,
290}
291
292impl<'a> Tabs<'a> {
293    /// The entry of `uuid`.
294    #[inline]
295    pub(crate) fn get(self, uuid: &Uuid) -> Option<TabRef<'a>> {
296        if let Some(p) = self.players.get(uuid) {
297            return Some(TabRef {
298                name: &p.name,
299                game_mode: p.game_mode,
300                generation: p.generation,
301            });
302        }
303        if self.lite.is_empty() {
304            return None;
305        }
306        let t = self.lite.get(uuid)?;
307        let name = if t.len == TabLite::LONG {
308            self.long_names.get(uuid).map_or("", |n| &**n)
309        } else {
310            std::str::from_utf8(&t.name[..usize::from(t.len)]).unwrap_or("")
311        };
312        Some(TabRef {
313            name,
314            game_mode: t.game_mode,
315            generation: t.generation,
316        })
317    }
318}
319
320/// The tracked entities and tab list (queries are the same for every version).
321#[derive(Clone, Debug, Default)]
322pub struct Entities {
323    pub(crate) map: Fast<i32, Entity>,
324    pub(crate) self_id: Option<i32>,
325    pub(crate) config: Config,
326    pub(crate) events: Vec<Event>,
327    pub(crate) players: Fast<Uuid, PlayerInfo>,
328    /// The names-only tab list ([`Config::player_names`] without [`Config::player_list`]).
329    pub(crate) lite: Fast<Uuid, TabLite>,
330    /// Names-only entries whose name does not fit inline.
331    pub(crate) long_names: Fast<Uuid, Box<str>>,
332    pub(crate) scratch: Vec<(u8, MetaValue)>,
333    /// Set once any leash link exists (skips the leash scan on removal otherwise).
334    pub(crate) any_leash: bool,
335    /// The tracker's protocol family (selects the vanilla size table).
336    pub(crate) era: crate::entity::Era,
337    /// Last tab list object generation handed out.
338    pub(crate) generations: u32,
339}
340
341impl Entities {
342    pub(crate) fn new(config: Config) -> Self {
343        Entities {
344            config,
345            ..Default::default()
346        }
347    }
348
349    /// The entity with this id (including the bot's own entry, see [`Entities::self_id`]).
350    #[inline]
351    #[must_use]
352    pub fn get(&self, id: i32) -> Option<&Entity> {
353        self.map.get(&id)
354    }
355
356    /// Number of tracked entities (including the bot's own entry).
357    #[must_use]
358    pub fn len(&self) -> usize {
359        self.map.len()
360    }
361
362    /// `true` when nothing is tracked.
363    #[must_use]
364    pub fn is_empty(&self) -> bool {
365        self.map.is_empty()
366    }
367
368    /// Other entities (the bot's own entry is skipped), arbitrary order.
369    pub fn iter(&self) -> impl Iterator<Item = &Entity> {
370        let me = self.self_id;
371        self.map.values().filter(move |e| Some(e.id) != me)
372    }
373
374    /// The bot's own entity id (from `login`). Its entry carries metadata, effects, equipment
375    /// and riding state, but **no position**: the client owns its own position.
376    #[must_use]
377    pub fn self_id(&self) -> Option<i32> {
378        self.self_id
379    }
380
381    /// The bot's own entry.
382    #[must_use]
383    pub fn me(&self) -> Option<&Entity> {
384        self.map.get(&self.self_id?)
385    }
386
387    /// Entities whose server position is within `radius` of `p` (linear scan).
388    pub fn within(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
389        let r2 = radius * radius;
390        self.iter().filter(move |e| {
391            let d = [e.pos[0] - p[0], e.pos[1] - p[1], e.pos[2] - p[2]];
392            d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= r2
393        })
394    }
395
396    /// Alias of [`Entities::within`].
397    pub fn near(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
398        self.within(p, radius)
399    }
400
401    /// The tab list.
402    #[must_use]
403    pub fn player_info(&self, uuid: &Uuid) -> Option<&PlayerInfo> {
404        self.players.get(uuid)
405    }
406
407    /// All tab-list entries.
408    pub fn players(&self) -> impl Iterator<Item = (&Uuid, &PlayerInfo)> {
409        self.players.iter()
410    }
411
412    /// Name of a player entity (from the tab list: the full one, or the names-only one of
413    /// [`Config::player_names`]).
414    #[must_use]
415    pub fn player_name(&self, id: i32) -> Option<&str> {
416        let e = self.map.get(&id)?;
417        e.is_player()
418            .then(|| self.tab(&e.uuid).map(|t| t.name))
419            .flatten()
420    }
421
422    /// Profile name of a tab-list entry (full list or names only).
423    #[must_use]
424    pub fn tab_name(&self, uuid: &Uuid) -> Option<&str> {
425        self.tab(uuid).map(|t| t.name)
426    }
427
428    /// Game mode of a tab-list entry (full list or names only).
429    #[must_use]
430    pub fn tab_game_mode(&self, uuid: &Uuid) -> Option<i32> {
431        self.tab(uuid).map(|t| t.game_mode)
432    }
433
434    /// Number of tab-list entries kept (full list or names only).
435    #[must_use]
436    pub fn tab_len(&self) -> usize {
437        self.players.len() + self.lite.len()
438    }
439
440    /// The names-only list is in use.
441    #[inline]
442    pub(crate) fn lite_mode(&self) -> bool {
443        !self.config.player_list && self.config.player_names
444    }
445
446    /// The tab-list entry of `uuid` (full or names only).
447    #[inline]
448    pub(crate) fn tab(&self, uuid: &Uuid) -> Option<TabRef<'_>> {
449        self.tabs().get(uuid)
450    }
451
452    /// The tab lists, borrowed apart from the entity map.
453    #[inline]
454    pub(crate) fn tabs(&self) -> Tabs<'_> {
455        Tabs {
456            players: &self.players,
457            lite: &self.lite,
458            long_names: &self.long_names,
459        }
460    }
461
462    /// `true` when the tab list (full or names only) has `uuid`.
463    #[inline]
464    pub(crate) fn tab_has(&self, uuid: &Uuid) -> bool {
465        self.players.contains_key(uuid) || self.lite.contains_key(uuid)
466    }
467
468    /// Adds a names-only entry unless `uuid` has one (vanilla's `putIfAbsent`; 1.8 – 1.16
469    /// replace, `replace` = true). Returns `true` when an entry was added.
470    pub(crate) fn lite_add(
471        &mut self,
472        uuid: Uuid,
473        name: &str,
474        game_mode: i32,
475        generation: u32,
476        replace: bool,
477    ) -> bool {
478        if !replace && self.lite.contains_key(&uuid) {
479            return false;
480        }
481        let mut t = TabLite {
482            name: [0; TabLite::INLINE],
483            len: TabLite::LONG,
484            game_mode,
485            generation,
486        };
487        if name.len() <= TabLite::INLINE {
488            t.name[..name.len()].copy_from_slice(name.as_bytes());
489            t.len = name.len() as u8;
490            if self.long_names.remove(&uuid).is_some() {
491                shrink_map(&mut self.long_names);
492            }
493        } else {
494            self.long_names.insert(uuid, Box::from(name));
495        }
496        let cap = self.lite.capacity();
497        self.lite.insert(uuid, t);
498        after_insert(&mut self.lite, cap);
499        true
500    }
501
502    /// Removes `uuid` from the tab list (full or names only): its game mode and generation.
503    pub(crate) fn tab_remove(&mut self, uuid: &Uuid) -> Option<(i32, u32)> {
504        if let Some(p) = self.players.remove(uuid) {
505            shrink_map(&mut self.players);
506            return Some((p.game_mode, p.generation));
507        }
508        let t = self.lite.remove(uuid)?;
509        if t.len == TabLite::LONG && self.long_names.remove(uuid).is_some() {
510            shrink_map(&mut self.long_names);
511        }
512        shrink_map(&mut self.lite);
513        Some((t.game_mode, t.generation))
514    }
515
516    /// Sets the game mode of a names-only entry.
517    #[inline]
518    pub(crate) fn lite_game_mode(&mut self, uuid: &Uuid, game_mode: i32) {
519        if let Some(t) = self.lite.get_mut(uuid) {
520            t.game_mode = game_mode;
521        }
522    }
523
524    /// The configuration.
525    #[must_use]
526    pub fn config(&self) -> Config {
527        self.config
528    }
529
530    /// Takes the queued events (keeps the buffer's capacity).
531    pub fn drain_events(&mut self) -> std::vec::Drain<'_, Event> {
532        self.events.drain(..)
533    }
534
535    /// Removes every entity (keeps the tab list and the bot's id).
536    pub fn clear(&mut self) {
537        if self.config.events {
538            let me = self.self_id;
539            self.events.extend(
540                self.map
541                    .values()
542                    .filter(|e| Some(e.id) != me)
543                    .map(|e| Event::Removed { id: e.id, ty: e.ty }),
544            );
545        }
546        let me = self.self_id.and_then(|id| self.map.remove(&id));
547        self.map.clear();
548        shrink_map(&mut self.map);
549        if let Some(mut me) = me {
550            me.set_vehicle(None);
551            if let Some(l) = &mut me.links {
552                l.passengers.clear();
553                l.leash_holder = None;
554            }
555            me.tidy_links();
556            self.map.insert(me.id, me);
557        }
558    }
559
560    #[inline]
561    pub(crate) fn event(&mut self, e: Event) {
562        if self.config.events {
563            self.events.push(e);
564        }
565    }
566
567    pub(crate) fn set_self(&mut self, id: i32) {
568        if let Some(old) = self.self_id {
569            self.map.remove(&old);
570        }
571        self.self_id = Some(id);
572        let mut me = Entity::new(id, EntityType::Player);
573        self.resolve(&mut me);
574        self.map.insert(id, me);
575    }
576
577    /// Stamps the protocol family and resolves the vanilla size entry.
578    fn resolve(&self, e: &mut Entity) {
579        use crate::entity::Era;
580        e.era = self.era;
581        e.sizer = match self.era {
582            #[cfg(feature = "v1_8")]
583            Era::V1_8 => crate::v1_8::vanilla_size(e),
584            #[cfg(feature = "v1_12")]
585            Era::V1_12 => crate::v1_12::vanilla_size(e),
586            #[cfg(feature = "v1_16_5")]
587            Era::V1_16 => crate::v1_16_5::vanilla_size(e),
588            #[cfg(feature = "v26_1")]
589            Era::V26 => crate::v26_1::vanilla_size(e),
590            #[cfg(feature = "v26_2")]
591            Era::V26_2 => crate::v26_2::vanilla_size(e),
592            #[allow(unreachable_patterns)]
593            _ => None,
594        };
595    }
596
597    /// Adds an entity, replacing (and unlinking) any entity with the same id, as vanilla does.
598    pub(crate) fn spawn(&mut self, mut e: Entity) {
599        let id = e.id;
600        self.resolve(&mut e);
601        if Some(id) == self.self_id {
602            return;
603        }
604        if self.map.contains_key(&id) {
605            self.unlink(id);
606        }
607        let cap = self.map.capacity();
608        self.map.insert(id, e);
609        after_insert(&mut self.map, cap);
610        self.event(Event::Spawned(id));
611    }
612
613    pub(crate) fn remove(&mut self, id: i32) -> bool {
614        if Some(id) == self.self_id || !self.map.contains_key(&id) {
615            return false;
616        }
617        self.unlink(id);
618        if let Some(e) = self.map.remove(&id) {
619            self.event(Event::Removed { id, ty: e.ty });
620        }
621        shrink_map(&mut self.map);
622        true
623    }
624
625    /// Detaches `id` from its vehicle, passengers and leash links.
626    fn unlink(&mut self, id: i32) {
627        let Some(e) = self.map.get_mut(&id) else {
628            return;
629        };
630        if e.links.is_none() && !e.rides && !self.any_leash {
631            return;
632        }
633        let vehicle = e.take_vehicle();
634        let passengers = e.take_passengers();
635        if let Some(v) = vehicle
636            && let Some(v) = self.map.get_mut(&v)
637        {
638            v.remove_passenger(id);
639        }
640        for p in passengers {
641            if let Some(p) = self.map.get_mut(&p)
642                && p.vehicle() == Some(id)
643            {
644                p.set_vehicle(None);
645            }
646        }
647        if self.any_leash {
648            for other in self.map.values_mut() {
649                if other.leash_holder() == Some(id) {
650                    other.set_leash_holder(None);
651                }
652            }
653        }
654    }
655
656    /// `true` when `vehicle` is `rider` or (indirectly) rides `rider`.
657    fn rides(&self, vehicle: i32, rider: i32) -> bool {
658        let mut cur = Some(vehicle);
659        let mut guard = 0;
660        while let Some(c) = cur {
661            if c == rider {
662                return true;
663            }
664            guard += 1;
665            if guard > 64 {
666                return true;
667            }
668            cur = self.map.get(&c).and_then(Entity::vehicle);
669        }
670        false
671    }
672
673    /// Makes `rider` ride `vehicle` (or dismount with `None`). `single` = 1.8 semantics (one
674    /// rider per vehicle: a previous rider is dismounted). Returns `false` when ignored.
675    pub(crate) fn mount(&mut self, rider: i32, vehicle: Option<i32>, single: bool) -> bool {
676        if !self.map.contains_key(&rider) {
677            return false;
678        }
679        if let Some(v) = vehicle
680            && (!self.map.contains_key(&v) || self.rides(v, rider))
681        {
682            return false;
683        }
684        // Leave the old vehicle.
685        let old = self.map.get_mut(&rider).and_then(Entity::take_vehicle);
686        if let Some(o) = old
687            && let Some(o) = self.map.get_mut(&o)
688        {
689            o.remove_passenger(rider);
690        }
691        if let Some(v) = vehicle {
692            let prev: Vec<i32> = if single {
693                self.map
694                    .get_mut(&v)
695                    .map(Entity::take_passengers)
696                    .unwrap_or_default()
697            } else {
698                Vec::new()
699            };
700            for p in prev {
701                if let Some(p) = self.map.get_mut(&p) {
702                    p.set_vehicle(None);
703                }
704            }
705            if let Some(ve) = self.map.get_mut(&v) {
706                ve.push_passenger(rider);
707            }
708            if let Some(r) = self.map.get_mut(&rider) {
709                r.set_vehicle(Some(v));
710            }
711        }
712        self.event(Event::Mounted { id: rider, vehicle });
713        true
714    }
715
716    /// 1.16 `set_passengers`: ejects every current passenger of `vehicle`, then mounts `ids`.
717    pub(crate) fn set_passengers(&mut self, vehicle: i32, ids: impl Iterator<Item = i32>) -> bool {
718        let Some(v) = self.map.get_mut(&vehicle) else {
719            return false;
720        };
721        let old = v.take_passengers();
722        for p in &old {
723            if let Some(p) = self.map.get_mut(p)
724                && p.vehicle() == Some(vehicle)
725            {
726                p.set_vehicle(None);
727            }
728        }
729        // Reuse the old buffer for the new list (no allocation in steady state).
730        let mut old = old;
731        old.clear();
732        if let Some(v) = self.map.get_mut(&vehicle) {
733            v.set_passengers(old);
734        }
735        for id in ids {
736            self.mount(id, Some(vehicle), false);
737        }
738        true
739    }
740
741    pub(crate) fn leash(&mut self, id: i32, holder: Option<i32>) -> bool {
742        match self.map.get_mut(&id) {
743            Some(e) => {
744                e.set_leash_holder(holder);
745                self.any_leash |= holder.is_some();
746                true
747            }
748            None => false,
749        }
750    }
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756
757    fn store() -> Entities {
758        let mut s = Entities::new(Config {
759            events: true,
760            ..Config::default()
761        });
762        for id in 1..=4 {
763            s.spawn(Entity::new(id, EntityType::Registry(6)));
764        }
765        s
766    }
767
768    /// Bytes per tracked entity (the map slot adds the 4-byte key, padded).
769    #[test]
770    fn entity_size() {
771        let n = std::mem::size_of::<Entity>();
772        eprintln!("size_of::<Entity>() = {n}");
773        // 0.3.0 – 0.4.3: 232 bytes. Riding, leash and effects sit behind one pointer, the
774        // metadata is an exact-size block (pointer + length); the 26.x state is boxed.
775        let modern = cfg!(any(feature = "v26_1", feature = "v26_2"));
776        assert!(n <= if modern { 168 } else { 160 }, "{n}");
777        #[cfg(any(feature = "v26_1", feature = "v26_2"))]
778        {
779            let b = std::mem::size_of::<crate::modern_state::State>();
780            eprintln!("size_of::<modern_state::State>() = {b} (heap, 26.x entities only)");
781            assert!(b <= 120, "{b}");
782        }
783    }
784
785    #[test]
786    fn mount_single_and_multi() {
787        let mut s = store();
788        assert!(s.mount(1, Some(2), true));
789        assert!(s.mount(3, Some(2), true)); // 1.8: replaces rider 1
790        assert_eq!(s.get(2).unwrap().passengers(), &[3]);
791        assert_eq!(s.get(1).unwrap().vehicle(), None);
792        assert!(!s.mount(2, Some(3), true), "cycle");
793        assert!(s.set_passengers(4, [1, 3].into_iter()));
794        assert_eq!(s.get(4).unwrap().passengers(), &[1, 3]);
795        assert_eq!(s.get(2).unwrap().passengers(), &[] as &[i32]);
796        assert_eq!(s.get(3).unwrap().vehicle(), Some(4));
797        s.remove(4);
798        assert_eq!(s.get(1).unwrap().vehicle(), None);
799        assert_eq!(s.get(3).unwrap().vehicle(), None);
800    }
801
802    #[test]
803    fn self_entry_survives_clear() {
804        let mut s = store();
805        s.set_self(9);
806        s.spawn(Entity::new(9, EntityType::Registry(1))); // ignored: own id
807        assert_eq!(s.get(9).unwrap().entity_type(), EntityType::Player);
808        assert!(!s.remove(9));
809        s.drain_events().for_each(drop);
810        s.clear();
811        assert_eq!(s.len(), 1);
812        assert!(s.me().is_some());
813        assert_eq!(s.drain_events().count(), 4);
814        assert_eq!(s.iter().count(), 0);
815    }
816}