ghast-client 0.5.3

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
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
//! 1.12.2: vehicles and mounts the player rides (boats, minecarts, living mounts): boarding,
//! their packets and their ticks, and the living mounts the client watches.

use super::*;

impl Sim12 {
    /// A tick in the boat we control (`ghast_physics::v1_12::tick_boat`), at the boat's place
    /// in the client world's entity list: the tracked entities before it step first (their
    /// interpolation, the lily pads their boats break), then the boat collides with the
    /// entities around it as they are then and the passenger with the boats and shulkers.
    /// Their pushes on the passenger are not applied (its motion is zeroed before its next
    /// tick, they change no packet).
    #[cold]
    #[inline(never)]
    pub(super) fn step_ride(&mut self, pose: &Pose, controls: Controls) {
        let Some(r) = self.ride.as_deref_mut() else {
            return;
        };
        let id = r.id;
        let Seat12::Boat(boat) = &mut r.seat else {
            return;
        };
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            // The passenger tick has no item slowdown.
            using_item: false,
        };
        let (solids, boat_solids): (&[_], &[_]) =
            match (self.near.as_deref_mut(), self.entities.as_ref()) {
                (Some(n), Some(t)) => {
                    if let Some(&k) = n.index.get(&id) {
                        let seq = n.list[k as usize].seq;
                        n.tick(t, &self.world, &self.player.bb, false, "", 0..seq);
                        for &[x, y, z] in &n.lily_pads {
                            self.world
                                .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
                        }
                    }
                    n.solids(t, &self.world, &self.player);
                    // As far as the boat can move this tick (its velocity grows by at most
                    // the paddle and the flow push before the move).
                    let b = &*boat;
                    let reach = |v: f64| v.abs() + 3.0;
                    n.boat_solids(
                        t,
                        &self.world,
                        &b.bb,
                        [reach(b.vel[0]), reach(b.vel[1]), reach(b.vel[2])],
                    );
                    (&n.solids, &n.boat_solids)
                }
                _ => (&[], &[]),
            };
        let still = ghast_physics::v1_12::tick_boat(
            &mut self.player,
            &mut self.ext,
            boat,
            solids,
            boat_solids,
            &input,
            &self.world,
            &mut self.packets,
        );
        for &[x, y, z] in boat.broken_lily_pads() {
            self.world
                .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
        }
        let (pos, bb) = (boat.pos, boat.bb);
        if let Some(n) = self.near.as_deref_mut()
            && let Some(c) = n.get_mut(id)
        {
            // The entry follows the client's boat (its interpolation stays where it was).
            c.follow(pos, bb);
        }
        if !still {
            log::debug!("boat {id} fell out of the world");
            self.leave_boat();
        }
    }

    /// A tick in the minecart we sit in (`ghast_physics::v1_12::tick_minecart`), at the cart's
    /// place in the client world's entity list (the entities before it step first).
    #[cold]
    #[inline(never)]
    pub(super) fn step_cart(&mut self, pose: &Pose, controls: Controls) {
        let Some(r) = self.ride.as_deref_mut() else {
            return;
        };
        let id = r.id;
        let Seat12::Cart(cart) = &mut r.seat else {
            return;
        };
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            // The passenger tick has no item slowdown.
            using_item: false,
        };
        let solids: &[_] = match (self.near.as_deref_mut(), self.entities.as_ref()) {
            (Some(n), Some(t)) => {
                if let Some(&k) = n.index.get(&id) {
                    let seq = n.list[k as usize].seq;
                    n.tick(t, &self.world, &self.player.bb, false, "", 0..seq);
                    for &[x, y, z] in &n.lily_pads {
                        self.world
                            .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
                    }
                }
                n.solids(t, &self.world, &self.player);
                &n.solids
            }
            _ => &[],
        };
        ghast_physics::v1_12::tick_minecart(
            &mut self.player,
            &mut self.ext,
            cart,
            solids,
            &input,
            &self.world,
            &mut self.packets,
        );
        let (pos, bb) = (cart.pos, cart.bb);
        if let Some(n) = self.near.as_deref_mut()
            && let Some(c) = n.get_mut(id)
        {
            c.follow(pos, bb);
        }
    }

    /// The server's moves of the boat we ride (`onEntityPosition` / `onEntityUpdate`): the
    /// tracked position always, the interpolation while someone else drives it (the entity
    /// list follows our copy, see [`Near12::ridden`]).
    #[cold]
    #[inline(never)]
    pub(super) fn boat_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let Some(Ride12 {
            id,
            seat: Seat12::Boat(b),
        }) = self.ride.as_deref_mut()
        else {
            return Ok(());
        };
        let id = *id;
        match raw.id {
            cb::id::ENTITY_TELEPORT => {
                let p: cb::EntityTeleport = raw.decode_as()?;
                if p.entity_id == id {
                    b.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
                }
            }
            cb::id::REL_ENTITY_MOVE => {
                let p: cb::RelEntityMove = raw.decode_as()?;
                if p.entity_id == id {
                    b.server_update([p.d_x, p.d_y, p.d_z], None, p.on_ground);
                }
            }
            cb::id::ENTITY_MOVE_LOOK => {
                let p: cb::EntityMoveLook = raw.decode_as()?;
                if p.entity_id == id {
                    b.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)), p.on_ground);
                }
            }
            cb::id::ENTITY_LOOK => {
                let p: cb::EntityLook = raw.decode_as()?;
                if p.entity_id == id {
                    b.server_update([0; 3], Some((p.yaw, p.pitch)), p.on_ground);
                }
            }
            cb::id::ENTITY => {
                let p: cb::Entity = raw.decode_as()?;
                if p.entity_id == id {
                    b.server_update([0; 3], None, false);
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// The server's moves of the minecart we sit in and its removal.
    #[cold]
    #[inline(never)]
    pub(super) fn cart_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let Some(Ride12 {
            id,
            seat: Seat12::Cart(c),
        }) = self.ride.as_deref_mut()
        else {
            return Ok(());
        };
        let id = *id;
        match raw.id {
            cb::id::ENTITY_TELEPORT => {
                let p: cb::EntityTeleport = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch);
                }
            }
            cb::id::REL_ENTITY_MOVE => {
                let p: cb::RelEntityMove = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([p.d_x, p.d_y, p.d_z], None);
                }
            }
            cb::id::ENTITY_MOVE_LOOK => {
                let p: cb::EntityMoveLook = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)));
                }
            }
            cb::id::ENTITY_LOOK => {
                let p: cb::EntityLook = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([0; 3], Some((p.yaw, p.pitch)));
                }
            }
            cb::id::ENTITY => {
                let p: cb::Entity = raw.decode_as()?;
                if p.entity_id == id {
                    c.server_update([0; 3], None);
                }
            }
            cb::id::ENTITY_DESTROY => {
                let p: cb::EntityDestroy = raw.decode_as()?;
                if p.entity_ids.contains(&id) {
                    log::debug!("minecart {id} destroyed");
                    self.leave_boat();
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// We ride a pig (it follows the carrot on a stick in our hands).
    #[inline]
    pub(super) fn pig_ride(&self) -> bool {
        matches!(self.ride.as_deref(), Some(Ride12 { seat: Seat12::Mount(m), .. })
            if m.kind() == ghast_physics::v1_12::MountKind::Pig)
    }

    /// Our hands hold a carrot on a stick (or no longer do): a pig we ride is steered by it.
    pub(super) fn set_carrot(&mut self, on: bool) {
        if self.carrot == on {
            return;
        }
        self.carrot = on;
        if let Some(t) = &mut self.entities {
            t.set_steer_carrot(on);
        }
        if let Some(Ride12 {
            seat: Seat12::Mount(m),
            ..
        }) = self.ride.as_deref_mut()
        {
            m.carrot = on;
        }
    }

    /// `entity_update_attributes` of a living mount: its movement speed and jump strength,
    /// kept for when we board it (and applied to the one we ride).
    #[cold]
    #[inline(never)]
    pub(super) fn mount_attributes(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let mut r = ghast_protocol::Reader::new(&raw.body);
        let id = r.read_varint()?;
        let Some(t) = self.entities.as_ref() else {
            return Ok(());
        };
        if t.get(id)
            .and_then(|e| mount_kind_12(e.entity_type()))
            .is_none()
        {
            return Ok(());
        }
        let p: cb::EntityUpdateAttributes = raw.decode_as()?;
        let k = match self.mount_attrs.iter().position(|a| a.id == id) {
            Some(k) => k,
            None => {
                if self.mount_attrs.len() >= MOUNT_ATTRS_CAP {
                    // Forget the mounts the tracker no longer knows, else the oldest.
                    self.mount_attrs.retain(|a| t.get(a.id).is_some());
                    if self.mount_attrs.len() >= MOUNT_ATTRS_CAP {
                        self.mount_attrs.remove(0);
                    }
                }
                self.mount_attrs.push(MountAttrs12 {
                    id,
                    ..MountAttrs12::default()
                });
                self.mount_attrs.len() - 1
            }
        };
        let a = &mut self.mount_attrs[k];
        for prop in &p.properties {
            let key: &str = &prop.key;
            if key.ends_with("generic.movementSpeed") {
                let mods = prop
                    .modifiers
                    .iter()
                    .map(|m| (m.uuid.as_u128(), m.amount, m.operation as u8))
                    .collect();
                a.speed = Some((prop.value, mods));
            } else if key == "horse.jumpStrength" {
                a.jump = Some(prop.value);
            }
        }
        let a = a.clone();
        if let Some(Ride12 {
            id: rid,
            seat: Seat12::Mount(m),
        }) = self.ride.as_deref_mut()
            && *rid == id
        {
            apply_mount_attrs(m, &a);
        }
        Ok(())
    }

    /// The living mount the server just seated us on, as the client has it: its client
    /// position (the server's when it is not followed), rotation, entity data and attributes.
    fn board_mount(&mut self, id: i32) -> Option<ghast_physics::v1_12::Mount> {
        use ghast_entity::MetaValue;
        let t = self.entities.as_ref()?;
        let e = t.get(id)?;
        let kind = mount_kind_12(e.entity_type())?;
        // What the client held while it watched the mob: its interpolation, velocity, body,
        // rearing, entity data.
        let shadow = self.near.as_deref_mut().and_then(|n| {
            let k = n.watched.iter().position(|w| w.0 == id)?;
            Some(n.watched.swap_remove(k).1)
        });
        if let Some(mut m) = shadow.filter(|m| m.kind() == kind) {
            m.board();
            if let Some(a) = self.mount_attrs.iter().find(|a| a.id == id) {
                apply_mount_attrs(&mut m, a);
            }
            m.carrot = self.carrot;
            return Some(m);
        }
        log::debug!("boarding {kind:?} {id} without its watched state (spawn not seen)");
        let pos = self
            .near
            .as_deref()
            .and_then(|n| n.index.get(&id).map(|&k| n.list[k as usize].pos))
            .unwrap_or(e.position());
        let mut m =
            ghast_physics::v1_12::Mount::new(kind, pos, e.yaw(), e.pitch(), e.head_yaw(), [0.0; 3]);
        m.set_tracked(e.position().map(|v| (v * 4096.0).floor() as i64));
        // The interpolation the client copy has pending (towards the server's rotation).
        if let Some(c) = self
            .near
            .as_deref()
            .and_then(|n| n.index.get(&id).map(|&k| &n.list[k as usize]))
            && c.steps > 0
        {
            m.set_interpolation(c.target, e.yaw(), e.pitch(), i32::from(c.steps));
        }
        let meta = e.metadata();
        if kind.horse_family() {
            // Without the metadata store (or before the server's entity data) a horse counts
            // as tame and saddled.
            use ghast_physics::v1_12::{HORSE_SADDLED, HORSE_TAME};
            let flags = meta.byte(13).map(|f| f as u8);
            if flags.is_none() {
                log::warn!(
                    "riding horse {id} without its entity data (the metadata store is off): \
                     its saddle / tame / rearing flags are unknown, taken as tame and saddled"
                );
            }
            m.apply_flags(flags.unwrap_or(HORSE_TAME | HORSE_SADDLED));
        } else {
            if let Some(MetaValue::Bool(b)) = meta.get(13) {
                m.apply_saddle(*b);
            }
            if let Some(MetaValue::VarInt(v)) = meta.get(14) {
                m.apply_boost(*v);
            }
        }
        if let Some(a) = self.mount_attrs.iter().find(|a| a.id == id) {
            apply_mount_attrs(&mut m, a);
        }
        m.carrot = self.carrot;
        Some(m)
    }

    /// The server's packets about the living mount we ride: its moves (followed only when the
    /// client does not move it), head yaw, entity data (horse status, pig saddle and boost) and
    /// its removal.
    #[cold]
    #[inline(never)]
    pub(super) fn mount_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::defs::p340::types::EntityMetadataValue as V;
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let Some(Ride12 {
            id,
            seat: Seat12::Mount(m),
        }) = self.ride.as_deref_mut()
        else {
            return Ok(());
        };
        let id = *id;
        let mut r = ghast_protocol::Reader::new(&raw.body);
        if raw.id != cb::id::ENTITY_DESTROY && r.read_varint()? != id {
            return Ok(());
        }
        match raw.id {
            cb::id::ENTITY_TELEPORT => {
                let p: cb::EntityTeleport = raw.decode_as()?;
                m.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
            }
            cb::id::REL_ENTITY_MOVE => {
                let p: cb::RelEntityMove = raw.decode_as()?;
                m.server_update([p.d_x, p.d_y, p.d_z], None, p.on_ground);
            }
            cb::id::ENTITY_MOVE_LOOK => {
                let p: cb::EntityMoveLook = raw.decode_as()?;
                m.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)), p.on_ground);
            }
            cb::id::ENTITY_LOOK => {
                let p: cb::EntityLook = raw.decode_as()?;
                m.server_update([0; 3], Some((p.yaw, p.pitch)), p.on_ground);
            }
            cb::id::ENTITY => m.server_update([0; 3], None, false),
            cb::id::ENTITY_HEAD_ROTATION => {
                let p: cb::EntityHeadRotation = raw.decode_as()?;
                m.server_head_yaw(p.head_yaw);
            }
            cb::id::ENTITY_VELOCITY => {
                let p: cb::EntityVelocity = raw.decode_as()?;
                m.server_velocity(p.velocity.x, p.velocity.y, p.velocity.z);
            }
            cb::id::ENTITY_METADATA => {
                let p: cb::EntityMetadata = raw.decode_as()?;
                let horse = m.kind().horse_family();
                for e in &p.metadata {
                    match (e.key, &e.value) {
                        (13, V::Byte(b)) if horse => m.apply_flags(*b as u8),
                        (13, V::Boolean(b)) if !horse => m.apply_saddle(*b),
                        (14, V::VarInt(v)) if !horse => m.apply_boost(*v),
                        _ => {}
                    }
                }
            }
            cb::id::ENTITY_DESTROY => {
                let p: cb::EntityDestroy = raw.decode_as()?;
                if p.entity_ids.contains(&id) {
                    log::debug!("mount {id} destroyed");
                    self.leave_boat();
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// A tick on the living mount we ride (`ghast_physics::v1_12::tick_mount`), at the mount's
    /// place in the client world's entity list: the tracked entities before it step first, then
    /// the mount and its passenger collide with the boats and shulkers around each.
    #[cold]
    #[inline(never)]
    pub(super) fn step_mount(&mut self, pose: &Pose, controls: Controls) {
        let Some(r) = self.ride.as_deref_mut() else {
            return;
        };
        let id = r.id;
        let Seat12::Mount(m) = &mut r.seat else {
            return;
        };
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            // The passenger tick has no item slowdown.
            using_item: false,
        };
        let mut mount_solids = Vec::new();
        let solids: &[_] = match (self.near.as_deref_mut(), self.entities.as_ref()) {
            (Some(n), Some(t)) => {
                if let Some(&k) = n.index.get(&id) {
                    let seq = n.list[k as usize].seq;
                    n.tick(t, &self.world, &self.player.bb, false, "", 0..seq);
                    for &[x, y, z] in &n.lily_pads {
                        self.world
                            .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
                    }
                }
                n.solids(t, &self.world, m.body());
                mount_solids.extend_from_slice(&n.solids);
                n.solids(t, &self.world, &self.player);
                &n.solids
            }
            _ => &[],
        };
        ghast_physics::v1_12::tick_mount(
            &mut self.player,
            &mut self.ext,
            &mut self.rider_jump,
            m,
            solids,
            &mount_solids,
            &input,
            &self.world,
            &mut self.packets,
        );
        let (pos, bb) = (m.pos(), m.bb());
        if let Some(n) = self.near.as_deref_mut()
            && let Some(c) = n.get_mut(id)
        {
            // The entry follows the client's mount.
            c.follow(pos, bb);
        }
    }

    /// The player is off the boat it drove: the boat stays where it is on the client.
    pub(super) fn leave_boat(&mut self) {
        // A boat keeps the interpolation it has pending (frozen while we drove it) and its
        // turn.
        if let Some(Ride12 {
            id,
            seat: Seat12::Boat(b),
        }) = self.ride.as_deref()
        {
            if let Some(n) = self.near.as_deref_mut()
                && let Some(c) = n.get_mut(*id)
            {
                c.target = b.interpolation_target();
                c.steps = b.interpolation_steps().clamp(0, 255) as u8;
            }
            let mut boat = b.clone();
            boat.leave();
            // Left between ticks (from inside one only when the boat fell out of the world).
            let tick = self.piston_time;
            self.left_boat = Some(Box::new(LeftBoat12 {
                id: *id,
                tick,
                boat,
            }));
        }
        // The mount keeps the interpolation its client copy had pending (also one frozen while
        // it was steered); the client watches it again from where it is.
        if let Some(Ride12 {
            id,
            seat: Seat12::Mount(m),
        }) = self.ride.as_deref()
            && let Some(n) = self.near.as_deref_mut()
        {
            if let Some(c) = n.get_mut(*id) {
                c.target = m.interpolation_target();
                c.steps = m.interpolation_steps().clamp(0, 255) as u8;
            }
            let mut m = (**m).clone();
            m.leave();
            n.watched.retain(|w| w.0 != *id);
            n.watched.push((*id, m));
        }
        self.ride = None;
        if let Some(n) = self.near.as_deref_mut() {
            n.ridden = None;
        }
    }

    /// Our entity id: the tracker's, else the join packet's.
    pub(super) fn own_id(&self) -> i32 {
        self.entities
            .as_ref()
            .and_then(|t| t.self_id())
            .unwrap_or(self.glide.own_id)
    }

    /// `set_passengers` (boarding / leaving a boat) and `vehicle_move` (the server's correction
    /// of the boat we control: `onVehicleMove` applies it and answers with the boat's position at
    /// once).
    #[cold]
    #[inline(never)]
    pub(super) fn vehicle_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        if raw.id == cb::id::VEHICLE_MOVE {
            if let Some(Ride12 {
                id: rid,
                seat: Seat12::Mount(m),
            }) = self.ride.as_deref_mut()
            {
                let rid = *rid;
                let p: cb::VehicleMove = raw.decode_as()?;
                // Only a mount the client moves takes the server's correction (and answers).
                if let Some(ghast_physics::Packet::MoveVehicle {
                    pos,
                    yaw,
                    pitch,
                    on_ground,
                }) = m.server_move([p.x, p.y, p.z], p.yaw, p.pitch)
                {
                    self.reply = Some(Outbound::VehicleMove {
                        pos: Vec3::new(pos[0], pos[1], pos[2]),
                        yaw,
                        pitch,
                        on_ground,
                    });
                    if let Some(r) = &mut self.rec {
                        r.vehicle_reply(pos, yaw, pitch, on_ground);
                    }
                    let (pos, bb) = (m.pos(), m.bb());
                    if let Some(n) = self.near.as_deref_mut()
                        && let Some(c) = n.get_mut(rid)
                    {
                        c.follow(pos, bb);
                    }
                }
                return Ok(());
            }
            if let Some(Ride12 {
                id: rid,
                seat: Seat12::Boat(boat),
            }) = self.ride.as_deref_mut()
                && boat.controlled()
            {
                let rid = *rid;
                let p: cb::VehicleMove = raw.decode_as()?;
                if let ghast_physics::Packet::MoveVehicle {
                    pos,
                    yaw,
                    pitch,
                    on_ground,
                } = boat.server_move([p.x, p.y, p.z], p.yaw, p.pitch)
                {
                    self.reply = Some(Outbound::VehicleMove {
                        pos: Vec3::new(pos[0], pos[1], pos[2]),
                        yaw,
                        pitch,
                        on_ground,
                    });
                }
                let (id, pos, bb) = (rid, boat.pos, boat.bb);
                if let Some(n) = self.near.as_deref_mut()
                    && let Some(c) = n.get_mut(id)
                {
                    c.follow(pos, bb);
                }
            }
            return Ok(());
        }
        let p: cb::SetPassengers = raw.decode_as()?;
        let me = self.own_id();
        let on = p.passengers.contains(&me);
        let seat = p.passengers.iter().position(|&v| v == me);
        let riding_it = self.ride.as_ref().is_some_and(|r| r.id == p.entity_id);
        if on
            && riding_it
            && let (
                Some(Ride12 {
                    seat: Seat12::Boat(b),
                    ..
                }),
                Some(i),
            ) = (self.ride.as_deref_mut(), seat)
        {
            // The passengers changed: our seat, and whether we still drive it.
            b.set_seat(i, p.passengers.len());
        }
        if on && !riding_it {
            // A minecart: at its client position (the server's when it is not followed), with
            // the server's position of it for the relative moves.
            let cart = self.entities.as_ref().and_then(|t| {
                let e = t.get(p.entity_id)?;
                if e.entity_type() != ghast_entity::EntityType::LegacyObject(10) {
                    return None;
                }
                let pos = self
                    .near
                    .as_deref()
                    .and_then(|n| n.index.get(&p.entity_id).map(|&k| n.list[k as usize].pos))
                    .unwrap_or(e.position());
                let mut c = ghast_physics::v1_12::Minecart::new(pos, e.yaw(), e.pitch());
                c.tracked = e.position().map(|v| (v * 4096.0).floor() as i64);
                Some(c)
            });
            if let Some(cart) = cart {
                log::debug!("in minecart {}", p.entity_id);
                self.ride = Some(Box::new(Ride12 {
                    id: p.entity_id,
                    seat: Seat12::Cart(cart),
                }));
                if let Some(n) = self.near.as_deref_mut() {
                    n.ridden = Some(p.entity_id);
                }
                return Ok(());
            }
            // A living mount: at its client position, with the rotation, entity data and
            // attributes the server last sent.
            if let Some(m) = self.board_mount(p.entity_id) {
                log::debug!(
                    "riding {:?} {} at {:?} (server {:?}, {} interpolation steps left), \
                     velocity {:?}, on ground {}",
                    m.kind(),
                    p.entity_id,
                    m.pos(),
                    m.tracked().map(|v| v as f64 / 4096.0),
                    m.interpolation_steps(),
                    m.vel(),
                    m.on_ground()
                );
                self.ride = Some(Box::new(Ride12 {
                    id: p.entity_id,
                    seat: Seat12::Mount(Box::new(m)),
                }));
                if let Some(n) = self.near.as_deref_mut() {
                    n.ridden = Some(p.entity_id);
                }
                return Ok(());
            }
            // startRiding a boat the client knows: at its client position and box, with the
            // rotation the server last sent, the interpolation the client copy has pending and
            // the turn of a boat we drove. Other vehicles are not simulated (the walking tick
            // goes on).
            let left = self.left_boat.take().filter(|l| l.id == p.entity_id);
            let now = self.piston_time;
            let boat = self.entities.as_ref().and_then(|t| {
                let e = t.get(p.entity_id)?;
                if e.entity_type() != ghast_entity::EntityType::LegacyObject(1) {
                    return None;
                }
                let mut b = match left {
                    // Left and boarded again with no tick between: as it was.
                    Some(l) if l.tick == now => l.boat,
                    _ => {
                        let c = self
                            .near
                            .as_deref()
                            .and_then(|n| n.index.get(&p.entity_id).map(|&k| &n.list[k as usize]));
                        let pos = c.map_or(e.position(), |c| c.pos);
                        let mut b = ghast_physics::v1_12::Boat::new(pos, e.yaw(), 0.0);
                        if let Some(c) = c {
                            b.bb = c.bb;
                        }
                        let (target, steps) = c.map_or((pos, 0), |c| (c.target, c.steps));
                        b.set_interpolation(
                            target,
                            e.yaw(),
                            e.pitch(),
                            i32::from(steps),
                            e.traced(),
                        );
                        if let Some(l) = left {
                            b.set_turn(l.boat.yaw_velocity(), l.boat.paddles());
                        }
                        b
                    }
                };
                b.set_seat(seat.unwrap_or(0), p.passengers.len());
                Some(b)
            });
            match boat {
                Some(boat) => {
                    log::debug!("riding boat {}", p.entity_id);
                    self.ride = Some(Box::new(Ride12 {
                        id: p.entity_id,
                        seat: Seat12::Boat(boat),
                    }));
                    if let Some(n) = self.near.as_deref_mut() {
                        n.ridden = Some(p.entity_id);
                    }
                }
                None => log::debug!(
                    "riding {} (not simulated: no entity tracking or not a boat)",
                    p.entity_id
                ),
            }
        } else if !on && riding_it {
            log::debug!("left boat {}", p.entity_id);
            self.leave_boat();
        }
        Ok(())
    }
}

