ghast-entity 0.5.7

Entity tracking for the ghast Minecraft Java Edition client library: zero-allocation parsing of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 entity packets, vanilla-exact positions, O(1) lookup
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
//! 1.16.5 (protocol 754) entity tracking.
//!
//! Positions follow the vanilla client exactly: each entity keeps its "packet coordinates"
//! (`f64`). Spawns and teleports set them to the sent doubles; a relative move with delta `d`
//! on an axis computes `floor(x * 4096) + d` and divides by 4096 (`(double) l / 4096.0`), an
//! axis with delta 0 keeps its exact value. Velocities are `v / 8000.0` (double) except at mob
//! spawn (`(float) v / 8000.0F`). Angles are `(float)(b * 360) / 256.0F`. A boat the bot steers
//! (the bot is its first passenger) ignores relative moves and keeps only teleported packet
//! coordinates, like vanilla's `isControlledByLocalInstance` (other controllable vehicles are not
//! modelled).
//!
//! Every packet is parsed by hand from the body; movement packets touch no allocator.

use std::ops::Deref;

use bytes::Bytes;
use ghast_protocol::types::PositionLayout;
use ghast_protocol::types::slot::modern::Slot;
use ghast_protocol::v1_16_5::play::clientbound::{Login, Respawn, id};
use ghast_protocol::v1_16_5::types::Particle;
use ghast_protocol::{BlockPos, Decode, DecodeError, RawPacket, Reader};

use crate::Applied;
pub use crate::client16::ClientLerp;
use crate::common::{
    IdMask, R, angle, for_each_varint, modern_item, own_nbt, own_str, player_info,
};
use crate::common::{block_pos, remove_effect, set_effect, vel3};
use crate::entity::{Effect, Entity, EntityType, Item, MetaValue};
use crate::store::{Config, Entities, Event};

/// Spawn, movement, destroy, riding, pickup, status packets, plus `login` / `respawn`.
pub const CORE_IDS: &[i32] = &[
    id::LOGIN,
    id::RESPAWN,
    id::NAMED_ENTITY_SPAWN,
    id::SPAWN_ENTITY,
    id::SPAWN_ENTITY_LIVING,
    id::SPAWN_ENTITY_PAINTING,
    id::SPAWN_ENTITY_EXPERIENCE_ORB,
    id::ENTITY_VELOCITY,
    id::ENTITY_DESTROY,
    id::ENTITY,
    id::REL_ENTITY_MOVE,
    id::ENTITY_LOOK,
    id::ENTITY_MOVE_LOOK,
    id::ENTITY_TELEPORT,
    id::ENTITY_HEAD_ROTATION,
    id::ENTITY_STATUS,
    id::ATTACH_ENTITY,
    id::SET_PASSENGERS,
    id::COLLECT,
    id::ENTITY_METADATA,
];
/// `entity_metadata`. It is also in [`CORE_IDS`]: item entities need their stack for pickup
/// counts, so with [`Config::metadata`] off it is still read for item entities (and skipped
/// after the entity id for everything else).
pub const METADATA_IDS: &[i32] = &[id::ENTITY_METADATA];
/// `entity_equipment`.
pub const EQUIPMENT_IDS: &[i32] = &[id::ENTITY_EQUIPMENT];
/// `entity_effect`, `remove_entity_effect`.
pub const EFFECT_IDS: &[i32] = &[id::ENTITY_EFFECT, id::REMOVE_ENTITY_EFFECT];
/// `player_info`.
pub const PLAYER_LIST_IDS: &[i32] = &[id::PLAYER_INFO];
/// `animation` (arm swings, [`Event::Swing`]): wanted only with [`Config::events`].
pub const EVENT_IDS: &[i32] = &[id::ANIMATION];

/// Registry ids used by the tracker's rules.
mod ty {
    pub const BOAT: u16 = 6;
    pub const ITEM: u16 = 37;
    pub const ITEM_FRAME: u16 = 38;
}

/// 1.16.5 metadata indices.
pub mod meta {
    /// Entity flags byte (0x01 on fire, 0x02 crouching, 0x08 sprinting, 0x10 swimming,
    /// 0x20 invisible, 0x40 glowing, 0x80 elytra flying).
    pub const FLAGS: u8 = 0;
    /// Air (VarInt).
    pub const AIR: u8 = 1;
    /// Custom name (optional chat).
    pub const CUSTOM_NAME: u8 = 2;
    /// Custom name visible.
    pub const CUSTOM_NAME_VISIBLE: u8 = 3;
    /// Silent.
    pub const SILENT: u8 = 4;
    /// No gravity.
    pub const NO_GRAVITY: u8 = 5;
    /// Pose.
    pub const POSE: u8 = 6;
    /// Item entity: the item stack.
    pub const ITEM: u8 = 7;
    /// Living: hand states.
    pub const HAND_STATES: u8 = 7;
    /// Living: health (float).
    pub const HEALTH: u8 = 8;
}

/// The bot's entity view on a 1.16.5 connection. Dereferences to the shared [`Entities`].
#[derive(Clone, Debug)]
pub struct Tracker {
    store: Entities,
    world_name: String,
    wanted: IdMask,
    /// The client's own entity state ([`Tracker::track_client_motion`]).
    client: Option<Box<crate::client16::Client16>>,
    /// The bot holds the stick that steers a pig (bit 1: carrot on a stick) or a strider (bit 2:
    /// warped fungus on a stick) ([`Tracker::set_steering_items`]).
    steering: u8,
}

impl Deref for Tracker {
    type Target = Entities;
    fn deref(&self) -> &Entities {
        &self.store
    }
}

impl Tracker {
    /// An empty tracker.
    #[must_use]
    pub fn new(config: Config) -> Self {
        let mut wanted = IdMask::default();
        wanted.add(CORE_IDS);
        if config.equipment {
            wanted.add(EQUIPMENT_IDS);
        }
        if config.effects {
            wanted.add(EFFECT_IDS);
        }
        if config.reads_tab_list() {
            wanted.add(PLAYER_LIST_IDS);
        }
        if config.events {
            wanted.add(EVENT_IDS);
        }
        let mut t = Tracker {
            store: Entities {
                era: crate::entity::Era::V1_16,
                ..Entities::new(config)
            },
            world_name: String::new(),
            wanted,
            client: None,
            steering: 0,
        };
        if config.client_motion {
            t.track_client_motion(true);
        }
        t
    }

