ghast-client 0.5.6

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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
//! Per-version world and player movement ("simulation"): the chunk store of `ghast-world` and
//! the vanilla-exact movement step of `ghast-physics`, one module per version.
//!
//! The engine is generic over [`Sim`]; the behaviour sees the world through the
//! version-free [`WorldView`].

use ghast_protocol::{BlockPos, DecodeError, RawPacket};
use ghast_world::{WorldConfig, WorldError};

use crate::common::{
    Abilities, Controls, EntityAction, MovePacket, Outbound, Pose, Teleport, Vec3,
};
use crate::hands::{BlockQuery, HeldItem};
use crate::version::DataSet;

#[macro_use]
mod shared;

#[cfg(test)]
mod boxed;
mod items;
#[cfg(feature = "v1_12_2")]
mod place112;
#[cfg(feature = "v1_16_5")]
mod place116;
#[cfg(feature = "v1_8")]
mod place18;
pub(crate) mod predict;
#[cfg(any(ghast_modern, feature = "v1_12_2", feature = "v1_16_5"))]
mod teams;
#[cfg(test)]
#[allow(unused_imports, dead_code)] // each helper is used by the tests of its version
pub(crate) mod test_chunks;
#[cfg(all(test, feature = "v1_8"))]
mod tests;
#[cfg(feature = "v1_12_2")]
mod use112;
#[cfg(feature = "v1_16_5")]
mod use116;
#[cfg(feature = "v1_8")]
mod use18;
#[cfg(feature = "v1_12_2")]
mod v1_12;
#[cfg(feature = "v1_16_5")]
mod v1_16_5;
#[cfg(feature = "v1_8")]
mod v1_8;
#[cfg(feature = "v26_1")]
pub(crate) mod v26_1;
#[cfg(feature = "v26_2")]
pub(crate) mod v26_2;
#[cfg(feature = "v26_3")]
pub(crate) mod v26_3;

#[cfg(feature = "v1_8")]
pub(crate) use v1_8::Sim18;
#[cfg(feature = "v1_12_2")]
pub(crate) use v1_12::Sim12;
#[cfg(feature = "v1_16_5")]
pub(crate) use v1_16_5::Sim16;
#[cfg(feature = "v26_1")]
pub(crate) use v26_1::Sim26;
#[cfg(feature = "v26_2")]
pub(crate) use v26_2::Sim262;
#[cfg(feature = "v26_3")]
pub(crate) use v26_3::Sim263;

#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
use items::ACTIVATED_1_8;
pub(crate) use items::{food_points, held_item_facts};

/// The crosshair pick's inputs besides the world (vanilla `GameRenderer.updateTargetedEntity`).
#[cfg_attr(
    not(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5")),
    allow(dead_code)
)]
pub(crate) struct PickQuery<'a> {
    /// The eyes (feet + eye height of the pose judged).
    pub eyes: Vec3,
    /// `(yaw, pitch)` of that pose.
    pub rotation: (f32, f32),
    /// The generic look vector (`hands::look_vector`); versions use their own.
    pub look: Vec3,
    /// The main-hand item id (1.16.5+: a held block changes some interaction shapes).
    pub held: Option<u16>,
    /// Pick from the sim's own current state (this tick's key handling: 26.1 eye lerp and
    /// range attributes) instead of `eyes`.
    pub now: bool,
    /// Creative reach (blocks 5, entities 6, no 3-block entity limit).
    pub creative: bool,
    /// The player's bounding box (the entity search box grows from it).
    pub player_bb: ghast_physics::math::Aabb,
    /// The pickable entities near the eyes, in the tracker's order.
    pub entities: &'a [ghast_physics::pick::PickEntity],
}

/// The crosshair target.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Crosshair {
    /// A block, or nothing (a miss, or an entity beyond the 3-block limit).
    Block(Option<crate::BlockHit>),
    /// An entity: index into [`PickQuery::entities`] and the point hit.
    Entity {
        /// Index into the query's entities.
        index: usize,
        /// The point on its (grown) box; the eyes when they are inside it.
        hit: Vec3,
    },
}

/// Why a world packet could not be applied.
#[derive(Debug)]
pub(crate) enum SimError {
    /// The packet itself did not decode.
    Decode(DecodeError),
    /// The chunk data inside it was malformed.
    World(WorldError),
}

impl From<DecodeError> for SimError {
    fn from(e: DecodeError) -> Self {
        SimError::Decode(e)
    }
}

impl From<WorldError> for SimError {
    fn from(e: WorldError) -> Self {
        SimError::World(e)
    }
}

/// Block access for behaviours, independent of the protocol version.
pub trait WorldView {
    /// Whether the chunk column is loaded (sent by the server and not unloaded).
    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool;

    /// The block state at a position as the version's raw id: the 1.8 `id << 4 | meta` or the
    /// 1.16 global palette id (decode it with `ghast-data`). `None` when the column is not
    /// loaded — never treat that as air.
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32>;

    /// Number of loaded columns.
    fn loaded_columns(&self) -> usize;

    /// The build height `(min_y, height)` of the current dimension when the version has
    /// dimension-dependent heights (26.1: the overworld is `(-64, 384)`); `None` for the
    /// fixed `0..256` worlds of 1.8.9 – 1.16.5.
    fn build_height(&self) -> Option<(i32, i32)> {
        None
    }

    /// The tracked entities (`None` unless the behaviour asked for [`crate::Interests::ENTITIES`]).
    fn entities(&self) -> Option<&ghast_entity::Entities>;

    /// Dig / place facts of a block (hardness, tool group, ray box); `None` when the column
    /// is not loaded.
    fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery>;

    /// The whole loaded column (sections, light / biomes when kept, see
    /// [`crate::Client::world_config`]) for bulk reads without a call per block. Block states
    /// are the version's raw ids, as in [`WorldView::raw_block`]. `None` when not loaded.
    fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&ghast_world::Column> {
        let _ = (chunk_x, chunk_z);
        None
    }