/// The server's packets about the living mounts the client watches (not the one we ride): a
/// mob spawn of a mount type starts watching it (its spawn position, angle bytes, velocity and
/// entity data); moves, looks, head yaw, velocity and entity data follow; a removal ends it.
#[cold]
#[inline(never)]
pub(super) fn watched_packet(
    n: &mut Near12,
    ridden: Option<i32>,
    raw: &RawPacket,
) -> Result<(), SimError> {
    use ghast_entity::EntityType;
    use ghast_protocol::defs::p340::types::EntityMetadataValue as V;
    use ghast_protocol::v1_12_2::play::clientbound as cb;
    let horse_meta = |m: &mut ghast_physics::v1_12::Mount, list: &[_]| {
        let list: &[ghast_protocol::defs::p340::types::EntityMetadataEntry] = list;
        let horse = m.kind().horse_family();
        for e in list {
            match (e.key, &e.value) {
                (13, V::Byte(b)) if horse => m.apply_flags(*b as u8),
                (13, V::Boolean(b)) if !horse => m.apply_saddle(*b),
                (14, V::VarInt(v)) if !horse => m.apply_boost(*v),
                _ => {}
            }
        }
    };
    if raw.id == cb::id::ENTITY_DESTROY {
        let p: cb::EntityDestroy = raw.decode_as()?;
        n.watched.retain(|w| !p.entity_ids.contains(&w.0));
        return Ok(());
    }
    if raw.id == cb::id::SPAWN_ENTITY_LIVING {
        let p: cb::SpawnEntityLiving = raw.decode_as()?;
        n.watched.retain(|w| w.0 != p.entity_id);
        let Some(kind) = u8::try_from(p.r#type)
            .ok()
            .and_then(|t| mount_kind_12(EntityType::LegacyMob(t)))
        else {
            return Ok(());
        };
        // onMobSpawn: angles `byte * 360 / 256.0F`, velocity `raw / 8000.0F`.
        let deg = |b: i8| (i32::from(b) * 360) as f32 / 256.0;
        let v = p.velocity;
        let vel = [v.x, v.y, v.z].map(|c| f64::from(f32::from(c) / 8000.0));
        let mut m = ghast_physics::v1_12::Mount::watched(
            kind,
            [p.x, p.y, p.z],
            deg(p.yaw),
            deg(p.pitch),
            deg(p.head_pitch),
            vel,
        );
        horse_meta(&mut m, &p.metadata);
        n.watched.push((p.entity_id, m));
        return Ok(());
    }
    let id = ghast_protocol::Reader::new(&raw.body).read_varint()?;
    if ridden == Some(id) {
        return Ok(());
    }
    let Some((_, m)) = n.watched.iter_mut().find(|w| w.0 == id) else {
        return Ok(());
    };
    match raw.id {
        cb::id::ENTITY_TELEPORT => {
            let p: cb::EntityTeleport = raw.decode_as()?;
            log::trace!("watched mount {id}: teleport {:?}", [p.x, p.y, p.z]);
            m.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
        }
        cb::id::REL_ENTITY_MOVE => {
            let p: cb::RelEntityMove = raw.decode_as()?;
            m.server_update([p.d_x, p.d_y, p.d_z], None, p.on_ground);
        }
        cb::id::ENTITY_MOVE_LOOK => {
            let p: cb::EntityMoveLook = raw.decode_as()?;
            m.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)), p.on_ground);
        }
        cb::id::ENTITY_LOOK => {
            let p: cb::EntityLook = raw.decode_as()?;
            m.server_update([0; 3], Some((p.yaw, p.pitch)), p.on_ground);
        }
        cb::id::ENTITY => m.server_update([0; 3], None, false),
        cb::id::ENTITY_HEAD_ROTATION => {
            let p: cb::EntityHeadRotation = raw.decode_as()?;
            m.server_head_yaw(p.head_yaw);
        }
        cb::id::ENTITY_VELOCITY => {
            let p: cb::EntityVelocity = raw.decode_as()?;
            log::trace!("watched mount {id}: velocity {:?}", p.velocity);
            m.server_velocity(p.velocity.x, p.velocity.y, p.velocity.z);
        }
        cb::id::ENTITY_METADATA => {
            let p: cb::EntityMetadata = raw.decode_as()?;
            horse_meta(m, &p.metadata);
        }
        _ => {}
    }
    Ok(())
}

