ghast-client 0.5.5

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
//! 1.16.5: the chunk store and the vanilla-exact physics.

use ghast_protocol::{BlockPos, RawPacket};

use super::*;
use crate::common::{Abilities, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};
use crate::sim::shared::aabb;

mod blocks;
mod elytra;
mod entities;
mod fishing;
mod hooks;
mod nonliving;
mod piston;
mod records;
mod vehicles;

// ---- 1.16.5: world + stand-still mover --------------------------------------------------

/// 1.16.5: the chunk store and the stand-still mover (no 1.16 physics yet).
pub(crate) struct Sim16 {
    world: ghast_world::v1_16_5::World,
    player: ghast_physics::v1_16_5::PlayerState,
    packets: ghast_physics::Packets,
    rec: Option<crate::record::Recorder>,
    force_step_position: ForceStepPosition,
    entities: Option<ghast_entity::v1_16_5::Tracker>,
    /// Block changes since the last drain (position, version raw state), when collected.
    updates: BlockUpdates,
    /// The session's last join and respawn packets: a tracker started mid-session replays
    /// them to learn our entity id and dimension.
    session: SessionPackets,
    /// The world keeps block entities (signs, tile entity NBT).
    block_entities: bool,
    /// Other entities push the player ([`Sim::set_entity_push`]).
    entity_push: bool,
    /// With entity tracking: the teams' collision rules (`teams` packets).
    teams: Option<Box<super::teams::Teams>>,
    /// The player's scoreboard name (team rules).
    profile_name: Box<str>,
    /// This tick's entity scratch (see [`Sim16::entities_around`]).
    around: Around16,
    /// Where the client world files the player: its position after its last tick.
    filed_pos: [f64; 3],
    /// Movement state beyond the player (the dimension type, riptide).
    ext: ghast_physics::v1_16_5::PlayerExt,
    /// The tick takes the slow path: entity tracking, an extension state that changes the
    /// movement or a use the riptide follows ([`Sim16::update_slow`]); a use that starts takes
    /// it too.
    slow: bool,
    /// Riptide: the tridents in the hands, the rain, the use (see [`Riptide16`]).
    rt: Riptide16,
    /// `ClientPlayerInteractionManager.unacknowledgedPlayerActions`: the dig actions the
    /// server has not answered yet.
    unacked: crate::sim::predict::Unacked,
    /// An answer moved the player back ([`Sim::take_snap`]).
    snapped: bool,
    /// Gliding: the server's flag 7 and the firework rockets attached to us (see [`Glide16`]).
    glide: Box<Glide16>,
    /// The boat we ride and control (`set_passengers` naming us, with entity tracking).
    ride: Option<Box<Ride16>>,
    /// The answer to a server packet that goes out at once (`vehicle_move`).
    reply: Option<Outbound>,
    /// The boat the player left (see [`Parked16`]).
    parked: Option<Parked16>,
    /// The boat the player left last (see [`LeftBoat16`]).
    left_boat: Option<Box<LeftBoat16>>,
    /// Living mounts: the item ids in our hands and the attributes the server sent for the
    /// mount types around (see [`Mounts16`]).
    mounts: Box<Mounts16>,
    /// The flags byte (entity data index 0) the server last sent for our entity.
    server_flags: Option<u8>,
    /// The absorption the server last sent for our entity (player entity data; 0 before any).
    absorption: f32,
    /// `absorption` changed since the engine last took it.
    /// Our living flags (entity data index 7) when a packet set them (taken per tick).
    living_flags: Option<u8>,
    absorption_dirty: bool,
    /// Our sleeping position changed in the entity data (`take_sleep`).
    sleep: Option<Option<ghast_protocol::BlockPos>>,
    /// Blocks pistons move (the client runs the piston itself on a block-event packet).
    pistons: ghast_physics::v1_16_5::Pistons,
    /// World changes of the pistons, applied right away (kept to reuse the allocation).
    piston_edits: ghast_physics::v1_16_5::Edits,
    /// An unmodelled piston condition in the last movement step or the packets since
    /// ([`super::WorldView::piston_uncertain`]): the player's `age` when it was raised (it
    /// holds while that counter has not moved on, so the plain tick never touches it).
    piston_uncertain_at: Option<i32>,
    /// Client ticks so far: the world time pistons compare (it advances by one per tick).
    piston_time: i64,
    /// What the pistons' pushes of other entities carry between ticks, by entity id.
    piston_carry: Vec<(i32, ghast_physics::v1_16_5::PistonCarry)>,
    /// A piston moved a shulker off its block in the last tick (it pushes from there at its
    /// next tick before it sits back).
    piston_moved_shulker: bool,
    /// With entity tracking and [`crate::Interests::ENTITY_PHYSICS`]: the client-side physics
    /// of the tracked non-living entities (`None`: off, nothing runs for them).
    nonliving: Option<Box<nonliving::NonLiving16>>,
    /// The bot's own fishing bobber ([`crate::fishing`]).
    fishing: crate::fishing::Fishing,
}

