Skip to main content

ghast_entity/
v26_1.rs

1//! Modern entity tracking: 26.1 (protocol 775) as `v26_1`, 26.2 (protocol 776) as `v26_2`.
2//!
3//! Both modules are the same source compiled over their version's protocol and data modules:
4//! entity type ids, sizes and the slot codec are that version's; the behaviour below is the
5//! same in both clients (26.2 replays its own golden dump, `tests/golden/26.2/`).
6//!
7//! The modern client no longer keeps a separate "server position": an entity *is* at
8//! `Entity.position()`, and what a position packet does depends on the type
9//! (`ghast_data::modern::EntityTypeData::interpolation`, from the jar):
10//!
11//! - **Interpolated** types (living entities, boats, minecarts, experience orbs, fishing bobbers)
12//!   get a target; [`Tracker::tick`] moves them a third of the remaining way per tick
13//!   (`InterpolationHandler`: `Mth.lerp` / `Mth.rotLerp` in doubles, the target follows position
14//!   changes made between steps unless the moved box would collide, see [`Tracker::tick_with`]).
15//!   Head rotations of living entities are lerped over 3 ticks the same way.
16//! - **Other** types (items, projectiles, end crystals, ...) move at once.
17//!
18//! Packet coordinates: spawns and `entity_position_sync` set the `VecDeltaCodec` base (doubles);
19//! a relative move decodes `round(base * 4096) + delta` per non-zero axis, divided by 4096
20//! (`Math.round`, half up; an axis with delta 0 keeps the base exactly). `teleport_entity` does
21//! not touch the base; its relative axes are relative to the interpolation target. Syncs farther
22//! than 64 blocks, and syncs of entities in chunks the client has not loaded, snap. Spawn
23//! rotations follow `recreateFromPacket` (living: `absSnapTo` with x / z clamped to ±3e7).
24//!
25//! **Position at pick time.** Vanilla's `Minecraft.tick` runs the crosshair pick *before*
26//! `ClientLevel.tickEntities`, after the tick's packets: apply this tick's packets, pick with
27//! [`Entity::position`] / [`Entity::bounding_box`], then call [`Tracker::tick`]. Proven against
28//! the real client by `tests/golden/26.1/entity_tracking.jsonl.gz` (oracle `EntityTrackDump`).
29//!
30//! Not modelled: the client-side physics of non-interpolated entities between packets (items,
31//! projectiles, experience orbs move on their own in vanilla), passenger positions (vanilla places
32//! riders on their vehicle every tick), vehicles the bot controls other than boats (they ignore
33//! position packets in vanilla), and the client-side decay of velocities: [`Entity::velocity`] is
34//! the last velocity the server sent (a relative teleport adds to it without `ROTATE_DELTA`).
35//!
36//! Every packet is parsed by hand from the body; movement packets touch no allocator, and with
37//! [`Config::metadata`] off metadata is walked without allocating (the size keys, sleeping
38//! position and item counts are always applied).
39
40use std::ops::Deref;
41
42use super::data::entities::{self as data, EntityTypeData, type_flags};
43use super::proto::play::clientbound::{Login, Respawn, id};
44use super::read_stack;
45use crate::modern_state::st;
46use bytes::Bytes;
47use ghast_protocol::nbt::AnonNbt;
48use ghast_protocol::types::LpVec3;
49use ghast_protocol::types::slot::v775::ItemStack;
50use ghast_protocol::{Decode, DecodeError, RawPacket, Reader};
51
52use crate::Applied;
53use crate::common::{IdMask, R, angle, for_each_varint, own_str, skip_string};
54use crate::common::{remove_effect, set_effect};
55use crate::entity::{Effect, Entity, EntityClass, EntityType, Item, MetaValue};
56use crate::store::{Config, Entities, Event, Fast, PlayerInfo};
57
58/// Spawn, movement, destroy, riding, pickup, status, metadata, attribute packets, chunk loads
59/// (only their coordinates are read: an entity in an unloaded chunk does not tick), plus `login`
60/// / `respawn`.
61pub const CORE_IDS: &[i32] = &[
62    id::LOGIN,
63    id::RESPAWN,
64    id::SPAWN_ENTITY,
65    id::ENTITY_VELOCITY,
66    id::ENTITY_DESTROY,
67    id::REL_ENTITY_MOVE,
68    id::ENTITY_LOOK,
69    id::ENTITY_MOVE_LOOK,
70    id::SYNC_ENTITY_POSITION,
71    id::ENTITY_TELEPORT,
72    id::ENTITY_HEAD_ROTATION,
73    id::ENTITY_STATUS,
74    id::ATTACH_ENTITY,
75    id::SET_PASSENGERS,
76    id::COLLECT,
77    id::ENTITY_METADATA,
78    id::ENTITY_UPDATE_ATTRIBUTES,
79    id::MAP_CHUNK,
80    id::UNLOAD_CHUNK,
81];
82/// `entity_metadata` (always in [`CORE_IDS`]: poses, baby flags, sizes, sleeping positions and
83/// item counts change boxes and positions).
84pub const METADATA_IDS: &[i32] = &[id::ENTITY_METADATA];
85/// `entity_equipment`.
86pub const EQUIPMENT_IDS: &[i32] = &[id::ENTITY_EQUIPMENT];
87/// `entity_effect`, `remove_entity_effect`.
88pub const EFFECT_IDS: &[i32] = &[id::ENTITY_EFFECT, id::REMOVE_ENTITY_EFFECT];
89/// `player_info` (update), `player_remove`. Player spawns need the tab list: vanilla skips a
90/// player spawn whose profile is not in it (with [`Config::player_list`] off every spawn is kept).
91pub const PLAYER_LIST_IDS: &[i32] = &[id::PLAYER_INFO, id::PLAYER_REMOVE];
92
93/// Index of the fox flags byte (`Fox.DATA_FLAGS_ID`; 0x20 = sleeping).
94const FOX_FLAGS: u8 = 19;
95
96/// Registry id of `minecraft:scale` in this version (checked against the jar by the oracle test).
97pub const SCALE_ATTRIBUTE: i32 = super::SCALE_ATTRIBUTE_ID;
98
99/// Metadata indices shared by every entity / living entity (the same in 26.1 and 26.2).
100pub mod meta {
101    /// Entity flags byte (0x01 on fire, 0x02 crouching, 0x08 sprinting, 0x10 swimming,
102    /// 0x20 invisible, 0x40 glowing, 0x80 fall flying).
103    pub const FLAGS: u8 = 0;
104    /// Air (VarInt).
105    pub const AIR: u8 = 1;
106    /// Custom name (optional component).
107    pub const CUSTOM_NAME: u8 = 2;
108    /// No gravity.
109    pub const NO_GRAVITY: u8 = 5;
110    /// Pose.
111    pub const POSE: u8 = 6;
112    /// Living: hand states.
113    pub const LIVING_FLAGS: u8 = 8;
114    /// Living: health (float).
115    pub const HEALTH: u8 = 9;
116    /// Living: sleeping position (optional block position; setting it moves the entity onto
117    /// the bed: `x + 0.5, y + 0.6875, z + 0.5`).
118    pub const SLEEPING_POS: u8 = 14;
119    /// Item entity: the stack.
120    pub const ITEM: u8 = 8;
121}
122
123/// The bot's entity view on a modern (26.1 / 26.2) connection. Dereferences to the shared [`Entities`].
124#[derive(Clone, Debug)]
125pub struct Tracker {
126    store: Entities,
127    dimension: String,
128    wanted: IdMask,
129    /// Loaded chunk columns (`x & 0xffffffff | z << 32`).
130    chunks: Fast<u64, ()>,
131    /// Ids held in vanilla's tick list by a spawn the entity lookup refused (duplicate UUID): the
132    /// tick list is keyed by id, so `isTickingEntity` says yes for any entity with that id until
133    /// a real one with it starts ticking.
134    ghosts: Fast<i32, ()>,
135    /// The client's tick list (`EntityTickList`, a linked map by id): each member's insertion
136    /// number. Re-adding an id that is still a member keeps its place.
137    order: Fast<i32, u32>,
138    next_seq: u32,
139    /// `order`'s capacity after its last insert (see `store::after_insert`).
140    order_cap: usize,
141    /// Entities [`Tracker::tick_early`] already ticked this client tick (the next
142    /// [`Tracker::tick_with`] skips them once).
143    early: Vec<i32>,
144    /// Tick list membership may have changed in a way only a full re-check finds (passengers
145    /// changed vehicles): re-checked at the start of the next tick.
146    order_dirty: bool,
147}
148
149impl Deref for Tracker {
150    type Target = Entities;
151    fn deref(&self) -> &Entities {
152        &self.store
153    }
154}
155
156#[inline]
157fn chunk_key(x: i32, z: i32) -> u64 {
158    u64::from(x as u32) | (u64::from(z as u32) << 32)
159}
160
161/// `Mth.floor(double)`: `(int) v`, minus one when that is above `v` (no libm `floor` call).
162#[inline]
163fn mth_floor(v: f64) -> i32 {
164    let i = v as i32;
165    if v < f64::from(i) { i - 1 } else { i }
166}
167
168/// `Mth.floor` of a coordinate, then the chunk.
169#[inline]
170fn chunk_of(p: [f64; 3]) -> u64 {
171    chunk_key(mth_floor(p[0]) >> 4, mth_floor(p[2]) >> 4)
172}
173
174/// Java `Math.round(double)` (half up, saturating, NaN = 0), without a libm `floor` call.
175#[inline]
176fn jround(x: f64) -> i64 {
177    if x.is_nan() || x.abs() >= 4.5e15 {
178        // Integral already (or NaN / out of range): the saturating cast is Java's result.
179        return x as i64;
180    }
181    let t = x as i64;
182    let f = if x < t as f64 { t - 1 } else { t };
183    if x - f as f64 >= 0.5 { f + 1 } else { f }
184}
185
186/// The `VecDeltaCodec` base (the last absolute packet position), kept inline in the entity's
187/// version-specific `traced` slot (as `f64` bits) so a move needs no second cache line for it.
188#[inline]
189fn base(e: &Entity) -> [f64; 3] {
190    e.traced.map(|b| f64::from_bits(b as u64))
191}
192
193#[inline]
194fn set_base(e: &mut Entity, p: [f64; 3]) {
195    e.traced = p.map(|c| c.to_bits() as i64);
196}
197
198/// `VecDeltaCodec.decode`.
199#[inline]
200fn decode_delta(base: [f64; 3], d: [i16; 3]) -> [f64; 3] {
201    if d == [0; 3] {
202        return base;
203    }
204    let ax = |b: f64, d: i16| {
205        if d == 0 {
206            b
207        } else {
208            jround(b * 4096.0).wrapping_add(i64::from(d)) as f64 / 4096.0
209        }
210    };
211    [ax(base[0], d[0]), ax(base[1], d[1]), ax(base[2], d[2])]
212}
213
214/// `Float.equals` / `Double.compare == 0` (bits, NaN equal to NaN).
215#[inline]
216fn same_f32(a: f32, b: f32) -> bool {
217    a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())
218}
219
220#[inline]
221fn same_f64(a: f64, b: f64) -> bool {
222    a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())
223}
224
225/// `Mth.wrapDegrees(double)`.
226#[inline]
227fn wrap_degrees(a: f64) -> f64 {
228    let mut r = a % 360.0;
229    if r >= 180.0 {
230        r -= 360.0;
231    }
232    if r < -180.0 {
233        r += 360.0;
234    }
235    r
236}
237
238/// `Entity.setYRot` (non-finite values are discarded).
239#[inline]
240fn set_yrot(e: &mut Entity, y: f32) {
241    if y.is_finite() {
242        e.yaw = y;
243    }
244}
245
246/// `Entity.setXRot`: `clamp(x % 360, -90, 90)`.
247#[inline]
248fn set_xrot(e: &mut Entity, x: f32) {
249    if x.is_finite() {
250        e.pitch = (x % 360.0).clamp(-90.0, 90.0);
251    }
252}
253
254#[inline]
255fn living(e: &Entity) -> bool {
256    e.m.td.is_some_and(EntityTypeData::is_living)
257}
258
259/// `snapTo(pos, yRot, xRot)`.
260fn snap_to(e: &mut Entity, p: [f64; 3], y: f32, x: f32) {
261    e.pos = p;
262    set_yrot(e, y);
263    set_xrot(e, x);
264}
265
266/// `Entity.moveOrInterpolateTo(position?, yRot?, xRot?)`.
267#[inline]
268fn move_or_interpolate(e: &mut Entity, p: Option<[f64; 3]>, y: Option<f32>, x: Option<f32>) {
269    // One borrow of the boxed state for the whole update.
270    let m = &mut *e.m;
271    match m.td.and_then(|t| t.interpolation) {
272        Some(n) => {
273            let active = m.steps > 0;
274            let p = p.unwrap_or(if active { m.target } else { e.pos });
275            let y = y.unwrap_or(if active { m.target_rot[0] } else { e.yaw });
276            let x = x.unwrap_or(if active { m.target_rot[1] } else { e.pitch });
277            if n == 0 {
278                m.steps = 0;
279                m.set_flag(st::HAS_PREV, false);
280                snap_to(e, p, y, x);
281            } else if !active
282                || !same_f32(m.target_rot[0], y)
283                || !same_f32(m.target_rot[1], x)
284                || !(0..3).all(|i| same_f64(m.target[i], p[i]))
285            {
286                m.steps = n;
287                m.target = p;
288                m.target_rot = [y, x];
289                m.prev = e.pos;
290                m.prev_rot = [e.pitch, e.yaw];
291                m.set_flag(st::HAS_PREV, true);
292            }
293        }
294        None => {
295            if let Some(p) = p {
296                e.pos = p;
297            }
298            if let Some(y) = y {
299                set_yrot(e, y % 360.0);
300            }
301            if let Some(x) = x {
302                set_xrot(e, x % 360.0);
303            }
304        }
305    }
306}
307
308/// `true` when the bot (`me`) steers `e` (a boat whose first passenger is the bot).
309#[inline]
310fn controlled(me: Option<i32>, e: &Entity) -> bool {
311    // Entities without links (nearly all) leave at the first test.
312    let Some(l) = &e.links else {
313        return false;
314    };
315    me.is_some()
316        && l.passengers.first().copied() == me
317        && e.m
318            .td
319            .is_some_and(|t| t.name.ends_with("_boat") || t.name.ends_with("_raft"))
320}
321
322impl Tracker {
323    /// An empty tracker.
324    #[must_use]
325    pub fn new(config: Config) -> Self {
326        let mut wanted = IdMask::default();
327        wanted.add(CORE_IDS);
328        if config.equipment {
329            wanted.add(EQUIPMENT_IDS);
330        }
331        if config.effects {
332            wanted.add(EFFECT_IDS);
333        }
334        if config.reads_tab_list() {
335            wanted.add(PLAYER_LIST_IDS);
336        }
337        Tracker {
338            store: Entities {
339                era: super::ERA,
340                ..Entities::new(config)
341            },
342            dimension: String::new(),
343            wanted,
344            chunks: Fast::default(),
345            ghosts: Fast::default(),
346            order: Fast::default(),
347            next_seq: 0,
348            order_cap: 0,
349            early: Vec::new(),
350            order_dirty: false,
351        }
352    }
353
354    /// `EntityTickList.add`: an id that is already a member keeps its place.
355    fn start_ticking(&mut self, id: i32) {
356        let next = &mut self.next_seq;
357        let mut added = false;
358        self.order.entry(id).or_insert_with(|| {
359            *next += 1;
360            added = true;
361            *next
362        });
363        if added {
364            self.added_to_order();
365        }
366    }
367
368    /// After a new tick list entry: undoes a growth forced by deletion markers, renumbers when
369    /// the numbers ran out.
370    #[cold]
371    #[inline(never)]
372    fn added_to_order(&mut self) {
373        crate::store::after_insert(&mut self.order, self.order_cap);
374        self.order_cap = self.order.capacity();
375        if self.next_seq == u32::MAX {
376            self.renumber();
377        }
378    }
379
380    /// Renumbers the tick list from 1, keeping its order (the numbers are stored as `u32`; this
381    /// runs once per four billion entries).
382    #[cold]
383    fn renumber(&mut self) {
384        let mut v: Vec<(u32, i32)> = self.order.iter().map(|(&id, &q)| (q, id)).collect();
385        v.sort_unstable();
386        for (n, (_, id)) in v.iter().enumerate() {
387            self.order.insert(*id, n as u32 + 1);
388        }
389        self.next_seq = v.len() as u32;
390    }
391
392    /// The entity's place in the client's tick list (`ClientLevel.tickingEntities`, the order
393    /// `tickEntities` runs them in and, within a chunk section, the order `getEntities` lists
394    /// them in): a number that grows with each entity that starts ticking; `None` while it does
395    /// not tick. Entities start ticking when they spawn into a loaded chunk column, when their
396    /// column loads, or when they move into a loaded column; they stop when removed or when their
397    /// column unloads, and re-enter at the end. The local player (its id from the login packet)
398    /// enters first at login and at a dimension change, and last at a respawn in the same
399    /// dimension. Several entities entering at the same moment for a column load or a move are
400    /// ordered by id (vanilla's order there follows its section storage). After 2³² − 1 entries
401    /// the numbers restart from 1 with the order kept.
402    #[must_use]
403    pub fn tick_seq(&self, id: i32) -> Option<u64> {
404        self.order
405            .get(&id)
406            .map(|&q| u64::from(q))
407            .filter(|_| self.member(id))
408    }
409
410    /// Still in the level (removed entities leave the tick list; [`Tracker::tick`] purges them).
411    fn member(&self, id: i32) -> bool {
412        Some(id) == self.store.self_id
413            || self.store.map.contains_key(&id)
414            || self.ghosts.contains_key(&id)
415    }
416
417    /// The ids of the ticking entities (the local player included) in the client's tick order
418    /// (see [`Tracker::tick_seq`]).
419    #[must_use]
420    pub fn tick_order(&self) -> Vec<i32> {
421        let mut v: Vec<(u32, i32)> = self
422            .order
423            .iter()
424            .filter(|&(&id, _)| self.member(id))
425            .map(|(&id, &q)| (q, id))
426            .collect();
427        v.sort_unstable();
428        v.into_iter().map(|(_, id)| id).collect()
429    }
430
431    /// The chunk that decides an entity's tick list membership: a passenger sits where its root
432    /// vehicle puts it (`positionRider`; the tracker keeps a passenger's own last packet position).
433    fn member_chunk(&self, e: &Entity) -> u64 {
434        let mut root = e;
435        for _ in 0..16 {
436            match root.vehicle().and_then(|v| self.store.map.get(&v)) {
437                Some(v) => root = v,
438                None => break,
439            }
440        }
441        chunk_of(root.pos)
442    }
443
444    /// [`Tracker::member_chunk`] for the per-packet path: the common no-vehicle case inline,
445    /// the vehicle walk out of line.
446    #[inline]
447    fn member_chunk_one(&self, e: &Entity) -> u64 {
448        if e.vehicle().is_none() {
449            return chunk_of(e.pos);
450        }
451        self.member_chunk_cold(e)
452    }
453
454    #[inline(never)]
455    fn member_chunk_cold(&self, e: &Entity) -> u64 {
456        self.member_chunk(e)
457    }
458
459    /// Re-checks tick list membership after positions changed (a move into or out of a loaded
460    /// column), entering newcomers in id order.
461    fn refresh_order(&mut self) {
462        let me = self.store.self_id;
463        let (map, ghosts) = (&self.store.map, &self.ghosts);
464        self.order
465            .retain(|id, _| Some(*id) == me || map.contains_key(id) || ghosts.contains_key(id));
466        crate::store::shrink_map(&mut self.order);
467        self.order_cap = self.order.capacity();
468        let mut enter: Vec<i32> = Vec::new();
469        let mut leave: Vec<i32> = Vec::new();
470        for e in self.store.map.values() {
471            let ticks = Some(e.id) == me
472                || e.is_player()
473                || self.chunks.contains_key(&self.member_chunk(e))
474                || self.ghosts.contains_key(&e.id);
475            match (ticks, self.order.contains_key(&e.id)) {
476                (true, false) => enter.push(e.id),
477                (false, true) => leave.push(e.id),
478                _ => {}
479            }
480        }
481        for id in leave {
482            self.order.remove(&id);
483        }
484        enter.sort_unstable();
485        for id in enter {
486            self.start_ticking(id);
487        }
488    }
489
490    /// The shared store, mutable for [`Entities::drain_events`].
491    pub fn store_mut(&mut self) -> &mut Entities {
492        &mut self.store
493    }
494
495    /// `true` when this tracker wants packet `id` (for a `PacketFilter`).
496    #[inline]
497    #[must_use]
498    pub fn wants(&self, id: i32) -> bool {
499        self.wanted.contains(id)
500    }
501
502    /// Every packet id this tracker wants.
503    pub fn packet_ids(&self) -> impl Iterator<Item = i32> + '_ {
504        self.wanted.iter()
505    }
506
507    /// `true` when the chunk column holding `p` is loaded (its entities tick).
508    #[must_use]
509    pub fn chunk_loaded(&self, p: [f64; 3]) -> bool {
510        self.chunks.contains_key(&chunk_of(p))
511    }
512
513    /// A chunk column became loaded (what a `map_chunk` packet does here; for a tracker started
514    /// while chunks are already loaded): its entities tick again.
515    pub fn mark_column_loaded(&mut self, x: i32, z: i32) {
516        self.order_dirty = true;
517        let k = chunk_key(x, z);
518        let cap = self.chunks.capacity();
519        let new = self.chunks.insert(k, ()).is_none();
520        crate::store::after_insert(&mut self.chunks, cap);
521        if new {
522            let mut ids: Vec<i32> = self
523                .store
524                .map
525                .values()
526                .filter(|e| self.member_chunk(e) == k)
527                .map(|e| e.id)
528                .collect();
529            ids.sort_unstable();
530            for id in ids {
531                self.start_ticking(id);
532            }
533        }
534        if !self.ghosts.is_empty() {
535            // startTicking: the column's entities take their ids' tick list slots.
536            for e in self.store.map.values() {
537                if chunk_of(e.pos) == k {
538                    self.ghosts.remove(&e.id);
539                }
540            }
541        }
542    }
543
544    /// A chunk column was unloaded (`unload_chunk`): its entities stop ticking.
545    pub fn mark_column_unloaded(&mut self, x: i32, z: i32) {
546        self.order_dirty = true;
547        let k = chunk_key(x, z);
548        self.chunks.remove(&k);
549        self.column_unloaded(k);
550    }
551
552    fn column_unloaded(&mut self, k: u64) {
553        let me = self.store.self_id;
554        let leave: Vec<i32> = self
555            .store
556            .map
557            .values()
558            .filter(|e| Some(e.id) != me && !e.is_player() && self.member_chunk(e) == k)
559            .map(|e| e.id)
560            .collect();
561        for id in leave {
562            self.order.remove(&id);
563        }
564        crate::store::shrink_map(&mut self.order);
565        self.order_cap = self.order.capacity();
566        crate::store::shrink_map(&mut self.chunks);
567    }
568
569    /// `ClientLevel.isTickingEntity`: players always tick, other entities while their chunk
570    /// column is loaded.
571    #[must_use]
572    pub fn is_ticking(&self, e: &Entity) -> bool {
573        e.is_player()
574            || self.chunks.contains_key(&chunk_of(e.pos))
575            || self.ghosts.contains_key(&e.id)
576    }
577
578    /// Whether vanilla's crosshair pick can hit `e`: its type is pickable (`isPickable`), it is
579    /// not an armor stand marker, and not a spectator (players: tab list game mode 3).
580    #[must_use]
581    pub fn pickable(&self, e: &Entity) -> bool {
582        let Some(t) = e.m.td else { return false };
583        if !t.is_pickable() {
584            return false;
585        }
586        if t.flags_meta.is_some() && e.m.stand_flags & 0x10 != 0 {
587            return false;
588        }
589        !(e.is_player() && self.player_spectator(e))
590    }
591
592    /// [`Tracker::is_spectator`] of a player entity, out of line: callers that test every
593    /// entity pay only the player check.
594    #[inline(never)]
595    fn player_spectator(&self, e: &Entity) -> bool {
596        game_mode(self.store.tabs(), e) == Some(3)
597    }
598
599    /// The game mode vanilla's client knows for player entity `e`
600    /// (`AbstractClientPlayer.getPlayerInfo`): its tab-list entry (full list or
601    /// [`Config::player_names`]); an entity that already looked its entry up keeps that entry's
602    /// last game mode after the entry left the tab list. `None` for other entities, or without a
603    /// tab list.
604    #[must_use]
605    pub fn game_mode(&self, e: &Entity) -> Option<i32> {
606        if !e.is_player() {
607            return None;
608        }
609        game_mode(self.store.tabs(), e)
610    }
611
612    /// `isSpectator` of a player entity (game mode 3, see [`Tracker::game_mode`]): spectators are
613    /// not pickable, not pushable and never on the ground. `false` for other entities.
614    #[must_use]
615    pub fn is_spectator(&self, e: &Entity) -> bool {
616        e.is_player() && self.player_spectator(e)
617    }
618
619    /// `getScoreboardName` (what team rules match): a player's profile name (the tab-list entry
620    /// it spawned with, kept after the entry left), else `None`; vanilla uses the UUID string
621    /// for other entities. Needs the full tab list or [`Config::player_names`].
622    #[must_use]
623    pub fn scoreboard_name<'a>(&'a self, e: &'a Entity) -> Option<&'a str> {
624        if !e.is_player() {
625            return None;
626        }
627        if let Some(n) = e.links.as_ref().and_then(|l| l.profile_name.as_deref()) {
628            return Some(n);
629        }
630        let t = self.store.tab(&e.uuid)?;
631        (e.m.info_gen == 0 || t.generation == e.m.info_gen).then_some(t.name)
632    }
633
634    /// One client tick of the tracked entities (`ClientLevel.tickEntities`): every entity in a
635    /// loaded chunk takes one interpolation step and one head-rotation step. Call it once per
636    /// client tick, **after** the tick's crosshair pick (see the module docs). Assumes the
637    /// moved interpolation target never collides; use [`Tracker::tick_with`] for vanilla's check.
638    pub fn tick(&mut self) {
639        self.tick_with(|_, _| true);
640    }
641
642    /// [`Tracker::tick`] with vanilla's collision test: when an entity moved since its last
643    /// interpolation step (a snap, a teleport, a bed position), the step first moves the target
644    /// along, but only if `no_collision(entity, box)` says the entity's box at the moved target
645    /// (`[min_x, min_y, min_z, max_x, max_y, max_z]`) is free (`Level.noCollision`: blocks,
646    /// collidable entities, world border).
647    pub fn tick_with(&mut self, mut no_collision: impl FnMut(&Entity, [f64; 6]) -> bool) {
648        // The full membership re-check, only when packets were applied since the last one.
649        if std::mem::take(&mut self.order_dirty) {
650            self.refresh_order();
651        }
652        let early = std::mem::take(&mut self.early);
653        // Entities whose column changed in this tick (interpolation steps).
654        let mut moved: Vec<i32> = Vec::new();
655        let mut moved_vehicle = false;
656        let me = self.store.self_id;
657        let chunks = &self.chunks;
658        // Vehicles whose first passenger is a mob (their body control skips the idle turn).
659        let mut carrying: Vec<i32> = Vec::new();
660        for e in self.store.map.values() {
661            if let Some(v) = e.vehicle()
662                && e.m.td.is_some_and(|t| t.flags & type_flags::MOB != 0)
663                && self
664                    .store
665                    .map
666                    .get(&v)
667                    .is_some_and(|v| v.passengers().first() == Some(&e.id))
668            {
669                carrying.push(v);
670            }
671        }
672        let mut discard: Vec<i32> = Vec::new();
673        for e in self.store.map.values_mut() {
674            if e.m.flag(st::SETTLED)
675                || Some(e.id) == me
676                || (!early.is_empty() && early.contains(&e.id))
677            {
678                continue;
679            }
680            if !e.is_player() && !chunks.contains_key(&chunk_of(e.pos)) {
681                continue;
682            }
683            if !self.ghosts.is_empty() {
684                self.ghosts.remove(&e.id);
685            }
686            if e.ty == EntityType::Registry(data::ITEM) && e.m.item_count <= 0 {
687                // ItemEntity.tick: an empty stack discards the entity.
688                discard.push(e.id);
689                continue;
690            }
691            if e.is_player() {
692                let tabs = crate::store::Tabs {
693                    players: &self.store.players,
694                    lite: &self.store.lite,
695                    long_names: &self.store.long_names,
696                };
697                player_tick(e, tabs);
698            }
699            let c = !carrying.is_empty() && carrying.contains(&e.id);
700            let before = chunk_of(e.pos);
701            tick_entity(e, c, &mut no_collision);
702            if chunk_of(e.pos) != before {
703                moved.push(e.id);
704                moved_vehicle |= !e.passengers().is_empty();
705            }
706        }
707        for id in discard {
708            self.store.remove(id);
709        }
710        // Moves made by the tick (interpolation): only when some entity changed its column.
711        if !moved.is_empty() || moved_vehicle {
712            self.refresh_order();
713        }
714    }
715
716    /// Ticks entity `id` now, ahead of the rest of this client tick (a vehicle ticks before
717    /// its passenger: the local player riding a vehicle the server moves reads where the vehicle
718    /// is after its tick). The next [`Tracker::tick_with`] skips it once. Returns its position
719    /// after the tick (`None`: not tracked).
720    pub fn tick_early(
721        &mut self,
722        id: i32,
723        mut no_collision: impl FnMut(&Entity, [f64; 6]) -> bool,
724    ) -> Option<[f64; 3]> {
725        let again = self.early.contains(&id);
726        let e = self.store.map.get_mut(&id)?;
727        if !again
728            && !e.m.flag(st::SETTLED)
729            && (e.is_player() || self.chunks.contains_key(&chunk_of(e.pos)))
730        {
731            tick_entity(e, false, &mut no_collision);
732        }
733        if !self.early.contains(&id) {
734            self.early.push(id);
735        }
736        Some(e.pos)
737    }
738
739    /// Applies one clientbound play packet.
740    ///
741    /// # Errors
742    /// A malformed body (multi-entry packets may be partly applied).
743    pub fn apply(&mut self, raw: &RawPacket) -> Result<Applied, DecodeError> {
744        self.apply_body(raw.id, &raw.body)
745    }
746
747    /// [`Tracker::apply`] with the packet id and body.
748    ///
749    /// # Errors
750    /// See [`Tracker::apply`].
751    pub fn apply_body(&mut self, packet_id: i32, body: &Bytes) -> Result<Applied, DecodeError> {
752        if !self.wants(packet_id) {
753            return Ok(Applied::NotEntityPacket);
754        }
755        // A packet that moves one entity: its tick list membership follows the move at once
756        // (the entity section changes in setPos), in packet order.
757        let mover = matches!(
758            packet_id,
759            id::REL_ENTITY_MOVE
760                | id::ENTITY_MOVE_LOOK
761                | id::SYNC_ENTITY_POSITION
762                | id::ENTITY_TELEPORT
763                | id::ENTITY_LOOK
764                | id::ENTITY_VELOCITY
765                | id::ENTITY_METADATA
766        )
767        .then(|| Reader::new(body).read_varint().ok())
768        .flatten();
769        let out = self.apply_inner(packet_id, body);
770        self.order_dirty = true;
771        if let Some(eid) = mover {
772            self.refresh_one(eid);
773        }
774        out
775    }
776
777    /// Tick list membership of one entity after it moved (a vehicle carries its passengers).
778    fn refresh_one(&mut self, id: i32) {
779        let Some(e) = self.store.map.get(&id) else {
780            return;
781        };
782
783        if Some(id) == self.store.self_id || e.is_player() || self.ghosts.contains_key(&id) {
784            return;
785        }
786        if self.chunks.contains_key(&self.member_chunk_one(e)) {
787            self.start_ticking(id);
788        } else {
789            self.order.remove(&id);
790        }
791    }
792
793    fn apply_inner(&mut self, packet_id: i32, body: &Bytes) -> Result<Applied, DecodeError> {
794        let r = &mut Reader::new(body);
795        let ticking = (&self.chunks, &self.ghosts);
796        let s = &mut self.store;
797        let changed = match packet_id {
798            id::REL_ENTITY_MOVE => relative(s, r, true, false)?,
799            id::ENTITY_MOVE_LOOK => relative(s, r, true, true)?,
800            id::ENTITY_LOOK => relative(s, r, false, true)?,
801            id::SYNC_ENTITY_POSITION => sync(s, r, ticking)?,
802            id::ENTITY_TELEPORT => teleport(s, r)?,
803            id::ENTITY_VELOCITY => {
804                let eid = r.read_varint()?;
805                let v = LpVec3::read(r)?.to_vec3();
806                match s.map.get_mut(&eid) {
807                    Some(e) => {
808                        e.velocity = v;
809                        s.event(Event::Velocity(eid));
810                        true
811                    }
812                    None => false,
813                }
814            }
815            id::ENTITY_HEAD_ROTATION => {
816                let eid = r.read_varint()?;
817                let b = r.read_i8()?;
818                match s.map.get_mut(&eid) {
819                    // `lerpHeadTo(yRot, 3)`; a no-op for non-living entities.
820                    Some(e) if living(e) => {
821                        e.m.head_target = angle(b);
822                        e.m.head_steps = 3;
823                        e.m.set_flag(st::SETTLED, false);
824                        true
825                    }
826                    _ => false,
827                }
828            }
829            id::ENTITY_DESTROY => {
830                let mut any = false;
831                for_each_varint(r, |eid| any |= s.remove(eid))?;
832                any
833            }
834            id::ENTITY_STATUS => {
835                let eid = r.read_i32()?;
836                let status = r.read_i8()?;
837                let keep = s.config.metadata;
838                let known = match s.map.get_mut(&eid) {
839                    Some(e) => {
840                        // LivingEntity.handleEntityEvent(3): setHealth(0), die.
841                        if status == 3 && e.living {
842                            e.mark_dead();
843                            e.m.set_flag(st::DEAD, true);
844                            if keep {
845                                e.meta.set(meta::HEALTH, MetaValue::Float(0.0));
846                            }
847                        }
848                        true
849                    }
850                    None => false,
851                };
852                if known {
853                    s.event(Event::Status { id: eid, status });
854                }
855                known
856            }
857            id::SPAWN_ENTITY => {
858                let eid = r.clone().read_varint()?;
859                let old = s.map.get(&eid).map(|e| e.uuid);
860                let (applied, slot) = spawn(s, r, &self.chunks)?;
861                let now = self.store.map.get(&eid).map(|e| e.uuid);
862                match slot {
863                    TickSlot::Ghost(id) => {
864                        // A refused spawn: its id's slot (kept if already a member).
865                        self.ghosts.insert(id, ());
866                        self.start_ticking(id);
867                    }
868                    TickSlot::Taken(id) => {
869                        // A new entity enters at the end (one over a known id removes the old
870                        // one first); a ghost's slot keeps its place.
871                        if self.ghosts.remove(&id).is_none() {
872                            self.order.remove(&id);
873                        }
874                        self.start_ticking(id);
875                    }
876                    TickSlot::None => {
877                        if old.is_some() && now != old {
878                            self.order.remove(&eid);
879                        }
880                    }
881                }
882                return Ok(applied);
883            }
884            id::ATTACH_ENTITY => {
885                let eid = r.read_i32()?;
886                let holder = r.read_i32()?;
887                s.leash(eid, (holder != 0).then_some(holder))
888            }
889            id::SET_PASSENGERS => {
890                let vehicle = r.read_varint()?;
891                let start = r.position();
892                for_each_varint(r, |_| {})?;
893                let mut again = Reader::new(body);
894                again.skip(start)?;
895                if !s.map.contains_key(&vehicle) {
896                    return Ok(Applied::Ignored);
897                }
898                let n = again.read_varint()?.max(0);
899                let ids = (0..n).map_while(|_| again.read_varint().ok());
900                let r = s.set_passengers(vehicle, ids);
901                // Riding changes the body turn of mob vehicles: let every entity tick again.
902                for e in s.map.values_mut() {
903                    e.m.set_flag(st::SETTLED, false);
904                }
905                r
906            }
907            id::COLLECT => {
908                let collected = r.read_varint()?;
909                let collector = r.read_varint()?;
910                let amount = r.read_varint()?;
911                match s.map.get_mut(&collected) {
912                    None => false,
913                    Some(e) => {
914                        let t = match e.ty {
915                            EntityType::Registry(t) => t,
916                            _ => u16::MAX,
917                        };
918                        let gone = match t {
919                            data::ITEM => {
920                                if e.m.item_count > 0 {
921                                    e.m.item_count = e.m.item_count.wrapping_sub(amount);
922                                    shrink_stack(e, amount);
923                                }
924                                e.m.item_count <= 0
925                            }
926                            data::EXPERIENCE_ORB => false,
927                            _ => true,
928                        };
929                        s.event(Event::Collected {
930                            collected,
931                            collector,
932                        });
933                        if gone {
934                            s.remove(collected);
935                        }
936                        true
937                    }
938                }
939            }
940            id::ENTITY_METADATA => metadata(s, r)?,
941            id::ENTITY_UPDATE_ATTRIBUTES => attributes(s, r)?,
942            id::ENTITY_EQUIPMENT => {
943                let eid = r.read_varint()?;
944                let mut list: [Option<(usize, Option<Item>)>; 8] = Default::default();
945                let mut n = 0;
946                loop {
947                    let b = r.read_u8()?;
948                    let item = read_stack(r)?.map(|i| Item {
949                        id: i.id,
950                        count: i.count.clamp(0, 127) as i8,
951                        damage: 0,
952                        nbt: None,
953                    });
954                    if n < list.len() {
955                        list[n] = Some((usize::from(b & 0x7F), item));
956                        n += 1;
957                    }
958                    if b & 0x80 == 0 {
959                        break;
960                    }
961                }
962                match s.map.get_mut(&eid) {
963                    Some(e) => {
964                        let eq = e.equipment.get_or_insert_with(Default::default);
965                        for (slot, item) in list.into_iter().flatten() {
966                            if let Some(dst) = eq.get_mut(slot) {
967                                *dst = item;
968                            }
969                        }
970                        s.event(Event::Equipment(eid));
971                        true
972                    }
973                    None => false,
974                }
975            }
976            id::ENTITY_EFFECT => {
977                let eid = r.read_varint()?;
978                let effect = Effect {
979                    id: r.read_varint()? as u8,
980                    amplifier: r.read_varint()?.clamp(-128, 127) as i8,
981                    duration: r.read_varint()?,
982                    flags: r.read_u8()?,
983                };
984                set_effect(s, eid, effect)
985            }
986            id::REMOVE_ENTITY_EFFECT => {
987                let eid = r.read_varint()?;
988                let eff = r.read_varint()? as u8;
989                remove_effect(s, eid, eff)
990            }
991            id::PLAYER_INFO => {
992                player_info(s, r)?;
993                // Game modes feed Player.tick (spectators leave the ground).
994                for e in s.map.values_mut() {
995                    if e.is_player() {
996                        e.m.set_flag(st::SETTLED, false);
997                    }
998                }
999                true
1000            }
1001            id::PLAYER_REMOVE => {
1002                let n = r.read_varint()?;
1003                let n = r.check_count(i64::from(n), 16)?;
1004                for _ in 0..n {
1005                    let uuid = r.read_uuid()?;
1006                    let Some(t) = s.tab(&uuid) else {
1007                        continue;
1008                    };
1009                    let (gm, generation) = (t.game_mode, t.generation);
1010                    let name: Box<str> = Box::from(t.name);
1011                    // Player entities keep their profile (the name) and, once they looked the
1012                    // entry up, the tab list object (frozen game mode).
1013                    for e in s.map.values_mut() {
1014                        if e.m.info_gen == generation {
1015                            e.m.frozen_game_mode = gm as i8;
1016                        }
1017                        if e.is_player()
1018                            && e.uuid == uuid
1019                            && (e.m.info_gen == 0 || e.m.info_gen == generation)
1020                            && e.links.as_ref().is_none_or(|l| l.profile_name.is_none())
1021                        {
1022                            e.links_mut().profile_name = Some(name.clone());
1023                        }
1024                    }
1025                    s.tab_remove(&uuid);
1026                }
1027                s.event(Event::PlayerList);
1028                true
1029            }
1030            id::MAP_CHUNK => {
1031                let (x, z) = (r.read_i32()?, r.read_i32()?);
1032                self.mark_column_loaded(x, z);
1033                return Ok(Applied::Ignored);
1034            }
1035            id::UNLOAD_CHUNK => {
1036                let k = r.read_i64()? as u64;
1037                self.chunks.remove(&k);
1038                self.column_unloaded(k);
1039                return Ok(Applied::Ignored);
1040            }
1041            id::LOGIN => {
1042                let p = Login::decode(r)?;
1043                s.clear();
1044                s.set_self(p.entity_id);
1045                self.chunks.clear();
1046                self.ghosts.clear();
1047                self.order.clear();
1048                self.start_ticking(p.entity_id);
1049                self.dimension = p.world_state.name.to_string();
1050                true
1051            }
1052            id::RESPAWN => {
1053                let p = Respawn::decode(r)?;
1054                // A new client player: effects and equipment reset; metadata is copied only with
1055                // the keep-entity-data flag (2).
1056                if let Some(me) = s.self_id.and_then(|i| s.map.get_mut(&i)) {
1057                    me.clear_effects();
1058                    me.equipment = None;
1059                    if p.copy_metadata & 2 == 0 {
1060                        me.meta.clear();
1061                    }
1062                }
1063                let me = s.self_id;
1064                if *p.world_state.name != *self.dimension {
1065                    s.clear();
1066                    self.chunks.clear();
1067                    self.ghosts.clear();
1068                    self.order.clear();
1069                    self.dimension = p.world_state.name.to_string();
1070                } else if let Some(me) = me {
1071                    // The new player object is added after the others.
1072                    self.order.remove(&me);
1073                }
1074                if let Some(me) = me {
1075                    self.start_ticking(me);
1076                }
1077                true
1078            }
1079            _ => return Ok(Applied::NotEntityPacket),
1080        };
1081        Ok(if changed {
1082            Applied::Changed
1083        } else {
1084            Applied::Ignored
1085        })
1086    }
1087}
1088
1089/// `Mth.wrapDegrees(float)`.
1090#[inline]
1091fn wrap_f32(a: f32) -> f32 {
1092    let mut r = a % 360.0;
1093    if r >= 180.0 {
1094        r -= 360.0;
1095    }
1096    if r < -180.0 {
1097        r += 360.0;
1098    }
1099    r
1100}
1101
1102/// `Mth.clamp(float)`: `v < min ? min : Math.min(v, max)`.
1103#[inline]
1104fn jclamp(v: f32, min: f32, max: f32) -> f32 {
1105    if v < min {
1106        min
1107    } else if v.is_nan() {
1108        v
1109    } else if v == 0.0 && max == 0.0 {
1110        if v.is_sign_negative() || max.is_sign_negative() {
1111            -0.0
1112        } else {
1113            0.0
1114        }
1115    } else if v <= max {
1116        v
1117    } else {
1118        max
1119    }
1120}
1121
1122/// `Mth.rotateIfNecessary`.
1123#[inline]
1124fn rotate_if_necessary(base: f32, target: f32, max: f32) -> f32 {
1125    target - jclamp(wrap_f32(target - base), -max, max)
1126}
1127
1128/// One `ClientLevel.tickNonPassenger` of a 26.1 entity, as far as it changes tracked state:
1129/// dirty attributes (`baseTick`), the interpolation and head-rotation steps (`aiStep`), the mob
1130/// body / head turn (`tickHeadTurn`: `BodyRotationControl.clientTick`).
1131fn tick_entity(
1132    e: &mut Entity,
1133    carrying_mob: bool,
1134    no_collision: &mut impl FnMut(&Entity, [f64; 6]) -> bool,
1135) {
1136    let old = e.pos;
1137    if e.m.steps > 0 {
1138        step(e, no_collision);
1139    }
1140    if e.m.head_steps > 0 {
1141        let a = 1.0 / f64::from(e.m.head_steps);
1142        let from = f64::from(e.head_yaw);
1143        e.head_yaw = (from + a * wrap_degrees(f64::from(e.m.head_target) - from)) as f32;
1144        e.m.head_steps -= 1;
1145    }
1146    let Some(t) = e.m.td else {
1147        e.m.set_flag(st::SETTLED, true);
1148        return;
1149    };
1150    let mut settled =
1151        e.m.steps == 0 && e.m.head_steps == 0 && !(t.id == data::ITEM && e.m.item_count <= 0);
1152    if t.flags & (type_flags::MOB | type_flags::DEFAULT_BODY)
1153        == (type_flags::MOB | type_flags::DEFAULT_BODY)
1154    {
1155        let max = f32::from(t.max_head_y_rot);
1156        let (xd, zd) = (e.pos[0] - old[0], e.pos[2] - old[2]);
1157        let m = &mut e.m;
1158        if xd * xd + zd * zd > f64::from(2.500_000_3e-7_f32) {
1159            m.body_yaw = e.yaw;
1160            e.head_yaw = rotate_if_necessary(e.head_yaw, m.body_yaw, max);
1161            m.last_stable_head = e.head_yaw;
1162            m.head_stable_time = 0;
1163            settled = false;
1164        } else if carrying_mob {
1165            // Idle turning resumes once the mob passenger is gone: keep ticking.
1166            settled = false;
1167        } else {
1168            if (e.head_yaw - m.last_stable_head).abs() > 15.0 {
1169                m.head_stable_time = 0;
1170                m.last_stable_head = e.head_yaw;
1171                m.body_yaw = rotate_if_necessary(m.body_yaw, e.head_yaw, max);
1172                settled = false;
1173            } else {
1174                m.head_stable_time = m.head_stable_time.saturating_add(1).min(30);
1175                if m.head_stable_time > 10 {
1176                    let since = m.head_stable_time - 10;
1177                    let frac = (since as f32 / 10.0).clamp(0.0, 1.0);
1178                    let angle = max * (1.0 - frac);
1179                    m.body_yaw = rotate_if_necessary(m.body_yaw, e.head_yaw, angle);
1180                }
1181                settled &= m.head_stable_time >= 20 && m.body_yaw.to_bits() == e.head_yaw.to_bits();
1182            }
1183        }
1184    } else if t.flags_meta.is_some() {
1185        // ArmorStand.tickHeadTurn: the body follows yRot.
1186        e.m.body_yaw = e.yaw;
1187    }
1188    let sleeping = if t.name == "fox" {
1189        e.m.fox_flags & 0x20 != 0
1190    } else {
1191        e.m.flag(st::SLEEPING)
1192    };
1193    if sleeping {
1194        set_xrot(e, 0.0);
1195    }
1196    // refreshDirtyAttributes, at the end of LivingEntity.tick.
1197    if e.m.flag(st::SCALE_DIRTY) {
1198        e.m.set_flag(st::SCALE_DIRTY, false);
1199        {
1200            let d = compute_dims(e);
1201            e.m.set_dims(d);
1202        }
1203    }
1204    e.m.set_flag(st::SETTLED, settled);
1205}
1206
1207/// The tab-list part of `Player.tick` for a remote player: the entity caches its tab-list
1208/// object on first use; spectators and passengers are never on the ground. Out of line: the
1209/// tick loop over all entities only pays the player check.
1210#[inline(never)]
1211fn player_tick(e: &mut Entity, tabs: crate::store::Tabs<'_>) {
1212    if e.m.info_gen == 0
1213        && let Some(p) = tabs.get(&e.uuid)
1214    {
1215        e.m.info_gen = p.generation;
1216    }
1217    if e.vehicle().is_some() || game_mode(tabs, e) == Some(3) {
1218        e.on_ground = false;
1219    }
1220}
1221
1222/// The game mode a player entity sees (`AbstractClientPlayer.getPlayerInfo` caches the tab list
1223/// object on first use; it stays frozen once the server removes the entry).
1224fn game_mode(tabs: crate::store::Tabs<'_>, e: &Entity) -> Option<i32> {
1225    let cur = tabs.get(&e.uuid);
1226    if e.m.info_gen == 0 {
1227        return cur.map(|p| p.game_mode);
1228    }
1229    match cur {
1230        Some(p) if p.generation == e.m.info_gen => Some(p.game_mode),
1231        _ => Some(i32::from(e.m.frozen_game_mode)),
1232    }
1233}
1234
1235/// One `InterpolationHandler.interpolate()` step.
1236fn step(e: &mut Entity, no_collision: &mut impl FnMut(&Entity, [f64; 6]) -> bool) {
1237    let alpha = 1.0 / f64::from(e.m.steps);
1238    if e.m.flag(st::HAS_PREV) {
1239        let d = [
1240            e.pos[0] - e.m.prev[0],
1241            e.pos[1] - e.m.prev[1],
1242            e.pos[2] - e.m.prev[2],
1243        ];
1244        let t = e.m.target;
1245        let moved = [t[0] + d[0], t[1] + d[1], t[2] + d[2]];
1246        // Adding +0.0 changes nothing (but -0.0): skip the collision test then.
1247        let noop = (0..3).all(|i| moved[i].to_bits() == t[i].to_bits());
1248        if !noop {
1249            let bb = dimensions(e).map(|dm| {
1250                let b = dm.bounding_box(moved[0], moved[1], moved[2]);
1251                [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]
1252            });
1253            if bb.is_none_or(|bb| no_collision(&*e, bb)) {
1254                e.m.target = moved;
1255            }
1256        }
1257        // previousTickRot = (xRot, yRot).
1258        e.m.target_rot[0] += e.yaw - e.m.prev_rot[1];
1259        e.m.target_rot[1] += e.pitch - e.m.prev_rot[0];
1260    }
1261    let t = e.m.target;
1262    let lerp = |a: f64, b: f64| a + alpha * (b - a);
1263    let p = [
1264        lerp(e.pos[0], t[0]),
1265        lerp(e.pos[1], t[1]),
1266        lerp(e.pos[2], t[2]),
1267    ];
1268    let y0 = f64::from(e.yaw);
1269    let ny = (y0 + alpha * wrap_degrees(f64::from(e.m.target_rot[0]) - y0)) as f32;
1270    let nx = lerp(f64::from(e.pitch), f64::from(e.m.target_rot[1])) as f32;
1271    e.pos = p;
1272    // setRot: setYRot(y % 360), setXRot(x % 360).
1273    set_yrot(e, ny % 360.0);
1274    set_xrot(e, nx % 360.0);
1275    e.m.steps -= 1;
1276    e.m.prev = p;
1277    e.m.prev_rot = [e.pitch, e.yaw];
1278    e.m.set_flag(st::HAS_PREV, true);
1279}
1280
1281/// What a spawn did to vanilla's id-keyed tick list.
1282enum TickSlot {
1283    None,
1284    /// A refused (duplicate UUID) spawn that still entered the tick list.
1285    Ghost(i32),
1286    /// A ticking spawn took its id's slot.
1287    Taken(i32),
1288}
1289
1290fn spawn(s: &mut Entities, r: &mut Reader<'_>, chunks: &Fast<u64, ()>) -> R<(Applied, TickSlot)> {
1291    let eid = r.read_varint()?;
1292    let uuid = r.read_uuid()?;
1293    let t = r.read_varint()?;
1294    let pos = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
1295    let v = LpVec3::read(r)?.to_vec3();
1296    let pitch = angle(r.read_i8()?);
1297    let yaw = angle(r.read_i8()?);
1298    let head = angle(r.read_i8()?);
1299    let data = r.read_varint()?;
1300    let Some(td) = u16::try_from(t).ok().and_then(data::entity_type) else {
1301        return Ok((Applied::Ignored, TickSlot::None));
1302    };
1303    let ty = if td.id == data::PLAYER {
1304        if s.config.reads_tab_list() && !s.tab_has(&uuid) {
1305            // "Server attempted to add player prior to sending player info".
1306            return Ok((Applied::Ignored, TickSlot::None));
1307        }
1308        EntityType::Player
1309    } else {
1310        EntityType::Registry(td.id)
1311    };
1312    let mut e = Entity::new(eid, ty);
1313    e.living = td.is_living();
1314    e.uuid = uuid;
1315    e.m.td = Some(td);
1316    set_base(&mut e, pos);
1317    e.data = data;
1318    e.velocity = v;
1319    if td.is_living() {
1320        // LivingEntity.recreateFromPacket: absSnapTo, head = body = the head byte.
1321        e.pos = [
1322            pos[0].clamp(-3.0e7, 3.0e7),
1323            pos[1],
1324            pos[2].clamp(-3.0e7, 3.0e7),
1325        ];
1326        set_yrot(&mut e, yaw % 360.0);
1327        set_xrot(&mut e, pitch.clamp(-90.0, 90.0) % 360.0);
1328        e.head_yaw = head;
1329        e.m.body_yaw = if td.name == "shulker" { 0.0 } else { head };
1330        if td.name == "warden" && data == 1 {
1331            e.m.pose = 13; // emerging
1332        }
1333    } else {
1334        snap_to(&mut e, pos, yaw, pitch);
1335        e.head_yaw = e.yaw;
1336    }
1337    let d = compute_dims(&e);
1338    e.m.set_dims(d);
1339    // ClientLevel.addEntity: the old entity with this id goes first; then the entity lookup
1340    // refuses a UUID that another entity already has ("Duplicate entity UUID").
1341    let removed = s.remove(eid);
1342    if s.map.values().any(|o| o.uuid == uuid && o.id != eid) {
1343        // The rest of TransientEntitySectionManager.addEntity still runs: a ticking entity
1344        // enters the tick list under its id.
1345        let ticks = e.is_player() || chunks.contains_key(&chunk_of(e.pos));
1346        let a = if removed {
1347            Applied::Changed
1348        } else {
1349            Applied::Ignored
1350        };
1351        return Ok((
1352            a,
1353            if ticks {
1354                TickSlot::Ghost(eid)
1355            } else {
1356                TickSlot::None
1357            },
1358        ));
1359    }
1360    let ticks = e.is_player() || chunks.contains_key(&chunk_of(e.pos));
1361    s.spawn(e);
1362    Ok((
1363        Applied::Changed,
1364        if ticks {
1365            TickSlot::Taken(eid)
1366        } else {
1367            TickSlot::None
1368        },
1369    ))
1370}
1371
1372#[inline]
1373fn relative(s: &mut Entities, r: &mut Reader<'_>, pos: bool, look: bool) -> R<bool> {
1374    let eid = r.read_varint()?;
1375    let d = if pos {
1376        [r.read_i16()?, r.read_i16()?, r.read_i16()?]
1377    } else {
1378        [0; 3]
1379    };
1380    let rot = if look {
1381        Some((angle(r.read_i8()?), angle(r.read_i8()?)))
1382    } else {
1383        None
1384    };
1385    let on_ground = r.read_bool()?;
1386    let me = s.self_id;
1387    if Some(eid) == me {
1388        return Ok(false);
1389    }
1390    let Some(e) = s.map.get_mut(&eid) else {
1391        return Ok(false);
1392    };
1393    let ctl = controlled(me, e);
1394    let m = &mut *e.m;
1395    if ctl {
1396        set_base(e, decode_delta(base(e), d));
1397        return Ok(true);
1398    }
1399    m.set_flag(st::SETTLED, false);
1400    if pos {
1401        let p = decode_delta(base(e), d);
1402        set_base(e, p);
1403        move_or_interpolate(e, Some(p), rot.map(|r| r.0), rot.map(|r| r.1));
1404    } else if let Some((y, x)) = rot {
1405        move_or_interpolate(e, None, Some(y), Some(x));
1406    }
1407    e.on_ground = on_ground;
1408    s.event(Event::Moved(eid));
1409    Ok(true)
1410}
1411
1412/// `PositionMoveRotation.STREAM_CODEC`: position, delta movement, yRot, xRot.
1413fn pmr(r: &mut Reader<'_>) -> R<([f64; 3], [f64; 3], f32, f32)> {
1414    Ok((
1415        [r.read_f64()?, r.read_f64()?, r.read_f64()?],
1416        [r.read_f64()?, r.read_f64()?, r.read_f64()?],
1417        r.read_f32()?,
1418        r.read_f32()?,
1419    ))
1420}
1421
1422fn dist_sqr(a: [f64; 3], b: [f64; 3]) -> f64 {
1423    let d = [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
1424    d[0] * d[0] + d[1] * d[1] + d[2] * d[2]
1425}
1426
1427fn sync(
1428    s: &mut Entities,
1429    r: &mut Reader<'_>,
1430    (chunks, ghosts): (&Fast<u64, ()>, &Fast<i32, ()>),
1431) -> R<bool> {
1432    let eid = r.read_varint()?;
1433    let (p, _, y, x) = pmr(r)?;
1434    let on_ground = r.read_bool()?;
1435    let me = s.self_id;
1436    if Some(eid) == me {
1437        return Ok(false);
1438    }
1439    let Some(e) = s.map.get_mut(&eid) else {
1440        return Ok(false);
1441    };
1442    let ctl = controlled(me, e);
1443    set_base(e, p);
1444    e.m.set_flag(st::SETTLED, false);
1445    if !ctl {
1446        let far = dist_sqr(e.pos, p) > 4096.0;
1447        let ticking =
1448            e.is_player() || chunks.contains_key(&chunk_of(e.pos)) || ghosts.contains_key(&eid);
1449        if ticking && !far {
1450            move_or_interpolate(e, Some(p), Some(y), Some(x));
1451        } else {
1452            snap_to(e, p, y, x);
1453        }
1454        e.on_ground = on_ground;
1455    }
1456    s.event(Event::Moved(eid));
1457    Ok(true)
1458}
1459
1460fn teleport(s: &mut Entities, r: &mut Reader<'_>) -> R<bool> {
1461    let eid = r.read_varint()?;
1462    let (cp, cd, cy, cx) = pmr(r)?;
1463    let flags = r.read_i32()?;
1464    let on_ground = r.read_bool()?;
1465    if Some(eid) == s.self_id {
1466        return Ok(false);
1467    }
1468    let Some(e) = s.map.get_mut(&eid) else {
1469        return Ok(false);
1470    };
1471    let has = |bit: u32| flags & (1 << bit) != 0;
1472    e.m.set_flag(st::SETTLED, false);
1473    // PositionMoveRotation.of: the interpolation target while interpolating.
1474    let active = e.m.steps > 0;
1475    let (sp, sy, sx) = if active {
1476        (e.m.target, e.m.target_rot[0], e.m.target_rot[1])
1477    } else {
1478        (e.pos, e.yaw, e.pitch)
1479    };
1480    let p = [
1481        if has(0) { sp[0] } else { 0.0 } + cp[0],
1482        if has(1) { sp[1] } else { 0.0 } + cp[1],
1483        if has(2) { sp[2] } else { 0.0 } + cp[2],
1484    ];
1485    let y = if has(3) { sy } else { 0.0 } + cy;
1486    let x = (if has(4) { sx } else { 0.0 } + cx).clamp(-90.0, 90.0);
1487    let v = [
1488        if has(5) { e.velocity[0] + cd[0] } else { cd[0] },
1489        if has(6) { e.velocity[1] + cd[1] } else { cd[1] },
1490        if has(7) { e.velocity[2] + cd[2] } else { cd[2] },
1491    ];
1492    // Interpolated unless a non-ticking vehicle the bot controls gets an absolute teleport;
1493    // that case (and a jump over 64 blocks) sets the values directly.
1494    let far = dist_sqr(sp, p) > 4096.0;
1495    if far {
1496        e.pos = p;
1497        set_yrot(e, y);
1498        set_xrot(e, x);
1499    } else {
1500        move_or_interpolate(e, Some(p), Some(y), Some(x));
1501    }
1502    e.velocity = v;
1503    e.on_ground = on_ground;
1504    s.event(Event::Moved(eid));
1505    Ok(true)
1506}
1507
1508/// The value of one metadata entry: stored (owned) when wanted, else skipped. Size keys are
1509/// returned through `keys`.
1510struct Keys {
1511    pose: Option<u8>,
1512    baby: Option<bool>,
1513    slime: Option<i32>,
1514    stand: Option<u8>,
1515    fox: Option<u8>,
1516    bed: Option<Option<[i32; 3]>>,
1517    count: Option<i32>,
1518    stack: Option<Option<ItemStack>>,
1519    health: Option<f32>,
1520}
1521
1522fn block_pos(v: i64) -> [i32; 3] {
1523    // BlockPos.of(long): x 26 bits, z 26 bits, y 12 bits.
1524    [
1525        (v >> 38) as i32,
1526        ((v << 52) >> 52) as i32,
1527        ((v << 26) >> 38) as i32,
1528    ]
1529}
1530
1531/// Copies `[start, end)` of the packet out (stored values never pin a packet buffer).
1532fn owned(r: &Reader<'_>, start: usize) -> Bytes {
1533    Bytes::copy_from_slice(&r.bytes_since(start))
1534}
1535
1536fn read_value(
1537    r: &mut Reader<'_>,
1538    index: u8,
1539    ty: u32,
1540    td: &EntityTypeData,
1541    keep: bool,
1542    keys: &mut Keys,
1543) -> R<Option<MetaValue>> {
1544    let live = td.is_living();
1545    let v = match ty {
1546        0 => {
1547            let b = r.read_i8()?;
1548            if td.flags_meta == Some(index) {
1549                keys.stand = Some(b as u8);
1550            }
1551            if index == FOX_FLAGS && td.name == "fox" {
1552                keys.fox = Some(b as u8);
1553            }
1554            MetaValue::Byte(b)
1555        }
1556        1 => {
1557            let n = r.read_varint()?;
1558            if td.size_meta == Some(index) {
1559                keys.slime = Some(n);
1560            }
1561            MetaValue::VarInt(n)
1562        }
1563        2 => MetaValue::Long(r.read_varlong()?),
1564        3 => {
1565            let f = r.read_f32()?;
1566            if !keep && live && index == meta::HEALTH {
1567                // Without the store, `alive` keeps this one fact.
1568                keys.health = Some(f);
1569            }
1570            MetaValue::Float(f)
1571        }
1572        4 => {
1573            if !keep {
1574                skip_string(r)?;
1575                return Ok(None);
1576            }
1577            MetaValue::String(own_str(r)?)
1578        }
1579        5 => {
1580            let start = r.position();
1581            AnonNbt::read(r)?;
1582            if !keep {
1583                return Ok(None);
1584            }
1585            MetaValue::Component(owned(r, start))
1586        }
1587        6 => {
1588            if r.read_bool()? {
1589                let start = r.position();
1590                AnonNbt::read(r)?;
1591                if !keep {
1592                    return Ok(None);
1593                }
1594                MetaValue::OptComponent(Some(owned(r, start)))
1595            } else {
1596                MetaValue::OptComponent(None)
1597            }
1598        }
1599        7 => {
1600            let start = r.position();
1601            let s = read_stack(r)?;
1602            let is_item = td.id == data::ITEM && index == meta::ITEM;
1603            if is_item {
1604                keys.count = Some(s.as_ref().map_or(0, |s| s.count));
1605            }
1606            if !keep && !is_item {
1607                return Ok(None);
1608            }
1609            // Re-read from an owned copy: the stored stack must not pin the packet buffer.
1610            let copy = owned(r, start);
1611            let s = read_stack(&mut Reader::new(&copy))?;
1612            if is_item {
1613                keys.stack = Some(s.clone());
1614            }
1615            if !keep {
1616                return Ok(None);
1617            }
1618            MetaValue::Stack(s)
1619        }
1620        8 => {
1621            let b = r.read_bool()?;
1622            if td.baby_meta == Some(index) {
1623                keys.baby = Some(b);
1624            }
1625            MetaValue::Bool(b)
1626        }
1627        9 => MetaValue::Rotation([r.read_f32()?, r.read_f32()?, r.read_f32()?]),
1628        10 => MetaValue::BlockPos(block_pos(r.read_i64()?)),
1629        11 => {
1630            let p = if r.read_bool()? {
1631                Some(block_pos(r.read_i64()?))
1632            } else {
1633                None
1634            };
1635            if live && index == meta::SLEEPING_POS {
1636                keys.bed = Some(p);
1637            }
1638            MetaValue::OptBlockPos(p)
1639        }
1640        12 => MetaValue::Direction(r.read_varint()?),
1641        13 => MetaValue::OptUuid(if r.read_bool()? {
1642            Some(r.read_uuid()?)
1643        } else {
1644            None
1645        }),
1646        14 => MetaValue::BlockState(r.read_varint()?),
1647        18 => MetaValue::VillagerData([r.read_varint()?, r.read_varint()?, r.read_varint()?]),
1648        19 => MetaValue::OptVarInt(r.read_varint()?),
1649        20 => {
1650            let p = r.read_varint()?;
1651            if index == meta::POSE {
1652                // Pose.BY_ID: out-of-range ids read as standing.
1653                keys.pose = Some(if (0..18).contains(&p) { p as u8 } else { 0 });
1654            }
1655            MetaValue::Pose(p)
1656        }
1657        21..=32 | 35..=38 | 42 => MetaValue::Enum(ty as u8, r.read_varint()?),
1658        39 => MetaValue::Vector3([r.read_f32()?, r.read_f32()?, r.read_f32()?]),
1659        40 => MetaValue::Quaternion([r.read_f32()?, r.read_f32()?, r.read_f32()?, r.read_f32()?]),
1660        15 | 16 | 17 | 33 | 34 | 41 => {
1661            let start = r.position();
1662            skip_complex(r, ty)?;
1663            if !keep {
1664                return Ok(None);
1665            }
1666            MetaValue::Raw(ty as u8, owned(r, start))
1667        }
1668        _ => return Err(DecodeError::Invalid("unknown metadata serializer")),
1669    };
1670    Ok(keep.then_some(v))
1671}
1672
1673/// Skips the values with a complex layout using the generated decoders.
1674fn skip_complex(r: &mut Reader<'_>, ty: u32) -> R<()> {
1675    use super::proto::types::{
1676        EntityMetadataPaintingVariant, GlobalPos, Particle, ResolvableProfile,
1677    };
1678    match ty {
1679        15 => {
1680            r.read_varint()?;
1681        }
1682        16 => {
1683            Particle::decode(r)?;
1684        }
1685        17 => {
1686            let n = r.read_varint()?;
1687            let n = r.check_count(i64::from(n), 1)?;
1688            for _ in 0..n {
1689                Particle::decode(r)?;
1690            }
1691        }
1692        33 => {
1693            if r.read_bool()? {
1694                GlobalPos::decode(r)?;
1695            }
1696        }
1697        34 => {
1698            // Holder: registry id + 1, or 0 and the variant inline.
1699            if r.read_varint()? == 0 {
1700                EntityMetadataPaintingVariant::decode(r)?;
1701            }
1702        }
1703        41 => {
1704            ResolvableProfile::decode(r)?;
1705        }
1706        _ => unreachable!(),
1707    }
1708    Ok(())
1709}
1710
1711fn metadata(s: &mut Entities, r: &mut Reader<'_>) -> R<bool> {
1712    let eid = r.read_varint()?;
1713    let Some(e) = s.map.get(&eid) else {
1714        return Ok(false);
1715    };
1716    let Some(td) = e.m.td.or_else(|| data::entity_type(data::PLAYER)) else {
1717        return Ok(false);
1718    };
1719    let keep = s.config.metadata;
1720    let mut keys = Keys {
1721        pose: None,
1722        baby: None,
1723        slime: None,
1724        stand: None,
1725        fox: None,
1726        bed: None,
1727        count: None,
1728        stack: None,
1729        health: None,
1730    };
1731    let mut scratch = std::mem::take(&mut s.scratch);
1732    scratch.clear();
1733    let res = (|| -> R<()> {
1734        loop {
1735            let index = r.read_u8()?;
1736            if index == 0xFF {
1737                return Ok(());
1738            }
1739            let ty = r.read_varint()? as u32;
1740            if let Some(v) = read_value(r, index, ty, td, keep, &mut keys)? {
1741                scratch.push((index, v));
1742            }
1743        }
1744    })();
1745    if res.is_ok()
1746        && let Some(e) = s.map.get_mut(&eid)
1747    {
1748        e.meta.set_from(&mut scratch, |_| true);
1749        e.m.set_flag(st::SETTLED, false);
1750        let resize = keys.pose.is_some()
1751            || keys.baby.is_some()
1752            || keys.stand.is_some()
1753            || keys.slime.is_some();
1754        if let Some(p) = keys.pose {
1755            e.m.pose = p;
1756        }
1757        if let Some(b) = keys.baby {
1758            e.m.set_flag(st::BABY, b);
1759        }
1760        if let Some(f) = keys.stand {
1761            e.m.stand_flags = f;
1762        }
1763        if let Some(f) = keys.fox {
1764            e.m.fox_flags = f;
1765        }
1766        if let Some(n) = keys.slime {
1767            e.m.slime_size = n;
1768            // Slime.onSyncedDataUpdated: setYRot(yHeadRot), yBodyRot = yHeadRot.
1769            set_yrot(e, e.head_yaw);
1770            e.m.body_yaw = e.head_yaw;
1771        }
1772        if resize {
1773            {
1774                let d = compute_dims(e);
1775                e.m.set_dims(d);
1776            }
1777        }
1778        if let Some(b) = keys.bed {
1779            e.m.set_flag(st::SLEEPING, b.is_some());
1780            if let Some(b) = b {
1781                // LivingEntity.setPosToBed.
1782                e.pos = [
1783                    f64::from(b[0]) + 0.5,
1784                    f64::from(b[1]) + 0.6875,
1785                    f64::from(b[2]) + 0.5,
1786                ];
1787            }
1788        }
1789        if let Some(h) = keys.health {
1790            // LivingEntity.isAlive: getHealth() > 0 (NaN is not alive).
1791            let alive = h > 0.0;
1792            e.m.set_flag(st::DEAD, !alive);
1793        }
1794        if let Some(c) = keys.count {
1795            e.m.item_count = c;
1796            if !keep && let Some(st) = keys.stack.take() {
1797                e.meta.set(meta::ITEM, MetaValue::Stack(st));
1798            }
1799        }
1800        s.event(Event::Metadata(eid));
1801    }
1802    s.scratch = scratch;
1803    res?;
1804    Ok(true)
1805}
1806
1807fn attributes(s: &mut Entities, r: &mut Reader<'_>) -> R<bool> {
1808    let eid = r.read_varint()?;
1809    let n = r.read_varint()?;
1810    let n = r.check_count(i64::from(n), 10)?;
1811    let mut scale = None;
1812    for _ in 0..n {
1813        let attr = r.read_varint()?;
1814        let base = r.read_f64()?;
1815        let m = r.read_varint()?;
1816        let m = r.check_count(i64::from(m), 10)?;
1817        let (mut add, mut mul_base, mut mul_total) = (Vec::new(), Vec::new(), Vec::new());
1818        let want = attr == SCALE_ATTRIBUTE;
1819        for _ in 0..m {
1820            skip_string(r)?;
1821            let amount = r.read_f64()?;
1822            let op = r.read_varint()?;
1823            if want {
1824                match op {
1825                    0 => add.push(amount),
1826                    1 => mul_base.push(amount),
1827                    _ => mul_total.push(amount),
1828                }
1829            }
1830        }
1831        if want {
1832            // AttributeInstance.calculateValue (modifiers in packet order), then the
1833            // RangedAttribute clamp [0.0625, 16].
1834            let mut b = base;
1835            for a in &add {
1836                b += a;
1837            }
1838            let mut v = b;
1839            for a in &mul_base {
1840                v += b * a;
1841            }
1842            for a in &mul_total {
1843                v *= 1.0 + a;
1844            }
1845            let v = if v.is_nan() {
1846                0.0625
1847            } else {
1848                v.clamp(0.0625, 16.0)
1849            };
1850            scale = Some(v as f32);
1851        }
1852    }
1853    let Some(e) = s.map.get_mut(&eid) else {
1854        return Ok(false);
1855    };
1856    if !living(e) {
1857        return Ok(false);
1858    }
1859    if let Some(v) = scale {
1860        e.m.scale = match e.m.td.map(|t| t.name) {
1861            Some("ender_dragon") => 1.0,
1862            Some("happy_ghast") => v.min(1.0),
1863            _ => v,
1864        };
1865        e.m.set_flag(st::SCALE_DIRTY, true);
1866        e.m.set_flag(st::SETTLED, false);
1867    }
1868    Ok(true)
1869}
1870
1871fn shrink_stack(e: &mut Entity, amount: i32) {
1872    if let Some(MetaValue::Stack(Some(st))) = e
1873        .meta
1874        .entries_mut()
1875        .find(|(i, _)| *i == meta::ITEM)
1876        .map(|(_, v)| v)
1877    {
1878        st.count = st.count.wrapping_sub(amount);
1879    }
1880}
1881
1882/// 26.1 `player_info` (update): an action bitset (enum order), then per entry the fields of every
1883/// set action. `ADD_PLAYER` only adds unknown profiles (`putIfAbsent`); the other actions apply
1884/// to the entry the client has.
1885fn player_info(s: &mut Entities, r: &mut Reader<'_>) -> R<()> {
1886    let actions = r.read_u8()?;
1887    let n = r.read_varint()?;
1888    let n = r.check_count(i64::from(n), 16)?;
1889    let has = |bit: u8| actions & (1 << bit) != 0;
1890    for _ in 0..n {
1891        let uuid = r.read_uuid()?;
1892        if has(0) {
1893            let name = r.read_string()?;
1894            let props = r.read_varint()?;
1895            let props = r.check_count(i64::from(props), 3)?;
1896            let mut textures = None;
1897            for _ in 0..props {
1898                if s.config.skins {
1899                    let key = r.read_string()?;
1900                    let value = r.read_string()?;
1901                    if &*key == "textures" {
1902                        textures = Some(Box::<str>::from(&*value));
1903                    }
1904                } else {
1905                    skip_string(r)?;
1906                    skip_string(r)?;
1907                }
1908                if r.read_bool()? {
1909                    skip_string(r)?;
1910                }
1911            }
1912            let next = s.generations.wrapping_add(1).max(1);
1913            let fresh = !s.tab_has(&uuid);
1914            if fresh {
1915                s.generations = next;
1916            }
1917            if s.lite_mode() {
1918                s.lite_add(uuid, &name, 0, next, false);
1919            } else {
1920                s.players.entry(uuid).or_insert(PlayerInfo {
1921                    name: Box::from(&*name),
1922                    game_mode: 0,
1923                    ping: 0,
1924                    display_name: None,
1925                    textures,
1926                    display_name_nbt: None,
1927                    listed: false,
1928                    list_order: 0,
1929                    generation: next,
1930                });
1931            }
1932        }
1933        if has(1) && r.read_bool()? {
1934            // Chat session: id, key expiry, key bytes, key signature.
1935            r.read_uuid()?;
1936            r.read_i64()?;
1937            let k = r.read_len_varint(r.remaining())?;
1938            r.skip(k)?;
1939            let k = r.read_len_varint(r.remaining())?;
1940            r.skip(k)?;
1941        }
1942        // GameType.byId: out-of-range ids read as survival.
1943        let gm = if has(2) {
1944            Some(
1945                Some(r.read_varint()?)
1946                    .filter(|g| (0..4).contains(g))
1947                    .unwrap_or(0),
1948            )
1949        } else {
1950            None
1951        };
1952        let listed = if has(3) { Some(r.read_bool()?) } else { None };
1953        let ping = if has(4) { Some(r.read_varint()?) } else { None };
1954        let display = if has(5) {
1955            Some(if r.read_bool()? {
1956                let start = r.position();
1957                AnonNbt::read(r)?;
1958                Some(owned(r, start))
1959            } else {
1960                None
1961            })
1962        } else {
1963            None
1964        };
1965        let order = if has(6) { Some(r.read_varint()?) } else { None };
1966        if has(7) {
1967            r.read_bool()?;
1968        }
1969        if let Some(g) = gm {
1970            s.lite_game_mode(&uuid, g);
1971        }
1972        if let Some(p) = s.players.get_mut(&uuid) {
1973            if let Some(g) = gm {
1974                p.game_mode = g;
1975            }
1976            if let Some(l) = listed {
1977                p.listed = l;
1978            }
1979            if let Some(l) = ping {
1980                p.ping = l;
1981            }
1982            if let Some(d) = display {
1983                p.display_name_nbt = d;
1984            }
1985            if let Some(o) = order {
1986                p.list_order = o;
1987            }
1988        }
1989    }
1990    s.event(Event::PlayerList);
1991    Ok(())
1992}
1993
1994/// The packet coordinates of a 26.1 entity (`VecDeltaCodec` base: the last spawn, relative move
1995/// or position sync; teleports do not change it).
1996#[must_use]
1997pub fn server_position(e: &Entity) -> [f64; 3] {
1998    base(e)
1999}
2000
2001/// The interpolation target and its `(yRot, xRot)` while an interpolation is active.
2002#[must_use]
2003pub fn interpolation_target(e: &Entity) -> Option<([f64; 3], [f32; 2])> {
2004    (e.m.steps > 0).then_some((e.m.target, e.m.target_rot))
2005}
2006
2007/// The type facts from ghast-data.
2008#[must_use]
2009pub fn entity_type(e: &Entity) -> Option<&'static EntityTypeData> {
2010    e.m.td
2011}
2012
2013/// Pick radius (`getPickRadius`, 0 for every 26.1 type).
2014#[must_use]
2015pub fn pick_radius(e: &Entity) -> f32 {
2016    e.m.td
2017        .and_then(|t| t.size)
2018        .map_or(0.0, |s| s.targeting_margin)
2019}
2020
2021/// `yBodyRot` of mobs with the default body control and armor stands (exact); other entities
2022/// keep their spawn value (players turn their body from movement, not modelled).
2023#[must_use]
2024pub fn body_yaw(e: &Entity) -> f32 {
2025    e.m.body_yaw
2026}
2027
2028/// The pose id (`Pose`: 0 standing, 2 sleeping, 3 swimming, 5 crouching, 10 sitting, ...).
2029#[must_use]
2030pub fn pose(e: &Entity) -> u8 {
2031    e.m.pose
2032}
2033
2034/// The `minecraft:scale` value the client uses for the entity's size.
2035#[must_use]
2036pub fn scale(e: &Entity) -> f32 {
2037    e.m.scale
2038}
2039
2040/// Stack size of an item entity (0 before its stack arrived).
2041#[must_use]
2042pub fn item_count(e: &Entity) -> i32 {
2043    e.m.item_count
2044}
2045
2046/// The stack of an item entity (always kept for item entities).
2047#[must_use]
2048pub fn item_stack(e: &Entity) -> Option<&ItemStack> {
2049    match e.meta.get(meta::ITEM)? {
2050        MetaValue::Stack(s) if e.ty == EntityType::Registry(data::ITEM) => s.as_ref(),
2051        _ => None,
2052    }
2053}
2054
2055/// 26.1 health of a living entity (with [`Config::metadata`]).
2056#[must_use]
2057pub fn health(e: &Entity) -> Option<f32> {
2058    e.metadata().float(meta::HEALTH)
2059}
2060
2061/// Vanilla `LivingEntity.isAlive` as far as the packets tell (removed entities are not
2062/// tracked): `false` once the server sent a health that is not above 0 (NaN included), `true`
2063/// for other entities and before any health arrived. Kept with and without [`Config::metadata`].
2064#[must_use]
2065pub fn alive(e: &Entity) -> bool {
2066    if !living(e) {
2067        return true;
2068    }
2069    match health(e) {
2070        Some(h) => h > 0.0,
2071        None => !e.m.flag(st::DEAD),
2072    }
2073}
2074
2075/// 26.1 entity flags byte (0 when unknown).
2076#[must_use]
2077pub fn flags(e: &Entity) -> u8 {
2078    e.metadata().byte(meta::FLAGS).unwrap_or(0) as u8
2079}
2080
2081/// 26.1 custom name (raw network NBT text component).
2082#[must_use]
2083pub fn custom_name(e: &Entity) -> Option<&Bytes> {
2084    match e.metadata().get(meta::CUSTOM_NAME)? {
2085        MetaValue::OptComponent(Some(b)) => Some(b),
2086        _ => None,
2087    }
2088}
2089
2090/// Static type information from ghast-data.
2091#[must_use]
2092pub fn info(t: EntityType) -> Option<&'static ghast_data::EntityInfo> {
2093    match t {
2094        EntityType::Registry(id) => super::data::entity(id),
2095        EntityType::Player => super::data::entity(data::PLAYER),
2096        _ => None,
2097    }
2098}
2099
2100pub(crate) fn class(e: &Entity) -> EntityClass {
2101    match e.ty {
2102        EntityType::Player => EntityClass::Player,
2103        EntityType::Registry(data::ITEM) => EntityClass::Item,
2104        EntityType::Registry(data::EXPERIENCE_ORB) => EntityClass::ExperienceOrb,
2105        EntityType::Registry(data::PAINTING) => EntityClass::Painting,
2106        _ if e.living => EntityClass::Mob,
2107        _ => EntityClass::Object,
2108    }
2109}
2110
2111pub(crate) fn vanilla_size(e: &Entity) -> Option<&'static ghast_data::VanillaEntitySize> {
2112    e.m.td.and_then(|t| t.size)
2113}
2114
2115/// The client's cached dimensions (`Entity.dimensions`).
2116pub(crate) fn dimensions(e: &Entity) -> Option<ghast_data::EntityDimensions> {
2117    e.m.dims()
2118}
2119
2120/// `getDimensions(getPose())`: variant (baby flag, slime size, armor stand flags), pose, scale.
2121fn compute_dims(e: &Entity) -> Option<ghast_data::EntityDimensions> {
2122    let t = e.m.td?;
2123    let m = &e.m;
2124    let (variant, slime) = if t.size_meta.is_some() {
2125        ("default", Some(m.slime_size))
2126    } else if t.flags_meta.is_some() {
2127        let f = m.stand_flags;
2128        let v = match (f & 0x01 != 0, f & 0x10 != 0) {
2129            (true, true) => "small_marker",
2130            (false, true) => "marker",
2131            (true, false) => "small",
2132            _ => "default",
2133        };
2134        (v, None)
2135    } else if t.baby_meta.is_some() && m.flag(st::BABY) {
2136        ("baby", None)
2137    } else {
2138        ("default", None)
2139    };
2140    let d = t.dimensions(variant, slime, i32::from(m.pose))?;
2141    if t.is_living() && m.pose != 2 {
2142        let fixed = t.flags & type_flags::FIXED != 0
2143            || variant.ends_with("marker")
2144            || t.fixed_poses & (1 << m.pose) != 0;
2145        return Some(EntityTypeData::scaled(d, m.scale, fixed));
2146    }
2147    Some(d)
2148}
2149
2150#[cfg(test)]
2151mod tests {
2152    use super::*;
2153
2154    #[test]
2155    fn java_round_and_delta_codec() {
2156        assert_eq!(jround(2.5), 3);
2157        assert_eq!(jround(-2.5), -2);
2158        assert_eq!(jround(-2.500_000_1), -3);
2159        assert_eq!(jround(0.499_999_999_999_999_94), 0);
2160        assert_eq!(jround(f64::NAN), 0);
2161        assert_eq!(jround(-0.5), 0);
2162        assert_eq!(jround(-0.500_000_000_000_000_1), -1);
2163        assert_eq!(jround(1e300), i64::MAX);
2164        assert_eq!(jround(-4.5e15 - 1.0), -4_500_000_000_000_001);
2165        for i in -2000..2000 {
2166            let x = f64::from(i) * 0.137_5 + 1e-3 * f64::from(i % 7);
2167            assert_eq!(jround(x), (x + 0.5).floor() as i64, "{x}");
2168            assert_eq!(mth_floor(x), x.floor() as i32, "{x}");
2169        }
2170        let b = [1.0 / 3.0, -7.25, 1e-9];
2171        assert_eq!(decode_delta(b, [0; 3]), b);
2172        let d = decode_delta(b, [4096, 0, -1]);
2173        assert_eq!(d[0], (1365.0 + 4096.0) / 4096.0);
2174        assert_eq!(d[1].to_bits(), b[1].to_bits());
2175        assert_eq!(d[2], -1.0 / 4096.0);
2176    }
2177
2178    fn varint(out: &mut Vec<u8>, v: i32) {
2179        let mut v = v as u32;
2180        loop {
2181            if v < 0x80 {
2182                out.push(v as u8);
2183                return;
2184            }
2185            out.push((v as u8 & 0x7F) | 0x80);
2186            v >>= 7;
2187        }
2188    }
2189
2190    /// Spawns `eid` (type `ty`) and sends it `entries` as one metadata packet.
2191    fn spawn_with(t: &mut Tracker, eid: i32, ty: u16, entries: &[u8]) {
2192        let mut b = Vec::new();
2193        varint(&mut b, eid);
2194        b.extend_from_slice(&(0x1000_u128 + eid as u128).to_be_bytes());
2195        varint(&mut b, i32::from(ty));
2196        for c in [0.5, 64.0, 0.5_f64] {
2197            b.extend_from_slice(&c.to_be_bytes());
2198        }
2199        b.extend_from_slice(&[0, 0, 0, 0]); // zero LpVec3, pitch, yaw, head
2200        varint(&mut b, 0);
2201        let spawned = t.apply_body(id::SPAWN_ENTITY, &Bytes::from(b)).unwrap();
2202        assert_eq!(spawned, Applied::Changed);
2203        let mut m = Vec::new();
2204        varint(&mut m, eid);
2205        m.extend_from_slice(entries);
2206        m.push(0xFF);
2207        assert_eq!(
2208            t.apply_body(id::ENTITY_METADATA, &Bytes::from(m)).unwrap(),
2209            Applied::Changed
2210        );
2211    }
2212
2213    /// Pins what one tracked entity costs (map slot + heap) so a change cannot silently grow
2214    /// it. A player with what a server sends at spawn (health, skin parts), a zombie with its
2215    /// health.
2216    #[test]
2217    fn bytes_per_tracked_entity() {
2218        // Health (index 9, float 20.0) and the skin parts byte (index 16).
2219        let mut player = vec![9, 3];
2220        player.extend_from_slice(&20.0_f32.to_be_bytes());
2221        player.extend_from_slice(&[16, 0, 0x7F]);
2222        let mut zombie = vec![9, 3];
2223        zombie.extend_from_slice(&20.0_f32.to_be_bytes());
2224        let mut t = Tracker::new(Config::default().with_player_list(false));
2225        spawn_with(&mut t, 10, data::PLAYER, &player);
2226        let ty = |n| data::entity_by_name(n).unwrap().id;
2227        spawn_with(&mut t, 11, ty("zombie"), &zombie);
2228        let slot = std::mem::size_of::<(i32, Entity)>();
2229        let p = t.get(10).unwrap();
2230        let z = t.get(11).unwrap();
2231        assert_eq!(p.metadata().len(), 2);
2232        let (pb, zb) = (slot + p.heap_bytes(), slot + z.heap_bytes());
2233        eprintln!(
2234            "slot {slot} B; player {pb} B ({} heap), zombie {zb} B ({} heap)",
2235            p.heap_bytes(),
2236            z.heap_bytes()
2237        );
2238        // 0.4.3: slot 240 B, metadata block 448 B (four-entry capacity), state 120 B: 808 B.
2239        assert!(slot <= 176, "{slot}");
2240        assert!(pb <= 520, "player {pb}");
2241        assert!(zb <= 408, "zombie {zb}");
2242        // Without the metadata store (`Config::metadata` off): slot and state only.
2243        let mut t = Tracker::new(
2244            Config::default()
2245                .with_player_list(false)
2246                .with_metadata(false),
2247        );
2248        spawn_with(&mut t, 10, data::PLAYER, &player);
2249        let p = t.get(10).unwrap();
2250        assert!(p.metadata().is_empty());
2251        let lean = slot + p.heap_bytes();
2252        eprintln!("without the metadata store: player {lean} B");
2253        assert!(lean <= 296, "player {lean}");
2254    }
2255
2256    fn destroy(t: &mut Tracker, ids: &[i32]) {
2257        let mut b = Vec::new();
2258        varint(&mut b, ids.len() as i32);
2259        for &id in ids {
2260            varint(&mut b, id);
2261        }
2262        t.apply_body(id::ENTITY_DESTROY, &Bytes::from(b)).unwrap();
2263    }
2264
2265    /// A steady crowd with fresh ids does not grow the tables (deletion markers would double
2266    /// them), and a crowd that leaves gives the memory back.
2267    #[test]
2268    fn tables_follow_the_live_crowd() {
2269        let zombie = data::entity_by_name("zombie").unwrap().id;
2270        let mut t = Tracker::new(Config::default().with_metadata(false));
2271        for x in -2..=2 {
2272            for z in -2..=2 {
2273                t.mark_column_loaded(x, z);
2274            }
2275        }
2276        let health = [9, 3, 0x41, 0xA0, 0, 0];
2277        for id in 0..150 {
2278            spawn_with(&mut t, 100 + id, zombie, &health);
2279        }
2280        for id in 150..6000 {
2281            spawn_with(&mut t, 100 + id, zombie, &health);
2282            destroy(&mut t, &[100 + id - 150]);
2283            if id % 97 == 0 {
2284                t.tick();
2285            }
2286        }
2287        t.tick();
2288        assert_eq!(t.len(), 150);
2289        assert!(t.map.capacity() <= 224, "entity map {}", t.map.capacity());
2290        assert!(
2291            t.order.capacity() <= 224,
2292            "tick order {}",
2293            t.order.capacity()
2294        );
2295        for id in 6000..8000 {
2296            spawn_with(&mut t, 100 + id, zombie, &health);
2297        }
2298        let gone: Vec<i32> = (5850..7899).map(|i| 100 + i).collect();
2299        destroy(&mut t, &gone);
2300        t.tick();
2301        assert_eq!(t.len(), 101);
2302        assert!(t.map.capacity() <= 224, "entity map {}", t.map.capacity());
2303        assert!(
2304            t.order.capacity() <= 224,
2305            "tick order {}",
2306            t.order.capacity()
2307        );
2308    }
2309
2310    /// `alive` follows the health with the metadata store off; the store stays empty.
2311    #[test]
2312    fn alive_without_metadata_store() {
2313        let zombie = data::entity_by_name("zombie").unwrap().id;
2314        let mut t = Tracker::new(Config::default().with_metadata(false));
2315        spawn_with(&mut t, 7, zombie, &[9, 3, 0x41, 0xA0, 0, 0]); // 20.0
2316        assert!(alive(t.get(7).unwrap()));
2317        let mut zero = vec![9, 3];
2318        zero.extend_from_slice(&0.0_f32.to_be_bytes());
2319        let mut m = Vec::new();
2320        varint(&mut m, 7);
2321        m.extend_from_slice(&zero);
2322        m.push(0xFF);
2323        t.apply_body(id::ENTITY_METADATA, &Bytes::from(m)).unwrap();
2324        let e = t.get(7).unwrap();
2325        assert!(!alive(e));
2326        assert_eq!(health(e), None);
2327        assert!(e.metadata().is_empty());
2328        let mut t = Tracker::new(Config::default());
2329        spawn_with(&mut t, 7, zombie, &zero);
2330        assert!(!alive(t.get(7).unwrap()));
2331        assert_eq!(health(t.get(7).unwrap()), Some(0.0));
2332    }
2333
2334    fn mc_string(out: &mut Vec<u8>, v: &str) {
2335        varint(out, v.len() as i32);
2336        out.extend_from_slice(v.as_bytes());
2337    }
2338
2339    /// `player_info` adding `(uuid, name, game mode)` entries (actions: add player, game mode).
2340    fn tab_add(t: &mut Tracker, entries: &[(u128, &str, i32)]) {
2341        let mut b = vec![0b101];
2342        varint(&mut b, entries.len() as i32);
2343        for &(u, name, gm) in entries {
2344            b.extend_from_slice(&u.to_be_bytes());
2345            mc_string(&mut b, name);
2346            varint(&mut b, 0); // no properties
2347            varint(&mut b, gm);
2348        }
2349        t.apply_body(id::PLAYER_INFO, &Bytes::from(b)).unwrap();
2350    }
2351
2352    fn tab_game_mode(t: &mut Tracker, u: u128, gm: i32) {
2353        let mut b = vec![0b100];
2354        varint(&mut b, 1);
2355        b.extend_from_slice(&u.to_be_bytes());
2356        varint(&mut b, gm);
2357        t.apply_body(id::PLAYER_INFO, &Bytes::from(b)).unwrap();
2358    }
2359
2360    fn tab_remove(t: &mut Tracker, u: u128) {
2361        let mut b = Vec::new();
2362        varint(&mut b, 1);
2363        b.extend_from_slice(&u.to_be_bytes());
2364        t.apply_body(id::PLAYER_REMOVE, &Bytes::from(b)).unwrap();
2365    }
2366
2367    /// What the entity and tab-list accessors answer, for comparing two trackers.
2368    fn tab_view(t: &Tracker) -> Vec<String> {
2369        let mut v = vec![format!("len {} tab {}", t.len(), t.tab_len())];
2370        for id in [10, 11, 12, 13] {
2371            v.push(match t.get(id) {
2372                Some(e) => format!(
2373                    "{id}: name {:?} sb {:?} gm {:?} spec {} pick {} ground {}",
2374                    t.player_name(id),
2375                    t.scoreboard_name(e),
2376                    t.game_mode(e),
2377                    t.is_spectator(e),
2378                    t.pickable(e),
2379                    e.on_ground()
2380                ),
2381                None => format!("{id}: none"),
2382            });
2383        }
2384        for u in [0x100A_u128, 0x100B, 0x100C, 0x100D] {
2385            let u = uuid::Uuid::from_u128(u);
2386            v.push(format!(
2387                "{u}: {:?} {:?}",
2388                t.tab_name(&u),
2389                t.tab_game_mode(&u)
2390            ));
2391        }
2392        v
2393    }
2394
2395    /// The names-only tab list answers every entity question the full list answers.
2396    #[test]
2397    fn names_only_tab_list_matches_the_full_one() {
2398        let long = "a_very_long_offline_mode_name_x";
2399        let full = Config::default().with_metadata(false);
2400        let lite = full.with_player_list(false).with_player_names(true);
2401        let mut views = Vec::new();
2402        for config in [full, lite] {
2403            let mut t = Tracker::new(config);
2404            assert!(t.wants(id::PLAYER_INFO) && t.wants(id::PLAYER_REMOVE));
2405            tab_add(&mut t, &[(0x100A, "Alice", 0), (0x100B, long, 1)]);
2406            spawn_with(&mut t, 10, data::PLAYER, &[]);
2407            spawn_with(&mut t, 11, data::PLAYER, &[]);
2408            // No tab entry: vanilla refuses the spawn.
2409            let mut b = Vec::new();
2410            varint(&mut b, 12);
2411            b.extend_from_slice(&0x100C_u128.to_be_bytes());
2412            varint(&mut b, i32::from(data::PLAYER));
2413            b.extend_from_slice(&[0; 28]);
2414            varint(&mut b, 0);
2415            t.apply_body(id::SPAWN_ENTITY, &Bytes::from(b)).unwrap();
2416            let mut steps = vec![tab_view(&t)];
2417            tab_game_mode(&mut t, 0x100A, 3);
2418            t.tick();
2419            steps.push(tab_view(&t));
2420            tab_remove(&mut t, 0x100A);
2421            tab_remove(&mut t, 0x100B);
2422            steps.push(tab_view(&t));
2423            // A new entry with the same UUID: the entity keeps its profile and old entry.
2424            tab_add(&mut t, &[(0x100A, "Bob", 0)]);
2425            t.tick();
2426            steps.push(tab_view(&t));
2427            views.push(steps);
2428        }
2429        for (a, b) in views[0].iter().zip(&views[1]) {
2430            assert_eq!(a, b);
2431        }
2432        let s = &views[1];
2433        assert!(s[0][3].contains("12: none"), "{:?}", s[0]);
2434        assert!(s[1][1].contains("spec true pick false"), "{:?}", s[1]);
2435        assert!(
2436            s[2][1].contains("sb Some(\"Alice\") gm Some(3)"),
2437            "{:?}",
2438            s[2]
2439        );
2440        assert!(s[2][2].contains(long), "{:?}", s[2]);
2441        assert!(
2442            s[3][1].contains("name Some(\"Bob\") sb Some(\"Alice\") gm Some(3)"),
2443            "{:?}",
2444            s[3]
2445        );
2446    }
2447
2448    /// Bytes per names-only tab entry (map slot, with the table's spare room at 100 entries).
2449    #[test]
2450    fn bytes_per_names_only_tab_entry() {
2451        let slot = std::mem::size_of::<(uuid::Uuid, crate::store::TabLite)>();
2452        let full = std::mem::size_of::<(uuid::Uuid, PlayerInfo)>();
2453        let mut t = Tracker::new(
2454            Config::default()
2455                .with_player_list(false)
2456                .with_player_names(true),
2457        );
2458        let names: Vec<String> = (0..100).map(|i| format!("Player_{i:04}")).collect();
2459        let entries: Vec<(u128, &str, i32)> = names
2460            .iter()
2461            .enumerate()
2462            .map(|(i, n)| (0x5000 + i as u128, n.as_str(), 0))
2463            .collect();
2464        tab_add(&mut t, &entries);
2465        assert_eq!(t.tab_len(), 100);
2466        assert!(t.store.long_names.is_empty() && t.store.players.is_empty());
2467        let buckets = (t.store.lite.capacity() * 8 / 7).next_power_of_two();
2468        let per = (buckets * (slot + 1) + 16) / 100;
2469        eprintln!(
2470            "names-only slot {slot} B (full list slot {full} B + heap), {per} B per entry at 100"
2471        );
2472        assert!(slot <= 48, "{slot}");
2473        assert!(per <= 64, "{per}");
2474    }
2475
2476    #[test]
2477    fn tick_order_renumbers_without_reordering() {
2478        let mut t = Tracker::new(Config::default());
2479        for id in [5, 3, 9] {
2480            t.start_ticking(id);
2481        }
2482        t.next_seq = u32::MAX - 2;
2483        t.start_ticking(1);
2484        t.start_ticking(7); // takes the last number: renumbers after
2485        let mut v: Vec<(u32, i32)> = t.order.iter().map(|(&i, &q)| (q, i)).collect();
2486        v.sort_unstable();
2487        assert_eq!(v, [(1, 5), (2, 3), (3, 9), (4, 1), (5, 7)]);
2488        t.start_ticking(3); // a member keeps its place
2489        assert_eq!(t.order[&3], 2);
2490    }
2491
2492    #[test]
2493    fn block_pos_unpacks() {
2494        let pack = |x: i64, y: i64, z: i64| {
2495            ((x & 0x3FF_FFFF) << 38) | ((z & 0x3FF_FFFF) << 12) | (y & 0xFFF)
2496        };
2497        assert_eq!(block_pos(pack(-5, 70, 123)), [-5, 70, 123]);
2498        assert_eq!(
2499            block_pos(pack(30_000_000, -64, -30_000_000)),
2500            [30_000_000, -64, -30_000_000]
2501        );
2502    }
2503}