ghast-entity 0.5.6

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
//! What the vanilla client draws and picks of the other entities, and a few per-entity clocks
//! (opt-in: `track_client_motion` of each version's tracker).
//!
//! * **1.8.9 and 1.12.2.** A position packet does not move a living entity at once: it sets an
//!   interpolation target and a step count (`updateTrackedPositionAndAngles(.., 3, ..)`), and
//!   each client tick (`LivingEntity.tickMovement`, `OtherClientPlayerEntity.tickMovement`)
//!   moves the entity `1 / steps` of the remaining way and counts down. The crosshair pick
//!   (`GameRenderer.updateTargetedEntity`, at the start of the tick, before the entities tick)
//!   reads that position. Every relative-move, look and bare `entity` packet restarts the 3
//!   steps (a look-only packet towards the current target, rotation-less ones keep the drawn
//!   rotation as the target rotation). A teleport to within 1/32 (y: 1/64) of the drawn position
//!   freezes it there (1.8: 3 steps towards the drawn position, 1.12: 0 steps). Spawns place the
//!   entity at once. Both versions tick every entity of the client world every tick (their
//!   client chunk check passes for any column). A 1.12 shulker ignores position packets and sits
//!   on the attached block of its entity data, its box stretched by the lid's opening
//!   ([`Shulker12`]).
//! * **1.16.5** keeps its own client view (`client16`); the drawn position and box are copied
//!   from it.
//! * **26.x** entities *are* the drawn state ([`crate::Entity::position`]); only the clocks live
//!   here.
//!
//! Not modelled (drawn = the server position at once, as before): non-living entities of 1.8 /
//! 1.12 (boats and minecarts interpolate with their own rules; 1.8's base entity is pushed up out
//! of blocks it would overlap), riders (vanilla places them on their vehicle) and the client's
//! own removal of a dead entity after its death animation.

use crate::entity::{Entity, EntityType, Era};

/// How an entity's drawn position follows the server.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Lerp {
    /// `OtherClientPlayerEntity` (yaw wrapped with two loops).
    Player,
    /// `LivingEntity` (yaw wrapped with `MathHelper.wrapDegrees`).
    Living,
    /// 1.12 shulker: position and look packets do nothing; attached-block entity data puts it
    /// on the block, and its tick keeps it there with the box the lid's opening stretches
    /// ([`Shulker12`]).
    Shulker,
    /// 1.8 boat (`BoatEntity` of another entity, its "empty" flag set): a position packet
    /// interpolates over 3 + 5 steps and restores the server's velocity; between packets it
    /// moves by its own velocity (a hit's knockback, the server's velocity packets), halved on
    /// the ground, × (0.99, 0.95, 0.99) per tick.
    Boat,
    /// 1.8 / 1.12 minecart: interpolates over the packet's steps + 2 (3 + 2; 1.12's near
    /// teleport 0 + 2; `AbstractMinecartEntity`); its velocity does not move it on the client.
    Minecart,
    /// 1.12 boat of another entity: every position packet interpolates over 10 steps
    /// (`BoatEntity.updateTrackedPositionAndAngles`); its velocity is zeroed each tick.
    Boat12,
    /// The drawn state is copied from another client view (1.16.5) or is the entity itself
    /// (26.x): only the clocks are kept.
    External,
    /// 1.8 / 1.12 entities that do not interpolate: drawn at the server position at once
    /// (`updateTrackedPositionAndAngles` sets the position; 1.8's push out of overlapping
    /// blocks is not modelled), kept for the clocks and the chunk-section order.
    Fixed,
}

/// The chunk section (`MathHelper.floor(c / 16.0)` per axis) of a position.
#[inline]
pub(crate) fn section_of(p: [f64; 3]) -> [i32; 3] {
    p.map(|c| (c / 16.0).floor() as i32)
}