    /// The player's last movement step: `(horizontalCollision, verticalCollision)` (`false`
    /// for a view without a player).
    fn collisions(&self) -> (bool, bool) {
        (false, false)
    }

    /// `true` when, in the last tick (its packets and its step), moving blocks ran into a case
    /// the physics model does not cover ([`crate::TickView::piston_uncertain`] lists them). The
    /// simulation goes on with the model's result; the server corrects the rest.
    fn piston_uncertain(&self) -> bool {
        false
    }

    /// The block the crosshair is on from `eyes` with the look `(yaw, pitch)` (`look` is its
    /// unit vector, [`crate::hands::look_vector`]) within `reach`, by the version's ray rules.
    /// `None` when nothing is hit.
    fn crosshair(
        &self,
        eyes: Vec3,
        rotation: (f32, f32),
        look: Vec3,
        reach: f64,
    ) -> Option<crate::BlockHit> {
        let _ = rotation;
        let blocks = |x: i32, y: i32, z: i32| self.block_query(x, y, z);
        crate::hands::pick(&blocks, eyes, look, reach)
    }
}

/// The join / respawn packets of the session (cheap `Bytes` copies).
#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
#[derive(Debug, Default)]
pub(super) struct SessionPackets {
    login: Option<RawPacket>,
    respawn: Option<RawPacket>,
}

#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
impl SessionPackets {
    fn note(&mut self, raw: &RawPacket, login: i32, respawn: i32) {
        // Copies: a body shares the receive buffer it arrived in (or the whole inflated
        // packet), which a clone would keep alive for the session.
        let own = || RawPacket::new(raw.id, bytes::Bytes::copy_from_slice(&raw.body));
        if raw.id == login {
            self.login = Some(own());
            self.respawn = None;
        } else if raw.id == respawn {
            self.respawn = Some(own());
        }
    }

    /// Feeds them to a fresh tracker.
    fn replay(&self, mut apply: impl FnMut(&RawPacket)) {
        for r in [&self.login, &self.respawn].into_iter().flatten() {
            apply(r);
        }
    }
}

/// Most block changes kept between two behaviour ticks (a chunk-sized burst is 65536).
pub(super) const MAX_BLOCK_UPDATES: usize = 4096;

/// Block changes buffered for the behaviour.
#[derive(Debug, Default)]
pub(super) struct BlockUpdates {
    on: bool,
    list: Vec<(BlockPos, u32)>,
    dropped: usize,
}

impl BlockUpdates {
    fn push(&mut self, pos: BlockPos, state: u32) {
        if self.on {
            if self.list.len() < MAX_BLOCK_UPDATES {
                self.list.push((pos, state));
            } else {
                self.dropped += 1;
            }
        }
    }
}

/// What [`Sim::pre_tick`] gets each tick.
#[derive(Debug, Clone, Copy)]
// Read by the 26.1 sim only.
#[cfg_attr(not(ghast_modern), allow(dead_code))]
pub(crate) struct PreTick {
    /// The use in progress: (off hand, item id).
    pub(crate) using: Option<(bool, u16)>,
    /// This tick's key handling released a use: (off hand, item id, player ticks it lasted).
    pub(crate) released: Option<(bool, u16, u32)>,
    /// The tick's movement keys.
    pub(crate) controls: Controls,
    /// The tick's look (after the mouse turn): a riptide launches along it.
    pub(crate) look: (f32, f32),
}

