Skip to main content

ghast_viewer/
lib.rs

1//! A bot screen for bots built on [ghast](https://crates.io/crates/ghast): a live 3D view of
2//! the bot's world in the browser, plus recordings and replays.
3//!
4//! - [`Viewer`]: one per bot. [`Viewer::watch`] wraps the bot's behaviour so each client tick
5//!   feeds the viewer (read-only: it never writes to the connection), [`Viewer::start`] serves
6//!   the page over HTTP + WebSocket (127.0.0.1 by default).
7//! - Zero cost while nobody watches: no frames are built and no columns copied; the server
8//!   stops itself after [`ViewerConfig::idle`] without a page.
9//! - Textures and models are taken at run time from the vanilla client jar (downloaded from
10//!   Mojang's servers into a local cache, or [`ViewerConfig::client_jar`]); nothing of the game
11//!   is shipped with this crate.
12//! - [`FeedRecorder`] writes what a page would receive to disk; [`DashCam`] keeps the last
13//!   minutes in memory and saves them on [`DashCam::clip`]; recordings play back on the same page
14//!   (`/?replay=<name>`).
15//!
16//! ```no_run
17//! use ghast_client::{Account, Client, GameVersion, Idle};
18//! use ghast_viewer::{Viewer, ViewerConfig};
19//!
20//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
21//! let viewer = Viewer::new(ViewerConfig::new("Steve").port(8080));
22//! let addr = viewer.start().await?;
23//! println!("open http://{addr}/");
24//! let client = Client::new("127.0.0.1:25565".parse()?, GameVersion::V1_8_9, Account::offline("Steve")?)
25//!     .world_config(ghast_viewer::world_config());
26//! let mut behaviour = viewer.watch(Idle);
27//! client.run(&mut behaviour).await?;
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! Wire protocol: `docs/protocol.md`. 1.8.9, 26.1, 26.2 and 26.3 (features `v26_1`, `v26_2`,
33//! `v26_3`, mapped onto the 1.8.9 assets, see `v26_1`) sessions are drawn.
34
35#![forbid(unsafe_code)]
36#![warn(rust_2018_idioms)]
37
38pub mod assets;
39pub mod blocks18;
40pub mod dashcam;
41pub mod entities;
42pub mod feed;
43pub mod hub;
44#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
45mod legacy_table;
46pub mod protocol;
47pub mod record;
48pub mod replay;
49mod server;
50pub mod skins;
51pub mod stream;
52pub mod tiles;
53#[cfg(feature = "v26_1")]
54pub mod v26_1;
55#[cfg(feature = "v26_2")]
56pub mod v26_2;
57#[cfg(feature = "v26_3")]
58pub mod v26_3;
59mod watch;
60mod window;
61
62/// A modern version's mapping onto the page's 1.8 assets and its entity accessors (one constant
63/// per modern version module, chosen once per session).
64#[derive(Clone, Copy)]
65pub(crate) struct ModernMap {
66    pub(crate) block: fn(u32) -> u16,
67    pub(crate) item: fn(i32, i16) -> (u16, u16),
68    pub(crate) entity_text: fn(&ghast_entity::Entity) -> Option<serde_json::Value>,
69    pub(crate) stack_text:
70        for<'a> fn(&ghast_inventory::Stack, &dyn Fn(i32) -> Option<&'a str>) -> serde_json::Value,
71    pub(crate) entity_name: fn(&str) -> String,
72    pub(crate) info: fn(ghast_entity::EntityType) -> Option<&'static ghast_data::EntityInfo>,
73    pub(crate) item_stack:
74        fn(&ghast_entity::Entity) -> Option<&ghast_protocol::types::slot::v775::ItemStack>,
75    pub(crate) flags: fn(&ghast_entity::Entity) -> u8,
76    pub(crate) inventory: ghast_inventory::Version,
77    /// Clientbound ids copied raw while a page watches (hand swings, hurts, deaths).
78    pub(crate) fx_packets: &'static [i32],
79    /// The page event (`protocol::event`) of one of those packets (id, body): `(entity id, kind)`.
80    pub(crate) fx: fn(i32, &bytes::Bytes) -> Option<(i32, u8)>,
81    /// The game version name (`"26.1"`).
82    pub(crate) game: &'static str,
83}
84
85impl std::fmt::Debug for ModernMap {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.debug_struct("ModernMap")
88            .field("inventory", &self.inventory)
89            .finish_non_exhaustive()
90    }
91}
92
93/// The modern mapping of a session's version (`None`: not a modern version, or its feature is
94/// off).
95pub(crate) fn modern_map(v: ghast_client::GameVersion) -> Option<&'static ModernMap> {
96    match v {
97        #[cfg(feature = "v26_1")]
98        ghast_client::GameVersion::V26_1 => Some(&v26_1::MAP),
99        #[cfg(feature = "v26_2")]
100        ghast_client::GameVersion::V26_2 => Some(&v26_2::MAP),
101        #[cfg(feature = "v26_3")]
102        ghast_client::GameVersion::V26_3 => Some(&v26_3::MAP),
103        _ => None,
104    }
105}
106
107use std::net::{IpAddr, Ipv4Addr, SocketAddr};
108use std::path::PathBuf;
109use std::sync::Arc;
110use std::time::Duration;
111
112pub use dashcam::{DashCam, DashCamOptions};
113pub use feed::{BotView, now_ms};
114pub use record::{FeedRecorder, ReplayMeta, list_recordings, prune_recordings};
115pub use watch::Watched;
116
117use crate::feed::FeedConfig;
118use crate::hub::Hub;
119use crate::skins::SkinStore;
120
121/// Viewer options.
122#[derive(Debug, Clone)]
123pub struct ViewerConfig {
124    /// Shown on the page (the bot's name).
125    pub account: String,
126    /// Listen address (default 127.0.0.1: put a proxy with access control in front for remote use).
127    pub host: IpAddr,
128    /// Port (0 = any free port).
129    pub port: u16,
130    /// Columns sent around the bot: a (2d − 1)² square, 1..=12 (default 8 → 15×15).
131    pub view_distance: u8,
132    /// Stop the server after this long without a page (default 60 s).
133    pub idle: Duration,
134    /// Required on every request as `Authorization: Bearer <token>`, `?token=<token>` (the page
135    /// then keeps it in a cookie) or that cookie. `None`: no check (fine on 127.0.0.1).
136    pub token: Option<String>,
137    /// Recordings folder (`/replays`, `?replay=`); `None`: no replays.
138    pub replay_dir: Option<PathBuf>,
139    /// Cache folder for the client jar, extracted textures and built assets
140    /// (default `.cache/ghast-viewer`).
141    pub cache_dir: PathBuf,
142    /// A local vanilla 1.8.9 client jar; `None`: downloaded from Mojang into the cache.
143    pub client_jar: Option<PathBuf>,
144    /// When to track entities, the tab list and skins for the page (default
145    /// [`EntityTracking::Always`]).
146    pub entities: EntityTracking,
147}
148
149impl ViewerConfig {
150    /// Defaults for a bot named `account`.
151    #[must_use]
152    pub fn new(account: impl Into<String>) -> Self {
153        ViewerConfig {
154            account: account.into(),
155            host: IpAddr::V4(Ipv4Addr::LOCALHOST),
156            port: 0,
157            view_distance: 8,
158            idle: Duration::from_secs(60),
159            token: None,
160            replay_dir: None,
161            cache_dir: PathBuf::from(".cache/ghast-viewer"),
162            client_jar: None,
163            entities: EntityTracking::Always,
164        }
165    }
166
167    /// Sets the port.
168    #[must_use]
169    pub fn port(mut self, port: u16) -> Self {
170        self.port = port;
171        self
172    }
173
174    /// Sets the listen address.
175    #[must_use]
176    pub fn host(mut self, host: IpAddr) -> Self {
177        self.host = host;
178        self
179    }
180
181    /// Sets the view distance (clamped to 1..=12).
182    #[must_use]
183    pub fn view_distance(mut self, d: u8) -> Self {
184        self.view_distance = d.clamp(1, 12);
185        self
186    }
187
188    /// Sets the access token.
189    #[must_use]
190    pub fn token(mut self, token: impl Into<String>) -> Self {
191        self.token = Some(token.into());
192        self
193    }
194
195    /// Sets the recordings folder.
196    #[must_use]
197    pub fn replay_dir(mut self, dir: impl Into<PathBuf>) -> Self {
198        self.replay_dir = Some(dir.into());
199        self
200    }
201
202    /// Sets the cache folder.
203    #[must_use]
204    pub fn cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
205        self.cache_dir = dir.into();
206        self
207    }
208
209    /// Uses a local client jar.
210    #[must_use]
211    pub fn client_jar(mut self, jar: impl Into<PathBuf>) -> Self {
212        self.client_jar = Some(jar.into());
213        self
214    }
215
216    /// Sets when entities are tracked.
217    #[must_use]
218    pub fn entities(mut self, e: EntityTracking) -> Self {
219        self.entities = e;
220        self
221    }
222
223    /// Sets the idle timeout.
224    #[must_use]
225    pub fn idle(mut self, d: Duration) -> Self {
226        self.idle = d;
227        self
228    }
229
230    fn feed(&self) -> FeedConfig {
231        FeedConfig {
232            account: self.account.clone(),
233            view_distance: i32::from(self.view_distance.clamp(1, 12)),
234            unbudgeted: false,
235        }
236    }
237}
238
239/// When the viewer has ghast track entities (`Interests::ENTITIES`, `PLAYER_LIST`,
240/// `PLAYER_SKINS`).
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
242pub enum EntityTracking {
243    /// For the whole session: a page opened later shows every entity at once.
244    #[default]
245    Always,
246    /// Only while a page or recording is attached (no cost otherwise). Tracking starts empty
247    /// when the first page opens: entities already around appear once the server sends them
248    /// again (when they move into view or respawn).
249    WhileWatched,
250    /// Never: no entities on the page.
251    Off,
252}
253
254/// The world settings a watched client should use (light for shading, biomes for grass and
255/// leaf colours, block entities for sign text, skulls, banners and flower pots):
256/// `Client::new(..).world_config(ghast_viewer::world_config())`.
257#[must_use]
258pub fn world_config() -> ghast_world::WorldConfig {
259    ghast_world::WorldConfig::default()
260        .with_light(true)
261        .with_biomes(true)
262        .with_block_entities(true)
263}
264
265/// Viewer state.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
267pub struct ViewerStatus {
268    pub running: bool,
269    pub port: Option<u16>,
270    pub viewers: usize,
271    #[serde(rename = "inGame")]
272    pub in_game: bool,
273}
274
275struct Inner {
276    cfg: ViewerConfig,
277    hub: Arc<Hub>,
278    server: server::Control,
279}
280
281/// The bot screen of one bot. Cheap to clone (a handle).
282#[derive(Clone)]
283pub struct Viewer {
284    inner: Arc<Inner>,
285}
286
287impl std::fmt::Debug for Viewer {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        f.debug_struct("Viewer")
290            .field("account", &self.inner.cfg.account)
291            .field("status", &self.status())
292            .finish()
293    }
294}
295
296impl Viewer {
297    /// A viewer (no server yet: see [`Viewer::start`]).
298    #[must_use]
299    pub fn new(cfg: ViewerConfig) -> Self {
300        Self::with_options(cfg, false)
301    }
302
303    /// Tests: encode columns on the tick thread.
304    #[doc(hidden)]
305    #[must_use]
306    pub fn new_inline(cfg: ViewerConfig) -> Self {
307        Self::with_options(cfg, true)
308    }
309
310    fn with_options(cfg: ViewerConfig, inline: bool) -> Self {
311        let mut feed = cfg.feed();
312        feed.unbudgeted = inline;
313        let hub = Hub::new(feed, Arc::clone(SkinStore::global()), inline);
314        Viewer {
315            inner: Arc::new(Inner {
316                cfg,
317                hub,
318                server: server::Control::default(),
319            }),
320        }
321    }
322
323    /// The configuration.
324    #[must_use]
325    pub fn config(&self) -> &ViewerConfig {
326        &self.inner.cfg
327    }
328
329    /// The hub (feed and streams).
330    #[must_use]
331    pub fn hub(&self) -> &Arc<Hub> {
332        &self.inner.hub
333    }
334
335    /// Wraps a behaviour so its ticks feed this viewer.
336    pub fn watch<B>(&self, behavior: B) -> Watched<B> {
337        Watched::new(behavior, self.clone())
338    }
339
340    /// Starts the server (idempotent; builds the assets on first use) and returns its address.
341    pub async fn start(&self) -> std::io::Result<SocketAddr> {
342        server::start(self).await
343    }
344
345    /// Stops the server (pages are disconnected; recordings go on).
346    pub async fn stop(&self) {
347        self.inner.server.stop().await;
348    }
349
350    /// The status line under the bot's name on the page, and the message shown while the bot
351    /// is not in game (empty: the default).
352    pub fn set_status(&self, status: &str, message: &str) {
353        self.inner.hub.set_status(status, message);
354    }
355
356    /// Running, port, pages watching, in game.
357    #[must_use]
358    pub fn status(&self) -> ViewerStatus {
359        ViewerStatus {
360            running: self.inner.server.port().is_some(),
361            port: self.inner.server.port(),
362            viewers: self
363                .inner
364                .hub
365                .viewers
366                .load(std::sync::atomic::Ordering::Relaxed)
367                + self.inner.server.replays(),
368            in_game: self.inner.hub.in_game(),
369        }
370    }
371
372    pub(crate) fn control(&self) -> &server::Control {
373        &self.inner.server
374    }
375}