/// The client-side state of one entity (boxed: only living entities with the client view on
/// carry it).
#[derive(Clone, Debug)]
pub(crate) struct Client {
    pub(crate) lerp: Lerp,
    /// Drawn position (`x`, `y`, `z`).
    pub(crate) pos: [f64; 3],
    /// Interpolation target (`serverX` …).
    pub(crate) target: [f64; 3],
    /// Drawn `(yaw, pitch)`.
    pub(crate) rot: [f32; 2],
    /// Target `(yaw, pitch)` (vanilla keeps them as doubles holding float values).
    pub(crate) target_rot: [f32; 2],
    /// Remaining interpolation steps (`bodyTrackingIncrements`).
    pub(crate) steps: u8,
    /// 1.16.5: the client box copied from the client view. 1.8.9 / 1.12.2: the box a moving
    /// piston left (`Entity.move` offsets the box and takes the position from it) until the next
    /// `setPosition` rebuilds it from the position.
    pub(crate) bb: Option<[f64; 6]>,
    /// 1.8.9 / 1.12.2: `inWeb` (a piston's push into a cobweb sets it, the next push clears it).
    pub(crate) in_web: bool,
    /// 1.8.9 / 1.12.2: `onGround` as a piston's push left it (`None`: the last packet's flag,
    /// [`Entity::on_ground`]); the next position packet sets it again.
    pub(crate) ground: Option<bool>,
    /// Tick the entity spawned.
    pub(crate) spawned: u64,
    /// Tick of the last server position change.
    pub(crate) moved: u64,
    /// Server position at the last change before the tick of [`Client::moved`], and its tick.
    pub(crate) from: [f64; 3],
    pub(crate) from_tick: u64,
    /// Server position after the last change.
    pub(crate) to: [f64; 3],
    /// Tick of the last hurt status / damage event.
    pub(crate) hurt: Option<u64>,
    /// The chunk section whose entity list holds the entity (`chunkX`, `chunkY`, `chunkZ`,
    /// unclamped): `World.checkChunk` moves it at the entity's tick.
    pub(crate) section: [i32; 3],
    /// When it entered that list (a store-wide counter): the list's order.
    pub(crate) seq: u32,
    /// When it spawned (the world's entity list order, in which the entities tick).
    pub(crate) spawn_seq: u32,
    /// A [`Lerp::Fixed`] entity moved since its last tick: its next tick checks its section.
    pub(crate) order_pending: bool,
    /// 1.8 boat: its velocity (`velocityX` …) and the server's last one (restored by every
    /// position packet).
    pub(crate) vel: [f64; 3],
    pub(crate) server_vel: [f64; 3],
    /// 1.12 shulker: its client state (`None` for everything else).
    pub(crate) shulker: Option<Box<Shulker12>>,
}

/// The 1.12 client's own shulker state (`ShulkerEntity`): the entity data its tick reads and
/// the lid's opening it animates.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Shulker12 {
    /// The attached block (entity data 13).
    pub(crate) attached: Option<[i32; 3]>,
    /// The attached face (`Direction` id, entity data 12).
    pub(crate) face: u8,
    /// The peek amount (entity data 14).
    pub(crate) peek: i8,
    /// `field_14768`: the lid's opening, 0.05 a tick towards `peek / 100`.
    pub(crate) open: f32,
    /// Nothing for its tick to change (the opening reached the peek, the shulker sits on its
    /// block with its box).
    pub(crate) settled: bool,
}

/// 1.12 shulker entity data entries in packet order (`onTrackedDataSet`): the face (12), the
/// attached block (13: a block puts the shulker on it at once, its box stays until the next
/// tick) and the peek (14). Returns the change of the store's busy count.
pub(crate) fn shulker_data(e: &mut Entity, entries: &[(u8, crate::entity::MetaValue)]) -> i32 {
    use crate::entity::MetaValue;
    let held = e.drawn_bounding_box();
    let Some(c) = e.client.as_deref_mut() else {
        return 0;
    };
    let idle = !c.busy();
    let Some(s) = c.shulker.as_mut() else {
        return 0;
    };
    let mut on = None;
    for (i, v) in entries {
        match (*i, v) {
            (12, MetaValue::Direction(f)) => s.face = (*f).clamp(0, 5) as u8,
            (13, MetaValue::OptBlockPos(p)) => {
                s.attached = *p;
                if p.is_some() {
                    on = *p;
                }
            }
            (14, MetaValue::Byte(b)) => s.peek = *b,
            _ => continue,
        }
        s.settled = false;
    }
    if let Some(b) = on {
        c.bb = held;
        c.pos = [
            f64::from(b[0]) + 0.5,
            f64::from(b[1]),
            f64::from(b[2]) + 0.5,
        ];
    }
    c.lerp_delta(idle)
}