/// A boat the player drove and left: the client moved it, the server sends no move for it, so
/// it stays where the player left it until the server moves it.
#[derive(Debug, Clone, Copy)]
struct Parked16 {
    id: i32,
    pos: [f64; 3],
    bb: [f64; 6],
    /// The tracker's position of it when the player left (a different one: the server moved it).
    tracked: Option<[f64; 3]>,
}

/// `park` from inside a tick (the tick count advances at its end) or between ticks.
const PARK_IN_TICK: i64 = 1;
const PARK_BETWEEN_TICKS: i64 = 0;

/// The boat the player last left, as it was then: a boat the client does not move keeps its
/// turn (`yawVelocity`, never decayed) and paddle flags; boarded again before it ticked, it is
/// exactly this.
#[derive(Debug)]
struct LeftBoat16 {
    id: i32,
    /// The client tick count (the sim's `piston_time`) of the next tick after it left.
    tick: i64,
    boat: ghast_physics::v1_16_5::Boat,
}

/// The client position and box of entity `id`: the tracker's, or where a parked boat is.
fn view(
    t: &ghast_entity::v1_16_5::Tracker,
    parked: Option<Parked16>,
    id: i32,
) -> (Option<[f64; 3]>, Option<[f64; 6]>) {
    // The client view holds where we left it (see `Tracker::client_vehicle_moved`) until an
    // interpolation step re-centres its box.
    if let Some(k) = parked
        && k.id == id
        && t.client_position(id) == k.tracked
        && (k.tracked.is_none() || t.client_box(id) == Some(k.bb))
    {
        return (Some(k.pos), Some(k.bb));
    }
    (t.client_position(id), t.client_box(id))
}

/// The minecart the player sits in: its entity id and its client-side interpolation.
#[derive(Debug)]
struct Cart16 {
    id: i32,
    cart: ghast_physics::v1_16_5::Minecart,
}

/// What riding a living mount reads beyond the tracker: the item ids in our hands (a pig or
/// strider follows a rider holding its stick) and, per entity of a mount type, the movement
/// speed and horse jump strength attributes of its last attributes packet.
#[derive(Debug, Default)]
struct Mounts16 {
    hands: [Option<i32>; 2],
    seen: Vec<MountSeen16>,
    /// The mount we got off by sneaking (it still lists us until the server says otherwise).
    left: Option<i32>,
}

/// What the server sent for an entity of a mount type: its movement speed and horse jump
/// strength attributes, its saddle and its boost time (entity data); and, from its spawn packet
/// on, the mob as the client watches it (`shadow`, see [`ghast_physics::v1_16_5::Mount::watched`]):
/// what the player boards.
#[derive(Debug, Clone, Copy)]
struct MountSeen16 {
    id: i32,
    speed: f64,
    jump: f64,
    saddled: bool,
    boost: Option<i32>,
    /// `None`: its spawn was not seen, or another entity rides it (not modelled).
    shadow: Option<ghast_physics::v1_16_5::Mount>,
}

