ghast-client 0.5.3

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! The client tick in vanilla's order (`Engine::tick_with`): clocks and HUD countdowns, the
//! level-load gate, the silent-server hold, the behaviour's tick, held slot sync, the key
//! handling (crosshair pick, hands, right-click rules), attacks, item-use checks, dig and place
//! predictions, flight, rotation, the movement step and its packets, `tick_end` and the
//! behaviour's `after_tick`; plus the behaviour's lifecycle (`interests`, `stop`).

use super::*;

impl<S: Sim> Engine<S> {
    /// The interests of the behaviour (the packet filter follows them).
    pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
        if self.state.failed {
            Interests::NONE
        } else {
            b.interests()
        }
    }

    /// Ends the behaviour (session over).
    pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
        if self.state.started && !self.state.failed {
            self.state.failed = true;
            let name = self.core.opts.name.clone();
            if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
                log::error!("[{name}] behaviour {} panicked in stop", b.name());
            }
        }
    }

    /// One client tick at `now` (dialog commands never parse: no command tree).
    #[cfg(test)]
    #[allow(dead_code, reason = "the engine tests need every version feature")]
    pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
        self.tick_with(b, now, &|_| crate::dialog::CommandCheck::ParseErrors);
    }

    /// One client tick at `now`; `commands` checks a dialog's command like vanilla's
    /// `verifyCommand` (the wire layer's command tree).
    pub(crate) fn tick_with<B: Behavior>(
        &mut self,
        b: &mut B,
        now: Instant,
        commands: &dyn Fn(&str) -> crate::dialog::CommandCheck,
    ) {
        let c = &mut self.core;
        c.tick += 1;
        // `ClientLevel.tickTime`: the game time and the clocks move on between updates.
        c.clocks.tick();
        // `Gui.tick` (every client tick, after the packets): the title and action bar count
        // down.
        if let Some(h) = &mut c.hud
            && h.counting()
        {
            hud_countdown(h, &mut c.pending);
        }
        // Per-tick packet-order guard and click timeout of the inventory.
        c.inv.tick();
        let was_ready = c.ready;
        // 1.21.4+ (`LocalPlayer.tick` without the old `hasChunkAt` check): once the level
        // loaded, the player ticks in an unloaded column too (its blocks read as void air).
        c.ready = c.teleported_once
            && ((c.opts.caps.player_loaded_gate && c.client_loaded) || c.column_loaded(&self.sim));
        if c.ready != was_ready {
            if c.ready {
                log::info!(
                    "[{}] t{} in the world at {:.3} {:.3} {:.3}",
                    c.opts.name,
                    c.tick,
                    c.pose.pos.x,
                    c.pose.pos.y,
                    c.pose.pos.z
                );
            } else {
                log::debug!(
                    "[{}] t{} player column not loaded: not ticking",
                    c.opts.name,
                    c.tick
                );
            }
        }
        if c.chat_session_due && c.joined {
            // ClientPacketListener.tick: the key pair future finished → chat_session_update,
            // before the level-load check.
            c.chat_session_due = false;
            c.out.push(Outbound::ChatSessionUpdate);
        }
        if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
            // 1.21.4+ LevelLoadTracker: after the server's "chunks load start" the level is
            // ready once the player's section is compiled and visible
            // (`isSectionCompiledAndVisible`; spectators and dead players at once); after 30 s
            // it lets the player in anyway. The first compile needs the 3x3 columns around the
            // player (`hasAllNeighbors`) and happens in a frame after the tick that received
            // them, so the earliest ready tick is the next one (a nearby section has no
            // fade-in). `player_loaded` goes out from the connection tick, before the key
            // handling and the player tick.
            c.load_wait += 1;
            let near = c.neighbourhood_loaded(&self.sim);
            c.near_loaded = if near {
                c.near_loaded.saturating_add(1)
            } else {
                0
            };
            // The oracle-proven gate (ghast_physics::modern::LoadGate) decides (dead players,
            // spectators and feet outside the build height included); "section compiled" is
            // ours: the nine columns on two consecutive ticks.
            let (compiled, timed_out) = (c.ready && c.near_loaded >= 2, c.load_wait >= 600);
            #[cfg(test)]
            let (compiled, timed_out) = c.test_gate.unwrap_or((compiled, timed_out));
            if self.sim.load_gate_tick(compiled, timed_out) {
                c.client_loaded = true;
                c.gate_tick = true;
                c.out.push(Outbound::PlayerLoaded);
                log::debug!("[{}] t{} player loaded", c.opts.name, c.tick);
            }
        }
        if !c.ready || (c.opts.caps.player_loaded_gate && !c.client_loaded) {
            // The client player does not tick outside a loaded column (1.16 vanilla; on 1.8
            // the bot waits for its column as well) nor before its level loaded (1.21.4+).
            if c.opts.caps.sends_tick_end && c.joined {
                c.out.push(Outbound::TickEnd);
            }
            // Behind the level-load gate only the player's entity tick counter runs.
            if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
                self.sim.tick_unloaded();
            }
            self.sim.tick_entities(&mut c.pose);
            c.stamp_entities(&mut self.sim);
            return;
        }

        let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
        let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
        if silent != c.silent {
            c.silent = silent;
            if silent {
                log::warn!(
                    "[{}] t{} server silent for {} ms: behaviour on hold",
                    c.opts.name,
                    c.tick,
                    silent_for.unwrap_or_default().as_millis()
                );
            } else {
                log::info!(
                    "[{}] t{} server answering again: behaviour resumes",
                    c.opts.name,
                    c.tick
                );
            }
        }

        // `Screen.tick` (after the packets, before the key handling): the sign screen may close
        // by itself.
        // Sleeping: the sim's news (1.16.5+ entity data) and `sleepTimer`.
        let slept = self.sim.take_sleep(&mut c.pose);
        debug_assert_eq!(c.rare, c.sign.is_some() || c.sleeping.is_some() || c.dead);
        if c.rare || slept.is_some() {
            rare_screens_tick(c, &self.sim, slept);
        }
        if silent {
            // Freeze: release the keys, keep only the vanilla movement packet.
            c.controls = Controls::default();
            c.aimed = false;
        } else if !self.state.failed && !self.state.done {
            std::mem::swap(&mut c.pending, &mut c.current);
            c.pending.clear();
            if let Some(a) = self.sim.take_absorption() {
                c.current.health_changed |= a.to_bits() != c.health.absorption.to_bits();
                c.health.absorption = a;
            }
            if let Some(f) = self.sim.take_living_flags()
                && c.opts.caps.living_flags_drive_use
            {
                living_flags_use(c, f);
            }
            if !c.dialogs.is_empty() || !c.dialogs_pending.is_empty() {
                c.dialogs.clear();
                std::mem::swap(&mut c.dialogs, &mut c.dialogs_pending);
            }
            c.current.inventory = c.inv.drain_events();
            if !c.hands.use_events.is_empty() {
                take_use_events(c);
            }
            if let Some(s) = self.sim.entities_mut() {
                let ev = s.drain_events();
                let n = ev.len();
                if n > 0 {
                    let skip = n.saturating_sub(MAX_PENDING_ENTITY_EVENTS);
                    let m = c.current.more();
                    m.entities.extend(ev.skip(skip));
                    m.entities_dropped = skip;
                }
            }
            c.current.block_updates_dropped =
                self.sim.drain_block_updates(&mut c.current.block_updates);
            if c.current.inventory.player_changed {
                // Armour enchantments that change movement / digging.
                let ench = |a: usize, id: i32, name: &str| {
                    c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
                };
                let depth = ench(3, 8, "minecraft:depth_strider");
                let soul = ench(3, -1, "minecraft:soul_speed");
                c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
                self.sim.boots(depth, soul);
                self.sim.feet_item(c.inv.armor(3).map(|s| s.id()));
            }
            // what the open screen sent by itself while the server's packets were applied (the
            // 1.16.5 anvil's rename_item), before this tick's actions
            for o in c.inv.take_screen_packets() {
                c.out.push(Outbound::Inventory(o));
            }
            let started = self.state.started;
            self.state.started = true;
            if !started {
                c.rotation.reset(c.pose.yaw, c.pose.pitch);
            }
            let name = c.opts.name.clone();
            let result = catch_unwind(AssertUnwindSafe(|| {
                let held = held_item(&c.inv, &self.sim);
                let mut ctx = TickContext {
                    core: c,
                    world: &self.sim,
                    held,
                    crosshair: std::cell::OnceCell::new(),
                    commands,
                };
                if !started {
                    b.start(&mut ctx);
                }
                b.tick(&mut ctx);
                b.running()
            }));
            match result {
                Ok(true) => {}
                Ok(false) => {
                    self.state.done = true;
                    log::info!("[{name}] behaviour {} finished", b.name());
                }
                Err(_) => {
                    log::error!("[{name}] behaviour {} panicked: stopped", b.name());
                    self.stop(b, "panic");
                }
            }
        }

        let c = &mut self.core;
        // The turn: vanilla turns the player at frame time, before the tick's key handling, so
        // the buttons pick with this tick's look and the movement packet carries the same look.
        // Rotation runs only on ticks the behaviour aimed (budgets untouched otherwise).
        c.turned = false;
        #[cfg(test)]
        if let Some((yaw, pitch)) = c.forced_look.take() {
            c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
            c.pose.yaw = yaw;
            c.pose.pitch = pitch;
            c.aimed = false;
        }
        // The behaviour may have switched entity pushes for this tick's entity ticks.
        if c.entity_push != c.entity_push_sim {
            c.entity_push_sim = c.entity_push;
            self.sim.set_entity_push(c.entity_push);
        }
        // ClientPlayerInteractionManager.tick (syncSelectedSlot) runs before the key
        // processing: a held slot the server changed is echoed before any click.
        if c.held_slot != c.sent_slot {
            c.sent_slot = c.held_slot;
            c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
        }
        c.slot_from_server = false;
        // MinecraftClient.tick key processing (a GUI takes the mouse: buttons up).
        {
            // The screen as the inventory models it (vanilla: a window the client has no
            // screen for opens none; a window the client closed is gone at once).
            // `taken`: the screen or the death screen takes the buttons. A sign editor, sleep
            // or death ([`Core::rare`]) takes one cold branch; otherwise only a window counts and
            // the eyes are the awake ones.
            let (gui, taken, eye) = if c.rare {
                rare_keys(c, &self.sim)
            } else {
                let gui = c.inv.gui_open();
                (
                    gui,
                    gui,
                    awake_eye_height(&self.sim, c.opts.caps, c.pose.sneaking),
                )
            };
            // 26.1: the riptide strength of the held tridents, while it can matter.
            if self.sim.modern_inputs() && ((c.buttons.right && !gui) || c.hands.using_item()) {
                self.sim.held_use_inputs(&mut c.inv);
            }
            let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
            let sim = &self.sim;
            let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
            let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
                sim.place_suppressed(p, f, id)
            };
            let pick_rot = pick_rotation(c);
            let look = hands::look_vector(pick_rot.0, pick_rot.1);
            let held_id = c.inv.held().and_then(|s| u16::try_from(s.id()).ok());
            // The death screen takes the input too, until the respawn.
            let (left, right) = (c.buttons.left && !taken, c.buttons.right && !taken);
            // GameRenderer.updateTargetedEntity before the key handling: one oracle-proven
            // pick for the block and the entity. With both buttons up the hands never read it
            // (no click, and the dig is reset whatever the target), so it is only computed
            // when a button is down — here, at the vanilla pick point, from this state.
            let (target, entity) = if left || right {
                c.pick.fill(sim, c.opts.caps, eyes);
                let crosshair = sim.crosshair_target(&PickQuery {
                    eyes,
                    rotation: pick_rot,
                    look,
                    held: held_id,
                    now: true,
                    creative: c.game_mode == GameMode::Creative,
                    player_bb: pick_box(c.pose.pos),
                    entities: &c.pick.entities,
                });
                let (b, mut e) = c.pick.split(crosshair, eyes);
                if right
                    && let Some(h) = &mut e
                    && let Some(ents) = sim.entities()
                {
                    h.interact = entity_click(c, ents, h.id);
                }
                (b, e)
            } else {
                (None, None)
            };
            let in_water = blocks(
                eyes.x.floor() as i32,
                eyes.y.floor() as i32,
                eyes.z.floor() as i32,
            )
            .is_some_and(|b| b.water);
            let mut held = held_item(&c.inv, sim);
            let mut off_held = off_held_item(&c.inv, sim);
            let creative = c.game_mode == GameMode::Creative;
            if right {
                use_equips(c, creative, &mut held, &mut off_held);
            }
            let mut placed = false;
            let first = c.out.len();
            // right clicks: the version's oracle-proven rules (`Sim::place_rules`,
            // `Sim::air_use`), built only on a tick with the right button (no work on the plain
            // tick)
            let rules_now;
            let rules: &dyn hands::RightRules = if right {
                rules_now = click_rules(
                    sim,
                    &c.inv,
                    &c.pose,
                    c.game_mode,
                    &c.abilities,
                    eyes,
                    use_food_level_of(&c.abilities, c.opts.caps.invulnerable_eating, c.health.food),
                );
                &rules_now
            } else {
                &hands::NoRightRules
            };
            let mut io = HandsIo {
                blocks: &blocks,
                target,
                held,
                held_stack: c.inv.held().cloned(),
                inv_version: c.inv.version(),
                food: use_food_level(c),
                off_held,
                off_stack: c.inv.offhand().cloned(),
                entity,
                factors: DigFactors {
                    on_ground: c.pose.on_ground,
                    in_water,
                    aqua_affinity: c.aqua_affinity,
                    haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
                    fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
                },
                sneaking: c.pose.sneaking,
                out: &mut c.out,
                broken: &mut c.broken_now,
                placed: &mut placed,
                spectator: c.game_mode == GameMode::Spectator,
                caps: c.opts.caps,
                creative,
                creative_dig: creative && c.opts.caps.creative_instant_dig,
                place_blocked: &blocked,
                rules,
            };
            c.hands.tick(left, right, &mut io);
            // Other placements: the server's set_slot brings the new count of the held stack.
            let _ = placed;
            // interactItem: the item's use put the stack on (the server's slot updates follow).
            if right && let Some(off_hand) = c.hands.equipped.take() {
                equip_from_hand(&mut c.inv, off_hand, creative);
            }
            predict_planting(c, sim, first);
            // The client's own stack changes of this tick's clicks (a use, a release, an
            // entity click: each one wrote a packet, so idle ticks skip it all).
            if c.out.len() != first {
                click_stack_effects(c, first, entity);
                // this tick's item uses in the air that the version's rules decided (each wrote
                // its packet): their blocks and the hands' stacks on the client
                if !c.hands.air_used.is_empty() {
                    air_used(c, &mut self.sim);
                }
            }
        }
        // This tick's attacks (behaviour and button): `PlayerEntity.attack` runs on the client
        // right after each attack packet, before the player's movement.
        if !c.hands.attacks.is_empty() {
            attack_effects(c, &mut self.sim);
        }
        // PlayerEntity.tick before the movement: the use ends when the used stack left the
        // hand (1.8: another slot, or the server replaced the held stack).
        if c.hands.using_item() && c.opts.caps.use_stop != crate::version::UseStop::AtSelect {
            held_use_check(c);
        } else {
            c.use_mark = None;
        }
        // PlayerEntity.tick after the cooldown count: another held item resets it.
        if c.opts.caps.cooldown_reset != crate::version::CooldownReset::AtSelect {
            cooldown_held_check(c);
        }
        // The tick's dig packets (behaviour actions and buttons): broken blocks turn to air
        // and the version keeps its records of them for the server's answers.
        if c.hands.dug || !c.hands.placing.is_empty() {
            // Only 1.16.5 records the digs that broke nothing.
            if !c.broken_now.is_empty() || !c.hands.placing.is_empty() || self.sim.records_digs() {
                sent_predictions(c, &mut self.sim);
            }
            c.hands.dug = false;
            c.hands.placing.clear();
        }
        // ClientPlayerEntity.tickMovement: a flight toggle is told to the server before the move.
        if let Some(f) = c.want_flying.take() {
            let first = c.out.len();
            self.sim.set_flying(f, &mut c.out);
            if c.out.len() > first {
                c.pose.flying = f;
            } else if f && !c.pose.flying {
                log::debug!(
                    "[{}] t{} set_flying(true) refused: flight not allowed",
                    c.opts.name,
                    c.tick
                );
            }
        }
        // The gate tick keeps the look (the loading screen held the mouse); an aim set on it
        // turns from the next tick. A sleeping tick is a held-look tick too (set by the sleep
        // timer, `held_look`).
        if std::mem::take(&mut c.gate_tick) {
            held_look(c);
        } else if c.aimed {
            let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
            if c.opts.hold_turn_on_action && !post_look_ok(c, &self.sim, yaw, pitch) {
                // Grim RotationPlace re-checks a dig / place with the look of the movement
                // packet that follows it: keep the mouse still on the clicked block this tick.
                c.held_turns += 1;
            } else {
                c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
                c.pose.yaw = yaw;
                c.pose.pitch = pitch;
            }
            c.aimed = false;
        }
        let first = c.out.len();
        // 26.1 per-tick inputs: updatingUsingItem, the glider (the other versions' sims do
        // nothing here).
        // 26.1 per-tick inputs, only when something can need them: a use, a release, a jump
        // press, attached rockets.
        // The keys the movement reads: none while dead (`isMovementBlocked`, the death screen
        // releases them) or while a screen is open (`setScreen` releases them).
        let controls = movement_controls(c);
        if self.sim.modern_inputs()
            && (c.hands.using_item()
                || c.hands.released_use().is_some()
                || controls.jump
                || self.sim.pre_tick_wanted())
        {
            let pre = crate::sim::PreTick {
                using: c.hands.use_item(),
                released: c.hands.released_use(),
                controls,
                look: (c.pose.yaw, c.pose.pitch),
            };
            if !self.sim.pre_tick(&c.inv, &pre) {
                c.hands.stop_using();
            }
        }
        let using = c.hands.using_item();
        self.sim.hand_items(&mut c.inv);
        self.sim
            .step(&mut c.pose, controls, using, c.entity_id, &mut c.out);
        if c.opts.caps.pick_head_yaw {
            // PlayerEntity.tickNewAi: the head turns to the yaw.
            c.head_yaw = Some(c.pose.yaw);
        }
        // ClientLevel.tickEntities: after this tick's pick and key handling, and after the
        // player (the first entity in the client's tick list): the other entities' ticks see
        // the moved player and push it (1.12.2, 26.1+).
        self.sim.tick_entities(&mut c.pose);
        // 26.3 Minecraft.tick: LocalPlayer.sendChanges after the entities and block entities
        // (the movement packets of a tick among moving blocks wait for it).
        self.sim.send_changes(c.entity_id, &mut c.out);
        c.stamp_entities(&mut self.sim);
        c.hands.count_use_tick();
        for o in &c.out[first..] {
            let Outbound::Move(m) = o else { continue };
            match *m {
                MovePacket::Position { pos, .. } => c.sent.pos = pos,
                MovePacket::Look { yaw, pitch, .. } => {
                    c.sent.yaw = yaw;
                    c.sent.pitch = pitch;
                }
                MovePacket::PositionLook {
                    pos, yaw, pitch, ..
                } => {
                    c.sent.pos = pos;
                    c.sent.yaw = yaw;
                    c.sent.pitch = pitch;
                }
                MovePacket::Flying { .. } => {}
            }
            if matches!(
                m,
                MovePacket::Position { .. } | MovePacket::PositionLook { .. }
            ) {
                c.sent.motion = c.pose.motion;
            }
        }
        c.sent.on_ground = c.pose.on_ground;
        c.sent.sneaking = c.pose.sneaking;
        c.sent.sprinting = c.pose.sprinting;
        c.sent.flying = c.pose.flying;
        c.swings += count_swings(&c.out);
        // Minecraft.tick's screen check: a dead player without a screen gets the death screen
        // or, with the immediate-respawn rule (1.15+, `respawn_screen` off), asks to respawn,
        // every tick until the server's respawn arrives (also when it joined already dead,
        // which brings no death event). With the death screen the behaviour decides
        // (`TickContext::respawn`).
        if c.dead && c.joined && !c.respawn_screen && !c.inv.gui_open() {
            c.out.push(Outbound::Respawn);
        }
        // Minecraft.tick ends with `tick_end` (1.21.2+), after the player's packets.
        if c.opts.caps.sends_tick_end {
            c.out.push(Outbound::TickEnd);
        }

        if self.state.started && !self.state.failed {
            let name = c.opts.name.clone();
            let view = TickView {
                core: &self.core,
                world: &self.sim,
            };
            if catch_unwind(AssertUnwindSafe(|| b.after_tick(&view))).is_err() {
                log::error!(
                    "[{name}] behaviour {} panicked in after_tick: stopped",
                    b.name()
                );
                self.stop(b, "panic");
            }
        }
    }
}