impl Shulker12 {
    /// One `ShulkerEntity.tick` on the client at drawn position `pos`: the opening moves, then
    /// on an attached block the position and the box (`None`: no block, nothing moves).
    fn tick(&mut self) -> Option<([f64; 3], [f64; 6])> {
        let g = f32::from(self.peek) * 0.01;
        // MathHelper.clamp(float): below the minimum gives the minimum, then the maximum.
        let clamp = |v: f32, lo: f32, hi: f32| {
            if v < lo {
                lo
            } else if v > hi {
                hi
            } else {
                v
            }
        };
        if self.open > g {
            self.open = clamp(self.open - 0.05, g, 1.0);
        } else if self.open < g {
            self.open = clamp(self.open + 0.05, 0.0, g);
        }
        self.settled = self.open == g;
        let b = self.attached?;
        let (x, y, z) = (
            f64::from(b[0]) + 0.5,
            f64::from(b[1]),
            f64::from(b[2]) + 0.5,
        );
        let d = 0.5 - f64::from(table_sin((0.5 + self.open) * std::f32::consts::PI)) * 0.5;
        let mut bb = [x - 0.5, y, z - 0.5, x + 0.5, y + 1.0, z + 0.5];
        // The box grows away from the attached face (down, up, north, south, west, east).
        match self.face {
            0 => bb[4] += d,
            1 => bb[1] -= d,
            2 => bb[5] += d,
            3 => bb[2] -= d,
            4 => bb[3] += d,
            _ => bb[0] -= d,
        }
        Some(([x, y, z], bb))
    }
}

/// The legacy (1.8 / 1.12) interpolation kind of `e` ([`Lerp::Fixed`]: drawn at the server
/// position).
pub(crate) fn legacy_lerp(e: &Entity) -> Option<Lerp> {
    match e.ty {
        EntityType::Player => Some(Lerp::Player),
        // 1.12 shulker (registry id 69).
        EntityType::LegacyMob(69) if e.era == Era::V1_12 => Some(Lerp::Shulker),
        EntityType::LegacyMob(_) => Some(Lerp::Living),
        // The armor stand is a living entity spawned as object 78.
        EntityType::LegacyObject(78) => Some(Lerp::Living),
        EntityType::LegacyObject(1) if e.era == Era::V1_8 => Some(Lerp::Boat),
        EntityType::LegacyObject(1) => Some(Lerp::Boat12),
        EntityType::LegacyObject(10) => Some(Lerp::Minecart),
        _ => Some(Lerp::Fixed),
    }
}

impl Client {
    /// A freshly spawned entity: drawn where the server put it. 1.12.2 player and mob spawns
    /// go through `updatePositionAndAngles`, which clamps x / z to ±3e7 and the pitch to ±90
    /// (objects such as the armor stand set their rotation directly).
    pub(crate) fn new(e: &Entity, lerp: Lerp, now: u64, seq: u32) -> Self {
        let (mut pos, mut pitch) = (e.pos, e.pitch);
        if e.era == Era::V1_12 && !matches!(e.ty, EntityType::LegacyObject(_)) {
            // MathHelper.clamp: NaN passes through, as with `clamp`.
            pos = [
                pos[0].clamp(-3.0e7, 3.0e7),
                pos[1],
                pos[2].clamp(-3.0e7, 3.0e7),
            ];
            pitch = pitch.clamp(-90.0, 90.0);
        }
        Client {
            lerp,
            pos,
            target: pos,
            rot: [e.yaw, pitch],
            target_rot: [e.yaw, pitch],
            steps: 0,
            bb: None,
            in_web: false,
            ground: None,
            spawned: now,
            moved: now,
            from: e.pos,
            from_tick: now,
            to: e.pos,
            hurt: None,
            section: section_of(pos),
            seq,
            spawn_seq: seq,
            order_pending: false,
            vel: [0.0; 3],
            server_vel: [0.0; 3],
            // Its first tick turns it (busy until then).
            shulker: (lerp == Lerp::Shulker).then(Box::<Shulker12>::default),
        }
    }

    /// The boat moves by its own velocity while it has one.
    #[inline]
    fn drifts(&self) -> bool {
        self.lerp == Lerp::Boat && self.vel != [0.0; 3]
    }

    /// `setVelocityClient` (the server's velocity packet): a boat keeps it as its velocity and
    /// as the server's.
    pub(crate) fn velocity_packet(&mut self, v: [f64; 3]) -> i32 {
        if self.lerp != Lerp::Boat {
            return 0;
        }
        let idle = !self.busy();
        self.vel = v;
        self.server_vel = v;
        self.lerp_delta(idle)
    }

    /// `Entity.addVelocity` (a hit's knockback on the client): only a boat moves by it.
    pub(crate) fn add_velocity(&mut self, d: [f64; 3]) -> i32 {
        if self.lerp != Lerp::Boat {
            return 0;
        }
        let idle = !self.busy();
        for k in 0..3 {
            self.vel[k] += d[k];
        }
        self.lerp_delta(idle)
    }