/// World + movement of one version.
pub(crate) trait Sim: WorldView + std::fmt::Debug {
    /// Applies a world packet (chunks, block changes, join / respawn / view changes).
    /// Other packets are ignored.
    fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError>;
    /// A new client player (join, respawn).
    fn reset_player(&mut self);
    /// The held stack's use facts from the stack itself (26.1: its components decide whether
    /// it has a use state and whether it is food); other versions keep the table facts.
    #[inline(always)]
    fn item_use_facts(
        &self,
        stack: &ghast_inventory::Stack,
        off_hand: bool,
        held: HeldItem,
    ) -> HeldItem {
        let _ = (stack, off_hand);
        held
    }
    /// The sim reads per-tick inputs from the inventory and keys (26.1); `false` lets the
    /// engine skip [`Sim::held_use_inputs`] and [`Sim::pre_tick`] without evaluating anything.
    #[inline(always)]
    fn modern_inputs(&self) -> bool {
        false
    }
    /// Before the key handling, while the use key is down or a use runs: what the held stacks'
    /// use depends on (26.1: the tridents' riptide strength, from the synced enchantments).
    #[inline(always)]
    fn held_use_inputs(&mut self, inv: &mut ghast_inventory::Inventory) {
        let _ = inv;
    }
    /// [`Sim::pre_tick`] has something to do even without a use, a release or a jump press
    /// (26.1: attached rockets).
    #[inline(always)]
    fn pre_tick_wanted(&self) -> bool {
        false
    }
    /// Once per tick before the movement: the inputs of the modern movement that come from the
    /// inventory and the keys (26.1: the used stack's `use_effects`, the equipped glider when
    /// jump is pressed, the hand that holds rockets). `using` is the use in progress (off hand,
    /// item id). Returns `false` when that hand no longer holds the item (`updatingUsingItem`:
    /// the use stops). New mechanics read their per-tick inputs here too.
    #[inline(always)]
    fn pre_tick(&mut self, inv: &ghast_inventory::Inventory, t: &PreTick) -> bool {
        let _ = (inv, t);
        true
    }
    /// Test hook: puts the 26.1 player (and its extension state) in place, level loaded.
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_modern(
        &mut self,
        p: ghast_physics::modern::PlayerState,
        x: ghast_physics::modern::PlayerExt,
    ) {
        let _ = (p, x);
    }
    /// Test hook: the 26.1 player's shared flags byte.
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_shared_flags(&self) -> u8 {
        0
    }
    /// Test hook: our entity id for the own-entity packets.
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_own_id(&mut self, id: i32) {
        let _ = id;
    }
    /// The player glides (26.1 elytra, shared flag 7).
    #[inline(always)]
    fn gliding(&self) -> bool {
        false
    }
    /// A weather game event: 1 start raining, 2 stop raining, 7 rain level `value`.
    fn weather(&mut self, reason: u8, value: f32) {
        let _ = (reason, value);
    }
    /// A mount's screen facts (26.1): entity type id, `canUseSlot(SADDLE)`, `canUseSlot(BODY)`.
    fn mount_info(&self, entity_id: i32) -> Option<(i32, bool, bool)> {
        let _ = entity_id;
        None
    }
    /// 1.8 – 1.16.5: a mount screen's slot rules read off the tracked entity `entity_id` like
    /// the client's `HorseScreenHandler` does (`None`: not tracked, not a mount, or the rules
    /// need entity data that is not kept).
    fn mount_rules(&self, entity_id: i32) -> Option<ghast_inventory::MountRules> {
        let _ = entity_id;
        None
    }
    /// The answer a world packet asks for at once (26.1 `move_vehicle`), taken after each one.
    #[inline(always)]
    fn take_reply(&mut self) -> Option<Outbound> {
        None
    }
    /// The packets the sim reads changed since the last call (rebuild the packet filter).
    #[inline(always)]
    fn take_filter_dirty(&mut self) -> bool {
        false
    }
    /// The vehicle the player rides, when the version models riding.
    #[inline(always)]
    fn vehicle(&self) -> Option<crate::common::Vehicle> {
        None
    }
    /// The client's main arm setting (left: `true`) for the parts of movement that read it.
    #[inline(always)]
    fn set_main_arm_left(&mut self, left: bool) {
        let _ = left;
    }
    /// Play → configuration (`start_configuration`): vanilla's `clearClientLevel` drops the
    /// level (chunks, entities) and the player until the next join.
    fn drop_level(&mut self) {
        self.reset_player();
    }
    /// A new client player after a respawn; `keep` is the respawn packet's kept-data bits
    /// (1.20.2+).
    fn respawn_player(&mut self, keep: u8) {
        let _ = keep;
        self.reset_player();
    }
    /// A server teleport: updates the pose like vanilla (the engine sends the reply).
    fn teleport(&mut self, pose: &mut Pose, t: &Teleport);
    /// Server abilities.
    fn abilities(&mut self, a: Abilities);
    /// Food level (sprinting needs more than 6).
    fn food(&mut self, food: i32);
    /// Velocity from the server (entity velocity for our entity, explosion push), in blocks
    /// per tick; `add` adds to the current velocity (explosion) instead of setting it.
    fn velocity(&mut self, v: Vec3, add: bool);
    /// Our movement speed attribute: base and every modifier `(uuid, amount, operation)` in
    /// packet order (the server's list includes the sprint modifier while sprinting; vanilla
    /// replaces the client's set with it).
    fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]);
    /// Our active status effects (id → amplifier).
    fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>);
    /// Boots enchantments that change movement.
    fn boots(&mut self, depth_strider: u8, soul_speed: u8);
    /// The item id in the feet slot (1.17+ powder snow: leather boots).
    fn feet_item(&mut self, id: Option<i32>) {
        let _ = id;
    }
    /// The inventory before each movement step, for the item ids in the main and the off hand
    /// (1.16.5+: a pig or strider follows a rider holding its stick). Read lazily: the versions
    /// that do not need the hands pay nothing on the plain tick. A version that reads them
    /// does so only when [`ghast_inventory::Inventory::take_player_touched`] says the slots
    /// may have changed (it is the flag's one caller).
    #[inline(always)]
    fn hand_items(&mut self, inv: &mut ghast_inventory::Inventory) {
        let _ = inv;
    }
    /// An inventory packet just changed what the hands may hold (between ticks): a version
    /// whose packet handlers read the hands (1.12.2: a pig we ride is steered by the carrot on
    /// a stick at each move packet) takes them now.
    #[inline(always)]
    fn hands_at_packet(&mut self, inv: &ghast_inventory::Inventory) {
        let _ = inv;
    }
    /// Spectator game mode (no collision).
    fn spectator(&mut self, on: bool);
    /// 26.1: the client player's movement state (see [`crate::TickContext::modern_player`]).
    #[cfg(ghast_modern)]
    fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
        None
    }
    /// One movement step: physics, then the sprint / sneak / abilities packets and exactly one
    /// movement packet appended to `out`. Updates `pose`.
    fn step(
        &mut self,
        pose: &mut Pose,
        controls: Controls,
        using_item: bool,
        entity_id: i32,
        out: &mut Vec<Outbound>,
    );
    /// Packet ids the entity tracker wants (empty without tracking).
    fn entity_packet_ids(&self) -> Vec<i32>;
    /// Packet ids the world consumes with its configuration.
    fn world_packet_ids(&self) -> Vec<i32>;
    /// The entity tracking configuration (`None`: not tracking).
    #[cfg_attr(
        not(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5")),
        allow(dead_code)
    )]
    fn entity_config(&self) -> Option<ghast_entity::Config>;
    /// Starts (empty, our entity id and dimension from the session's join / respawn), stops
    /// (frees the store) or reconfigures entity tracking mid-session.
    fn set_entities(&mut self, config: Option<ghast_entity::Config>);
    /// Client-side flight toggle: sets the physics' flying flag and appends the `abilities`
    /// packet when it changes (starting needs "may fly").
    fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>);
    /// Whether block changes are collected for [`Sim::drain_block_updates`].
    fn collect_block_updates(&mut self, on: bool);
    /// Moves the block changes (position, version raw state) received since the last call
    /// into `out`; returns how many were dropped because the buffer was full.
    fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize;
    /// The block was broken on the client (air until the server says otherwise).
    fn predict_air(&mut self, x: i32, y: i32, z: i32);
    /// A dig action packet of this tick, in packet order, with the player's position when it
    /// was sent (before the tick's movement). `broken`: the client broke the block with it
    /// (`breakBlock` / `destroyBlock`: air until the server says otherwise). `sequence`: the
    /// packet's 1.19+ prediction sequence (26.x remembers the server's state per predicted
    /// block until `block_changed_ack`; 1.16.5 remembers start / abort / finish until
    /// `acknowledge_player_digging`). 1.8.9 and 1.12.2 keep no records (the server sends a
    /// block change).
    #[inline]
    fn dig_sent(
        &mut self,
        pos: BlockPos,
        status: crate::common::DigStatus,
        broken: bool,
        sequence: i32,
        player: Vec3,
    ) {
        let _ = (status, sequence, player);
        if broken {
            self.predict_air(pos.x, pos.y, pos.z);
        }
    }
    /// A `block_place` of this tick that used the held block item, in packet order with the
    /// digs ([`Sim::dig_sent`]): the version places the block on the client when it knows the
    /// result exactly (see [`predict::PlaceSent`]); 26.x keeps the server's state until the ack,
    /// older versions take the server's block updates for the clicked block and its neighbour.
    /// Returns whether the block was placed on the client (the item is then used up there too).
    #[inline]
    fn place_sent(&mut self, p: &predict::PlaceSent<'_>) -> bool {
        let _ = p;
        false
    }
    /// 1.8.9 / 1.12.2: the vanilla client writes no `block_place` for a right click with block
    /// item `held` on `face` of `pos` (`BlockItem.canPlaceItemBlock` fails; see
    /// [`predict::legacy_place_suppressed`]). Always `false` from 1.13 on (no such check).
    #[inline]
    fn place_suppressed(&self, pos: BlockPos, face: crate::common::Face, held: u16) -> bool {
        let _ = (pos, face, held);
        false
    }
    /// 1.8.9: the oracle-proven rules of a right click on a block (`ghast_data::v1_8::place`):
    /// whether the packet is written and the click taken, where they decide it.
    #[inline]
    fn place_rules(&self, q: &predict::PlaceQuery<'_>) -> predict::PlaceRules {
        let _ = q;
        predict::PlaceRules::default()
    }
    /// 1.12.2, 1.16.5: the oracle-proven rules of a hand's item use in the air (`interactItem`
    /// after its packet: the stack's `use` on the client); [`predict::AirAnswer::Flags`] where
    /// the held-item flags decide it.
    #[inline]
    fn air_use(&self, q: &predict::AirQuery<'_>) -> predict::AirAnswer {
        let _ = q;
        predict::AirAnswer::Flags
    }
    /// The blocks an item use in the air set on the client ([`Sim::air_use`]; the version's
    /// state ids).
    #[inline]
    fn air_use_sent(&mut self, blocks: &[(BlockPos, u32)]) {
        let _ = blocks;
    }
    /// Test hook: an air-use oracle case's facts of the client world (`AirUseDump`: a dimension
    /// whose water vaporizes).
    #[cfg(test)]
    #[allow(dead_code)] // used by the legacy air-use replays
    fn test_air_case(&mut self, case: &serde_json::Value) {
        let _ = case;
    }
    /// Test hook: the entity tracker counts as started before the join (a replay starts it
    /// after its join packet, with no entity spawned before; 1.8 piston bounds).
    #[cfg(test)]
    #[allow(dead_code)] // used by the legacy combat replays
    fn test_tracker_from_join(&mut self) {}
    /// Test hook: moves the sim's player (as a fall between a prediction and its answer would).
    #[cfg(test)]
    #[allow(dead_code)] // used by the all-version prediction tests
    fn set_player_pos(&mut self, p: Vec3) {
        let _ = p;
    }
    /// [`Sim::dig_sent`] wants the dig packets that broke nothing too (1.16.5 records them).
    #[inline(always)]
    fn records_digs(&self) -> bool {
        false
    }
    /// A server teleport arrived while `sequence` was the last prediction sequence sent
    /// (26.x `BlockStatePredictionHandler.onTeleport`).
    #[inline(always)]
    fn teleport_sequence(&mut self, sequence: Option<i32>) {
        let _ = sequence;
    }
    /// After a prediction answer (`block_changed_ack`, 1.16.5 `acknowledge_player_digging`):
    /// the position the player was moved back to when a restored block would hold it.
    #[inline(always)]
    fn take_snap(&mut self) -> Option<Vec3> {
        None
    }
    /// A held item's version facts (tool speeds, block item, usable) from its id.
    fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem;
    /// The crosshair target as vanilla picks it at the start of this tick (before the key
    /// handling) with the player's own eye and ranges; `eyes` / `look` are the generic
    /// approximation (feet + eye height, `hands::look_vector`). `held` is the main-hand item id.
    fn crosshair_now(
        &self,
        eyes: Vec3,
        rotation: (f32, f32),
        look: Vec3,
        held: Option<u16>,
    ) -> Option<crate::BlockHit> {
        let _ = held;
        self.crosshair(eyes, rotation, look, crate::hands::REACH)
    }
    /// Whether the crosshair pick can hit `e` and by how much its box grows (`None`: not
    /// pickable). Default: the engine's 1.8 – 1.16.5 classification.
    fn pick_margin(&self, e: &ghast_entity::Entity) -> Option<f32> {
        crate::engine::legacy_pick_margin(self.entities()?, e)
    }
    /// Where vanilla's entity search meets `e` (the crosshair pick visits entities in this
    /// order): the client view's chunk-section key ([`ghast_entity::Entity::search_order`]).
    fn search_order(&self, e: &ghast_entity::Entity) -> Option<(i32, i32, i32, u32)> {
        e.search_order()
    }
    /// One client tick of the tracked entities (`ClientLevel.tickEntities`), after the tick's
    /// crosshair pick. Versions whose tracker has no client-side motion do nothing.
    fn tick_entities(&mut self, pose: &mut Pose) {
        let _ = pose;
    }
    /// 26.3 `LocalPlayer.sendChanges` after the level's entities and block entities ticked:
    /// the movement packets of a player tick whose packets wait for that phase (among moving
    /// blocks). Earlier versions send them in the step: nothing.
    #[inline(always)]
    fn send_changes(&mut self, entity_id: i32, out: &mut Vec<Outbound>) {
        let _ = (entity_id, out);
    }
    /// An entity event (`entity_status`) of another entity the sim simulates (26.3: the bubble
    /// column events 71 / 72 of the boat the player drives). Default: nothing.
    #[inline(always)]
    fn entity_event(&mut self, entity_id: i32, status: i8) {
        let _ = (entity_id, status);
    }
    /// The entity store, mutable (its clock and event queue); `None` without a tracker.
    fn entities_mut(&mut self) -> Option<&mut ghast_entity::Entities> {
        None
    }
    /// Whether entities push the player (`LivingEntity.pushEntities` and the boat's push on
    /// the client player; default on, as in vanilla). Versions whose client never pushes the
    /// player ignore it.
    fn set_entity_push(&mut self, on: bool) {
        let _ = on;
    }
    /// Whether the tracked non-living entities (projectiles, items, orbs, TNT, falling blocks)
    /// run their client-side physics ([`crate::Interests::ENTITY_PHYSICS`]); versions without
    /// it ignore it.
    fn set_entity_physics(&mut self, on: bool) {
        let _ = on;
    }
    /// Whether the block at `pos` is a sign (any standing, wall or hanging sign); `None` when
    /// its column is not loaded or the version does not need it (only 1.16.5 and 26.x ask:
    /// [`crate::sign::SignRules`]).
    fn sign_at(&self, pos: ghast_protocol::BlockPos) -> Option<bool> {
        let _ = pos;
        None
    }
    /// 1.8 / 1.12: the `bed` packet for our entity (`PlayerEntity.trySleep` on the client): the
    /// player is put on the bed (`pose` follows) and its velocity zeroed.
    fn sleep_at(&mut self, pose: &mut Pose, bed: ghast_protocol::BlockPos) {
        let _ = (pose, bed);
    }
    /// 1.8 / 1.12: animation 2 for our entity (`PlayerEntity.awaken` on the client): the box
    /// grows back to the standing size.
    fn wake_up(&mut self) {}
    /// 1.16.5+: our sleeping position changed in the entity data since the last call
    /// (`Some(Some(bed))`: asleep, the sim already put the player on the bed and `pose`
    /// follows; `Some(None)`: awake).
    fn take_sleep(&mut self, pose: &mut Pose) -> Option<Option<ghast_protocol::BlockPos>> {
        let _ = pose;
        None
    }
    /// The bot's own fishing bobber (with entity tracking; see [`crate::fishing`]).
    #[inline(always)]
    fn fishing(&self) -> Option<&crate::fishing::Bobber> {
        None
    }
    /// Fishing events are waiting ([`Sim::drain_fishing`]).
    #[inline(always)]
    fn fishing_news(&self) -> bool {
        false
    }
    /// Moves the fishing events since the last call into `out`.
    fn drain_fishing(&mut self, out: &mut Vec<crate::fishing::FishingEvent>) {
        let _ = out;
    }
    /// 26.x: the player's `block_interaction_range` attribute (4.5 by default).
    fn block_interaction_range(&self) -> f64 {
        4.5
    }
    /// 1.21.4+ level-load gate: the server's `game_event` 13 (`LEVEL_CHUNKS_LOAD_START`).
    fn level_load_start(&mut self) {}
    /// 1.21.4+ level-load gate: the player is alive (`set_health` above 0).
    fn player_alive(&mut self, alive: bool) {
        let _ = alive;
    }
    /// 1.21.4+ level-load gate, once per tick before the key handling: `true` on the tick the
    /// client sends `player_loaded`. `section_compiled`: the engine's readiness signal;
    /// `timed_out`: the client's 30 s wait is over.
    fn load_gate_tick(&mut self, section_compiled: bool, timed_out: bool) -> bool {
        let _ = (section_compiled, timed_out);
        false
    }
    /// 1.21.4+: a tick behind the level-load gate (the player does not tick; only its entity
    /// tick counter runs).
    fn tick_unloaded(&mut self) {}
    /// The whole crosshair target (vanilla `GameRenderer.updateTargetedEntity`): the block
    /// pick unless one of `q.entities` is hit nearer. Versions without an entity pick yet
    /// pick blocks only.
    fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
        Crosshair::Block(if q.now {
            self.crosshair_now(q.eyes, q.rotation, q.look, q.held)
        } else {
            self.crosshair(q.eyes, q.rotation, q.look, crate::hands::REACH)
        })
    }
    /// 1.20.5+ movement attributes of our entity, in packet order.
    fn attributes(&mut self, attributes: &[crate::common::AttributeUpdate]) {
        let _ = attributes;
    }
    /// 1.20.5+ movement attributes of another entity (a mount the player may ride).
    fn entity_attributes(&mut self, entity_id: i32, attributes: &[crate::common::AttributeUpdate]) {
        let _ = (entity_id, attributes);
    }
    /// `chunk_batch_start` arrived (1.20.2+), at `now_nanos` from any fixed origin.
    fn chunk_batch_start(&mut self, now_nanos: i64) {
        let _ = now_nanos;
    }
    /// `chunk_batch_finished` arrived: the chunks per tick to answer with (1.20.2+).
    fn chunk_batch_finished(&mut self, batch_size: i32, now_nanos: i64) -> f32 {
        let _ = (batch_size, now_nanos);
        // ChunkBatchSizeCalculator's initial value: 7 ms / 2 ms.
        3.5
    }
    /// A configuration-state `registry_data` packet (1.20.2+).
    fn registry_data(&mut self, raw: &RawPacket) {
        let _ = raw;
    }
    /// The clock of a [`crate::common::TimeUpdate`] that is the current dimension's day
    /// (26.x: its world clock registry id; `None` for a dimension without a day).
    fn day_clock(&self) -> Option<i32> {
        Some(crate::common::ClockUpdate::LEGACY_DAY)
    }
    /// `entity.damage(..)` / `hurtClient` of an attack target on the client returns `true`
    /// (with `isAttackable()` and no `handleAttack` / `skipAttackInteraction`): the attack's
    /// knockback part then runs on the client. Other players, vehicles, end crystals, … — the
    /// version's own list; a living mob is never hurt on the client.
    fn attack_hurts(&self, e: &ghast_entity::Entity) -> bool {
        e.is_player()
    }
    /// The player's eye height as its pose has it now (`getEyeHeight` / `getStandingEyeHeight`),
    /// when it can differ from standing / sneaking (1.12 gliding; 1.16.5 swimming, gliding,
    /// riptide). `None`: the standing / sneaking height.
    fn eye_height(&self) -> Option<f64> {
        None
    }
    /// [`Sim::eye_height`] when the engine knows the player is awake (not asleep: the sleeping
    /// 0.2 cannot apply), so a version whose only other height is the default answers `None`
    /// without reading its sleep state.
    fn awake_eye_height(&self) -> Option<f64> {
        self.eye_height()
    }
    /// `PlayerEntity.attack` after a hit that [`Sim::attack_hurts`]: with knockback
    /// (`knockback` enchantment level, 26.x: the attribute part, plus 1 for a sprint attack;
    /// 1.9+ only at full strength: `sprint_bonus`) the attacker's `velocity x/z *= 0.6` and
    /// `setSprinting(false)`, before this tick's movement. The target `target` takes the
    /// knockback from the attacker's `yaw` (1.8: a boat drifts by it in the client view).
    fn attack_slow(&mut self, target: i32, yaw: f32, knockback: i32, sprint_bonus: bool) {
        let _ = (target, yaw, knockback, sprint_bonus);
    }
    /// The player's sprint flag now (`isSprinting`, what [`Sim::attack_slow`] reads): the last
    /// movement step's, or what the server's entity data (the flags byte) set since.
    fn sprinting(&self) -> bool {
        false
    }
    /// The flags byte (entity data index 0) the server last sent for our entity (`None`
    /// before any).
    fn server_flags(&self) -> Option<u8> {
        None
    }
    /// The absorption amount the server last sent for our entity (player entity data; 0
    /// before any), once after each change (`None` while unchanged).
    fn take_absorption(&mut self) -> Option<f32> {
        None
    }
    /// Our living flags (1.9+ entity data: bit 1 using, bit 2 off hand) when a packet set them
    /// since the last call.
    fn take_living_flags(&mut self) -> Option<u8> {
        None
    }
    /// The player's velocity now (blocks per tick), with server velocity / explosion pushes
    /// applied since the last step.
    fn velocity_now(&self) -> Vec3 {
        Vec3::default()
    }
}