impl Mounts16 {
    /// A hand holds the stick that steers `kind`.
    fn holds_stick(&self, kind: ghast_physics::v1_16_5::MountKind) -> bool {
        use ghast_physics::v1_16_5::MountKind;
        let stick = match kind {
            MountKind::Pig => "carrot_on_a_stick",
            MountKind::Strider => "warped_fungus_on_a_stick",
            _ => return false,
        };
        self.hands.iter().flatten().any(|&id| {
            u16::try_from(id)
                .ok()
                .and_then(ghast_data::v1_16_5::Item::from_id)
                .is_some_and(|i| i.info().name == stick)
        })
    }
}

/// One client tick of every mount the client watches (`tick_watched`), where the client world
/// ticks it (a loaded column); one another entity rides is no longer modelled.
#[cold]
#[inline(never)]
fn tick_watched_mounts(
    mounts: &mut Mounts16,
    t: &ghast_entity::v1_16_5::Tracker,
    w: &ghast_world::v1_16_5::World,
    ultrawarm: bool,
    vehicle: Option<i32>,
) {
    let me = t.self_id();
    for s in &mut mounts.seen {
        if s.shadow.is_none() || vehicle == Some(s.id) {
            continue;
        }
        let Some(e) = t.get(s.id) else {
            continue;
        };
        if e.vehicle().is_some() || e.passengers().iter().any(|&p| Some(p) != me) {
            s.shadow = None;
            continue;
        }
        if !t.client_ticks(e, |x, z| w.is_column_loaded(x, z)) {
            continue;
        }
        if let Some(m) = s.shadow.as_mut() {
            ghast_physics::v1_16_5::tick_watched(m, w, ultrawarm);
        }
    }
}

/// A watched mount that pushed the player (`rank`: its tick-order key in the push lists) takes
/// the opposite push itself.
#[cold]
#[inline(never)]
fn watched_mount_pushed(
    mounts: &mut Mounts16,
    t: &ghast_entity::v1_16_5::Tracker,
    rank: u32,
    player: [f64; 2],
) {
    for s in &mut mounts.seen {
        if t.client_tick_rank(s.id).map(|r| r.saturating_mul(4)) == Some(rank)
            && let Some(m) = s.shadow.as_mut()
        {
            m.pushed_player(player);
            return;
        }
    }
}

/// The tracker's client view of the mount we ride is ours: its position, box and ground flag; a
/// mount the client moves also drops its interpolation and is its own tracked position every
/// tick (`LivingEntity.tickMovement`), what the server's moves start from once it no longer is.
#[cold]
#[inline(never)]
fn mount_view(t: &mut ghast_entity::v1_16_5::Tracker, id: i32, m: &ghast_physics::v1_16_5::Mount) {
    let b = m.bb;
    let bb = [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z];
    if m.controlled() {
        t.client_vehicle_moved(id, m.pos, bb, m.yaw, m.tracked);
    }
    t.client_pushed(id, m.pos, bb, m.on_ground);
}

/// We left the living mount we rode (`ride` is then empty): the client watches it again from
/// where it is.
fn unmount(ride: &mut Option<Box<Ride16>>, mounts: &mut Mounts16) {
    if let Some(r) = ride.take() {
        match *r {
            Ride16::Mount(Mount16 { id, mut mount }) => {
                mount.leave();
                if let Some(s) = mounts.seen.iter_mut().find(|a| a.id == id) {
                    s.shadow = Some(mount);
                }
            }
            other => *ride = Some(Box::new(other)),
        }
    }
}

/// The living mount the player rides: its entity id and its client-side state.
#[derive(Debug)]
struct Mount16 {
    id: i32,
    mount: ghast_physics::v1_16_5::Mount,
}

/// The mount type of a tracked entity.
fn mount_kind(e: &ghast_entity::Entity) -> Option<ghast_physics::v1_16_5::MountKind> {
    ghast_physics::v1_16_5::MountKind::from_name(ghast_entity::v1_16_5::info(e.entity_type())?.name)
}