    /// What the bot holds in either hand, as far as it steers a mount: a carrot on a stick
    /// (pigs) and a warped fungus on a stick (striders). A pig or strider the bot rides as its
    /// first passenger ignores position packets while it holds the stick (the client moves it);
    /// horses, donkeys, mules, skeleton and zombie horses always do, llamas never.
    pub fn set_steering_items(&mut self, carrot_on_a_stick: bool, warped_fungus_on_a_stick: bool) {
        self.steering = u8::from(carrot_on_a_stick) | u8::from(warped_fungus_on_a_stick) << 1;
    }

    /// Keeps the vanilla client's own view of the entities from now on (off by default): the
    /// client world's tick order ([`Tracker::ticks_before_self`]), the positions the client
    /// interpolates to and the boxes it holds ([`Tracker::client_box`]), each player's profile
    /// name and the living entities' health. What the local player's pushes and entity
    /// collisions read (`ghast-physics` `v1_16_5::push_by`); see the `client16` notes in the
    /// crate docs for what is not modelled. Turn it on before the login packet: the tick order
    /// depends on every entity id the client world has held.
    pub fn track_client_motion(&mut self, on: bool) {
        if on == self.client.is_some() {
            return;
        }
        self.client = on.then(|| {
            let mut c = Box::<crate::client16::Client16>::default();
            c.new_world(self.store.self_id);
            for e in self.store.map.values() {
                c.map.insert(e.id);
                c.spawned(e, None);
            }
            c
        });
        self.store.set_client_motion(on);
        if let Some(c) = &self.client {
            let ids: Vec<i32> = self.store.map.keys().copied().collect();
            for id in ids {
                mirror(&mut self.store, c, id);
            }
        }
    }

    /// `true` while [`Tracker::track_client_motion`] is on.
    #[must_use]
    pub fn tracks_client_motion(&self) -> bool {
        self.client.is_some()
    }

    /// The position the vanilla client holds for entity `id` (interpolated; `None` without
    /// [`Tracker::track_client_motion`] or for types the client view does not keep: only living
    /// entities, boats and shulkers).
    #[must_use]
    pub fn client_position(&self, id: i32) -> Option<[f64; 3]> {
        self.client.as_ref()?.motion.get(&id).map(|m| m.pos)
    }

    /// The interpolation the vanilla client holds for entity `id`: its rotation, the target
    /// position and rotation and the steps left (see [`Tracker::client_position`]).
    #[must_use]
    pub fn client_interpolation(&self, id: i32) -> Option<ClientLerp> {
        self.client
            .as_ref()?
            .motion
            .get(&id)
            .map(|m| m.lerp_state())
    }

    /// `isOnGround` of the vanilla client's copy of entity `id` (the last move packet's flag, or
    /// where a move the client made itself left it; see [`Tracker::client_position`]).
    #[must_use]
    pub fn client_on_ground(&self, id: i32) -> Option<bool> {
        self.client.as_ref()?.motion.get(&id).map(|m| m.on_ground)
    }

    /// A move the vanilla client makes itself on entity `id` (a moving block pushes it with
    /// `Entity.move`): its new position, box `[min_x, min_y, min_z, max_x, max_y, max_z]` and
    /// ground state. The client view interpolates on from there toward the server's position.
    /// `false` when the client view does not keep the entity.
    pub fn client_pushed(&mut self, id: i32, pos: [f64; 3], bb: [f64; 6], on_ground: bool) -> bool {
        let Some(c) = &mut self.client else {
            return false;
        };
        if !c.pushed(id, pos, bb, on_ground) {
            return false;
        }
        mirror(&mut self.store, c, id);
        true
    }

    /// The client ran entity `id`'s own tick itself, or a packet handler changed its client copy
    /// differently from the packet coordinates (the client-side physics of a projectile, item,
    /// experience orb, primed TNT or falling block, `ghast_physics::v1_16_5`): its position,
    /// motion ([`Entity::velocity`] is then the client copy's `getVelocity`), rotation and ground
    /// flag become the client's. From then on [`Entity::position`] is the client's position; the
    /// tracked position relative moves add to is kept apart (`getTrackedPosition`, see
    /// [`Entity::traced`]), and a move or teleport packet still puts the entity at the new tracked
    /// position as vanilla's `updateTrackedPositionAndAngles` does. `false`: not tracked (or our
    /// own entity).
    pub fn client_simulated(
        &mut self,
        id: i32,
        pos: [f64; 3],
        vel: [f64; 3],
        rot: [f32; 2],
        on_ground: bool,
    ) -> bool {
        if Some(id) == self.store.self_id {
            return false;
        }
        let Some(e) = self.store.map.get_mut(&id) else {
            return false;
        };
        if e.bits & Entity::SIMULATED == 0 {
            e.traced = e.pos.map(|c| c.to_bits() as i64);
            e.bits |= Entity::SIMULATED;
        }
        e.pos = pos;
        e.velocity = vel;
        e.yaw = rot[0];
        e.pitch = rot[1];
        e.on_ground = on_ground;
        true
    }

    /// The client's own tick discarded entity `id` (a primed TNT whose fuse ran out, a fishing
    /// bobber without its player owner, a falling block of air): it leaves the client world as in
    /// vanilla, with a [`Event::Removed`] when events are on. `false`: not tracked (or our own
    /// entity).
    pub fn client_discarded(&mut self, id: i32) -> bool {
        if Some(id) == self.store.self_id {
            return false;
        }
        if let Some(c) = self.client.as_deref_mut() {
            c.remove(id);
        }
        self.store.remove(id)
    }