/// `velocity *= (0.6, 1, 0.6)` and `setSprinting(false)` when an attack has knockback:
/// `knockback + (sprinting && sprint_bonus ? 1 : 0) > 0`. Returns whether it applied.
#[inline]
pub(super) fn attack_knockback_applies(
    knockback: i32,
    sprinting: bool,
    sprint_bonus: bool,
) -> bool {
    knockback + i32::from(sprinting && sprint_bonus) > 0
}

/// Options of the per-version sim.
#[derive(Debug, Clone, Default)]
pub(crate) struct SimOptions {
    /// Write a movement recording there.
    pub record: Option<std::path::PathBuf>,
    /// Grim compatibility (not vanilla): send the position on ticks whose feet height changed
    /// although the move stayed under the 0.03 resend threshold.
    pub force_step_position: ForceStepPosition,
    /// Track entities (and the tab list).
    pub entities: Option<ghast_entity::Config>,
    /// What the world keeps besides block states (default: nothing, see [`config`]).
    pub world: Option<WorldConfig>,
    /// Share section storage through this store (modern versions; the others ignore it).
    pub shared_chunks: Option<ghast_world::SharedChunks>,
    /// The player's scoreboard name (team membership for entity pushes, 1.12.2, 1.16.5 and
    /// 26.1+).
    #[cfg_attr(
        not(any(ghast_modern, feature = "v1_12_2", feature = "v1_16_5")),
        allow(dead_code)
    )]
    pub profile_name: Option<String>,
}