    /// The next client tick has work: interpolation steps, or a section check.
    #[inline]
    pub(crate) fn busy(&self) -> bool {
        self.steps > 0
            || self.order_pending
            || self.drifts()
            || self.shulker.as_ref().is_some_and(|s| !s.settled)
    }

    /// The pick's order key: chunk x, chunk z, the section list (`chunkY` clamped to 0 … 15)
    /// and the place in it (`World.getEntitiesIn`: chunks x-major, then z, sections upwards,
    /// each list in insertion order).
    #[inline]
    pub(crate) fn order(&self) -> (i32, i32, i32, u32) {
        (
            self.section[0],
            self.section[2],
            self.section[1].clamp(0, 15),
            self.seq,
        )
    }

    /// The server position became `p` at tick `now` (updates the estimated velocity).
    #[inline]
    pub(crate) fn server_moved(&mut self, p: [f64; 3], now: u64) {
        if p == self.to {
            return;
        }
        if now != self.moved {
            self.from = self.to;
            self.from_tick = self.moved;
        }
        self.to = p;
        self.moved = now;
    }

    /// The busy-count change after an update that found it `idle` (not [`Client::busy`]).
    #[inline]
    fn lerp_delta(&self, idle: bool) -> i32 {
        i32::from(self.busy()) - i32::from(!idle)
    }

    /// Blocks per tick between the last two server positions.
    pub(crate) fn velocity(&self) -> [f64; 3] {
        let dt = self.moved.saturating_sub(self.from_tick).max(1) as f64;
        [
            (self.to[0] - self.from[0]) / dt,
            (self.to[1] - self.from[1]) / dt,
            (self.to[2] - self.from[2]) / dt,
        ]
    }

    /// `updateTrackedPositionAndAngles(target, rot, steps)`.
    #[inline]
    fn track(&mut self, target: [f64; 3], rot: [f32; 2], steps: u8) {
        self.target = target;
        self.target_rot = rot;
        self.steps = steps;
    }

    /// One client tick (`tickMovement`'s interpolation step; a shulker's block snap). Returns
    /// `true` when the entity has no work left ([`Client::busy`]); the caller then checks its
    /// section.
    #[inline]
    pub(crate) fn step(&mut self, on_ground: bool) -> bool {
        self.order_pending = false;
        self.step_motion(on_ground);
        !self.busy()
    }

    #[inline]
    fn step_motion(&mut self, on_ground: bool) -> bool {
        match self.lerp {
            Lerp::Minecart | Lerp::Boat12 if self.steps > 0 => self.lerp_step(),
            Lerp::Minecart => {
                // `setPosition` at the same place: the box from the position again.
                self.bb = None;
                false
            }
            Lerp::Boat if self.steps > 0 => self.lerp_step(),
            Lerp::Boat => {
                // The empty boat's free move: position + velocity, then the drag.
                for k in 0..3 {
                    self.pos[k] += self.vel[k];
                }
                self.bb = None;
                if on_ground {
                    self.vel = self.vel.map(|v| v * 0.5);
                }
                self.vel[0] *= f64::from(0.99f32);
                self.vel[1] *= f64::from(0.95f32);
                self.vel[2] *= f64::from(0.99f32);
                false
            }
            Lerp::Player | Lerp::Living if self.steps > 0 => {
                let n = f64::from(self.steps);
                let p = [
                    self.pos[0] + (self.target[0] - self.pos[0]) / n,
                    self.pos[1] + (self.target[1] - self.pos[1]) / n,
                    self.pos[2] + (self.target[2] - self.pos[2]) / n,
                ];
                let mut g = f64::from(self.target_rot[0]) - f64::from(self.rot[0]);
                if self.lerp == Lerp::Player {
                    while g < -180.0 {
                        g += 360.0;
                    }
                    while g >= 180.0 {
                        g -= 360.0;
                    }
                } else {
                    g = wrap_degrees(g);
                }
                let yaw = (f64::from(self.rot[0]) + g / n) as f32;
                let pitch = (f64::from(self.rot[1])
                    + (f64::from(self.target_rot[1]) - f64::from(self.rot[1])) / n)
                    as f32;
                self.steps -= 1;
                self.pos = p;
                self.bb = None;
                // setRotation: `% 360.0F`.
                self.rot = [yaw % 360.0, pitch % 360.0];
                self.steps == 0
            }
            Lerp::Shulker => {
                if let Some((p, bb)) = self.shulker.as_mut().and_then(|s| s.tick()) {
                    self.pos = p;
                    self.bb = Some(bb);
                }
                // `tickMovement` turns it to 180 every tick.
                self.rot[0] = 180.0;
                true
            }
            _ => false,
        }
    }
}