    /// The bot moved the vehicle it drives (entity `id`, the client moves it): its new position,
    /// box `[min_x, min_y, min_z, max_x, max_y, max_z]` and yaw. The vehicle's other passengers
    /// are seated from there (a boat's seats) and `tracked` (the boat's position when its tick
    /// began) becomes its packet position ([`Entity::position`]). Call it after the bot's tick; `false` when the client view does
    /// not keep the entity.
    pub fn client_vehicle_moved(
        &mut self,
        id: i32,
        pos: [f64; 3],
        bb: [f64; 6],
        yaw: f32,
        tracked: [f64; 3],
    ) -> bool {
        let Some(c) = &mut self.client else {
            return false;
        };
        if !c.vehicle_moved(&mut self.store, id, pos, bb, yaw) {
            return false;
        }
        mirror(&mut self.store, c, id);
        // BoatEntity.method_7555: a boat the client moves is its own tracked position (where
        // it was when its tick began; what the server's relative moves add to once another
        // passenger drives it).
        if let Some(e) = self.store.map.get_mut(&id) {
            e.pos = tracked;
        }
        true
    }

    /// The bot got off vehicle `id` by itself (the 1.16.5 client's own dismount on sneak,
    /// `stopRiding`): the client's passenger list of the vehicle no longer has it, so the other
    /// passengers' seats change at once (the server's set-passengers packet comes later).
    pub fn self_dismounted(&mut self, id: i32) {
        let Some(me) = self.store.self_id else { return };
        let Some(v) = self.store.map.get(&id) else {
            return;
        };
        if !v.passengers().contains(&me) {
            return;
        }
        let rest: Vec<i32> = v
            .passengers()
            .iter()
            .copied()
            .filter(|&p| p != me)
            .collect();
        self.store.set_passengers(id, rest.into_iter());
    }

    /// Where the client world files the bot's own player: `pos` is its position after its last
    /// tick (`checkEntityChunkPos`; a new section puts it at the end of that section's list, see
    /// [`Tracker::search_order`]). Call it once per client tick before [`Tracker::tick_client`].
    pub fn self_filed(&mut self, pos: [f64; 3]) {
        if let (Some(c), Some(me)) = (&mut self.client, self.store.self_id) {
            c.self_filed(me, pos);
        }
    }

    /// The client view's search order of entity `id` (see [`Entity::search_order`]).
    #[must_use]
    pub fn search_order(&self, id: i32) -> Option<(i32, i32, i32, u32)> {
        self.client.as_ref()?.search_order(id)
    }

    /// `getStandingEyeHeight()` of the vanilla client's copy of entity `id`: the eye height of
    /// the pose its entity data set (a player: crouching 1.27, swimming / gliding 0.4, ...; see
    /// [`Tracker::client_position`]).
    #[must_use]
    pub fn client_eye_height(&self, id: i32) -> Option<f32> {
        let e = self.store.map.get(&id)?;
        let d = self.client.as_ref()?.motion.get(&id)?.dimensions(e)?;
        Some(d.eye_height)
    }

    /// The bounding box the vanilla client holds for entity `id` (see
    /// [`Tracker::client_position`]), `[min_x, min_y, min_z, max_x, max_y, max_z]`.
    #[must_use]
    pub fn client_box(&self, id: i32) -> Option<[f64; 6]> {
        self.client.as_ref()?.motion.get(&id).map(|m| m.bb)
    }

    /// `isAlive` as far as the client view knows it: `false` once the last health the server
    /// sent a living entity is not above 0 (`true` without the client view).
    #[must_use]
    pub fn client_alive(&self, id: i32) -> bool {
        self.client
            .as_ref()
            .and_then(|c| c.motion.get(&id))
            .is_none_or(|m| !m.dead)
    }

    /// `true` when entity `id` ticks before the bot's own player in the client world's tick
    /// order (needs [`Tracker::track_client_motion`]).
    #[must_use]
    pub fn ticks_before_self(&self, id: i32) -> bool {
        match (&self.client, self.store.self_id) {
            (Some(c), Some(me)) => c.map.before(id, me),
            _ => false,
        }
    }

    /// Entity `id`'s place in the client world's tick order as a sort key (smaller ticks
    /// earlier; `None` when the client world does not hold it or without
    /// [`Tracker::track_client_motion`]).
    #[must_use]
    pub fn client_tick_rank(&self, id: i32) -> Option<u32> {
        self.client.as_ref()?.map.rank(id)
    }