/// Grim compatibility (**not vanilla**): when to send the position on a tick whose move stayed
/// under vanilla's 0.03-block resend threshold (every version; on 26.x also bounce landings on
/// slime and beds). See `crates/ghast-physics/GRIM_NOTES.md`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ForceStepPosition {
    /// Vanilla: never.
    #[default]
    Off,
    /// Whenever the feet height changed since the last sent position (step-ups and landings).
    Always,
    /// Only step-ups: on ground after the move and the feet went up. Falls, landings and
    /// descents stay vanilla.
    StepUpOnly,
}

/// Grim compatibility: when the tick's movement packet carries no position but the feet height
/// changed since the last sent position (a step-up or landing under the 0.03 threshold),
/// upgrade it to `position` / `position_look` and update the sent bookkeeping.
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(super) fn force_position(
    packets: &mut ghast_physics::Packets,
    cur: [f64; 3],
    sent_pos: &mut [f64; 3],
    ticks_since_pos: &mut i32,
    mode: ForceStepPosition,
) {
    use ghast_physics::Packet as P;
    if mode == ForceStepPosition::Off || cur[1] == sent_pos[1] {
        return;
    }
    let Some(last) = packets.as_slice().last().copied() else {
        return;
    };
    if mode == ForceStepPosition::StepUpOnly {
        let on_ground = matches!(
            last,
            P::Flying { on_ground: true }
                | P::Look {
                    on_ground: true,
                    ..
                }
        );
        if !on_ground || cur[1] <= sent_pos[1] {
            return;
        }
    }
    let new = match last {
        P::Flying { on_ground } => P::Position {
            x: cur[0],
            y: cur[1],
            z: cur[2],
            on_ground,
        },
        P::Look {
            yaw,
            pitch,
            on_ground,
        } => P::PositionLook {
            x: cur[0],
            y: cur[1],
            z: cur[2],
            yaw,
            pitch,
            on_ground,
        },
        _ => return,
    };
    let mut out = ghast_physics::Packets::new();
    let n = packets.len();
    for p in &packets.as_slice()[..n - 1] {
        out.push(*p);
    }
    out.push(new);
    *packets = out;
    *sent_pos = cur;
    *ticks_since_pos = 0;
}