impl Client {
    /// A 1.8 boat's / minecart's `updateTrackedPositionAndAngles(target, rot, 3)`: 3 + 5 / 3 + 2
    /// steps; the boat takes the server's last velocity back.
    #[inline]
    fn vehicle_track(&mut self, target: [f64; 3], rot: [f32; 2], steps: u8) {
        match self.lerp {
            Lerp::Boat => {
                self.track(target, rot, steps + 5);
                self.vel = self.server_vel;
            }
            Lerp::Boat12 => self.track(target, rot, 10),
            _ => self.track(target, rot, steps + 2),
        }
    }

    /// One interpolation step towards the target (`MathHelper.wrapDegrees` for the yaw, as
    /// `LivingEntity` and the 1.8 vehicles do).
    #[inline]
    fn lerp_step(&mut self) -> bool {
        let n = f64::from(self.steps);
        let p = [
            self.pos[0] + (self.target[0] - self.pos[0]) / n,
            self.pos[1] + (self.target[1] - self.pos[1]) / n,
            self.pos[2] + (self.target[2] - self.pos[2]) / n,
        ];
        let g = wrap_degrees(f64::from(self.target_rot[0]) - f64::from(self.rot[0]));
        let yaw = (f64::from(self.rot[0]) + g / n) as f32;
        let pitch = (f64::from(self.rot[1])
            + (f64::from(self.target_rot[1]) - f64::from(self.rot[1])) / n)
            as f32;
        self.steps -= 1;
        self.pos = p;
        self.bb = None;
        self.rot = [yaw % 360.0, pitch % 360.0];
        self.steps == 0
    }

    /// A [`Lerp::Fixed`] entity's position packet: drawn there at once, its section checked at
    /// its next tick.
    #[inline]
    fn fixed_move(&mut self, pos: [f64; 3], rot: [f32; 2]) {
        self.pos = pos;
        self.bb = None;
        self.rot = rot;
        self.order_pending = true;
    }
}

impl Client {
    /// A moving piston moved the entity on the client (`Entity.move`): its new position, box,
    /// ground and web state (`sits_back`: a 1.12 shulker with an attached block, which its tick
    /// puts back there). Returns the change of the store's count of busy entities (its next
    /// tick checks its chunk section).
    pub(crate) fn legacy_pushed(
        &mut self,
        pos: [f64; 3],
        bb: [f64; 6],
        on_ground: bool,
        in_web: bool,
        sits_back: bool,
    ) -> i32 {
        let idle = !self.busy();
        self.pos = pos;
        self.bb = Some(bb);
        self.ground = Some(on_ground);
        self.in_web = in_web;
        self.order_pending = true;
        if let Some(s) = self.shulker.as_mut()
            && sits_back
        {
            // Its next tick puts it back on its attached block.
            s.settled = false;
        }
        self.lerp_delta(idle)
    }
}

/// 1.8 `updatePassengerPosition` of vehicle `v` (drawn state `vc`) for rider `r`: the seat
/// (`None`: a vehicle whose seat is not modelled, a horse).
pub(crate) fn seat_1_8(v: &Entity, vc: &Client, r: &Entity) -> Option<[f64; 3]> {
    let height = || v.sizer.and_then(|s| s.registered).map(|(_, h)| h);
    let mounted = match v.ty {
        // BoatEntity -0.3, AbstractMinecartEntity 0.
        EntityType::LegacyObject(1) => -0.3,
        EntityType::LegacyObject(10) => 0.0,
        // HorseBaseEntity places its rider with its own rotation: not modelled.
        EntityType::LegacyMob(100) => return None,
        // SpiderEntity / CaveSpiderEntity: `height * 0.5F`.
        EntityType::LegacyMob(52 | 59) => f64::from(height()? * 0.5),
        // Entity: `height * 0.75`.
        _ => f64::from(height()?) * 0.75,
    };
    let baby = || r.meta.byte(12).is_some_and(|b| b == 1);
    let offset = match r.ty {
        EntityType::Player => -0.35,
        // ZombieEntity (and the zombie pigman), SkeletonEntity: adults -0.35.
        EntityType::LegacyMob(54 | 57) if baby() => 0.0,
        EntityType::LegacyMob(51 | 54 | 57) => -0.35,
        // SilverfishEntity.
        EntityType::LegacyMob(60) => 0.2,
        _ => 0.0,
    };
    let [x, y, z] = vc.pos;
    if v.ty == EntityType::LegacyObject(1) {
        // `Math.cos(yaw * PI / 180) * 0.4` (the JVM's cos; the platform's here).
        let a = f64::from(vc.rot[0]) * std::f64::consts::PI / 180.0;
        return Some([x + a.cos() * 0.4, y + mounted + offset, z + a.sin() * 0.4]);
    }
    Some([x, y + mounted + offset, z])
}