    /// The client world's tick order: every entity id the client world holds, the bot's own
    /// included (empty without [`Tracker::track_client_motion`]).
    pub fn client_tick_order(&self) -> impl Iterator<Item = i32> + '_ {
        self.client.iter().flat_map(|c| c.map.order())
    }

    /// One client tick of the client view (`ClientWorld.tickEntities`): every kept entity that
    /// ticks takes one interpolation step. `column_loaded(chunk_x, chunk_z)` says which columns
    /// the client has (an entity elsewhere does not tick; players always do). Passengers are
    /// left alone. Call it once per client tick, where the bot's world ticks its entities.
    pub fn tick_client(&mut self, column_loaded: impl Fn(i32, i32) -> bool) {
        let Some(c) = &mut self.client else { return };
        c.tick(&mut self.store, |_, p| {
            column_loaded(chunk(p[0]), chunk(p[2]))
        });
    }

    /// `true` when the client would tick `e` this tick: not riding, and a player or in a
    /// loaded column (`ClientChunkManager.shouldTickEntity` at its client position).
    #[must_use]
    pub fn client_ticks(&self, e: &Entity, column_loaded: impl Fn(i32, i32) -> bool) -> bool {
        !e.rides()
            && (e.is_player()
                || match self.client_position(e.id) {
                    Some(p) => column_loaded(chunk(p[0]), chunk(p[2])),
                    None => entity_ticks_at(e, &column_loaded),
                })
    }

    /// `isSpectator` of a player entity: its tab-list game mode is spectator (needs the tab
    /// list or [`Config::player_names`]).
    #[must_use]
    pub fn is_spectator(&self, e: &Entity) -> bool {
        e.is_player() && self.store.tab_game_mode(&e.uuid) == Some(3)
    }

    /// `getEntityName`, what team rules match: a player's profile name (from the tab-list
    /// entry it spawned with; needs [`Tracker::track_client_motion`] and the tab list or
    /// [`Config::player_names`]), else `None`; vanilla uses the UUID string for other entities.
    #[must_use]
    pub fn scoreboard_name(&self, e: &Entity) -> Option<&str> {
        if !e.is_player() {
            return None;
        }
        self.client.as_ref()?.motion.get(&e.id)?.name.as_deref()
    }

    /// The shared store, mutable for [`Entities::drain_events`].
    pub fn store_mut(&mut self) -> &mut Entities {
        &mut self.store
    }

    /// `true` when this tracker wants packet `id` (for a `PacketFilter`).
    #[inline]
    #[must_use]
    pub fn wants(&self, id: i32) -> bool {
        self.wanted.contains(id)
    }

    /// Every packet id this tracker wants.
    pub fn packet_ids(&self) -> impl Iterator<Item = i32> + '_ {
        self.wanted.iter()
    }

    /// Applies one clientbound play packet.
    ///
    /// # Errors
    /// A malformed body (multi-entry packets may be partly applied).
    pub fn apply(&mut self, raw: &RawPacket) -> Result<Applied, DecodeError> {
        self.apply_body(raw.id, &raw.body)
    }

    /// [`Tracker::apply`] with the packet id and body.
    ///
    /// # Errors
    /// See [`Tracker::apply`].
    pub fn apply_body(&mut self, packet_id: i32, body: &Bytes) -> Result<Applied, DecodeError> {
        if !self.wants(packet_id) {
            return Ok(Applied::NotEntityPacket);
        }
        let r = &mut Reader::new(body);
        let s = &mut self.store;
        let mut client = self.client.as_deref_mut();
        let st = self.steering;
        let changed = match packet_id {
            id::REL_ENTITY_MOVE => relative(s, client, r, true, false, st)?,
            id::ENTITY_MOVE_LOOK => relative(s, client, r, true, true, st)?,
            id::ENTITY_LOOK => relative(s, client, r, false, true, st)?,
            id::ENTITY => relative(s, client, r, false, false, st)?,
            id::ENTITY_TELEPORT => teleport(s, client, r, st)?,
            id::ENTITY_VELOCITY => {
                let eid = r.read_varint()?;
                let v = vel3(r)?;
                match s.map.get_mut(&eid) {
                    Some(e) => {
                        e.velocity = v.map(|c| f64::from(c) / 8000.0);
                        s.event(Event::Velocity(eid));
                        true
                    }
                    None => false,
                }
            }
            id::ENTITY_HEAD_ROTATION => {
                let eid = r.read_varint()?;
                let b = r.read_i8()?;
                match s.map.get_mut(&eid) {
                    Some(e) => {
                        e.head_yaw = angle(b);
                        true
                    }
                    None => false,
                }
            }
            id::ENTITY_DESTROY => {
                let mut any = false;
                for_each_varint(r, |eid| {
                    if let Some(c) = client.as_deref_mut()
                        && Some(eid) != s.self_id
                    {
                        c.remove(eid);
                    }
                    any |= s.remove(eid);
                })?;
                any
            }
            id::ANIMATION => {
                let eid = r.read_varint()?;
                let action = r.read_u8()?;
                if (action == 0 || action == 3) && s.map.contains_key(&eid) {
                    s.event(Event::Swing {
                        id: eid,
                        off_hand: action == 3,
                    });
                }
                false
            }
            id::ENTITY_STATUS => {
                let eid = r.read_i32()?;
                let status = r.read_i8()?;
                let keep = s.config.metadata;
                let known = match s.map.get_mut(&eid) {
                    Some(e) => {
                        // LivingEntity.handleEntityEvent(3): setHealth(0), die.
                        if status == 3 && e.living {
                            e.mark_dead();
                            if keep {
                                e.meta.set(meta::HEALTH, MetaValue::Float(0.0));
                            }
                        }
                        true
                    }
                    None => false,
                };
                if known {
                    s.event(Event::Status { id: eid, status });
                    // LivingEntity.handleStatus: 2 hurt, 33 thorns, 36 drowning, 37 burning,
                    // 44 sweet berry bush.
                    if matches!(status, 2 | 33 | 36 | 37 | 44) {
                        s.hurt(eid, None);
                    }
                }
                known
            }
            id::NAMED_ENTITY_SPAWN => {
                let mut e = Entity::new(r.read_varint()?, EntityType::Player);
                e.uuid = r.read_uuid()?;
                e.pos = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
                e.yaw = angle(r.read_i8()?);
                e.pitch = angle(r.read_i8()?);
                e.head_yaw = e.yaw;
                // The client builds the player from its tab-list entry (none: the spawn fails).
                let name = s.tab_name(&e.uuid).map(Box::<str>::from);
                let listed = name.is_some() || !s.config.reads_tab_list();
                let eid = e.id;
                s.spawn(e);
                if listed {
                    client_spawned(s, client, eid, name);
                }
                true
            }
            id::SPAWN_ENTITY => {
                let eid = r.read_varint()?;
                let uuid = r.read_uuid()?;
                let t = r.read_varint()?;
                let pos = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
                let pitch = r.read_i8()?;
                let yaw = r.read_i8()?;
                let data = r.read_i32()?;
                let v = vel3(r)?;
                let Some(t) = known_type(t) else {
                    return Ok(Applied::Ignored);
                };
                let mut e = Entity::new(eid, EntityType::Registry(t));
                e.uuid = uuid;
                e.pos = pos;
                e.pitch = angle(pitch);
                e.yaw = angle(yaw);
                e.head_yaw = e.yaw;
                e.data = data;
                e.velocity = v.map(|c| f64::from(c) / 8000.0);
                // Item frames (38) and leash knots (40) hang on the block of the position.
                if t == 38 || t == 40 {
                    // Their tracked position is the packet's (a later move starts from there).
                    e.traced = e.pos.map(|c| c.to_bits() as i64);
                    let b = e.pos.map(|c| c.floor() as i32);
                    e.pos = if t == 40 {
                        crate::hanging::knot_1_8(b)
                    } else {
                        crate::hanging::frame_1_16(b, data)
                    };
                }
                s.spawn(e);
                client_spawned(s, client, eid, None);
                true
            }
            id::SPAWN_ENTITY_LIVING => {
                let eid = r.read_varint()?;
                let uuid = r.read_uuid()?;
                let t = r.read_varint()?;
                let pos = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
                let yaw = r.read_i8()?;
                let pitch = r.read_i8()?;
                let head = r.read_i8()?;
                let v = vel3(r)?;
                let Some(t) = known_type(t) else {
                    return Ok(Applied::Ignored);
                };
                let mut e = Entity::new(eid, EntityType::Registry(t));
                e.living = true;
                e.uuid = uuid;
                e.pos = pos;
                e.yaw = angle(yaw);
                // `updatePositionAndAngles` clamps the pitch to ±90.
                e.pitch = angle(pitch).clamp(-90.0, 90.0);
                e.head_yaw = angle(head);
                e.velocity = v.map(|c| f64::from(f32::from(c) / 8000.0));
                s.spawn(e);
                client_spawned(s, client, eid, None);
                true
            }
            id::SPAWN_ENTITY_EXPERIENCE_ORB => {
                let mut e = Entity::new(r.read_varint()?, EntityType::Registry(24));
                e.pos = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
                e.data = i32::from(r.read_i16()?);
                let eid = e.id;
                s.spawn(e);
                client_spawned(s, client, eid, None);
                true
            }
            id::SPAWN_ENTITY_PAINTING => {
                let eid = r.read_varint()?;
                let uuid = r.read_uuid()?;
                let motive = r.read_varint()?;
                let p = BlockPos::read(r, PositionLayout::Xzy)?;
                let dir = r.read_u8()?;
                let mut e = Entity::new(eid, EntityType::Registry(55));
                e.uuid = uuid;
                e.data = i32::from(dir) | i32::from(crate::hanging::motive_1_16(motive)) << 8;
                // `setFacing`: turned to the facing; its tracked position stays at the origin
                // (the spawn handler never sets it).
                e.yaw = f32::from(dir % 4) * 90.0;
                // Where it hangs (on the block, facing `dir`).
                e.pos = crate::hanging::attach_1_8(&e, [p.x, p.y, p.z], e.data).unwrap_or([
                    f64::from(p.x),
                    f64::from(p.y),
                    f64::from(p.z),
                ]);
                s.spawn(e);
                client_spawned(s, client, eid, None);
                true
            }
            id::ATTACH_ENTITY => {
                let eid = r.read_i32()?;
                let holder = r.read_i32()?;
                s.leash(eid, (holder != 0).then_some(holder))
            }
            id::SET_PASSENGERS => {
                let vehicle = r.read_varint()?;
                // Validate the list first so a bad packet changes nothing.
                let start = r.position();
                for_each_varint(r, |_| {})?;
                let mut again = Reader::new(body);
                again.skip(start)?;
                if !s.map.contains_key(&vehicle) {
                    return Ok(Applied::Ignored);
                }
                let n = again.read_varint()?.max(0);
                let ids = (0..n).map_while(|_| again.read_varint().ok());
                s.set_passengers(vehicle, ids)
            }
            id::COLLECT => {
                let collected = r.read_varint()?;
                let collector = r.read_varint()?;
                let amount = r.read_varint()?;
                match s.map.get_mut(&collected) {
                    None => false,
                    Some(e) => {
                        let is_item = e.ty == EntityType::Registry(ty::ITEM);
                        let held = is_item
                            .then(|| item(e).map(|i| (i.id, i32::from(i.count))))
                            .flatten();
                        let gone = if is_item {
                            shrink_item(e, amount)
                        } else {
                            true
                        };
                        s.picked_up(collected, collector, Some(amount), held, gone);
                        if gone {
                            s.remove(collected);
                            if let Some(c) = client {
                                c.remove(collected);
                            }
                        }
                        true
                    }
                }
            }
            id::ENTITY_METADATA => {
                let eid = r.read_varint()?;
                let wanted = match s.map.get(&eid) {
                    None => false,
                    // Without metadata tracking, item entities still need their stack for
                    // pickup counts, item frames theirs for a right click (entry 7 too).
                    Some(e) => {
                        s.config.metadata
                            || matches!(e.ty, EntityType::Registry(ty::ITEM | ty::ITEM_FRAME))
                    }
                };
                // The client view reads the size, health and attachment entries.
                let viewed = client.as_ref().is_some_and(|c| c.motion.contains_key(&eid));
                if !wanted && !viewed {
                    return Ok(Applied::Ignored);
                }
                let mut scratch = std::mem::take(&mut s.scratch);
                scratch.clear();
                let res = read_metadata(r, &mut scratch);
                if res.is_ok()
                    && viewed
                    && let Some(c) = client
                    && let Some(e) = s.map.get(&eid)
                {
                    c.data(e, &scratch);
                    mirror(s, c, eid);
                }
                if res.is_ok()
                    && wanted
                    && let Some(e) = s.map.get_mut(&eid)
                {
                    let all = s.config.metadata;
                    e.meta.set_from(&mut scratch, |i| all || i == meta::ITEM);
                    s.event(Event::Metadata(eid));
                }
                s.scratch = scratch;
                res?;
                true
            }
            id::ENTITY_EQUIPMENT => {
                let eid = r.read_varint()?;
                // Parse the whole list before touching the entity.
                let mut list: [Option<(usize, Option<Item>)>; 8] = Default::default();
                let mut n = 0;
                loop {
                    let b = r.read_u8()?;
                    let item = modern_item(Slot::decode(r)?);
                    if n < list.len() {
                        list[n] = Some((usize::from(b & 0x7F), item));
                        n += 1;
                    }
                    if b & 0x80 == 0 {
                        break;
                    }
                }
                match s.map.get_mut(&eid) {
                    Some(e) => {
                        let eq = e.equipment.get_or_insert_with(Default::default);
                        for (slot, item) in list.into_iter().flatten() {
                            if let Some(dst) = eq.get_mut(slot) {
                                *dst = item;
                            }
                        }
                        s.event(Event::Equipment(eid));
                        true
                    }
                    None => false,
                }
            }
            id::ENTITY_EFFECT => {
                let eid = r.read_varint()?;
                let effect = Effect {
                    id: r.read_i8()? as u8,
                    amplifier: r.read_i8()?,
                    duration: r.read_varint()?,
                    flags: r.read_i8()? as u8,
                };
                set_effect(s, eid, effect)
            }
            id::REMOVE_ENTITY_EFFECT => {
                let eid = r.read_varint()?;
                let eff = r.read_i8()? as u8;
                remove_effect(s, eid, eff)
            }
            id::PLAYER_INFO => {
                player_info(s, r)?;
                true
            }
            id::LOGIN => {
                let p = Login::decode(r)?;
                s.clear();
                s.set_self(p.entity_id);
                self.world_name = p.world_name.to_string();
                // A new client world holding the new player.
                if let Some(c) = client {
                    c.new_world(Some(p.entity_id));
                }
                true
            }
            id::RESPAWN => {
                let p = Respawn::decode(r)?;
                // A new player entity: effects reset, metadata is copied over by vanilla.
                if let Some(me) = s.self_id.and_then(|i| s.map.get_mut(&i)) {
                    me.clear_effects();
                    me.equipment = None;
                }
                if *p.world_name != *self.world_name {
                    s.clear();
                    self.world_name = p.world_name.to_string();
                    if let Some(c) = client {
                        c.new_world(s.self_id);
                    }
                } else if let (Some(c), Some(me)) = (client, s.self_id) {
                    // The same world: the new player replaces the old one (`addEntityPrivate`).
                    c.map.remove(me);
                    c.map.insert(me);
                }
                true
            }
            _ => return Ok(Applied::NotEntityPacket),
        };
        Ok(if changed {
            Applied::Changed
        } else {
            Applied::Ignored
        })
    }
}