/// One client tick of every living mount the client watches (`tick_watched`); one another
/// entity rides is no longer modelled.
#[cold]
#[inline(never)]
pub(super) fn tick_watched_mounts(
    n: &mut Near12,
    t: &ghast_entity::v1_12::Tracker,
    w: &ghast_world::v1_12::World,
    ridden: Option<i32>,
) {
    let me = t.self_id();
    n.watched.retain(|(id, _)| {
        t.get(*id)
            .is_some_and(|e| e.vehicle().is_none() && e.passengers().iter().all(|&p| Some(p) == me))
    });
    for (id, m) in &mut n.watched {
        if ridden == Some(*id) {
            continue;
        }
        let [x, _, z] = m.pos();
        if !w.is_column_loaded((x.floor() as i32) >> 4, (z.floor() as i32) >> 4) {
            continue;
        }
        ghast_physics::v1_12::tick_watched(m, w);
    }
}

/// A watched mount that pushed the player (`key`: its sort key in the push list, its place in
/// the entity list × 4) takes the opposite push itself.
#[cold]
#[inline(never)]
pub(super) fn watched_mount_pushed(n: &mut Near12, key: u64, player: [f64; 2]) {
    let Some(id) = n.list.iter().find(|c| c.seq * 4 == key).map(|c| c.id) else {
        return;
    };
    if let Some((_, m)) = n.watched.iter_mut().find(|w| w.0 == id) {
        m.pushed_player(player);
    }
}