/// 1.12 `updatePassengerPosition` of vehicle `v` for rider `r`: the seat and, on a boat, the
/// rider's yaw kept within 105° of the boat's (`copyEntityData`). `None`: not modelled (horses
/// and other vehicles with their own seats).
pub(crate) fn seat_1_12(v: &Entity, vc: &Client, r: &Entity) -> Option<([f64; 3], Option<f32>)> {
    let baby = || matches!(r.meta.get(12), Some(crate::entity::MetaValue::Bool(true)));
    let offset = match r.ty {
        EntityType::Player => -0.35,
        // ZombieEntity and its kinds (zombie pigman, husk, zombie villager): adults -0.45.
        EntityType::LegacyMob(54 | 57 | 23 | 27) if baby() => 0.0,
        EntityType::LegacyMob(54 | 57 | 23 | 27) => -0.45,
        // SilverfishEntity, EndermiteEntity.
        EntityType::LegacyMob(60 | 67) => 0.1,
        _ => 0.0,
    };
    let [x, y, z] = vc.pos;
    match v.ty {
        EntityType::LegacyObject(1) => {
            // Boat: `(float)(-0.1 + offset)`; a second passenger sits 0.6 behind, the first 0.2
            // ahead, turned with the boat (MathHelper's table).
            let g = (-0.1 + offset) as f32;
            let ps = v.passengers();
            let f: f32 = if ps.len() > 1 {
                if ps.first() == Some(&r.id) { 0.2 } else { -0.6 }
            } else {
                0.0
            };
            let yaw = vc.rot[0];
            let (dx, dz) = if f == 0.0 {
                (0.0, 0.0)
            } else {
                let a = -yaw * (std::f64::consts::PI / 180.0) as f32
                    - (std::f64::consts::PI / 2.0) as f32;
                let (c, s) = (table_cos(a), table_sin(a));
                let fx = f64::from(f);
                (fx * f64::from(c), -fx * f64::from(s))
            };
            let ry = r.client.as_ref().map_or(r.yaw, |rc| rc.rot[0]);
            let d = wrap_degrees_f32(ry - yaw);
            let k = d.clamp(-105.0, 105.0);
            Some(([x + dx, y + f64::from(g), z + dz], Some(ry + (k - d))))
        }
        EntityType::LegacyObject(10) => Some(([x, y + offset, z], None)),
        EntityType::LegacyMob(100) => None,
        _ => {
            let h = v.sizer.and_then(|s| s.registered).map(|(_, h)| h)?;
            Some(([x, y + f64::from(h) * 0.75 + offset, z], None))
        }
    }
}

/// MathHelper's table `(cos, sin)` of a float angle.
#[inline]
pub(crate) fn table_cos_sin(a: f32) -> (f32, f32) {
    (table_cos(a), table_sin(a))
}

/// `MathHelper.wrapDegrees(float)`.
#[inline]
pub(crate) fn wrap_degrees_f32(d: f32) -> f32 {
    let mut d = d % 360.0;
    if d >= 180.0 {
        d -= 360.0;
    }
    if d < -180.0 {
        d += 360.0;
    }
    d
}

/// MathHelper's table sine of a float angle (65536 entries, `i * 2 PI / 65536`).
pub(crate) fn table_sin(a: f32) -> f32 {
    SIN_TABLE[((a * 10430.378) as i32 & 0xFFFF) as usize]
}

/// MathHelper's table cosine (a quarter turn into the sine table).
fn table_cos(a: f32) -> f32 {
    SIN_TABLE[((a * 10430.378 + 16384.0) as i32 & 0xFFFF) as usize]
}