/// Arm swings (main or off hand) in a packet list.
pub(super) fn count_swings(out: &[Outbound]) -> u64 {
    out.iter()
        .filter(|o| matches!(o, Outbound::Swing | Outbound::SwingOffHand))
        .count() as u64
}

/// The movement keys of this tick's step: [`Controls::NONE`] while dead (`isMovementBlocked`
/// at health 0; the death screen released the keys) and, unless switched off
/// ([`crate::Client::gui_releases_keys`]), while a screen is open (a window, the player
/// inventory, a dialog: `setScreen` releases every key and the screen takes the keyboard;
/// 1.16.5's own inventory passes the keys pressed while it is open, [`screen_controls`]).
#[inline]
pub(super) fn movement_controls(c: &mut Core) -> Controls {
    if c.rare {
        rare_controls(c)
    } else if c.opts.gui_releases_keys && (c.inv.gui_open() || c.dialog.is_some()) {
        screen_controls(c)
    } else {
        c.controls
    }
}

/// [`movement_controls`] with a sign editor open, asleep or dead ([`Core::rare`]).
#[cold]
#[inline(never)]
fn rare_controls(c: &mut Core) -> Controls {
    // asleep: `isImmobile` (and the sleep screen holds the keys)
    if c.dead || c.sleeping.is_some() {
        Controls::NONE
    } else if c.opts.gui_releases_keys
        && (c.inv.gui_open() || c.dialog.is_some() || c.sign.is_some())
    {
        screen_controls(c)
    } else {
        c.controls
    }
}