/// 1.16 blocks whose `onUse` succeeds for a plain right click (GUIs, doors,
/// switches, …). Name-based approximation of vanilla's per-block `use` overrides.
#[cfg(any(feature = "v1_16_5", ghast_modern))]
pub(super) fn activates_1_16(name: &str) -> bool {
    const EXACT: &[&str] = &[
        "chest",
        "trapped_chest",
        "ender_chest",
        "crafting_table",
        "furnace",
        "blast_furnace",
        "smoker",
        "barrel",
        "anvil",
        "chipped_anvil",
        "damaged_anvil",
        "enchanting_table",
        "brewing_stand",
        "hopper",
        "dispenser",
        "dropper",
        "repeater",
        "comparator",
        "note_block",
        "jukebox",
        "cake",
        "loom",
        "stonecutter",
        "grindstone",
        "cartography_table",
        "smithing_table",
        "lectern",
        "bell",
        "beacon",
        "daylight_detector",
        "respawn_anchor",
        "composter",
        "lever",
        "command_block",
        "chain_command_block",
        "repeating_command_block",
        "structure_block",
        "jigsaw",
        "dragon_egg",
        "flower_pot",
        "sweet_berry_bush",
    ];
    EXACT.contains(&name)
        || name.ends_with("_shulker_box")
        || name == "shulker_box"
        || name.ends_with("_bed")
        || name.ends_with("_button")
        || name.ends_with("_fence_gate")
        || (name.ends_with("_door") && name != "iron_door")
        || (name.ends_with("_trapdoor") && name != "iron_trapdoor")
        || name.starts_with("potted_")
}