/// 1.16.5 health of a living entity.
#[must_use]
pub fn health(e: &Entity) -> Option<f32> {
    e.metadata().float(meta::HEALTH)
}

/// 1.16.5 item of an item entity or of an item frame (kept for both without
/// [`Config::metadata`]).
#[must_use]
pub fn item(e: &Entity) -> Option<&Item> {
    e.metadata().item(meta::ITEM).flatten()
}

/// 1.16.5 entity flags byte (0 when unknown).
#[must_use]
pub fn flags(e: &Entity) -> u8 {
    e.metadata().byte(meta::FLAGS).unwrap_or(0) as u8
}

/// 1.16.5 custom name (raw chat JSON).
#[must_use]
pub fn custom_name(e: &Entity) -> Option<&str> {
    match e.metadata().get(meta::CUSTOM_NAME)? {
        MetaValue::OptChat(Some(s)) => Some(s),
        _ => None,
    }
}

/// Static type information from ghast-data (players: `player`).
#[must_use]
pub fn info(t: EntityType) -> Option<&'static ghast_data::EntityInfo> {
    let id = match t {
        EntityType::Registry(id) => id,
        EntityType::Player => 106,
        _ => return None,
    };
    ghast_data::v1_16_5::entities().iter().find(|e| e.id == id)
}