/// The key handling's screen state with a sign editor open, asleep or dead ([`Core::rare`]):
/// whether a screen is open (the sign editor and the sleep screen count), whether the buttons
/// are taken (a screen or the death screen) and the eye height of the pick.
#[cold]
#[inline(never)]
fn rare_keys(c: &Core, sim: &(impl Sim + ?Sized)) -> (bool, bool, f64) {
    let gui = c.inv.gui_open() || c.sign.is_some() || c.sleeping.is_some();
    (
        gui,
        gui || c.dead,
        pick_eye_height(sim, c.opts.caps, c.pose.sneaking),
    )
}

/// A tick that holds the look: the level-load gate tick (an aim set on it turns from the next
/// tick) or a sleeping one (the sleep screen `SleepingChatScreen` / `InBedChatScreen` holds
/// the mouse, so no turn and the aim is dropped; 1.16.5+ `LivingEntity.tick` levels the pitch
/// every tick, the movement packet carries 0).
#[cold]
#[inline(never)]
fn held_look(c: &mut Core) {
    if c.sleeping.is_none() {
        return;
    }
    c.aimed = false;
    if c.opts.caps.sleep_levels_pitch {
        c.pose.pitch = 0.0;
    }
}

/// The keys of a step with a screen open: none, except on the own inventory screen of a
/// version whose screen passes key events ([`Capabilities::own_inventory_passes_keys`]):
/// the keys held when it opened stay released (`KeyBinding.unpressAll`; the screen gets no
/// new press of them) until the behaviour lets go of them once, every key pressed after that
/// applies. Key repeats of a key held through the opening (the OS repeats a held key after
/// its repeat delay) are not modelled: such a key stays released, a possible input.
#[cold]
#[inline(never)]
fn screen_controls(c: &mut Core) -> Controls {
    if !c.opts.caps.own_inventory_passes_keys
        || !c.inv.inventory_open()
        || c.dialog.is_some()
        || c.sign.is_some()
    {
        return Controls::NONE;
    }
    let keys = c.controls;
    let held = c.screen_keys.get_or_insert(keys);
    // A key let go of leaves the held set: its next press passes through.
    let still = |h: bool, k: bool| h && k;
    *held = Controls {
        forward: still(held.forward, keys.forward),
        back: still(held.back, keys.back),
        left: still(held.left, keys.left),
        right: still(held.right, keys.right),
        jump: still(held.jump, keys.jump),
        sneak: still(held.sneak, keys.sneak),
        sprint: still(held.sprint, keys.sprint),
    };
    Controls {
        forward: keys.forward && !held.forward,
        back: keys.back && !held.back,
        left: keys.left && !held.left,
        right: keys.right && !held.right,
        jump: keys.jump && !held.jump,
        sneak: keys.sneak && !held.sneak,
        sprint: keys.sprint && !held.sprint,
    }
}