/// The boat the player rides: its entity id and its client-side state.
#[derive(Debug)]
struct BoatRide16 {
    id: i32,
    boat: ghast_physics::v1_16_5::Boat,
}

/// The vehicle the player rides (one box, so the sim's layout does not change with it): the boat
/// it controls or the minecart the server moves.
#[derive(Debug)]
enum Ride16 {
    Boat(BoatRide16),
    Cart(Cart16),
    Mount(Mount16),
}

impl Ride16 {
    fn id(&self) -> i32 {
        match self {
            Ride16::Boat(r) => r.id,
            Ride16::Cart(c) => c.id,
            Ride16::Mount(m) => m.id,
        }
    }
}

fn boat_mut(r: &mut Option<Box<Ride16>>) -> Option<&mut BoatRide16> {
    match r.as_deref_mut() {
        Some(Ride16::Boat(b)) => Some(b),
        _ => None,
    }
}

fn mount_mut(r: &mut Option<Box<Ride16>>) -> Option<&mut Mount16> {
    match r.as_deref_mut() {
        Some(Ride16::Mount(m)) => Some(m),
        _ => None,
    }
}

fn cart_mut(r: &mut Option<Box<Ride16>>) -> Option<&mut Cart16> {
    match r.as_deref_mut() {
        Some(Ride16::Cart(c)) => Some(c),
        _ => None,
    }
}

/// What the 1.16.5 glide reads beyond the physics state: our shared flags and the firework
/// rockets attached to us, decoded once an elytra was seen in the chest slot.
#[derive(Debug, Default)]
struct Glide16 {
    /// Our entity data, rocket spawns and entity removals are read (an elytra was equipped on a
    /// jump press in the air).
    watch: bool,
    /// Firework rockets spawned but not (yet) known as attached to us: id, spawn position.
    pending: Vec<(i32, [f64; 3])>,
    /// The rockets attached to us (`FireworkRocketEntity` with us as its shooter).
    rockets: Vec<Rocket16>,
}

/// A firework rocket attached to us, as the client world has it.
#[derive(Clone, Copy, Debug)]
struct Rocket16 {
    id: i32,
    /// Its position: the spawn position, then ours after each of its ticks.
    pos: [f64; 3],
    /// In its chunk's entity section (`updateNeeded`): it ticks while that chunk is loaded.
    filed: bool,
    /// It ticks before us in the client world's entity map (with entity tracking; else after).
    before: bool,
}

/// Rockets spawned near us that may still get attached (a bound against a flood of rockets).
const MAX_PENDING_ROCKETS_16: usize = 32;
/// The 1.16.5 entity type id of `firework_rocket`.
const FIREWORK_ROCKET_16: i32 = 27;

/// What the engine's look at the held items ([`Sim::item_use_facts`], through `&self`) leaves
/// for the tick. Boxed: interior mutability inline in [`Sim16`] would cost every `&Sim16`
/// borrow of the engine its no-alias guarantees.
#[derive(Debug, Default)]
struct HeldCells {
    /// Per hand (main, off): the riptide level of the trident there (0: none), whether that
    /// hand's use would start (`HeldItem::usable` and the food rule, as the hands decide), and
    /// the player's age when the engine looked (an empty hand is not looked at: an older entry
    /// is stale).
    hands: std::cell::Cell<[(u8, bool, i32); 2]>,
    /// A riptide trident was held: our entity data is read from now on (the spin flag).
    watch: std::cell::Cell<bool>,
    /// The packet filter must change ([`Sim::take_filter_dirty`]).
    filter_dirty: std::cell::Cell<bool>,
}

/// What the 1.16.5 riptide reads beyond the physics state.
#[derive(Debug)]
struct Riptide16 {
    /// See [`HeldCells`].
    held: Box<HeldCells>,
    /// The use in progress (riptide level of its hand), and the player ticks it lasted.
    using: Option<u8>,
    use_ticks: u32,
    /// `World.rainGradient` (game state packets).
    rain_level: f32,
    /// The dimension type has sky light (no rain without it).
    sky: bool,
    /// The world's hashed seed (biome zoom, `BiomeAccess`).
    seed: i64,
    /// Our entity id (the join packet).
    own_id: i32,
}