fn known_type(t: i32) -> Option<u16> {
    let t = u16::try_from(t).ok()?;
    ghast_data::v1_16_5::entities()
        .iter()
        .any(|e| e.id == t)
        .then_some(t)
}

/// Vanilla `ItemEntity` pickup: the stack shrinks by `amount`; the entity goes when empty
/// (an unknown stack counts as empty, like vanilla's default empty stack).
fn shrink_item(e: &mut Entity, amount: i32) -> bool {
    let Some(MetaValue::Item(Some(it))) = e
        .meta
        .entries_mut()
        .find(|(i, _)| *i == meta::ITEM)
        .map(|(_, v)| v)
    else {
        return true;
    };
    let left = i32::from(it.count) - amount.max(0);
    if left <= 0 {
        return true;
    }
    it.count = left as i8;
    false
}

/// `lfloor(x * 4096)` (`EntityS2CPacket.encodePacketCoordinate`): the cast saturates like
/// Java's (NaN gives 0) and the `- 1` wraps like Java's `long` arithmetic, so a coordinate
/// below `i64::MIN / 4096` encodes to `i64::MAX` as in vanilla instead of overflowing.
#[inline]
fn encode(x: f64) -> i64 {
    let d = x * 4096.0;
    let l = d as i64;
    if d < l as f64 { l.wrapping_sub(1) } else { l }
}

#[inline]
fn axis(x: f64, d: i16) -> f64 {
    if d == 0 {
        x
    } else {
        encode(x).wrapping_add(i64::from(d)) as f64 / 4096.0
    }
}

/// `true` when the bot steers `vehicle` as its first passenger (`isLogicalSideForUpdatingMovement`):
/// a boat, a horse-family mount other than a llama, a pig or strider while the bot holds its
/// stick (`steering`, see [`Tracker::set_steering_items`]).
fn controlled(s: &Entities, e: &Entity, steering: u8) -> bool {
    if s.self_id.is_none() || e.passengers().first().copied() != s.self_id {
        return false;
    }
    if e.ty == EntityType::Registry(ty::BOAT) {
        return true;
    }
    match info(e.ty).map(|i| i.name) {
        Some("horse" | "donkey" | "mule" | "skeleton_horse" | "zombie_horse") => true,
        Some("pig") => steering & 1 != 0,
        Some("strider") => steering & 2 != 0,
        _ => false,
    }
}

/// The client view's side of a spawn: `addEntityPrivate` and the spawn position.
fn client_spawned(
    s: &mut Entities,
    client: Option<&mut crate::client16::Client16>,
    id: i32,
    name: Option<Box<str>>,
) {
    let Some(c) = client else { return };
    if Some(id) == s.self_id {
        return;
    }
    let Some(e) = s.map.get(&id) else { return };
    c.add(id);
    c.spawned(e, name);
    mirror(s, c, id);
}

/// Copies the client view's position and box of `id` into its drawn state
/// ([`Entity::drawn_position`]).
fn mirror(s: &mut Entities, c: &crate::client16::Client16, id: i32) {
    let Some(cl) = s.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) else {
        return;
    };
    if let Some((p, b)) = c.drawn(id) {
        cl.pos = p;
        cl.bb = Some(b);
    }
}