/// Hands the tick's dig and block-item placement packets to the sim in packet order
/// ([`Sim::dig_sent`], [`Sim::place_sent`]): whether each dig broke its block on the client,
/// each packet's 1.19+ prediction sequence (counted from the wire's last sequence the way the
/// wire will number this tick's predicting packets: dig start / finish, place, use item) and
/// the player's position before the tick's movement.
#[cold]
#[inline(never)]
fn sent_predictions<S: Sim>(c: &mut Core, sim: &mut S) {
    use crate::common::DigStatus;
    let player = c.pose.pos;
    let mut sequence = c.sequence.unwrap_or(0);
    let mut broken = 0;
    let mut placing = c.hands.placing.iter().copied().peekable();
    let any_item = c.inv.held().is_some() || c.inv.offhand().is_some();
    // items used by predicted placements: main hand, off hand
    let mut used = [0u8; 2];
    for (i, o) in c.out.iter().enumerate() {
        match *o {
            Outbound::Dig { status, pos, .. } => {
                let predicting = matches!(status, DigStatus::Start | DigStatus::Finish);
                if predicting {
                    sequence = sequence.wrapping_add(1);
                } else if status != DigStatus::Abort {
                    continue;
                }
                let b = predicting && c.broken_now.get(broken) == Some(&pos);
                if b {
                    broken += 1;
                }
                sim.dig_sent(pos, status, b, sequence, player);
            }
            Outbound::Place {
                pos,
                face,
                cursor,
                ref held,
                off_hand,
            }
            | Outbound::PlaceInside {
                pos,
                face,
                cursor,
                ref held,
                off_hand,
            } => {
                sequence = sequence.wrapping_add(1);
                while placing.next_if(|&p| (p as usize) < i).is_some() {}
                if placing.next_if_eq(&(i as u32)).is_some()
                    && sim.place_sent(&crate::sim::predict::PlaceSent {
                        pos,
                        face,
                        held: held.as_ref(),
                        sneaking: c.pose.sneaking,
                        any_item,
                        game_mode: c.game_mode,
                        sequence,
                        player,
                        cursor: [cursor.x as f32, cursor.y as f32, cursor.z as f32],
                        yaw: c.pose.yaw,
                    })
                    && crate::sim::predict::placing_uses_item(c.game_mode)
                {
                    used[usize::from(off_hand)] = used[usize::from(off_hand)].saturating_add(1);
                }
            }
            Outbound::UseItem { .. } => {
                sequence = sequence.wrapping_add(1);
            }
            _ => {}
        }
    }
    debug_assert_eq!(
        broken,
        c.broken_now.len(),
        "a broken block without its dig packet"
    );
    for p in &c.broken_now[broken..] {
        sim.predict_air(p.x, p.y, p.z);
    }
    c.broken_now.clear();
    if used[0] > 0 {
        c.inv.consume_held(used[0]);
    }
    if used[1] > 0 {
        c.inv.consume_offhand(used[1]);
    }
}