impl Default for Riptide16 {
    fn default() -> Self {
        Riptide16 {
            held: Box::default(),
            using: None,
            use_ticks: 0,
            rain_level: 0.0,
            sky: true,
            seed: 0,
            own_id: i32::MIN,
        }
    }
}

/// `VoronoiBiomeAccessType.getBiome`: the biome cell (quart position) whose biome the block at
/// `x`, `y`, `z` has, for the world's hashed seed. The client decodes the dimension type from
/// the join packet with `DimensionType.CODEC`, which always builds the 3D access type.
fn voronoi_cell(seed: i64, x: i32, y: i32, z: i32) -> [i32; 3] {
    // SeedMixer.mixSeed.
    let mix = |s: i64, salt: i64| {
        s.wrapping_mul(
            s.wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407),
        )
        .wrapping_add(salt)
    };
    let distribute = |s: i64| (f64::from((s >> 24).rem_euclid(1024) as i32) / 1024.0 - 0.5) * 0.9;
    let (x, y, z) = (x - 2, y - 2, z - 2);
    let base = [x >> 2, y >> 2, z >> 2];
    let frac = [
        f64::from(x & 3) / 4.0,
        f64::from(y & 3) / 4.0,
        f64::from(z & 3) / 4.0,
    ];
    let mut best = 0;
    let mut dist = 0.0;
    for o in 0..8 {
        let hi = [o & 4 != 0, o & 2 != 0, o & 1 != 0];
        let c: [i64; 3] = std::array::from_fn(|i| i64::from(base[i] + i32::from(hi[i])));
        let f: [f64; 3] = std::array::from_fn(|i| if hi[i] { frac[i] - 1.0 } else { frac[i] });
        let mut l = mix(seed, c[0]);
        l = mix(l, c[1]);
        l = mix(l, c[2]);
        l = mix(l, c[0]);
        l = mix(l, c[1]);
        l = mix(l, c[2]);
        let d = distribute(l);
        l = mix(l, seed);
        let e = distribute(l);
        l = mix(l, seed);
        let g = distribute(l);
        let sq = |v: f64| v * v;
        let v = sq(f[2] + g) + sq(f[1] + e) + sq(f[0] + d);
        if o == 0 || dist > v {
            best = o;
            dist = v;
        }
    }
    [
        base[0] + i32::from(best & 4 != 0),
        base[1] + i32::from(best & 2 != 0),
        base[2] + i32::from(best & 1 != 0),
    ]
}

/// A byte field of a 1.16.5 dimension type compound (`ultrawarm`, `has_skylight`).
fn dimension_flag(dimension: &ghast_protocol::nbt::RawNbt, name: &str) -> Option<bool> {
    use ghast_protocol::nbt::Tag;
    let Ok(Some(t)) = dimension.parse() else {
        return None;
    };
    match t.tag.as_compound().and_then(|c| c.get(name)) {
        Some(Tag::Byte(b)) => Some(*b != 0),
        _ => None,
    }
}

/// The riptide level (`Enchantments` list, `minecraft:riptide`) and the `Damage` of a 1.16.5
/// stack's NBT.
fn trident_nbt(s: &ghast_inventory::Stack) -> (u8, i32) {
    use ghast_protocol::nbt::Tag;
    let Some(root) = s.nbt().and_then(|n| n.parse().ok().flatten()) else {
        return (0, 0);
    };
    let Some(c) = root.tag.as_compound() else {
        return (0, 0);
    };
    let num = |t: Option<&Tag>| match t {
        Some(Tag::Short(v)) => i32::from(*v),
        Some(Tag::Int(v)) => *v,
        Some(Tag::Byte(v)) => i32::from(*v),
        _ => 0,
    };
    let mut level = 0;
    if let Some(Tag::List(l)) = c.get("Enchantments") {
        for e in l.items.iter().filter_map(Tag::as_compound) {
            if matches!(e.get("id"), Some(Tag::String(n)) if n == "minecraft:riptide") {
                level = u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
                break;
            }
        }
    }
    (level, num(c.get("Damage")))
}

