1use std::panic::{AssertUnwindSafe, catch_unwind};
25use std::sync::Arc;
26use std::time::{Duration, Instant};
27
28use crate::common::{
29 Abilities, ChatMessage, ClientSettings, Controls, GameMode, Health, Inbound, MovePacket,
30 Outbound, Pose, Vec3,
31};
32use crate::hands::{self, BlockHit, Buttons, DigFactors, Hands, HandsIo};
33use crate::interest::Interests;
34use crate::rotation::Rotation;
35use crate::sim::{Sim, WorldView};
36use crate::version::GameVersion;
37
38const MAX_PENDING_CHAT: usize = 512;
41
42pub trait Behavior {
48 fn name(&self) -> &str {
50 "behavior"
51 }
52
53 fn interests(&self) -> Interests {
56 Interests::NONE
57 }
58
59 fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
65 let _ = version;
66 std::borrow::Cow::Borrowed(&[])
67 }
68
69 fn start(&mut self, ctx: &mut TickContext<'_>) {
72 let _ = ctx;
73 }
74
75 fn tick(&mut self, ctx: &mut TickContext<'_>);
77
78 fn running(&self) -> bool {
82 true
83 }
84
85 fn stop(&mut self, reason: &str) {
87 let _ = reason;
88 }
89}
90
91impl<B: Behavior + ?Sized> Behavior for Box<B> {
93 fn name(&self) -> &str {
94 (**self).name()
95 }
96 fn interests(&self) -> Interests {
97 (**self).interests()
98 }
99 fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
100 (**self).raw_packets(version)
101 }
102 fn start(&mut self, ctx: &mut TickContext<'_>) {
103 (**self).start(ctx);
104 }
105 fn tick(&mut self, ctx: &mut TickContext<'_>) {
106 (**self).tick(ctx);
107 }
108 fn running(&self) -> bool {
109 (**self).running()
110 }
111 fn stop(&mut self, reason: &str) {
112 (**self).stop(reason);
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum ClickRefused {
119 Turning,
121 Inventory(ghast_inventory::ClickError),
123}
124
125impl std::fmt::Display for ClickRefused {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 match self {
128 ClickRefused::Turning => f.write_str("the player is turning"),
129 ClickRefused::Inventory(e) => write!(f, "{e}"),
130 }
131 }
132}
133
134impl std::error::Error for ClickRefused {}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139pub struct ClickTicket {
140 pub window_id: i32,
142 pub action: i16,
144}
145
146impl ClickTicket {
147 #[must_use]
149 pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
150 r.window_id == self.window_id && r.action == self.action
151 }
152}
153
154#[derive(Debug, Clone, Copy, Default)]
156pub struct Idle;
157
158impl Behavior for Idle {
159 fn name(&self) -> &str {
160 "idle"
161 }
162
163 fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct RawInbound {
169 pub id: i32,
171 pub body: bytes::Bytes,
173 pub at: Instant,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq)]
179pub struct TeleportEvent {
180 pub teleport: crate::common::Teleport,
183 pub sent_before: Pose,
186 pub pose_before: Pose,
188 pub after: Pose,
190}
191
192const MAX_PENDING_TELEPORTS: usize = 64;
194
195const MAX_PENDING_RAW: usize = 4096;
197
198#[derive(Debug, Clone, Default, PartialEq)]
200pub struct TickEvents {
201 pub chat: Vec<ChatMessage>,
203 pub chat_dropped: usize,
205 pub teleported: bool,
207 pub teleports: Vec<TeleportEvent>,
209 pub joined: bool,
211 pub respawned: bool,
213 pub died: bool,
215 pub health_changed: bool,
217 pub game_mode_changed: bool,
219 pub inventory: ghast_inventory::Events,
221 pub block_updates: Vec<(ghast_protocol::BlockPos, u32)>,
225 pub block_updates_dropped: usize,
227 pub raw: Vec<RawInbound>,
230 pub raw_dropped: usize,
232}
233
234impl TickEvents {
235 fn clear(&mut self) {
236 self.chat.clear();
237 self.chat_dropped = 0;
238 self.teleported = false;
239 self.teleports.clear();
240 self.joined = false;
241 self.respawned = false;
242 self.died = false;
243 self.health_changed = false;
244 self.game_mode_changed = false;
245 self.inventory = ghast_inventory::Events::default();
246 self.block_updates.clear();
247 self.block_updates_dropped = 0;
248 self.raw.clear();
249 self.raw_dropped = 0;
250 }
251}
252
253#[derive(Debug, Clone)]
255pub(crate) struct CoreOptions {
256 pub name: Arc<str>,
257 pub version: GameVersion,
258 pub settings: ClientSettings,
259 pub brand: Option<String>,
260 pub sensitivity: f32,
261 pub silent_hold: Duration,
262 pub inventory: ghast_inventory::Version,
263 pub hold_turn_on_action: bool,
266}
267
268#[derive(Debug)]
270pub(crate) struct Core {
271 opts: CoreOptions,
272 tick: u64,
273 entity_id: i32,
274 joined: bool,
275 teleported_once: bool,
276 ready: bool,
277 pose: Pose,
278 sent: Pose,
279 rotation: Rotation,
280 aimed: bool,
281 controls: Controls,
282 health: Health,
283 dead: bool,
284 abilities: Abilities,
285 game_mode: GameMode,
286 held_slot: u8,
287 sent_slot: u8,
288 open_window: i32,
289 dimension: String,
290 respawn_screen: bool,
291 pending: TickEvents,
292 current: TickEvents,
293 out: Vec<Outbound>,
294 last_inbound: Option<Instant>,
295 silent: bool,
296 quit: Option<String>,
297 status: String,
298 hands: Hands,
299 buttons: Buttons,
300 inv: ghast_inventory::Inventory,
302 turned: bool,
304 effects: std::collections::BTreeMap<i8, i8>,
306 aqua_affinity: bool,
308 broken_now: Vec<ghast_protocol::BlockPos>,
310 want_flying: Option<bool>,
312 held_turns: u64,
314 #[cfg(test)]
316 forced_look: Option<(f32, f32)>,
317}
318
319#[derive(Debug, Default)]
321struct BehaviorState {
322 started: bool,
323 failed: bool,
324 done: bool,
326}
327
328#[derive(Debug)]
330pub(crate) struct Engine<S> {
331 pub core: Core,
332 pub sim: S,
333 state: BehaviorState,
334}
335
336impl Core {
337 fn new(opts: CoreOptions) -> Self {
338 let rotation = Rotation::new(opts.sensitivity);
339 let inv = ghast_inventory::Inventory::new(opts.inventory);
340 Core {
341 opts,
342 tick: 0,
343 entity_id: 0,
344 joined: false,
345 teleported_once: false,
346 ready: false,
347 pose: Pose::default(),
348 sent: Pose::default(),
349 rotation,
350 aimed: false,
351 controls: Controls::default(),
352 health: Health::default(),
353 dead: false,
354 abilities: Abilities::default(),
355 game_mode: GameMode::default(),
356 held_slot: 0,
357 sent_slot: 0,
358 open_window: 0,
359 dimension: String::new(),
360 respawn_screen: true,
361 pending: TickEvents::default(),
362 current: TickEvents::default(),
363 out: Vec::with_capacity(16),
364 last_inbound: None,
365 silent: false,
366 quit: None,
367 status: String::new(),
368 hands: Hands::default(),
369 buttons: Buttons::default(),
370 inv,
371 turned: false,
372 effects: std::collections::BTreeMap::new(),
373 aqua_affinity: false,
374 broken_now: Vec::new(),
375 want_flying: None,
376 held_turns: 0,
377 #[cfg(test)]
378 forced_look: None,
379 }
380 }
381
382 fn reset_player(&mut self, why: &str) {
385 self.teleported_once = false;
386 self.ready = false;
387 self.pose = Pose::default();
388 self.sent = Pose::default();
389 self.controls = Controls::default();
390 self.aimed = false;
391 self.open_window = 0;
392 self.dead = false;
393 self.hands.reset();
394 self.buttons = Buttons::default();
395 self.effects.clear();
396 log::debug!(
397 "[{}] t{} {why}: waiting for the server position",
398 self.opts.name,
399 self.tick
400 );
401 }
402
403 fn column_loaded(&self, world: &dyn WorldView) -> bool {
404 let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
406 let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
407 world.is_column_loaded(cx, cz)
408 }
409}
410
411fn held_item<W: Sim + ?Sized>(
413 inv: &ghast_inventory::Inventory,
414 sim: &W,
415) -> Option<hands::HeldItem> {
416 let s = inv.held()?;
417 let id = u16::try_from(s.id).ok()?;
418 let count = u8::try_from(s.count.clamp(0, 255)).unwrap_or(0);
419 Some(sim.held_item(id, count, efficiency(s)))
420}
421
422fn collidable(e: &ghast_entity::Entity) -> bool {
426 use ghast_entity::{EntityClass, EntityType};
427 match e.class() {
428 EntityClass::Player | EntityClass::Mob | EntityClass::Painting => true,
429 EntityClass::Item | EntityClass::ExperienceOrb => false,
430 EntityClass::Object => match e.entity_type() {
431 EntityType::LegacyObject(t) => matches!(t, 1 | 10 | 50 | 51 | 70 | 71 | 77 | 78),
432 EntityType::Registry(_) => {
433 ghast_entity::v1_16_5::info(e.entity_type()).is_some_and(|i| {
434 matches!(
435 i.name,
436 "boat"
437 | "tnt"
438 | "end_crystal"
439 | "falling_block"
440 | "item_frame"
441 | "leash_knot"
442 | "armor_stand"
443 | "shulker_bullet"
444 ) || i.name.contains("minecart")
445 })
446 }
447 _ => false,
448 },
449 }
450}
451
452fn entity_pick<W: WorldView + ?Sized>(
455 w: &W,
456 version: GameVersion,
457 eyes: Vec3,
458 look: Vec3,
459 block_distance: Option<f64>,
460) -> Option<hands::EntityHit> {
461 let ents = w.entities()?;
462 let riding = ents.me().and_then(ghast_entity::Entity::vehicle);
463 let border = if version == GameVersion::V1_8_9 {
465 0.1
466 } else {
467 0.0
468 };
469 let cands = ents
470 .within([eyes.x, eyes.y, eyes.z], 8.0)
471 .filter(|e| collidable(e))
472 .filter_map(|e| {
473 let p = e.position();
474 Some((e.id(), e.bounding_box()?, Vec3::new(p[0], p[1], p[2])))
475 });
476 hands::pick_entity(cands, eyes, look, block_distance, border, riding)
477}
478
479fn off_held_item<W: Sim + ?Sized>(
481 inv: &ghast_inventory::Inventory,
482 sim: &W,
483) -> Option<hands::HeldItem> {
484 let s = inv.offhand()?;
485 let id = u16::try_from(s.id).ok()?;
486 let count = u8::try_from(s.count.clamp(0, 255)).unwrap_or(0);
487 Some(sim.held_item(id, count, 0))
488}
489
490fn efficiency(s: &ghast_inventory::Stack) -> u8 {
492 enchant_level(s, 32, "minecraft:efficiency")
493}
494
495fn enchant_level(s: &ghast_inventory::Stack, id_1_8: i32, name: &str) -> u8 {
498 use ghast_protocol::nbt::Tag;
499 let Some(root) = s.nbt.as_ref().and_then(|n| n.parse().ok().flatten()) else {
500 return 0;
501 };
502 let Some(c) = root.tag.as_compound() else {
503 return 0;
504 };
505 let num = |t: Option<&Tag>| match t {
506 Some(Tag::Short(v)) => i32::from(*v),
507 Some(Tag::Int(v)) => *v,
508 Some(Tag::Byte(v)) => i32::from(*v),
509 _ => -1,
510 };
511 for key in ["ench", "Enchantments"] {
512 if let Some(Tag::List(l)) = c.get(key) {
513 for e in l.items.iter().filter_map(Tag::as_compound) {
514 let hit = match e.get("id") {
515 Some(Tag::String(n)) => n == name,
516 other => num(other) == id_1_8,
517 };
518 if hit {
519 return u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
520 }
521 }
522 }
523 }
524 0
525}
526
527impl<S: Sim> Engine<S> {
528 pub(crate) fn new(opts: CoreOptions, sim: S) -> Self {
529 Engine {
530 core: Core::new(opts),
531 sim,
532 state: BehaviorState::default(),
533 }
534 }
535
536 pub(crate) fn note_inbound(&mut self, now: Instant) {
538 self.core.last_inbound = Some(now);
539 }
540
541 pub(crate) fn last_inbound(&self) -> Option<Instant> {
543 self.core.last_inbound
544 }
545
546 pub(crate) fn name(&self) -> &str {
548 &self.core.opts.name
549 }
550
551 pub(crate) fn push_raw(&mut self, p: RawInbound) {
553 let ev = &mut self.core.pending;
554 if ev.raw.len() < MAX_PENDING_RAW {
555 ev.raw.push(p);
556 } else {
557 ev.raw_dropped += 1;
558 }
559 }
560
561 pub(crate) fn raw_packets<B: Behavior>(&self, b: &B) -> std::borrow::Cow<'static, [i32]> {
563 if self.state.failed || self.state.done {
564 std::borrow::Cow::Borrowed(&[])
565 } else {
566 b.raw_packets(self.core.opts.version)
567 }
568 }
569
570 pub(crate) fn inventory_mut(&mut self) -> &mut ghast_inventory::Inventory {
572 &mut self.core.inv
573 }
574
575 pub(crate) fn outbound(&mut self) -> &mut Vec<Outbound> {
577 &mut self.core.out
578 }
579
580 pub(crate) fn quit_requested(&self) -> Option<&str> {
582 self.core.quit.as_deref()
583 }
584
585 pub(crate) fn core_name(&self) -> &str {
586 &self.core.opts.name
587 }
588
589 pub(crate) fn tick_count(&self) -> u64 {
590 self.core.tick
591 }
592
593 pub(crate) fn handle(&mut self, p: Inbound) {
596 let c = &mut self.core;
597 let sim = &mut self.sim;
598 match p {
599 Inbound::KeepAlive(id) => c.out.push(Outbound::KeepAlive(id)),
600 Inbound::JoinGame(j) => {
601 c.entity_id = j.entity_id;
602 c.game_mode = j.game_mode;
603 c.respawn_screen = j.respawn_screen;
604 c.dimension = j.dimension;
607 c.joined = true;
608 c.pending.joined = true;
609 c.health = Health::default();
610 c.abilities = Abilities::default();
611 c.reset_player("join game");
612 sim.reset_player();
613 sim.spectator(c.game_mode == GameMode::Spectator);
614 c.out.push(Outbound::Settings(c.opts.settings.clone()));
616 if let Some(brand) = &c.opts.brand {
617 c.out.push(Outbound::Brand(brand.clone()));
618 }
619 log::info!(
620 "[{}] joined: entity {} {:?} dimension {}",
621 c.opts.name,
622 c.entity_id,
623 c.game_mode,
624 c.dimension
625 );
626 }
627 Inbound::Respawn {
628 dimension,
629 game_mode,
630 } => {
631 if dimension != c.dimension {
632 c.dimension = dimension;
633 }
634 c.game_mode = game_mode;
635 c.pending.respawned = true;
636 c.reset_player("respawn");
637 sim.reset_player();
638 sim.spectator(c.game_mode == GameMode::Spectator);
639 }
640 Inbound::Teleport(t) => {
641 if c.teleported_once {
642 log::debug!(
643 "[{}] t{} teleport {:?} {:?} {:?} yaw {:?} pitch {:?} flags {}; we had sent \
644 {:?} {:?} {:?} yaw {:?} pitch {:?} ground {}",
645 c.opts.name,
646 c.tick,
647 t.x,
648 t.y,
649 t.z,
650 t.yaw,
651 t.pitch,
652 t.flags,
653 c.sent.pos.x,
654 c.sent.pos.y,
655 c.sent.pos.z,
656 c.sent.yaw,
657 c.sent.pitch,
658 c.sent.on_ground
659 );
660 }
661 let (sent_before, pose_before) = (c.sent, c.pose);
662 sim.teleport(&mut c.pose, &t);
663 if c.pending.teleports.len() < MAX_PENDING_TELEPORTS {
664 c.pending.teleports.push(TeleportEvent {
665 teleport: t,
666 sent_before,
667 pose_before,
668 after: c.pose,
669 });
670 }
671 if let Some(id) = t.teleport_id {
672 c.out.push(Outbound::TeleportConfirm(id));
673 }
674 c.out.push(Outbound::Move(MovePacket::PositionLook {
675 pos: c.pose.pos,
676 yaw: c.pose.yaw,
677 pitch: c.pose.pitch,
678 on_ground: false,
679 }));
680 c.sent = Pose {
682 on_ground: false,
683 ..c.pose
684 };
685 if !c.teleported_once {
686 log::debug!(
687 "[{}] t{} spawn position {:.3} {:.3} {:.3}",
688 c.opts.name,
689 c.tick,
690 c.pose.pos.x,
691 c.pose.pos.y,
692 c.pose.pos.z
693 );
694 }
695 c.teleported_once = true;
696 c.pending.teleported = true;
697 }
698 Inbound::Chat(m) => {
699 if c.pending.chat.len() < MAX_PENDING_CHAT {
700 c.pending.chat.push(m);
701 } else {
702 c.pending.chat_dropped += 1;
703 }
704 }
705 Inbound::Health(h) => {
706 let was_dead = c.dead;
707 c.health = h;
708 sim.food(h.food);
709 c.pending.health_changed = true;
710 if h.health <= 0.0 && !was_dead {
711 c.dead = true;
712 c.pending.died = true;
713 log::info!("[{}] t{} died", c.opts.name, c.tick);
714 }
715 }
716 Inbound::Died { entity_id } => {
717 if entity_id == c.entity_id && !c.respawn_screen {
718 c.out.push(Outbound::Respawn);
720 }
721 }
722 Inbound::Abilities(a) => {
723 c.abilities = a;
724 c.pose.flying = a.flying();
725 sim.abilities(a);
726 }
727 Inbound::HeldSlot(s) => {
728 if (0..9).contains(&s) {
729 if c.held_slot != s as u8 {
732 c.hands.stop_using();
733 }
734 c.held_slot = s as u8;
735 }
736 }
737 Inbound::GameState { reason, value } => match reason {
738 3 => {
739 c.game_mode = GameMode::from_wire(value as u8);
740 sim.spectator(c.game_mode == GameMode::Spectator);
741 c.pending.game_mode_changed = true;
742 }
743 11 if c.opts.version != GameVersion::V1_8_9 => c.respawn_screen = value == 0.0,
745 _ => {}
746 },
747 Inbound::Transaction { .. } => {}
749 Inbound::OpenWindow(id) => c.open_window = id,
750 Inbound::CloseWindow(_) => c.open_window = 0,
751 Inbound::Velocity { entity_id, motion } => {
752 if entity_id == c.entity_id {
753 sim.velocity(motion, false);
754 }
755 }
756 Inbound::ExplosionPush(motion) => sim.velocity(motion, true),
757 Inbound::MovementSpeed {
758 entity_id,
759 base,
760 modifiers,
761 } => {
762 if entity_id == c.entity_id {
763 log::debug!(
764 "[{}] t{} movement speed base {base:?} modifiers {modifiers:?}",
765 c.opts.name,
766 c.tick
767 );
768 let mods: Vec<(u128, f64, u8)> = modifiers
769 .iter()
770 .map(|&(id, amount, op)| (id.as_u128(), amount, op as u8))
771 .collect();
772 sim.movement_speed(base, &mods);
773 }
774 }
775 Inbound::Effect {
776 entity_id,
777 id,
778 amplifier,
779 } => {
780 if entity_id == c.entity_id {
781 c.effects.insert(id, amplifier);
782 sim.status_effects(&c.effects);
783 }
784 }
785 Inbound::EffectRemoved { entity_id, id } => {
786 if entity_id == c.entity_id {
787 c.effects.remove(&id);
788 sim.status_effects(&c.effects);
789 }
790 }
791 Inbound::EntityStatus { entity_id, status } => {
792 if entity_id == c.entity_id && status == 9 {
794 c.hands.stop_using();
795 }
796 }
797 Inbound::Disconnect(_) | Inbound::SetCompression(_) => {}
798 }
799 }
800
801 pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
803 if self.state.failed {
804 Interests::NONE
805 } else {
806 b.interests()
807 }
808 }
809
810 pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
812 if self.state.started && !self.state.failed {
813 self.state.failed = true;
814 let name = self.core.opts.name.clone();
815 if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
816 log::error!("[{name}] behaviour {} panicked in stop", b.name());
817 }
818 }
819 }
820
821 pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
823 let c = &mut self.core;
824 c.tick += 1;
825 c.inv.tick();
827 let was_ready = c.ready;
828 c.ready = c.teleported_once && c.column_loaded(&self.sim);
829 if c.ready != was_ready {
830 if c.ready {
831 log::info!(
832 "[{}] t{} in the world at {:.3} {:.3} {:.3}",
833 c.opts.name,
834 c.tick,
835 c.pose.pos.x,
836 c.pose.pos.y,
837 c.pose.pos.z
838 );
839 } else {
840 log::debug!(
841 "[{}] t{} player column not loaded: not ticking",
842 c.opts.name,
843 c.tick
844 );
845 }
846 }
847 if !c.ready {
848 return;
851 }
852
853 let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
854 let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
855 if silent != c.silent {
856 c.silent = silent;
857 if silent {
858 log::warn!(
859 "[{}] t{} server silent for {} ms: behaviour on hold",
860 c.opts.name,
861 c.tick,
862 silent_for.unwrap_or_default().as_millis()
863 );
864 } else {
865 log::info!(
866 "[{}] t{} server answering again: behaviour resumes",
867 c.opts.name,
868 c.tick
869 );
870 }
871 }
872
873 if silent {
874 c.controls = Controls::default();
876 c.aimed = false;
877 } else if !self.state.failed && !self.state.done {
878 std::mem::swap(&mut c.pending, &mut c.current);
879 c.pending.clear();
880 c.current.inventory = c.inv.drain_events();
881 c.current.block_updates_dropped =
882 self.sim.drain_block_updates(&mut c.current.block_updates);
883 if c.current.inventory.player_changed {
884 let ench = |a: usize, id: i32, name: &str| {
886 c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
887 };
888 let depth = ench(3, 8, "minecraft:depth_strider");
889 let soul = ench(3, -1, "minecraft:soul_speed");
890 c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
891 self.sim.boots(depth, soul);
892 }
893 let started = self.state.started;
894 self.state.started = true;
895 if !started {
896 c.rotation.reset(c.pose.yaw, c.pose.pitch);
897 }
898 let name = c.opts.name.clone();
899 let result = catch_unwind(AssertUnwindSafe(|| {
900 let held = held_item(&c.inv, &self.sim);
901 let mut ctx = TickContext {
902 core: c,
903 world: &self.sim,
904 held,
905 };
906 if !started {
907 b.start(&mut ctx);
908 }
909 b.tick(&mut ctx);
910 b.running()
911 }));
912 match result {
913 Ok(true) => {}
914 Ok(false) => {
915 self.state.done = true;
916 log::info!("[{name}] behaviour {} finished", b.name());
917 }
918 Err(_) => {
919 log::error!("[{name}] behaviour {} panicked: stopped", b.name());
920 self.stop(b, "panic");
921 }
922 }
923 }
924
925 let c = &mut self.core;
926 if c.held_slot != c.sent_slot {
929 c.sent_slot = c.held_slot;
930 c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
931 }
932 {
934 let gui = c.inv.gui_open();
937 let eye = if c.pose.sneaking {
938 c.opts.version.sneak_eye_height()
939 } else {
940 c.opts.version.eye_height()
941 };
942 let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
943 let sim = &self.sim;
944 let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
945 let look = hands::look_vector(c.pose.yaw, c.pose.pitch);
946 let target = hands::pick(&blocks, eyes, look, hands::REACH);
947 let entity = entity_pick(sim, c.opts.version, eyes, look, target.map(|t| t.distance));
948 let in_water = blocks(
949 eyes.x.floor() as i32,
950 eyes.y.floor() as i32,
951 eyes.z.floor() as i32,
952 )
953 .is_some_and(|b| b.water);
954 let held = held_item(&c.inv, sim);
955 let mut placed = false;
956 let first = c.out.len();
957 let mut io = HandsIo {
958 blocks: &blocks,
959 target,
960 held,
961 held_stack: c.inv.held().cloned(),
962 food: c.health.food,
963 modern: c.opts.version != GameVersion::V1_8_9,
964 off_held: off_held_item(&c.inv, sim),
965 off_stack: c.inv.offhand().cloned(),
966 entity,
967 factors: DigFactors {
968 on_ground: c.pose.on_ground,
969 in_water,
970 aqua_affinity: c.aqua_affinity,
971 haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
972 fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
973 },
974 sneaking: c.pose.sneaking,
975 out: &mut c.out,
976 broken: &mut c.broken_now,
977 placed: &mut placed,
978 };
979 let (left, right) = (c.buttons.left && !gui, c.buttons.right && !gui);
980 c.hands.tick(left, right, &mut io);
981 let _ = placed;
983 predict_planting(c, sim, first);
984 }
985 for p in c.broken_now.drain(..) {
986 self.sim.predict_air(p.x, p.y, p.z);
987 }
988 if let Some(f) = c.want_flying.take() {
990 let first = c.out.len();
991 self.sim.set_flying(f, &mut c.out);
992 if c.out.len() > first {
993 c.pose.flying = f;
994 } else if f && !c.pose.flying {
995 log::debug!(
996 "[{}] t{} set_flying(true) refused: flight not allowed",
997 c.opts.name,
998 c.tick
999 );
1000 }
1001 }
1002 c.turned = false;
1004 #[cfg(test)]
1005 if let Some((yaw, pitch)) = c.forced_look.take() {
1006 c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1007 c.pose.yaw = yaw;
1008 c.pose.pitch = pitch;
1009 c.aimed = false;
1010 }
1011 if c.aimed {
1012 let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
1013 if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
1014 c.held_turns += 1;
1017 } else {
1018 c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1019 c.pose.yaw = yaw;
1020 c.pose.pitch = pitch;
1021 }
1022 c.aimed = false;
1023 }
1024 let first = c.out.len();
1025 let using = c.hands.using_item();
1026 self.sim
1027 .step(&mut c.pose, c.controls, using, c.entity_id, &mut c.out);
1028 for o in &c.out[first..] {
1029 let Outbound::Move(m) = o else { continue };
1030 match *m {
1031 MovePacket::Position { pos, .. } => c.sent.pos = pos,
1032 MovePacket::Look { yaw, pitch, .. } => {
1033 c.sent.yaw = yaw;
1034 c.sent.pitch = pitch;
1035 }
1036 MovePacket::PositionLook {
1037 pos, yaw, pitch, ..
1038 } => {
1039 c.sent.pos = pos;
1040 c.sent.yaw = yaw;
1041 c.sent.pitch = pitch;
1042 }
1043 MovePacket::Flying { .. } => {}
1044 }
1045 if matches!(
1046 m,
1047 MovePacket::Position { .. } | MovePacket::PositionLook { .. }
1048 ) {
1049 c.sent.motion = c.pose.motion;
1050 }
1051 }
1052 c.sent.on_ground = c.pose.on_ground;
1053 c.sent.sneaking = c.pose.sneaking;
1054 c.sent.sprinting = c.pose.sprinting;
1055 c.sent.flying = c.pose.flying;
1056 }
1057}
1058
1059#[cfg(test)]
1060impl Core {
1061 pub(crate) fn test_set_slot(&mut self, slot: u8) {
1063 self.held_slot = slot;
1064 self.sent_slot = slot;
1065 self.inv.select(slot);
1066 }
1067
1068 pub(crate) fn test_poses(&mut self) -> (&mut Pose, &mut Pose) {
1070 (&mut self.pose, &mut self.sent)
1071 }
1072
1073 pub(crate) fn test_held_turns(&self) -> u64 {
1075 self.held_turns
1076 }
1077}
1078
1079#[cfg(test)]
1080impl TickContext<'_> {
1081 pub(crate) fn test_force_look(&mut self, yaw: f32, pitch: f32) {
1083 self.core.forced_look = Some((yaw, pitch));
1084 }
1085
1086 pub(crate) fn test_rotation(&self) -> Rotation {
1088 self.core.rotation
1089 }
1090}
1091
1092fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
1098 if c.opts.version != GameVersion::V1_8_9 || c.game_mode == GameMode::Creative {
1099 return;
1100 }
1101 let mut uses = 0u8;
1102 for o in &c.out[first..] {
1103 let Outbound::Place {
1104 pos,
1105 face: crate::common::Face::Up,
1106 held: Some(held),
1107 off_hand: false,
1108 ..
1109 } = o
1110 else {
1111 continue;
1112 };
1113 let soil = match held.id {
1116 295 | 361 | 362 | 391 | 392 => 60,
1117 372 => 88,
1118 _ => continue,
1119 };
1120 let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
1121 if held.count > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
1122 uses += 1;
1123 }
1124 }
1125 if uses > 0 {
1126 c.inv.consume_held(uses);
1127 }
1128}
1129
1130fn post_look_ok(c: &Core, yaw: f32, pitch: f32) -> bool {
1134 let looks = [
1135 hands::look_vector(c.pose.yaw, pitch),
1136 hands::look_vector(yaw, pitch),
1137 ];
1138 let heights = [
1139 c.opts.version.eye_height(),
1140 c.opts.version.sneak_eye_height(),
1141 ];
1142 c.out
1143 .iter()
1144 .filter_map(|o| match o {
1145 Outbound::Dig {
1146 status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
1147 pos,
1148 ..
1149 }
1150 | Outbound::Place { pos, .. } => Some(*pos),
1151 _ => None,
1152 })
1153 .all(|t| {
1154 [c.sent.pos, c.pose.pos].iter().all(|o| {
1155 heights.iter().any(|h| {
1156 let eyes = Vec3::new(o.x, o.y + *h, o.z);
1157 looks
1158 .iter()
1159 .any(|l| hands::ray_hits_cube(eyes, *l, t, ACTION_LOOK_REACH))
1160 })
1161 })
1162 })
1163}
1164
1165const ACTION_LOOK_REACH: f64 = 6.0;
1167
1168pub struct TickContext<'a> {
1173 core: &'a mut Core,
1174 world: &'a dyn WorldView,
1175 held: Option<hands::HeldItem>,
1176}
1177
1178impl std::fmt::Debug for TickContext<'_> {
1179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1180 f.debug_struct("TickContext")
1181 .field("tick", &self.core.tick)
1182 .field("pose", &self.core.pose)
1183 .finish_non_exhaustive()
1184 }
1185}
1186
1187impl TickContext<'_> {
1188 #[must_use]
1190 pub fn tick(&self) -> u64 {
1191 self.core.tick
1192 }
1193
1194 #[must_use]
1196 pub fn version(&self) -> GameVersion {
1197 self.core.opts.version
1198 }
1199
1200 #[must_use]
1202 pub fn pose(&self) -> &Pose {
1203 &self.core.pose
1204 }
1205
1206 #[must_use]
1208 pub fn sent(&self) -> &Pose {
1209 &self.core.sent
1210 }
1211
1212 #[must_use]
1214 pub fn eyes(&self, pose: &Pose) -> Vec3 {
1215 let v = self.core.opts.version;
1216 pose.eyes(if pose.sneaking {
1217 v.sneak_eye_height()
1218 } else {
1219 v.eye_height()
1220 })
1221 }
1222
1223 #[must_use]
1225 pub fn world(&self) -> &dyn WorldView {
1226 self.world
1227 }
1228
1229 #[must_use]
1231 pub fn events(&self) -> &TickEvents {
1232 &self.core.current
1233 }
1234
1235 #[must_use]
1237 pub fn entity_id(&self) -> i32 {
1238 self.core.entity_id
1239 }
1240
1241 #[must_use]
1243 pub fn health(&self) -> Health {
1244 self.core.health
1245 }
1246
1247 #[must_use]
1249 pub fn is_dead(&self) -> bool {
1250 self.core.dead
1251 }
1252
1253 #[must_use]
1255 pub fn game_mode(&self) -> GameMode {
1256 self.core.game_mode
1257 }
1258
1259 #[must_use]
1261 pub fn abilities(&self) -> Abilities {
1262 self.core.abilities
1263 }
1264
1265 #[must_use]
1267 pub fn can_fly(&self) -> bool {
1268 self.core.abilities.may_fly()
1269 }
1270
1271 #[must_use]
1273 pub fn held_slot(&self) -> u8 {
1274 self.core.held_slot
1275 }
1276
1277 #[must_use]
1279 pub fn open_window(&self) -> Option<i32> {
1280 (self.core.open_window != 0).then_some(self.core.open_window)
1281 }
1282
1283 #[must_use]
1285 pub fn dimension(&self) -> &str {
1286 &self.core.dimension
1287 }
1288
1289 #[must_use]
1291 pub fn controls(&self) -> Controls {
1292 self.core.controls
1293 }
1294
1295 #[must_use]
1297 pub fn aim(&self) -> (f32, f32) {
1298 self.core.rotation.target()
1299 }
1300
1301 pub fn chat(&mut self, text: impl Into<String>) {
1306 self.core.out.push(Outbound::Chat(text.into()));
1307 }
1308
1309 pub fn respawn(&mut self) -> bool {
1311 if self.core.dead {
1312 self.core.out.push(Outbound::Respawn);
1313 true
1314 } else {
1315 false
1316 }
1317 }
1318
1319 pub fn select_slot(&mut self, slot: u8) {
1322 if slot < 9 {
1323 if self.core.held_slot != slot {
1324 self.core.hands.stop_using();
1325 self.core.hands.ticks_since_swing = 0;
1326 }
1327 self.core.held_slot = slot;
1328 self.core.inv.select(slot);
1329 if self.core.sent_slot != slot {
1330 self.core.sent_slot = slot;
1331 self.core.out.push(Outbound::HeldSlot(i16::from(slot)));
1332 }
1333 }
1334 }
1335
1336 pub fn swing(&mut self) {
1338 self.core.out.push(Outbound::Swing);
1339 }
1340
1341 pub fn disconnect(&mut self, reason: impl Into<String>) {
1343 self.core.quit = Some(reason.into());
1344 }
1345
1346 pub fn set_aim(&mut self, yaw: f32, pitch: f32) {
1351 self.core.rotation.set_target(yaw, pitch);
1352 self.core.aimed = true;
1353 }
1354
1355 pub fn set_controls(&mut self, controls: Controls) {
1358 self.core.controls = controls;
1359 }
1360
1361 #[must_use]
1363 pub fn inventory(&self) -> &ghast_inventory::Inventory {
1364 &self.core.inv
1365 }
1366
1367 pub fn click(&mut self, click: ghast_inventory::Click) -> Result<ClickTicket, ClickRefused> {
1373 if self.core.turned || self.core.aimed {
1374 return Err(ClickRefused::Turning);
1375 }
1376 let o = self
1377 .core
1378 .inv
1379 .click(click)
1380 .map_err(ClickRefused::Inventory)?;
1381 let ticket = match &o {
1382 ghast_inventory::Outgoing::Click(p) => ClickTicket {
1383 window_id: i32::from(p.window_id),
1384 action: p.action,
1385 },
1386 _ => ClickTicket {
1387 window_id: -1,
1388 action: -1,
1389 },
1390 };
1391 self.core.out.push(Outbound::Inventory(o));
1392 Ok(ticket)
1393 }
1394
1395 pub fn open_inventory(&mut self) -> Result<(), ClickRefused> {
1398 if let Some(o) = self
1399 .core
1400 .inv
1401 .open_inventory()
1402 .map_err(ClickRefused::Inventory)?
1403 {
1404 self.core.out.push(Outbound::Inventory(o));
1405 }
1406 Ok(())
1407 }
1408
1409 pub fn close_window(&mut self) -> Result<(), ClickRefused> {
1411 let o = self.core.inv.close().map_err(ClickRefused::Inventory)?;
1412 self.core.out.push(Outbound::Inventory(o));
1413 self.core.open_window = 0;
1415 Ok(())
1416 }
1417
1418 pub fn set_buttons(&mut self, buttons: Buttons) {
1422 self.core.buttons = buttons;
1423 }
1424
1425 #[must_use]
1427 pub fn buttons(&self) -> Buttons {
1428 self.core.buttons
1429 }
1430
1431 #[must_use]
1434 pub fn target(&self) -> Option<BlockHit> {
1435 let s = &self.core.sent;
1436 let v = self.core.opts.version;
1437 let eye = if s.sneaking {
1438 v.sneak_eye_height()
1439 } else {
1440 v.eye_height()
1441 };
1442 let world = self.world;
1443 let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1444 hands::pick(
1445 &blocks,
1446 Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z),
1447 hands::look_vector(s.yaw, s.pitch),
1448 hands::REACH,
1449 )
1450 }
1451
1452 #[must_use]
1454 pub fn entities(&self) -> Option<&ghast_entity::Entities> {
1455 self.world.entities()
1456 }
1457
1458 #[must_use]
1461 pub fn target_entity(&self) -> Option<hands::EntityHit> {
1462 let s = &self.core.sent;
1463 let v = self.core.opts.version;
1464 let eye = if s.sneaking {
1465 v.sneak_eye_height()
1466 } else {
1467 v.eye_height()
1468 };
1469 let eyes = Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z);
1470 let look = hands::look_vector(s.yaw, s.pitch);
1471 let block = self.target().map(|t| t.distance);
1472 entity_pick(self.world, v, eyes, look, block)
1473 }
1474
1475 pub fn attack(&mut self, entity: i32) -> bool {
1479 if self.target_entity().is_none_or(|e| e.id != entity) {
1480 return false;
1481 }
1482 let world = self.world;
1483 let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1484 let c = &mut *self.core;
1485 let modern = c.opts.version != GameVersion::V1_8_9;
1486 let mut placed = false;
1487 let mut io = HandsIo {
1488 blocks: &blocks,
1489 target: None,
1490 held: self.held,
1491 held_stack: None,
1492 food: c.health.food,
1493 modern,
1494 off_held: None,
1495 off_stack: None,
1496 entity: None,
1497 factors: DigFactors::default(),
1498 sneaking: c.pose.sneaking,
1499 out: &mut c.out,
1500 broken: &mut c.broken_now,
1501 placed: &mut placed,
1502 };
1503 if !modern {
1504 io.out.push(Outbound::Swing);
1505 }
1506 c.hands.attack(entity, &mut io);
1507 if modern {
1508 c.out.push(Outbound::Swing);
1509 }
1510 true
1511 }
1512
1513 #[must_use]
1516 pub fn attack_strength(&self, attack_speed: f64) -> f32 {
1517 if self.core.opts.version == GameVersion::V1_8_9 {
1518 1.0
1519 } else {
1520 self.core.hands.attack_strength(attack_speed)
1521 }
1522 }
1523
1524 #[must_use]
1526 pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
1527 self.core.hands.mining()
1528 }
1529
1530 #[must_use]
1532 pub fn broken(&self) -> u64 {
1533 self.core.hands.broken
1534 }
1535
1536 #[must_use]
1538 pub fn using_item(&self) -> bool {
1539 self.core.hands.using_item()
1540 }
1541
1542 pub fn dig(&mut self, pos: ghast_protocol::BlockPos, face: crate::common::Face) -> bool {
1546 if !self
1547 .target()
1548 .is_some_and(|t| t.pos == pos && t.face == face)
1549 {
1550 return false;
1551 }
1552 let world = self.world;
1553 let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1554 let c = &mut *self.core;
1555 let mut placed = false;
1556 let mut io = HandsIo {
1557 blocks: &blocks,
1558 target: None,
1559 held: self.held,
1560 held_stack: c.inv.held().cloned(),
1561 food: c.health.food,
1562 modern: c.opts.version != GameVersion::V1_8_9,
1563 off_held: None,
1564 off_stack: None,
1565 entity: None,
1566 factors: DigFactors {
1567 on_ground: c.pose.on_ground,
1568 in_water: false,
1569 aqua_affinity: c.aqua_affinity,
1570 haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
1571 fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
1572 },
1573 sneaking: c.pose.sneaking,
1574 out: &mut c.out,
1575 broken: &mut c.broken_now,
1576 placed: &mut placed,
1577 };
1578 c.hands.click_block(pos, face, &mut io);
1579 c.out.push(Outbound::Swing);
1580 true
1581 }
1582
1583 pub fn place(
1587 &mut self,
1588 support: ghast_protocol::BlockPos,
1589 face: crate::common::Face,
1590 hit: Vec3,
1591 ) -> bool {
1592 let Some(t) = self.target().filter(|t| t.pos == support && t.face == face) else {
1593 return false;
1594 };
1595 let world = self.world;
1596 let Some(b) = world.block_query(support.x, support.y, support.z) else {
1597 return false;
1598 };
1599 let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1600 let c = &mut *self.core;
1601 let mut placed = false;
1602 let first = c.out.len();
1603 let mut io = HandsIo {
1604 blocks: &blocks,
1605 target: None,
1606 held: self.held,
1607 held_stack: c.inv.held().cloned(),
1608 food: c.health.food,
1609 modern: c.opts.version != GameVersion::V1_8_9,
1610 off_held: None,
1611 off_stack: None,
1612 entity: None,
1613 factors: DigFactors::default(),
1614 sneaking: c.pose.sneaking,
1615 out: &mut c.out,
1616 broken: &mut c.broken_now,
1617 placed: &mut placed,
1618 };
1619 c.hands
1620 .right_click_block(BlockHit { hit, ..t }, &b, &mut io);
1621 let _ = placed;
1622 predict_planting(c, world, first);
1623 c.out.push(Outbound::Swing);
1624 true
1625 }
1626
1627 #[must_use]
1629 pub fn last_inbound(&self) -> Option<Instant> {
1630 self.core.last_inbound
1631 }
1632
1633 #[must_use]
1639 pub fn planned_look(&self) -> (f32, f32) {
1640 let c = &*self.core;
1641 let now = (c.pose.yaw, c.pose.pitch);
1642 #[cfg(test)]
1643 if let Some(l) = c.forced_look {
1644 return l;
1645 }
1646 if !c.aimed {
1647 return now;
1648 }
1649 let mut r = c.rotation;
1650 let (yaw, pitch) = r.step(c.pose.yaw, c.pose.pitch);
1651 if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
1652 now
1653 } else {
1654 (yaw, pitch)
1655 }
1656 }
1657
1658 pub fn set_flying(&mut self, flying: bool) {
1662 self.core.want_flying = Some(flying);
1663 }
1664
1665 #[must_use]
1668 pub fn held_turns(&self) -> u64 {
1669 self.core.held_turns
1670 }
1671
1672 pub fn status(&mut self, text: &str) {
1674 if self.core.status != text {
1675 text.clone_into(&mut self.core.status);
1676 log::info!(
1677 "[{}] t{} status: {text}",
1678 self.core.opts.name,
1679 self.core.tick
1680 );
1681 }
1682 }
1683}
1684
1685#[cfg(test)]
1686mod tests {
1687 use super::*;
1688 use crate::common::Teleport;
1689 use crate::common::{ChatPosition, EntityAction, JoinGame};
1690 use ghast_protocol::RawPacket;
1691
1692 fn opts(version: GameVersion) -> CoreOptions {
1693 CoreOptions {
1694 name: "test".into(),
1695 version,
1696 settings: ClientSettings::default(),
1697 brand: Some("vanilla".into()),
1698 sensitivity: 0.5,
1699 silent_hold: Duration::from_millis(1500),
1700 hold_turn_on_action: true,
1701 inventory: match version {
1702 GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
1703 _ => ghast_inventory::Version::V1_16_5,
1704 },
1705 }
1706 }
1707
1708 fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
1710 let sim: Box<dyn Sim> = match version {
1711 GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
1712 _ => Box::new(crate::sim::Sim16::new()),
1713 };
1714 Engine::new(opts(version), sim)
1715 }
1716
1717 fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
1719 let raw = match e.core.opts.version {
1720 GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
1721 _ => crate::sim::test_chunks::v1_16_5(x, z),
1722 };
1723 e.sim.world_packet(&raw).unwrap();
1724 }
1725
1726 fn join(e: &mut Engine<Box<dyn Sim>>) {
1727 e.handle(Inbound::JoinGame(JoinGame {
1728 entity_id: 7,
1729 game_mode: GameMode::Survival,
1730 dimension: "0".into(),
1731 hardcore: false,
1732 dimension_nbt: None,
1733 respawn_screen: true,
1734 }));
1735 load(e, 0, 0);
1736 e.handle(Inbound::Teleport(Teleport {
1737 x: 8.5,
1738 y: 64.0,
1739 z: 8.5,
1740 yaw: 90.0,
1741 pitch: 0.0,
1742 flags: 0,
1743 teleport_id: None,
1744 }));
1745 e.outbound().clear();
1746 }
1747
1748 fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
1750 let v = out
1751 .iter()
1752 .map(|o| match o {
1753 Outbound::Move(m) => m.trace_id(),
1754 Outbound::Chat(_) => "chat",
1755 Outbound::HeldSlot(_) => "held_slot",
1756 Outbound::Swing => "swing",
1757 Outbound::EntityAction { .. } => "entity_action",
1758 Outbound::KeepAlive(_) => "keep_alive",
1759 Outbound::Transaction { .. } => "transaction",
1760 Outbound::TeleportConfirm(_) => "teleport_confirm",
1761 Outbound::Respawn => "respawn",
1762 Outbound::Settings(_) => "settings",
1763 Outbound::Brand(_) => "brand",
1764 Outbound::Abilities { .. } => "abilities",
1765 Outbound::Dig { .. } => "block_dig",
1766 Outbound::Place { .. } | Outbound::UseItem { .. } => "block_place",
1767 Outbound::SwingOffHand => "swing_off",
1768 Outbound::UseEntity { .. } => "use_entity",
1769 Outbound::Inventory(_) => "inventory",
1770 })
1771 .collect();
1772 out.clear();
1773 v
1774 }
1775
1776 struct Script<F: FnMut(&mut TickContext<'_>)>(F);
1777 impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
1778 fn tick(&mut self, ctx: &mut TickContext<'_>) {
1779 (self.0)(ctx);
1780 }
1781 }
1782
1783 #[test]
1784 fn join_sends_settings_then_brand() {
1785 let mut e = engine(GameVersion::V1_8_9);
1786 e.handle(Inbound::JoinGame(JoinGame {
1787 entity_id: 1,
1788 game_mode: GameMode::Creative,
1789 dimension: "0".into(),
1790 hardcore: false,
1791 dimension_nbt: None,
1792 respawn_screen: true,
1793 }));
1794 assert_eq!(names(e.outbound()), ["settings", "brand"]);
1795 }
1796
1797 #[test]
1798 fn nothing_before_the_first_teleport() {
1799 let mut e = engine(GameVersion::V1_8_9);
1800 let mut b = Idle;
1801 let t0 = Instant::now();
1802 load(&mut e, 0, 0);
1803 e.outbound().clear();
1804 for i in 0..5 {
1805 e.tick(&mut b, t0 + Duration::from_millis(50 * i));
1806 }
1807 assert!(e.outbound().is_empty());
1808 }
1809
1810 #[test]
1811 fn teleport_reply_per_version() {
1812 let mut e = engine(GameVersion::V1_16_5);
1813 e.handle(Inbound::Teleport(Teleport {
1814 x: 1.0,
1815 y: 2.0,
1816 z: 3.0,
1817 yaw: 450.0,
1818 pitch: 100.0,
1819 flags: 0,
1820 teleport_id: Some(5),
1821 }));
1822 let out = std::mem::take(e.outbound());
1823 assert_eq!(out[0], Outbound::TeleportConfirm(5));
1824 match out[1] {
1825 Outbound::Move(MovePacket::PositionLook {
1826 yaw,
1827 pitch,
1828 on_ground,
1829 ..
1830 }) => {
1831 assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
1832 }
1833 ref o => panic!("unexpected {o:?}"),
1834 }
1835 let mut e = engine(GameVersion::V1_8_9);
1836 e.handle(Inbound::Teleport(Teleport {
1837 x: 1.0,
1838 y: 2.0,
1839 z: 3.0,
1840 yaw: 450.0,
1841 pitch: 100.0,
1842 flags: 0,
1843 teleport_id: None,
1844 }));
1845 let out = std::mem::take(e.outbound());
1846 assert_eq!(out.len(), 1);
1847 assert!(matches!(
1849 out[0],
1850 Outbound::Move(MovePacket::PositionLook {
1851 yaw: 90.0,
1852 pitch: 100.0,
1853 ..
1854 })
1855 ));
1856 }
1857
1858 #[test]
1859 fn actions_precede_the_single_movement_packet() {
1860 let mut e = engine(GameVersion::V1_8_9);
1861 join(&mut e);
1862 let t0 = Instant::now();
1863 e.note_inbound(t0);
1864 let mut b = Script(|ctx: &mut TickContext<'_>| {
1865 if ctx.tick() == 2 {
1866 ctx.select_slot(3);
1867 ctx.chat("hello");
1868 ctx.swing();
1869 ctx.set_controls(Controls {
1870 sneak: true,
1871 ..Controls::default()
1872 });
1873 }
1874 });
1875 e.tick(&mut b, t0);
1876 assert_eq!(names(e.outbound()), ["C06"]);
1877 e.tick(&mut b, t0);
1878 assert_eq!(
1879 names(e.outbound()),
1880 ["held_slot", "chat", "swing", "entity_action", "C03"]
1881 );
1882 for _ in 0..100 {
1883 e.tick(&mut b, t0);
1884 let n = names(e.outbound());
1885 assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
1886 }
1887 }
1888
1889 #[test]
1890 fn standing_bot_packets() {
1891 let mut e = engine(GameVersion::V1_8_9);
1892 join(&mut e);
1893 let mut b = Idle;
1894 let t0 = Instant::now();
1895 e.note_inbound(t0);
1896 e.tick(&mut b, t0);
1898 let out = std::mem::take(e.outbound());
1899 assert!(matches!(
1900 out[..],
1901 [Outbound::Move(MovePacket::PositionLook {
1902 on_ground: false,
1903 ..
1904 })]
1905 ));
1906 let mut kinds = Vec::new();
1908 for _ in 0..42 {
1909 e.tick(&mut b, t0);
1910 kinds.extend(names(e.outbound()));
1911 }
1912 assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
1913 assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
1914 assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
1915 assert!(e.core.sent.on_ground);
1916 }
1917
1918 #[test]
1919 fn silent_server_freezes_behaviour() {
1920 let mut e = engine(GameVersion::V1_8_9);
1921 join(&mut e);
1922 let t0 = Instant::now();
1923 e.note_inbound(t0);
1924 let mut ticks = 0;
1925 let mut b = Script(|ctx: &mut TickContext<'_>| {
1926 ticks += 1;
1927 ctx.set_controls(Controls {
1928 sneak: true,
1929 ..Controls::default()
1930 });
1931 });
1932 e.tick(&mut b, t0 + Duration::from_millis(100));
1933 e.tick(&mut b, t0 + Duration::from_millis(1600));
1934 let n = names(e.outbound());
1936 assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
1937 e.note_inbound(t0 + Duration::from_millis(1700));
1938 e.tick(&mut b, t0 + Duration::from_millis(1700));
1939 let _ = b;
1940 assert_eq!(ticks, 2);
1941 }
1942
1943 #[test]
1944 fn keepalive_answered_transactions_left_to_the_inventory() {
1945 let mut e = engine(GameVersion::V1_8_9);
1946 join(&mut e);
1947 e.handle(Inbound::KeepAlive(42));
1948 e.handle(Inbound::Transaction {
1951 window_id: 0,
1952 action: -5,
1953 accepted: false,
1954 });
1955 assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
1956 }
1957
1958 #[test]
1959 fn panicking_behaviour_does_not_stop_the_tick() {
1960 let mut e = engine(GameVersion::V1_8_9);
1961 join(&mut e);
1962 let t0 = Instant::now();
1963 let mut b = Script(|ctx: &mut TickContext<'_>| {
1964 if ctx.tick() == 2 {
1965 panic!("boom");
1966 }
1967 });
1968 let hook = std::panic::take_hook();
1969 std::panic::set_hook(Box::new(|_| {}));
1970 for _ in 0..5 {
1971 e.tick(&mut b, t0);
1972 }
1973 std::panic::set_hook(hook);
1974 assert!(e.state.failed);
1975 assert_eq!(names(e.outbound()).len(), 5);
1976 }
1977
1978 #[test]
1979 fn chat_events_reach_the_behaviour_once() {
1980 let mut e = engine(GameVersion::V1_16_5);
1981 join(&mut e);
1982 e.handle(Inbound::Chat(ChatMessage {
1983 json: r#"{"text":"hi"}"#.into(),
1984 position: ChatPosition::System,
1985 sender: None,
1986 }));
1987 let mut seen = Vec::new();
1988 let mut b = Script(|ctx: &mut TickContext<'_>| {
1989 seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
1990 });
1991 let t0 = Instant::now();
1992 e.tick(&mut b, t0);
1993 e.tick(&mut b, t0);
1994 let _ = b;
1995 assert_eq!(seen, ["hi"]);
1996 }
1997
1998 #[test]
1999 fn immediate_respawn_1_16() {
2000 let mut e = engine(GameVersion::V1_16_5);
2001 join(&mut e);
2002 e.handle(Inbound::GameState {
2003 reason: 11,
2004 value: 1.0,
2005 });
2006 e.handle(Inbound::Died { entity_id: 7 });
2007 assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
2008 }
2009
2010 #[test]
2013 fn dig_with_the_left_button() {
2014 let mut e = engine(GameVersion::V1_8_9);
2015 join(&mut e);
2016 let t0 = Instant::now();
2017 e.note_inbound(t0);
2018 let mut b = Script(|ctx: &mut TickContext<'_>| {
2019 ctx.set_aim(90.0, 89.5);
2020 let down = ctx.target().is_some_and(|t| {
2021 t.pos == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
2022 });
2023 ctx.set_buttons(Buttons {
2024 left: down,
2025 right: false,
2026 });
2027 });
2028 let mut ticks = Vec::new();
2029 for _ in 0..200 {
2030 e.tick(&mut b, t0);
2031 let n = names(e.outbound());
2032 assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
2033 assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
2034 ticks.push(n);
2035 }
2036 let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
2037 assert_eq!(
2038 flat.iter().filter(|x| **x == "block_dig").count(),
2039 2,
2040 "start + finish"
2041 );
2042 assert!(e.core.hands.broken == 1);
2043 let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
2045 let finish = ticks
2046 .iter()
2047 .rposition(|t| t.contains(&"block_dig"))
2048 .unwrap();
2049 assert_eq!(finish - start, 150);
2050 assert!(e.sim.block_query(8, 63, 8).unwrap().air);
2051 assert!(
2052 e.core.pose.pos.y < 64.0,
2053 "falls into the hole: {:?}",
2054 e.core.pose.pos
2055 );
2056 }
2057
2058 #[test]
2061 fn place_needs_the_sent_look() {
2062 let mut e = engine(GameVersion::V1_8_9);
2063 join(&mut e);
2064 let t0 = Instant::now();
2065 e.note_inbound(t0);
2066 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2067 let mut results = Vec::new();
2068 let mut b = Script(|ctx: &mut TickContext<'_>| {
2069 ctx.set_aim(90.0, 89.5);
2070 results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
2071 });
2072 e.core
2074 .inv
2075 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2076 let mut placed_tick = None;
2077 for i in 0..20 {
2078 e.tick(&mut b, t0);
2079 let n = names(e.outbound());
2080 if n.contains(&"block_place") {
2081 assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
2082 placed_tick.get_or_insert(i);
2083 }
2084 }
2085 let _ = b;
2086 let first = results.iter().position(|r| *r).unwrap();
2087 assert!(first > 3, "refused while still turning");
2088 assert_eq!(placed_tick, Some(first));
2089 assert_eq!(e.core.inv.held().map(|s| s.id), Some(1));
2090 }
2091
2092 #[test]
2093 fn sneak_action_order() {
2094 let mut e = engine(GameVersion::V1_8_9);
2095 join(&mut e);
2096 let mut b = Script(|ctx: &mut TickContext<'_>| {
2097 ctx.set_controls(Controls {
2098 sneak: true,
2099 ..Controls::default()
2100 });
2101 });
2102 e.tick(&mut b, Instant::now());
2103 let out = std::mem::take(e.outbound());
2104 assert_eq!(
2105 out[0],
2106 Outbound::EntityAction {
2107 entity_id: 7,
2108 action: EntityAction::StartSneaking
2109 }
2110 );
2111 assert!(matches!(out[1], Outbound::Move(_)));
2112 }
2113
2114 #[test]
2116 fn block_updates_per_version() {
2117 use ghast_protocol::BlockPos;
2118 for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2119 let mut e = engine(v);
2120 join(&mut e);
2121 e.sim.collect_block_updates(true);
2122 let t0 = Instant::now();
2123 e.note_inbound(t0);
2124 let raws = match v {
2125 GameVersion::V1_8_9 => {
2126 use ghast_protocol::v1_8::play::clientbound as cb;
2127 vec![
2128 RawPacket::from_packet(&cb::BlockChange {
2129 location: BlockPos::new(3, 63, 4),
2130 r#type: 59 << 4 | 7,
2131 })
2132 .unwrap(),
2133 RawPacket::from_packet(&cb::MultiBlockChange {
2134 chunk_x: 0,
2135 chunk_z: 0,
2136 records: vec![cb::MultiBlockChangeRecords {
2137 horizontal_pos: 5 << 4 | 6,
2138 y: 62,
2139 block_id: 60 << 4 | 7,
2140 }],
2141 })
2142 .unwrap(),
2143 ]
2144 }
2145 _ => {
2146 use ghast_protocol::v1_16_5::play::clientbound as cb;
2147 let local = (5 << 8 | 6 << 4 | 14) as i64;
2149 vec![
2150 RawPacket::from_packet(&cb::BlockChange {
2151 location: BlockPos::new(3, 63, 4),
2152 r#type: 1,
2153 })
2154 .unwrap(),
2155 RawPacket::from_packet(&cb::MultiBlockChange {
2156 chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
2157 x: 0,
2158 z: 0,
2159 y: 0xF_FFFF,
2160 },
2161 not_trust_edges: false,
2162 records: vec![9 << 12 | local],
2163 })
2164 .unwrap(),
2165 ]
2166 }
2167 };
2168 for raw in &raws {
2169 e.sim.world_packet(raw).unwrap();
2170 }
2171 let mut seen = Vec::new();
2172 let mut b = Script(|ctx: &mut TickContext<'_>| {
2173 seen.push(ctx.events().block_updates.clone());
2174 });
2175 e.tick(&mut b, t0);
2176 e.tick(&mut b, t0);
2177 let _ = b;
2178 let want = match v {
2179 GameVersion::V1_8_9 => vec![
2180 (BlockPos::new(3, 63, 4), 59 << 4 | 7),
2181 (BlockPos::new(5, 62, 6), 60 << 4 | 7),
2182 ],
2183 _ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
2184 };
2185 assert_eq!(seen, [want, Vec::new()], "{v:?}");
2186
2187 e.sim.collect_block_updates(false);
2189 e.sim.world_packet(&raws[0]).unwrap();
2190 let mut n = usize::MAX;
2191 let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
2192 e.tick(&mut b, t0);
2193 let _ = b;
2194 assert_eq!(n, 0);
2195 }
2196 }
2197
2198 #[test]
2200 fn set_flying_needs_may_fly() {
2201 for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2202 let mut e = engine(v);
2203 join(&mut e);
2204 let t0 = Instant::now();
2205 e.note_inbound(t0);
2206 e.handle(Inbound::Teleport(Teleport {
2208 x: 8.5,
2209 y: 70.0,
2210 z: 8.5,
2211 yaw: 90.0,
2212 pitch: 0.0,
2213 flags: 0,
2214 teleport_id: Some(2),
2215 }));
2216 e.outbound().clear();
2217 let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
2218 e.tick(&mut b, t0);
2219 assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
2220 assert!(!e.core.pose.flying);
2221 e.handle(Inbound::Abilities(Abilities {
2222 flags: 4,
2223 ..Abilities::default()
2224 }));
2225 e.tick(&mut b, t0);
2226 let out = std::mem::take(e.outbound());
2227 assert_eq!(
2228 out[0],
2229 Outbound::Abilities {
2230 flags: 6,
2231 flying_speed: 0.05,
2232 walking_speed: 0.1
2233 },
2234 "{v:?}"
2235 );
2236 assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
2237 assert!(e.core.pose.flying && e.core.sent.flying);
2238 e.tick(&mut b, t0);
2240 assert!(!names(e.outbound()).contains(&"abilities"));
2241 let _ = b;
2242 }
2243 }
2244
2245 #[test]
2247 fn finished_behaviour_is_not_ticked() {
2248 struct Three(std::rc::Rc<std::cell::Cell<u32>>);
2249 impl Behavior for Three {
2250 fn tick(&mut self, _ctx: &mut TickContext<'_>) {
2251 self.0.set(self.0.get() + 1);
2252 }
2253 fn running(&self) -> bool {
2254 self.0.get() < 3
2255 }
2256 }
2257 let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
2258 let mut e = engine(GameVersion::V1_8_9);
2259 join(&mut e);
2260 let t0 = Instant::now();
2261 e.note_inbound(t0);
2262 let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
2263 for _ in 0..10 {
2264 e.tick(&mut b, t0);
2265 let out = std::mem::take(e.outbound());
2267 assert!(
2268 out.iter().any(|o| matches!(o, Outbound::Move(_))),
2269 "{out:?}"
2270 );
2271 }
2272 assert_eq!(
2273 ticks.get(),
2274 3,
2275 "not ticked after running() == false (through the Box)"
2276 );
2277 }
2278
2279 #[test]
2281 fn turn_held_on_a_place_tick() {
2282 let mut e = engine(GameVersion::V1_8_9);
2283 join(&mut e);
2284 let t0 = Instant::now();
2285 e.note_inbound(t0);
2286 e.core
2287 .inv
2288 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2289 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2290 let mut tick = 0;
2291 let mut placed_at = None;
2292 let mut pitches = Vec::new();
2293 let mut b = Script(|ctx: &mut TickContext<'_>| {
2294 tick += 1;
2295 if placed_at.is_none() {
2296 ctx.set_aim(90.0, 89.5);
2297 if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
2298 placed_at = Some(tick);
2299 ctx.set_aim(90.0, -60.0);
2301 }
2302 } else {
2303 ctx.set_aim(90.0, -60.0);
2304 }
2305 pitches.push(ctx.pose().pitch);
2306 });
2307 for _ in 0..30 {
2308 e.tick(&mut b, t0);
2309 e.outbound().clear();
2310 }
2311 let _ = b;
2312 let p = placed_at.expect("placed");
2313 assert_eq!(e.core.held_turns, 1);
2314 assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
2316 assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
2317 }
2318
2319 #[test]
2321 fn click_ticket_matches_the_confirm() {
2322 let mut e = engine(GameVersion::V1_8_9);
2323 join(&mut e);
2324 let t0 = Instant::now();
2325 e.note_inbound(t0);
2326 e.core
2327 .inv
2328 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2329 let mut ticket = None;
2330 let mut n = 0;
2331 let mut b = Script(|ctx: &mut TickContext<'_>| {
2332 n += 1;
2333 if n == 1 {
2334 ctx.open_inventory().unwrap();
2335 } else if ticket.is_none() {
2336 ticket = ctx
2337 .click(ghast_inventory::Click::Pickup {
2338 slot: 36,
2339 right: false,
2340 })
2341 .ok();
2342 }
2343 });
2344 for _ in 0..3 {
2345 e.tick(&mut b, t0);
2346 }
2347 let _ = b;
2348 let t = ticket.expect("click sent");
2349 assert_eq!(t.window_id, 0);
2350 assert!(t.matches(&ghast_inventory::ClickResult {
2351 window_id: 0,
2352 action: t.action,
2353 outcome: ghast_inventory::ClickOutcome::Accepted,
2354 }));
2355 }
2356
2357 #[test]
2360 fn planting_uses_the_seed_at_once() {
2361 use ghast_protocol::v1_8::play::clientbound as cb;
2362 for (soil, item, used) in [
2363 (60 << 4 | 7, 295, true),
2364 (1 << 4, 295, false),
2365 (60 << 4, 1, false),
2366 ] {
2367 let mut e = engine(GameVersion::V1_8_9);
2368 join(&mut e);
2369 let t0 = Instant::now();
2370 e.note_inbound(t0);
2371 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2372 let raw = RawPacket::from_packet(&cb::BlockChange {
2373 location: floor,
2374 r#type: soil,
2375 })
2376 .unwrap();
2377 e.sim.world_packet(&raw).unwrap();
2378 e.core
2379 .inv
2380 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
2381 let mut done = false;
2382 let mut b = Script(|ctx: &mut TickContext<'_>| {
2383 ctx.set_aim(90.0, 89.5);
2384 if !done {
2385 done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
2386 }
2387 });
2388 let mut sent = None;
2389 for _ in 0..20 {
2390 e.tick(&mut b, t0);
2391 for o in e.outbound().drain(..) {
2392 if let Outbound::Place { held, .. } = o {
2393 sent = held.map(|h| h.count);
2394 }
2395 }
2396 }
2397 let _ = b;
2398 assert_eq!(sent, Some(64), "the packet carries the stack before use");
2399 let left = e.core.inv.held().map(|s| s.count);
2400 assert_eq!(
2401 left,
2402 Some(if used { 63 } else { 64 }),
2403 "soil {soil} item {item}"
2404 );
2405 }
2406 }
2407
2408 #[test]
2411 fn planned_look_is_the_next_look() {
2412 let mut e = engine(GameVersion::V1_8_9);
2413 join(&mut e);
2414 let t0 = Instant::now();
2415 e.note_inbound(t0);
2416 e.core
2417 .inv
2418 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2419 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2420 let mut n = 0;
2421 let mut placed = false;
2422 let mut plans: Vec<(f32, f32)> = Vec::new();
2423 let mut b = Script(|ctx: &mut TickContext<'_>| {
2424 n += 1;
2425 if n % 5 == 0 {
2426 } else if !placed {
2428 ctx.set_aim(90.0, 89.5);
2429 if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
2430 placed = true;
2431 ctx.set_aim(90.0, -60.0);
2432 }
2433 } else {
2434 ctx.set_aim(150.0, -60.0);
2435 }
2436 let p = ctx.planned_look();
2438 assert_eq!(p, ctx.planned_look());
2439 plans.push(p);
2440 });
2441 let mut looks = Vec::new();
2442 for _ in 0..40 {
2443 e.tick(&mut b, t0);
2444 e.outbound().clear();
2445 looks.push((e.core.pose.yaw, e.core.pose.pitch));
2446 }
2447 let _ = b;
2448 assert!(placed);
2449 assert_eq!(e.core.test_held_turns(), 1);
2450 assert_eq!(plans, looks);
2451 }
2452
2453 #[test]
2456 fn teleport_event_has_the_sent_pose_before() {
2457 for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2458 let mut e = engine(v);
2459 join(&mut e);
2460 let t0 = Instant::now();
2461 e.note_inbound(t0);
2462 let mut seen = Vec::new();
2463 let mut b = Script(|ctx: &mut TickContext<'_>| {
2464 seen.extend(ctx.events().teleports.iter().copied());
2465 });
2466 e.tick(&mut b, t0);
2467 let sent = e.core.sent;
2468 let tp = Teleport {
2470 x: 10.5,
2471 y: 64.0,
2472 z: 8.5,
2473 yaw: 30.0,
2474 pitch: 0.0,
2475 flags: crate::common::teleport_flags::YAW,
2476 teleport_id: Some(9),
2477 };
2478 e.handle(Inbound::Teleport(tp));
2479 e.tick(&mut b, t0);
2480 e.tick(&mut b, t0);
2481 let _ = b;
2482 assert_eq!(seen.len(), 2, "{v:?}");
2484 let ev = seen[1];
2485 assert_eq!(ev.teleport, tp);
2486 assert_eq!(ev.sent_before, sent);
2487 assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
2488 assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
2489 }
2490 }
2491
2492 #[test]
2496 fn closed_window_frees_the_buttons() {
2497 for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2498 let mut e = engine(v);
2499 join(&mut e);
2500 let t0 = Instant::now();
2501 e.note_inbound(t0);
2502 if v == GameVersion::V1_16_5 {
2503 use ghast_protocol::v1_16_5::play::clientbound as cb;
2505 let raw = RawPacket::from_packet(&cb::BlockChange {
2506 location: ghast_protocol::BlockPos::new(8, 63, 8),
2507 r#type: 1,
2508 })
2509 .unwrap();
2510 e.sim.world_packet(&raw).unwrap();
2511 }
2512 e.core.inv.on_open_window(
2513 5,
2514 Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
2515 "Vault".into(),
2516 );
2517 e.handle(Inbound::OpenWindow(5));
2518 e.core
2521 .inv
2522 .on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
2523 let mut n = 0;
2524 let mut closed_at = None;
2525 let mut b = Script(|ctx: &mut TickContext<'_>| {
2526 n += 1;
2527 ctx.set_aim(90.0, 89.5);
2528 ctx.set_buttons(Buttons {
2529 left: true,
2530 right: false,
2531 });
2532 if n == 15 {
2533 assert!(ctx.inventory().cursor().is_some());
2534 ctx.close_window().unwrap();
2535 assert_eq!(ctx.open_window(), None);
2536 let inv = ctx.inventory();
2537 assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
2538 closed_at = Some(n);
2539 }
2540 });
2541 let mut first_dig = None;
2542 for i in 1..=30 {
2543 e.tick(&mut b, t0);
2544 let out = std::mem::take(e.outbound());
2545 if first_dig.is_none()
2546 && out.iter().any(|o| {
2547 matches!(
2548 o,
2549 Outbound::Dig {
2550 status: crate::common::DigStatus::Start,
2551 ..
2552 }
2553 )
2554 })
2555 {
2556 first_dig = Some(i);
2557 }
2558 }
2559 let _ = b;
2560 assert_eq!(closed_at, Some(15));
2561 let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
2562 assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
2564 }
2565 }
2566}