Skip to main content

ghast_viewer/
watch.rs

1//! The behaviour wrapper that feeds a viewer from the bot's tick.
2
3use std::borrow::Cow;
4
5use ghast_client::{
6    Behavior, GameVersion, Health, Interests, Pose, RawInbound, TickContext, TickView,
7};
8use ghast_entity::Entities;
9use ghast_inventory::Stack;
10use ghast_protocol::BlockPos;
11
12use crate::Viewer;
13use crate::feed::{BotView, RAW_ALWAYS_1_8, RAW_WATCHED_1_8};
14
15/// A behaviour that also feeds a [`Viewer`]. It only reads the tick context: it never writes to
16/// the connection and does not change the bot's timing. While nobody watches it adds a handful
17/// of rare packets to the filter (weather, experience, block entities) and does nothing else.
18///
19/// Side effects on the wrapped behaviour: while a page is open, `TickEvents::block_updates` and
20/// `TickEvents::raw` may hold entries it did not ask for (filter `raw` by packet id), and with
21/// [`crate::ViewerConfig::entities`] on, entity tracking (and the tab list) is enabled for the
22/// session. A wrapped behaviour that finishes stops being ticked, but the viewer keeps showing
23/// the bot standing there.
24///
25/// The viewer reads the bot in [`Behavior::after_tick`] (the pose after the movement step). For
26/// light, biomes and block entities (sign text, skulls …) the client must keep them: build it
27/// with `Client::world_config(ghast_viewer::world_config())`.
28pub struct Watched<B> {
29    inner: B,
30    viewer: Viewer,
31    inner_done: bool,
32}
33
34impl<B> Watched<B> {
35    pub(crate) fn new(inner: B, viewer: Viewer) -> Self {
36        Watched {
37            inner,
38            viewer,
39            inner_done: false,
40        }
41    }
42
43    /// The wrapped behaviour.
44    pub fn inner(&self) -> &B {
45        &self.inner
46    }
47
48    /// The wrapped behaviour.
49    pub fn inner_mut(&mut self) -> &mut B {
50        &mut self.inner
51    }
52
53    /// Unwraps.
54    pub fn into_inner(self) -> B {
55        self.inner
56    }
57}
58
59impl<B: Behavior> Behavior for Watched<B> {
60    fn name(&self) -> &str {
61        self.inner.name()
62    }
63
64    fn interests(&self) -> Interests {
65        let mut i = if self.inner_done {
66            Interests::NONE
67        } else {
68            self.inner.interests()
69        };
70        let watched = self.viewer.hub().active();
71        match self.viewer.config().entities {
72            crate::EntityTracking::Always => {
73                i |= Interests::ENTITIES | Interests::PLAYER_LIST | Interests::PLAYER_SKINS;
74            }
75            crate::EntityTracking::WhileWatched if watched => {
76                i |= Interests::ENTITIES | Interests::PLAYER_LIST | Interests::PLAYER_SKINS;
77            }
78            _ => {}
79        }
80        if self.viewer.hub().active() {
81            i |= Interests::BLOCK_UPDATES;
82        }
83        i
84    }
85
86    fn raw_packets(&self, version: GameVersion) -> Cow<'static, [i32]> {
87        let inner = if self.inner_done {
88            Cow::Borrowed(&[][..])
89        } else {
90            self.inner.raw_packets(version)
91        };
92        let active = self.viewer.hub().active();
93        let ours = if version == GameVersion::V1_8_9 {
94            if active {
95                RAW_WATCHED_1_8
96            } else {
97                RAW_ALWAYS_1_8
98            }
99        } else {
100            // modern sessions: only the entity events, only while a page watches
101            match crate::modern_map(version) {
102                Some(m) if active => m.fx_packets,
103                _ => return inner,
104            }
105        };
106        if inner.is_empty() {
107            return Cow::Borrowed(ours);
108        }
109        let mut all: Vec<i32> = inner.into_owned();
110        all.extend_from_slice(ours);
111        all.sort_unstable();
112        all.dedup();
113        Cow::Owned(all)
114    }
115
116    fn start(&mut self, ctx: &mut TickContext<'_>) {
117        self.inner.start(ctx);
118        self.inner_done = !self.inner.running();
119    }
120
121    fn tick(&mut self, ctx: &mut TickContext<'_>) {
122        if !self.inner_done {
123            self.inner.tick(ctx);
124            self.inner_done = !self.inner.running();
125        }
126    }
127
128    fn after_tick(&mut self, view: &TickView<'_>) {
129        // the engine calls this also once the inner behaviour has finished, like for any behaviour
130        self.inner.after_tick(view);
131        self.viewer.hub().tick(&View(view));
132    }
133
134    fn running(&self) -> bool {
135        // a finished behaviour is not ticked any more, but the viewer keeps its packets
136        true
137    }
138
139    fn stop(&mut self, reason: &str) {
140        self.inner.stop(reason);
141        self.viewer
142            .hub()
143            .session_ended(&format!("The bot left the game ({reason})"));
144    }
145}
146
147/// [`BotView`] over ghast's after-tick view (the pose after this tick's movement step).
148struct View<'a, 'b>(&'a TickView<'b>);
149
150impl BotView for View<'_, '_> {
151    fn tick(&self) -> u64 {
152        self.0.tick()
153    }
154    fn version(&self) -> GameVersion {
155        self.0.version()
156    }
157    fn pose(&self) -> Pose {
158        *self.0.pose()
159    }
160    fn entity_id(&self) -> i32 {
161        self.0.entity_id()
162    }
163    fn health(&self) -> Health {
164        self.0.health()
165    }
166    fn held_slot(&self) -> u8 {
167        self.0.held_slot()
168    }
169    fn hotbar(&self, k: usize) -> Option<&Stack> {
170        self.0.inventory().hotbar(k)
171    }
172    fn armor(&self, a: usize) -> Option<&Stack> {
173        self.0.inventory().armor(a)
174    }
175    fn mining(&self) -> Option<(BlockPos, f32)> {
176        self.0.mining()
177    }
178    fn broken(&self) -> u64 {
179        self.0.broken()
180    }
181    fn swings(&self) -> Option<u64> {
182        Some(self.0.swings())
183    }
184    fn using_item(&self) -> bool {
185        self.0.using_item()
186    }
187    fn dimension(&self) -> &str {
188        self.0.dimension()
189    }
190    fn is_column_loaded(&self, cx: i32, cz: i32) -> bool {
191        self.0.world().is_column_loaded(cx, cz)
192    }
193    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
194        self.0.world().raw_block(x, y, z)
195    }
196    fn column(&self, cx: i32, cz: i32) -> Option<&ghast_world::Column> {
197        self.0.world().column(cx, cz)
198    }
199    fn entities(&self) -> Option<&Entities> {
200        self.0.entities()
201    }
202    fn block_updates(&self) -> &[(BlockPos, u32)] {
203        &self.0.events().block_updates
204    }
205    fn raw(&self) -> &[RawInbound] {
206        &self.0.events().raw
207    }
208    fn joined(&self) -> bool {
209        self.0.events().joined
210    }
211    fn respawned(&self) -> bool {
212        self.0.events().respawned
213    }
214    fn build_height(&self) -> Option<(i32, i32)> {
215        self.0.world().build_height()
216    }
217    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
218    fn enchantment_name(&self, id: i32) -> Option<&str> {
219        self.0.inventory().enchantment_name_modern(id)
220    }
221}