/// The entities around the player this tick.
#[derive(Debug, Default)]
struct Around16 {
    /// The boxes the player collides with.
    boxes: Vec<ghast_physics::math::Aabb>,
    /// The pushes of the entities that tick after the player, in tick order.
    after: Vec<(u32, ghast_physics::v1_16_5::Pusher)>,
    /// The pushes of the entities that tick before it.
    before: Vec<(u32, ghast_physics::v1_16_5::Pusher)>,
    /// The tracker's client view ticked this tick (in [`Sim::step`]).
    ticked: bool,
    /// What the riptide spin can touch this tick.
    others: Vec<ghast_physics::v1_16_5::OtherEntity>,
    /// Pushing entities that ride a vehicle, as the client view held them before this tick
    /// (id, vehicle, position, box): they push from there when their vehicle ticks.
    riders: Vec<(i32, i32, [f64; 3], [f64; 6])>,
    /// Empty boats that tick after the player and may push it: they take the opposite push.
    empty_boats_after: Vec<ghast_physics::v1_16_5::Pusher>,
    /// The empty boats whose last tick pushed the player: their position and the velocity
    /// they took (read when the player boards one before its next tick).
    boat_pushes: Vec<([f64; 3], [f64; 2])>,
}

/// Per entity type: the player collides with it.
const COLLIDES: u8 = 1;
/// Per entity type: a living entity of this type pushes the player.
const PUSH_LIVING: u8 = 2;
/// Per entity type: its tick pushes the player like a boat.
const PUSH_BOAT: u8 = 4;

/// An empty boat near the player: when its tick pushes the player it takes the opposite push
/// (kept in [`Around16::boat_pushes`]). `now`: it ticks before the player, or the player has
/// ticked already; else it is kept for after the player's tick.
#[cold]
#[inline(never)]
fn empty_boat(
    a: &mut Around16,
    pusher: &ghast_physics::v1_16_5::Pusher,
    now: bool,
    p: &ghast_physics::v1_16_5::PlayerState,
    filed: [f64; 3],
    world: &ghast_world::v1_16_5::World,
) {
    if !now {
        a.empty_boats_after.push(*pusher);
        return;
    }
    if let Some(dv) =
        ghast_physics::v1_16_5::boat_push_from_player(pusher.pos, &pusher.bb, p, filed, world)
    {
        a.boat_pushes.push((pusher.pos, dv));
    }
}

/// The pushes of entities that ride a vehicle the bot is not in (`tickPassenger`: right after
/// their vehicle's tick, in seat order, from where they sat before their tick). `p_bb` / `at` /
/// `m` as for the other pushers.
#[cold]
#[inline(never)]
#[allow(clippy::too_many_arguments)]
fn rider_pushes(
    t: &ghast_entity::v1_16_5::Tracker,
    a: &mut Around16,
    p_bb: &ghast_physics::math::Aabb,
    at: &ghast_physics::math::Aabb,
    m: [f64; 3],
    entity_push: bool,
    teams: Option<&crate::sim::teams::Teams>,
    own: &str,
    loaded: &impl Fn(i32, i32) -> bool,
) {
    if !entity_push {
        return;
    }
    let me = t.self_id();
    for &(id, v, pos, b) in &a.riders {
        let Some(ve) = t.get(v) else { continue };
        // Not in the same vehicle (isConnectedThroughVehicle), and the vehicle ticks.
        if me.is_some_and(|me| ve.passengers().contains(&me)) || !t.client_ticks(ve, loaded) {
            continue;
        }
        let Some(e) = t.get(id) else { continue };
        if t.is_spectator(e) || !t.client_alive(id) {
            continue;
        }
        let before = t.ticks_before_self(v);
        let (margin, from) = if before { ([0.25; 3], p_bb) } else { (m, at) };
        if !near(&b, from, margin) {
            continue;
        }
        if let Some(teams) = teams {
            let mut buf = [0u8; 36];
            let name = match t.scoreboard_name(e) {
                Some(n) => n,
                None => e.uuid().hyphenated().encode_lower(&mut buf),
            };
            if !teams.may_push(name, own) {
                continue;
            }
        }
        let kind = if entity_bits(e) & PUSH_BOAT != 0 {
            ghast_physics::v1_16_5::PushKind::Boat
        } else {
            ghast_physics::v1_16_5::PushKind::Living
        };
        let seat = ve.passengers().iter().position(|&x| x == id).unwrap_or(0);
        let rank = t
            .client_tick_rank(v)
            .unwrap_or(u32::MAX)
            .saturating_mul(4)
            .saturating_add(1 + seat.min(2) as u32);
        let pusher = ghast_physics::v1_16_5::Pusher::new(pos, aabb(b), kind);
        if before {
            a.before.push((rank, pusher));
        } else {
            a.after.push((rank, pusher));
        }
    }
}