/// `MathHelper.SIN_TABLE`: `(float) Math.sin(i * PI * 2 / 65536)`, built at first use (only a
/// two-passenger boat reads it).
static SIN_TABLE: std::sync::LazyLock<Box<[f32; 65536]>> = std::sync::LazyLock::new(|| {
    let mut t = Box::new([0.0f32; 65536]);
    for (i, v) in t.iter_mut().enumerate() {
        *v = (i as f64 * std::f64::consts::PI * 2.0 / 65536.0).sin() as f32;
    }
    t
});

/// `MathHelper.wrapDegrees(double)` (1.8.9 / 1.12.2).
#[inline]
fn wrap_degrees(d: f64) -> f64 {
    let mut d = d % 360.0;
    if d >= 180.0 {
        d -= 360.0;
    }
    if d < -180.0 {
        d += 360.0;
    }
    d
}

/// A relative move, look or bare `entity` packet was applied to `e` (its server position and,
/// with `rotated`, its rotation are the new ones): `onEntityUpdate`'s
/// `updateTrackedPositionAndAngles(server position, rotation, 3)`, where a packet without a
/// rotation passes the drawn rotation.
///
/// Returns the change of the store's count of interpolating entities (+1 when it starts, −1
/// when it stops, else 0): a tick without any visits nothing.
#[inline]
#[must_use]
pub(crate) fn relative(e: &mut Entity, rotated: bool, now: u64) -> i32 {
    let (pos, rot) = (e.pos, [e.yaw, e.pitch]);
    let Some(c) = e.client.as_deref_mut() else {
        return 0;
    };
    let idle = !c.busy();
    c.server_moved(pos, now);
    c.ground = None;
    match c.lerp {
        Lerp::Player | Lerp::Living => {
            let rot = if rotated { rot } else { c.rot };
            c.track(pos, rot, 3);
        }
        // `ShulkerEntity.updateTrackedPositionAndAngles` does nothing.
        Lerp::Shulker | Lerp::External => {}
        Lerp::Fixed => c.fixed_move(pos, rot),
        Lerp::Boat | Lerp::Minecart | Lerp::Boat12 => {
            let rot = if rotated { rot } else { c.rot };
            c.vehicle_track(pos, rot, 3);
        }
    }
    c.lerp_delta(idle)
}