/// The version's rules of a right click for [`HandsIo::rules`] (`Sim::place_rules`,
/// `Sim::air_use`), with what they read of the player.
pub(super) struct ClickRules<'a, W: Sim + ?Sized> {
    pub(super) sim: &'a W,
    pub(super) inv: &'a ghast_inventory::Inventory,
    pub(super) sneaking: bool,
    pub(super) game_mode: GameMode,
    pub(super) yaw: f32,
    pub(super) pitch: f32,
    /// The eyes (the item uses in the air; unused by the behaviour's actions).
    pub(super) eyes: Vec3,
    /// [`use_food_level`].
    pub(super) food: i32,
    /// `abilities.creativeMode`.
    pub(super) creative: bool,
}

/// [`ClickRules`] of a tick with the right button (out of the plain tick's way).
#[cold]
#[inline(never)]
pub(super) fn click_rules<'a, W: Sim + ?Sized>(
    sim: &'a W,
    inv: &'a ghast_inventory::Inventory,
    pose: &Pose,
    game_mode: GameMode,
    abilities: &crate::common::Abilities,
    eyes: Vec3,
    food: i32,
) -> ClickRules<'a, W> {
    ClickRules {
        sim,
        inv,
        sneaking: pose.sneaking,
        game_mode,
        yaw: pose.yaw,
        pitch: pose.pitch,
        eyes,
        food,
        creative: abilities.creative_mode(),
    }
}