/// [`COLLIDES`] / [`PUSH_LIVING`] / [`PUSH_BOAT`] of a 1.16.5 entity (players push).
/// The 1.16.5 registry name of an entity's type (players: `"player"`).
fn type_name(e: &ghast_entity::Entity) -> Option<&'static str> {
    static NAMES: std::sync::OnceLock<Box<[Option<&'static str>]>> = std::sync::OnceLock::new();
    let names = NAMES.get_or_init(|| {
        let types = ghast_data::v1_16_5::entities();
        let n = types
            .iter()
            .map(|t| usize::from(t.id) + 1)
            .max()
            .unwrap_or(0);
        let mut v = vec![None; n];
        for t in types {
            v[usize::from(t.id)] = Some(t.name);
        }
        v.into_boxed_slice()
    });
    match e.entity_type() {
        ghast_entity::EntityType::Player => Some("player"),
        ghast_entity::EntityType::Registry(id) => names.get(usize::from(id)).copied().flatten(),
        _ => None,
    }
}

fn entity_bits(e: &ghast_entity::Entity) -> u8 {
    use ghast_physics::v1_16_5 as phys;
    static BITS: std::sync::OnceLock<Box<[u8]>> = std::sync::OnceLock::new();
    let bits = BITS.get_or_init(|| {
        let types = ghast_data::v1_16_5::entities();
        let mut v = vec![
            0u8;
            types
                .iter()
                .map(|t| usize::from(t.id) + 1)
                .max()
                .unwrap_or(0)
        ];
        for t in types {
            let mut b = 0;
            if phys::collides(t.name) {
                b |= COLLIDES;
            }
            match phys::push_kind(t.name, true) {
                Some(phys::PushKind::Boat) => b |= PUSH_BOAT,
                Some(phys::PushKind::Living) => b |= PUSH_LIVING,
                _ => {}
            }
            v[usize::from(t.id)] = b;
        }
        v.into_boxed_slice()
    });
    match e.entity_type() {
        ghast_entity::EntityType::Player => PUSH_LIVING,
        ghast_entity::EntityType::Registry(id) => {
            let b = bits.get(usize::from(id)).copied().unwrap_or(0);
            // Living pushes only for living entities (the living-entity spawn packet).
            if e.class() == ghast_entity::EntityClass::Mob {
                b
            } else {
                b & !PUSH_LIVING
            }
        }
        _ => 0,
    }
}

/// `true` when box `b` comes within `m` of the player's box on every axis.
fn near(b: &[f64; 6], p: &ghast_physics::math::Aabb, m: [f64; 3]) -> bool {
    !(b[3] < p.min_x - m[0]
        || b[0] > p.max_x + m[0]
        || b[4] < p.min_y - m[1]
        || b[1] > p.max_y + m[1]
        || b[5] < p.min_z - m[2]
        || b[2] > p.max_z + m[2])
}