/// A legacy (1.8.9 / 1.12.2) crosshair target as the engine takes it.
/// 1.8 / 1.12 `PlayerEntity.trySleep` on the client: where it puts the player on the bed at
/// `bed`. `meta`: the bed block's metadata when the block there is a bed (its facing is
/// `meta & 3`: 0 south, 1 west, 2 north, 3 east); otherwise the block's centre. 1.8 picks the
/// x / z offsets from literals (0.9F / 0.1F), 1.12 computes `0.5F + offset * 0.4F`; both add
/// in float, like the Java code.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(super) fn legacy_bed_position(
    bed: ghast_protocol::BlockPos,
    meta: Option<u8>,
    computed: bool,
) -> [f64; 3] {
    let (dx, dz) = match meta.map(|m| m & 3) {
        Some(0) => (0, 1),
        Some(1) => (-1, 0),
        Some(2) => (0, -1),
        Some(3) => (1, 0),
        _ => (0, 0),
    };
    let off = |d: i32| -> f32 {
        if computed {
            0.5f32 + d as f32 * 0.4f32
        } else {
            match d {
                1 => 0.9f32,
                -1 => 0.1f32,
                _ => 0.5f32,
            }
        }
    };
    [
        f64::from(bed.x as f32 + off(dx)),
        f64::from(bed.y as f32 + 0.6875f32),
        f64::from(bed.z as f32 + off(dz)),
    ]
}

#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(super) fn legacy_crosshair(t: ghast_physics::pick::legacy::Target, eye: [f64; 3]) -> Crosshair {
    use ghast_physics::pick::legacy::Target;
    match t {
        Target::Block(h) => Crosshair::Block(block_hit(&h, eye)),
        Target::Entity(e) => Crosshair::Entity {
            index: e.index,
            hit: Vec3::new(e.location[0], e.location[1], e.location[2]),
        },
        Target::None | Target::TooFar { .. } => Crosshair::Block(None),
    }
}

/// A modern (1.16.5+) crosshair target as the engine takes it.
#[cfg(any(feature = "v1_16_5", ghast_modern))]
pub(super) fn modern_crosshair(t: ghast_physics::pick::Target, eye: [f64; 3]) -> Crosshair {
    use ghast_physics::pick::Target;
    match t {
        Target::Block(h) => Crosshair::Block(block_hit(&h, eye)),
        Target::Entity(e) => Crosshair::Entity {
            index: e.index,
            hit: Vec3::new(e.location[0], e.location[1], e.location[2]),
        },
    }
}

/// A pick result as the hands take it (`None` for a miss).
pub(super) fn block_hit(
    hit: &ghast_physics::pick::BlockHit,
    eye: [f64; 3],
) -> Option<crate::BlockHit> {
    use ghast_physics::pick::Direction;
    if !hit.is_block() {
        return None;
    }
    let face = match hit.face {
        Direction::Down => crate::Face::Down,
        Direction::Up => crate::Face::Up,
        Direction::North => crate::Face::North,
        Direction::South => crate::Face::South,
        Direction::West => crate::Face::West,
        Direction::East => crate::Face::East,
    };
    let [lx, ly, lz] = hit.location;
    let distance = ((lx - eye[0]).powi(2) + (ly - eye[1]).powi(2) + (lz - eye[2]).powi(2)).sqrt();
    Some(crate::BlockHit {
        pos: BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
        face,
        hit: Vec3::new(lx, ly, lz),
        distance,
    })
}