/// A teleport was applied to `e`: `onEntityPosition` keeps the drawn position when the new one
/// is within 1/32 (y: 1/64) of it, then `updateTrackedPositionAndAngles(.., 3)` (1.8) or
/// `(.., 0)` for the kept position (1.12).
///
/// Returns the change of the store's count of interpolating entities (see [`relative`]).
#[inline]
#[must_use]
pub(crate) fn teleport(e: &mut Entity, now: u64) -> i32 {
    let (pos, rot, era) = (e.pos, [e.yaw, e.pitch], e.era);
    let ridden = !e.passengers().is_empty();
    let Some(c) = e.client.as_deref_mut() else {
        return 0;
    };
    let idle = !c.busy();
    c.server_moved(pos, now);
    c.ground = None;
    match c.lerp {
        Lerp::Player | Lerp::Living => {}
        Lerp::Shulker => return c.lerp_delta(idle),
        Lerp::External => return 0,
        Lerp::Fixed => {
            c.fixed_move(pos, rot);
            return c.lerp_delta(idle);
        }
        Lerp::Boat | Lerp::Minecart | Lerp::Boat12 => {}
    }
    let d = c.pos;
    // `!(a >= t)` as vanilla writes it: NaN counts as near.
    let far = |a: f64, t: f64| a.partial_cmp(&t).is_some_and(|o| o.is_ge());
    let near = !far((d[0] - pos[0]).abs(), 0.031_25)
        && !far((d[1] - pos[1]).abs(), 0.015_625)
        && !far((d[2] - pos[2]).abs(), 0.031_25);
    let target = if near { d } else { pos };
    if c.lerp == Lerp::Boat && ridden {
        // BoatEntity.updateTrackedPositionAndAngles with `interpolate` (a teleport) and a rider:
        // there at once, the interpolation and both velocities zeroed.
        c.pos = target;
        c.bb = None;
        c.rot = rot;
        c.steps = 0;
        c.vel = [0.0; 3];
        c.server_vel = [0.0; 3];
        c.order_pending = true;
    } else if matches!(c.lerp, Lerp::Boat | Lerp::Minecart | Lerp::Boat12) {
        // 1.12's near teleport passes 0 steps (a minecart then takes 2, a boat always 10).
        let steps = if near && era == Era::V1_12 { 0 } else { 3 };
        c.vehicle_track(target, rot, steps);
    } else if near {
        let steps = if era == Era::V1_8 { 3 } else { 0 };
        c.track(d, rot, steps);
    } else {
        c.track(pos, rot, 3);
    }
    c.lerp_delta(idle)
}

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

    fn player(pos: [f64; 3]) -> Entity {
        let mut e = Entity::new(7, EntityType::Player);
        e.pos = pos;
        e.client = Some(Box::new(Client::new(&e, Lerp::Player, 0, 0)));
        e
    }

    fn drawn(e: &Entity) -> [f64; 3] {
        e.client.as_ref().unwrap().pos
    }

    fn tick(e: &mut Entity) {
        let _ = e.client.as_deref_mut().unwrap().step(false);
    }

    /// Vanilla's three steps: 1/3, then 1/2 of the rest, then the rest; a second packet restarts
    /// the count from the drawn position.
    #[test]
    fn three_steps_and_restart() {
        let mut e = player([0.0, 64.0, 0.0]);
        e.pos = [3.0, 64.0, 0.0];
        let _ = relative(&mut e, false, 1);
        assert_eq!(
            drawn(&e),
            [0.0, 64.0, 0.0],
            "packets do not move the drawn entity"
        );
        tick(&mut e);
        assert_eq!(drawn(&e)[0], 1.0);
        e.pos = [6.0, 64.0, 0.0];
        let _ = relative(&mut e, false, 2);
        tick(&mut e);
        // 1 + (6 - 1) / 3
        assert_eq!(drawn(&e)[0], 1.0 + 5.0 / 3.0);
        tick(&mut e);
        let x = 1.0 + 5.0 / 3.0;
        assert_eq!(drawn(&e)[0], x + (6.0 - x) / 2.0);
        tick(&mut e);
        assert_eq!(drawn(&e)[0], 6.0);
        tick(&mut e);
        assert_eq!(drawn(&e)[0], 6.0);
        let c = e.client.as_ref().unwrap();
        assert_eq!((c.spawned, c.moved, c.from_tick), (0, 2, 1));
        assert_eq!(c.velocity(), [3.0, 0.0, 0.0]);
    }

    /// A look-only packet restarts the 3 steps towards the same target.
    #[test]
    fn look_restarts_steps() {
        let mut e = player([0.0, 64.0, 0.0]);
        e.pos = [3.0, 64.0, 0.0];
        let _ = relative(&mut e, false, 1);
        tick(&mut e);
        e.yaw = 90.0;
        let _ = relative(&mut e, true, 2);
        tick(&mut e);
        assert_eq!(drawn(&e)[0], 1.0 + 2.0 / 3.0);
        let c = e.client.as_ref().unwrap();
        assert_eq!(c.rot[0], 30.0);
        assert_eq!(c.moved, 1, "a look is not a position update");
    }

    /// Teleports near the drawn position freeze it (1.8: 3 steps there, 1.12: 0).
    #[test]
    fn near_teleport_freezes() {
        for (era, steps) in [(Era::V1_8, 3), (Era::V1_12, 0)] {
            let mut e = player([0.0, 64.0, 0.0]);
            e.era = era;
            e.pos = [0.03, 64.0, 0.0];
            let _ = teleport(&mut e, 1);
            let c = e.client.as_ref().unwrap();
            assert_eq!((c.target, c.steps), ([0.0, 64.0, 0.0], steps));
            e.pos = [0.0, 64.015_625, 0.0];
            let _ = teleport(&mut e, 2);
            assert_eq!(e.client.as_ref().unwrap().target, [0.0, 64.015_625, 0.0]);
        }
    }

    /// Yaw takes the short way round; players wrap with loops, living entities with
    /// `wrapDegrees`, and `setRotation` keeps the result below 360 in magnitude.
    #[test]
    fn yaw_wraps() {
        let mut e = player([0.0; 3]);
        e.client.as_deref_mut().unwrap().rot = [170.0, 0.0];
        e.yaw = -170.0;
        let _ = relative(&mut e, true, 1);
        tick(&mut e);
        let y = e.client.as_ref().unwrap().rot[0];
        assert_eq!(y, (170.0f64 + 20.0 / 3.0) as f32);
        for _ in 0..2 {
            tick(&mut e);
        }
        assert_eq!(e.client.as_ref().unwrap().rot[0], 190.0);
        assert_eq!(wrap_degrees(540.0), -180.0);
        assert_eq!(wrap_degrees(-190.0), 170.0);
    }
}