impl std::fmt::Debug for Sim16 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sim16")
            .field("world", &self.world)
            .finish_non_exhaustive()
    }
}

impl Sim16 {
    /// Test hook: the chunk store.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_world(&self) -> &ghast_world::v1_16_5::World {
        &self.world
    }

    /// Test hook: sets one block.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_set_block(
        &mut self,
        x: i32,
        y: i32,
        z: i32,
        st: ghast_data::v1_16_5::BlockState,
    ) {
        self.world.set_block_state(x, y, z, st);
    }

    pub(crate) fn new() -> Self {
        Sim16 {
            world: ghast_world::v1_16_5::World::new(config()),
            player: ghast_physics::v1_16_5::PlayerState::new([0.0; 3], 0.0, 0.0),
            packets: ghast_physics::Packets::new(),
            rec: None,
            force_step_position: ForceStepPosition::Off,
            entities: None,
            updates: BlockUpdates::default(),
            session: SessionPackets::default(),
            block_entities: false,
            entity_push: true,
            teams: None,
            profile_name: "".into(),
            around: Around16::default(),
            filed_pos: [0.0; 3],
            ext: ghast_physics::v1_16_5::PlayerExt::new(),
            slow: false,
            rt: Riptide16::default(),
            unacked: Default::default(),
            snapped: false,
            glide: Box::default(),
            ride: None,
            reply: None,
            parked: None,
            left_boat: None,
            mounts: Box::default(),
            server_flags: None,
            absorption: 0.0,
            living_flags: None,
            absorption_dirty: false,
            sleep: None,
            pistons: ghast_physics::v1_16_5::Pistons::new(),
            piston_edits: ghast_physics::v1_16_5::Edits::new(),
            piston_uncertain_at: None,
            piston_time: 0,
            piston_carry: Vec::new(),
            piston_moved_shulker: false,
            nonliving: None,
            fishing: crate::fishing::Fishing::default(),
        }
    }

    /// A sim with options (recording, Grim compatibility).
    pub(crate) fn with(opts: &SimOptions) -> Self {
        let mut s = Self::new();
        s.force_step_position = opts.force_step_position;
        s.entities = opts.entities.map(Self::tracker);
        s.teams = s.entities.is_some().then(Box::default);
        if let Some(n) = &opts.profile_name {
            s.profile_name = n.as_str().into();
        }
        if let Some(c) = opts.world {
            s.world = ghast_world::v1_16_5::World::new(c);
            s.block_entities = c.block_entities;
        }
        if opts.shared_chunks.is_some() {
            log::debug!("shared chunks are not used on 1.16.5; every section stays owned");
        }
        s.update_slow();
        if let Some(p) = opts.record.as_deref() {
            match crate::record::Recorder::create(p) {
                Ok(r) => s.rec = Some(r),
                Err(e) => log::warn!("cannot record to {}: {e}", p.display()),
            }
        }
        s
    }
}

sync_pose_fn!(
    sync_pose_16(p: ghast_physics::v1_16_5::PlayerState),
    y: p.pos[1],
    sneaking: sneaking
);

#[cfg(all(test, ghast_modern))]
mod tests {
    /// 1.16.5's `VoronoiBiomeAccessType` is the zoom of 26.1's `BiomeManager.getBiome` (whose
    /// port is checked against the 26.1 client): same cells over random seeds and positions.
    #[test]
    fn voronoi_cell_is_the_modern_zoom() {
        let mut r: u64 = 0x9E37_79B9_7F4A_7C15;
        let mut next = || {
            r ^= r << 13;
            r ^= r >> 7;
            r ^= r << 17;
            r
        };
        for _ in 0..20_000 {
            let seed = next() as i64;
            let p = [next(), next(), next()].map(|v| (v as i32) >> 8);
            assert_eq!(
                super::voronoi_cell(seed, p[0], p[1], p[2]),
                ghast_world::climate::zoom_cell(seed, p[0], p[1], p[2]),
                "seed {seed} at {p:?}"
            );
        }
    }
}