/// Union of the collision boxes as a ray box (`None` when there is none).
#[cfg(any(feature = "v1_12_2", feature = "v1_16_5", ghast_modern))]
pub(super) fn union(boxes: &[ghast_data::Aabb]) -> Option<[f64; 6]> {
    let mut u = [1.0_f64, 1.0, 1.0, 0.0, 0.0, 0.0];
    for b in boxes {
        u[0] = u[0].min(b.min_x);
        u[1] = u[1].min(b.min_y);
        u[2] = u[2].min(b.min_z);
        u[3] = u[3].max(b.max_x.min(1.0));
        u[4] = u[4].max(b.max_y.min(1.0));
        u[5] = u[5].max(b.max_z.min(1.0));
    }
    (!boxes.is_empty()).then_some(u)
}

pub(super) fn config() -> WorldConfig {
    // The bot needs block states only: no biomes, no light.
    WorldConfig::default()
        .with_biomes(false)
        .with_light(false)
        .with_block_entities(false)
}

pub(super) fn abilities_flags(a: &ghast_physics::Abilities) -> i8 {
    let mut f = 0;
    if a.invulnerable {
        f |= 1;
    }
    if a.flying {
        f |= 2;
    }
    if a.allow_flying {
        f |= 4;
    }
    if a.creative {
        f |= 8;
    }
    f
}

/// The physics' packets of a tick, in order, as wire packets.
pub(super) fn push_packets(
    packets: &ghast_physics::Packets,
    entity_id: i32,
    out: &mut Vec<Outbound>,
) {
    for p in packets {
        use ghast_physics::Packet as P;
        let action = |action| Outbound::EntityAction { entity_id, action };
        let wire = match *p {
            P::StartSneaking => action(EntityAction::StartSneaking),
            P::StopSneaking => action(EntityAction::StopSneaking),
            P::StartSprinting => action(EntityAction::StartSprinting),
            P::StopSprinting => action(EntityAction::StopSprinting),
            P::StartFallFlying => action(EntityAction::StartFallFlying),
            P::StartRidingJump { strength } => Outbound::RidingJump {
                entity_id,
                strength,
            },
            P::StopRidingJump => action(EntityAction::StopRidingJump),
            P::Abilities(a) => Outbound::Abilities {
                flags: abilities_flags(&a),
                flying_speed: a.fly_speed,
                walking_speed: a.walk_speed,
            },
            P::Flying { on_ground } => Outbound::Move(MovePacket::Flying {
                horizontal_collision: false,
                on_ground,
            }),
            P::Position { x, y, z, on_ground } => Outbound::Move(MovePacket::Position {
                horizontal_collision: false,
                pos: Vec3::new(x, y, z),
                on_ground,
            }),
            P::Look {
                yaw,
                pitch,
                on_ground,
            } => Outbound::Move(MovePacket::Look {
                horizontal_collision: false,
                yaw,
                pitch,
                on_ground,
            }),
            P::PositionLook {
                x,
                y,
                z,
                yaw,
                pitch,
                on_ground,
            } => Outbound::Move(MovePacket::PositionLook {
                horizontal_collision: false,
                pos: Vec3::new(x, y, z),
                yaw,
                pitch,
                on_ground,
            }),
            // The modern physics (1.21.2+): one move packet with optional parts, held keys.
            P::Move {
                pos,
                look,
                on_ground,
                horizontal_collision,
            } => Outbound::Move(match (pos, look) {
                (Some([x, y, z]), Some((yaw, pitch))) => MovePacket::PositionLook {
                    pos: Vec3::new(x, y, z),
                    yaw,
                    pitch,
                    on_ground,
                    horizontal_collision,
                },
                (Some([x, y, z]), None) => MovePacket::Position {
                    pos: Vec3::new(x, y, z),
                    on_ground,
                    horizontal_collision,
                },
                (None, Some((yaw, pitch))) => MovePacket::Look {
                    yaw,
                    pitch,
                    on_ground,
                    horizontal_collision,
                },
                (None, None) => MovePacket::Flying {
                    on_ground,
                    horizontal_collision,
                },
            }),
            P::MoveVehicle {
                pos,
                yaw,
                pitch,
                on_ground,
            } => Outbound::VehicleMove {
                pos: Vec3::new(pos[0], pos[1], pos[2]),
                yaw,
                pitch,
                on_ground,
            },
            P::PaddleBoat { left, right } => Outbound::SteerBoat { left, right },
            P::SteerVehicle {
                sideways,
                forward,
                jump,
                sneak,
            } => Outbound::SteerVehicle {
                sideways,
                forward,
                jump,
                sneak,
            },
            P::PlayerInput(k) => Outbound::PlayerInput(Controls {
                forward: k.forward,
                back: k.back,
                left: k.left,
                right: k.right,
                jump: k.jump,
                sneak: k.sneak,
                sprint: k.sprint,
            }),
            // A physics packet added later without a wire form here.
            _ => {
                debug_assert!(false, "physics packet without a wire form: {p:?}");
                continue;
            }
        };
        out.push(wire);
    }
}

#[cfg(any(feature = "v1_12_2", feature = "v1_16_5", ghast_modern))]
pub(super) fn physics_abilities(a: Abilities) -> ghast_physics::Abilities {
    ghast_physics::Abilities {
        invulnerable: a.flags & 1 != 0,
        flying: a.flags & 2 != 0,
        allow_flying: a.flags & 4 != 0,
        creative: a.flags & 8 != 0,
        fly_speed: a.flying_speed,
        walk_speed: a.walking_speed,
    }
}

pub(super) fn keys(c: Controls) -> ghast_physics::Keys {
    ghast_physics::Keys {
        forward: c.forward,
        back: c.back,
        left: c.left,
        right: c.right,
        jump: c.jump,
        sneak: c.sneak,
        sprint: c.sprint,
    }
}

#[cfg(any(feature = "v1_12_2", feature = "v1_16_5"))]
pub(super) fn rel_flags(flags: i8) -> [bool; 5] {
    use crate::common::teleport_flags as fl;
    [
        flags & fl::X != 0,
        flags & fl::Y != 0,
        flags & fl::Z != 0,
        flags & fl::YAW != 0,
        flags & fl::PITCH != 0,
    ]
}