#[inline]
fn relative(
    s: &mut Entities,
    client: Option<&mut crate::client16::Client16>,
    r: &mut Reader<'_>,
    pos: bool,
    look: bool,
    steering: u8,
) -> R<bool> {
    let eid = r.read_varint()?;
    let d = if pos {
        [r.read_i16()?, r.read_i16()?, r.read_i16()?]
    } else {
        [0; 3]
    };
    let rot = if look {
        Some((r.read_i8()?, r.read_i8()?))
    } else {
        None
    };
    let on_ground = if pos || look { r.read_bool()? } else { false };
    if Some(eid) == s.self_id {
        return Ok(false);
    }
    let Some(e) = s.map.get(&eid) else {
        return Ok(false);
    };
    if controlled(s, e, steering) {
        return Ok(false);
    }
    let now = s.now;
    let Some(e) = s.map.get_mut(&eid) else {
        return Ok(false);
    };
    if crate::hanging::is_hanging(e) {
        return Ok(hanging_moved(
            s,
            client,
            eid,
            pos.then_some(d),
            None,
            rot,
            on_ground,
        ));
    }
    if pos {
        // `calculateDeltaPosition(getTrackedPosition())`; the entity moves to the new tracked
        // position (a client-simulated one keeps the tracked position apart from its own).
        if e.bits & Entity::SIMULATED == 0 {
            e.pos = [
                axis(e.pos[0], d[0]),
                axis(e.pos[1], d[1]),
                axis(e.pos[2], d[2]),
            ];
        } else {
            let t = e.traced.map(|b| f64::from_bits(b as u64));
            e.pos = [axis(t[0], d[0]), axis(t[1], d[1]), axis(t[2], d[2])];
            e.traced = e.pos.map(|c| c.to_bits() as i64);
        }
    }
    if let Some((y, p)) = rot {
        e.yaw = angle(y);
        e.pitch = angle(p);
    }
    e.on_ground = on_ground;
    // External: never interpolates here (the client view does).
    let _ = crate::drawn::relative(e, look, now);
    if let Some(c) = client {
        let r = rot.map(|_| [e.yaw, e.pitch]);
        if pos {
            c.moved(eid, e.pos, r);
        } else if let Some(r) = r {
            c.looked(eid, r);
        }
        c.ground(eid, on_ground);
    }
    s.event(Event::Moved(eid));
    Ok(true)
}

/// A position packet for a painting, item frame or leash knot: the tracked position moves (by
/// the relative move `d`, or to the teleport's `to`), then the entity hangs where
/// [`crate::hanging::tracked_move`] puts it; a look turns it (a painting never turns).
#[cold]
#[inline(never)]
fn hanging_moved(
    s: &mut Entities,
    client: Option<&mut crate::client16::Client16>,
    eid: i32,
    d: Option<[i16; 3]>,
    to: Option<[f64; 3]>,
    rot: Option<(i8, i8)>,
    on_ground: bool,
) -> bool {
    let Some(e) = s.map.get_mut(&eid) else {
        return false;
    };
    let t = e.traced.map(|b| f64::from_bits(b as u64));
    let t = match (d, to) {
        (_, Some(p)) => Some(p),
        (Some(d), None) => Some([axis(t[0], d[0]), axis(t[1], d[1]), axis(t[2], d[2])]),
        (None, None) => None,
    };
    if let Some(t) = t {
        e.traced = t.map(|c| c.to_bits() as i64);
        crate::hanging::tracked_move(e, t);
    }
    if let Some((y, p)) = rot
        && !crate::hanging::is_painting(e)
    {
        e.yaw = angle(y);
        e.pitch = angle(p);
    }
    e.on_ground = on_ground;
    if let Some(c) = client
        && t.is_some()
    {
        // Not interpolated: its section is checked at its next tick.
        c.moved(eid, e.pos, None);
    }
    s.event(Event::Moved(eid));
    true
}

fn teleport(
    s: &mut Entities,
    client: Option<&mut crate::client16::Client16>,
    r: &mut Reader<'_>,
    steering: u8,
) -> R<bool> {
    let eid = r.read_varint()?;
    let p = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
    let (y, pi) = (r.read_i8()?, r.read_i8()?);
    let on_ground = r.read_bool()?;
    if Some(eid) == s.self_id {
        return Ok(false);
    }
    let Some(e) = s.map.get(&eid) else {
        return Ok(false);
    };
    let ctl = controlled(s, e, steering);
    let now = s.now;
    let Some(e) = s.map.get_mut(&eid) else {
        return Ok(false);
    };
    if crate::hanging::is_hanging(e) {
        return Ok(hanging_moved(
            s,
            client,
            eid,
            None,
            Some(p),
            Some((y, pi)),
            on_ground,
        ));
    }
    // Packet coordinates are set even for a vehicle the bot controls.
    e.pos = p;
    if e.bits & Entity::SIMULATED != 0 {
        e.traced = p.map(|c| c.to_bits() as i64);
    }
    if !ctl {
        let _ = crate::drawn::teleport(e, now);
        e.yaw = angle(y);
        e.pitch = angle(pi);
        e.on_ground = on_ground;
        if let Some(c) = client {
            c.moved(eid, p, Some([e.yaw, e.pitch]));
            c.ground(eid, on_ground);
        }
    }
    s.event(Event::Moved(eid));
    Ok(true)
}

/// 1.16 metadata: index byte (`0xFF` ends), VarInt serializer id, value.
fn read_metadata(r: &mut Reader<'_>, out: &mut Vec<(u8, MetaValue)>) -> R<()> {
    loop {
        let index = r.read_u8()?;
        if index == 0xFF {
            return Ok(());
        }
        let v = match r.read_varint()? {
            0 => MetaValue::Byte(r.read_i8()?),
            1 => MetaValue::VarInt(r.read_varint()?),
            2 => MetaValue::Float(r.read_f32()?),
            3 => MetaValue::String(own_str(r)?),
            4 => MetaValue::Chat(own_str(r)?),
            5 => MetaValue::OptChat(if r.read_bool()? {
                Some(own_str(r)?)
            } else {
                None
            }),
            6 => MetaValue::Item(modern_item(Slot::decode(r)?)),
            7 => MetaValue::Bool(r.read_bool()?),
            8 => MetaValue::Rotation([r.read_f32()?, r.read_f32()?, r.read_f32()?]),
            9 => MetaValue::BlockPos(block_pos(BlockPos::read(r, PositionLayout::Xzy)?)),
            10 => MetaValue::OptBlockPos(if r.read_bool()? {
                Some(block_pos(BlockPos::read(r, PositionLayout::Xzy)?))
            } else {
                None
            }),
            11 => MetaValue::Direction(r.read_varint()?),
            12 => MetaValue::OptUuid(if r.read_bool()? {
                Some(r.read_uuid()?)
            } else {
                None
            }),
            13 => MetaValue::BlockState(r.read_varint()?),
            14 => MetaValue::Nbt(
                own_nbt(Some(ghast_protocol::nbt::RawNbt::read(r)?)).unwrap_or_default(),
            ),
            15 => MetaValue::Particle(Particle::decode(r)?.particle_id),
            16 => MetaValue::VillagerData([r.read_varint()?, r.read_varint()?, r.read_varint()?]),
            17 => MetaValue::OptVarInt(r.read_varint()?),
            18 => MetaValue::Pose(r.read_varint()?),
            _ => return Err(DecodeError::Invalid("unknown metadata serializer")),
        };
        out.push((index, v));
    }
}