impl<W: Sim + ?Sized> hands::RightRules for ClickRules<'_, W> {
    fn place(
        &self,
        pos: ghast_protocol::BlockPos,
        face: crate::common::Face,
        cursor: [f32; 3],
        off_hand: bool,
    ) -> crate::sim::predict::PlaceRules {
        let inv = self.inv;
        self.sim.place_rules(&crate::sim::predict::PlaceQuery {
            pos,
            face,
            cursor,
            held: if off_hand { inv.offhand() } else { inv.held() },
            sneaking: self.sneaking,
            any_item: inv.held().is_some() || inv.offhand().is_some(),
            game_mode: self.game_mode,
            yaw: self.yaw,
            food: self.food,
        })
    }

    fn air(&self, off_hand: bool) -> crate::sim::predict::AirAnswer {
        let inv = self.inv;
        let Some(stack) = (if off_hand { inv.offhand() } else { inv.held() }) else {
            return crate::sim::predict::AirAnswer::Flags;
        };
        self.sim.air_use(&crate::sim::predict::AirQuery {
            off_hand,
            stack,
            inv,
            eyes: self.eyes,
            yaw: self.yaw,
            pitch: self.pitch,
            game_mode: self.game_mode,
            creative: self.creative,
        })
    }
}

/// 1.8 `SeedItem.use` / `CropItem.use` on the client: planting on the top of
/// its soil with air above uses one item at once (the server's set_slot follows later; it
/// sends none when the count already agrees). Applied to the `block_place` packets written
/// from `first` on. Other placements wait for the server's set_slot: predicting them needs
/// vanilla's full placement rules, and a wrong prediction would never be corrected.
pub(super) fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
    if !c.opts.caps.seed_planting_prediction || c.game_mode == GameMode::Creative {
        return;
    }
    let mut uses = 0u8;
    for o in &c.out[first..] {
        let Outbound::Place {
            pos,
            face: crate::common::Face::Up,
            held: Some(held),
            off_hand: false,
            ..
        } = o
        else {
            continue;
        };
        // Seed item → its soil (wheat, pumpkin, melon seeds, carrot, potato: farmland;
        // nether wart: soul sand).
        let soil = match held.id() {
            295 | 361 | 362 | 391 | 392 => 60,
            372 => 88,
            _ => continue,
        };
        let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
        if held.count() > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
            uses += 1;
        }
    }
    if uses > 0 {
        c.inv.consume_held(uses);
    }
}