#[inline]
fn chunk(v: f64) -> i32 {
    (v.floor() as i32) >> 4
}

fn entity_ticks_at(e: &Entity, column_loaded: &impl Fn(i32, i32) -> bool) -> bool {
    column_loaded(chunk(e.pos[0]), chunk(e.pos[2]))
}

/// The vanilla 1.16.5 size entry for an entity (`None` for hanging entities).
pub(crate) fn vanilla_size(e: &Entity) -> Option<&'static ghast_data::VanillaEntitySize> {
    let id = match e.ty {
        EntityType::Player => 106,
        EntityType::Registry(38 | 40 | 55) => return None, // item frame, leash knot, painting
        EntityType::Registry(id) => i32::from(id),
        _ => return None,
    };
    ghast_data::v1_16_5::vanilla_entity_sizes()
        .iter()
        .find(|v| v.registry_id == id)
}

/// 1.16.5 dimensions with the metadata variants the client applies.
pub(crate) fn dimensions(
    e: &Entity,
    vs: &'static ghast_data::VanillaEntitySize,
) -> Option<ghast_data::EntityDimensions> {
    let m = &e.meta;
    let pose = match m.get(meta::POSE) {
        Some(MetaValue::Pose(p)) => *p,
        _ => 0,
    };
    let slime = match m.get(15) {
        Some(MetaValue::VarInt(n)) => Some(*n),
        _ => None,
    };
    let idx = if e.ty == EntityType::Registry(60) {
        16
    } else {
        15
    };
    let baby = matches!(m.get(idx), Some(MetaValue::Bool(true)));
    dims_with(e.ty, vs, pose, slime, m.byte(14).unwrap_or(0) as u8, baby)
}

/// [`dimensions`] from the size data itself: the pose (players), the slime size (slimes and
/// magma cubes; `None` keeps the spawn size), the armor stand flags and the baby flag.
pub(crate) fn dims_with(
    ty: EntityType,
    vs: &'static ghast_data::VanillaEntitySize,
    pose: i32,
    slime: Option<i32>,
    stand: u8,
    baby: bool,
) -> Option<ghast_data::EntityDimensions> {
    use ghast_data::EntityDimensions;
    let base = vs.default_dimensions().or_else(|| {
        vs.registered.map(|(width, height)| EntityDimensions {
            width,
            height,
            eye_height: height * 0.85,
        })
    })?;
    let EntityType::Registry(id) = ty else {
        // Player: pose table.
        let name = [
            "standing",
            "fall_flying",
            "sleeping",
            "swimming",
            "spin_attack",
            "crouching",
            "dying",
        ]
        .get(pose as usize)
        .copied()
        .unwrap_or("standing");
        return Some(vs.pose(name).unwrap_or(base));
    };
    match id {
        // slime, magma cube: size VarInt at 15.
        75 | 44 => {
            if let Some(n) = slime {
                return Some(ghast_data::v1_16_5::slime_dimensions(n));
            }
        }
        // armor stand flags byte at 14: 0x01 small, 0x10 marker.
        1 => {
            let f = stand;
            let name = match (f & 0x01 != 0, f & 0x10 != 0) {
                (true, true) => "small_marker",
                (false, true) => "marker",
                (true, false) => "small",
                _ => "default",
            };
            return Some(vs.variant(name).map_or(base, |v| v.dimensions));
        }
        _ => {}
    }
    // Baby flag: Bool at 15 (ageable mobs, zombies), 16 for piglins.
    if baby && let Some(b) = vs.baby() {
        return Some(b);
    }
    Some(base)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `MathHelper.lfloor(x * 4096)` with Java's saturating cast and wrapping `long` maths,
    /// also at coordinates no server sends (no overflow panic in debug builds).
    #[test]
    fn encode_floors_and_wraps_like_java() {
        assert_eq!(encode(1.0), 4096);
        assert_eq!(encode(-0.0001), -1);
        assert_eq!(encode(0.5 / 4096.0), 0);
        assert_eq!(encode(-1.0), -4096);
        // -2^51 encodes to exactly i64::MIN; the next double below it floors below that and
        // Java's `l - 1L` wraps to i64::MAX.
        assert_eq!(encode(-2_251_799_813_685_248.0), i64::MIN);
        assert_eq!(encode(-2_251_799_813_685_248.5), i64::MAX);
        assert_eq!(encode(-1e300), i64::MAX);
        assert_eq!(encode(f64::NEG_INFINITY), i64::MAX);
        assert_eq!(encode(1e300), i64::MAX);
        assert_eq!(encode(f64::INFINITY), i64::MAX);
        assert_eq!(encode(f64::NAN), 0);
        // A relative move from there: `encode + delta` wraps as well, decoded as a double.
        assert_eq!(axis(-1e300, 1), i64::MIN as f64 / 4096.0);
        assert_eq!(axis(1e300, -1), (i64::MAX - 1) as f64 / 4096.0);
        assert_eq!(axis(f64::NAN, 4096), 1.0);
        assert!(axis(f64::NAN, 0).is_nan());
        assert_eq!(axis(-1e300, 0), -1e300);
    }
}