Skip to main content

ghast_ext/
find.rs

1//! Blocks and entities: naming raw states, searching the loaded world, entity snapshots.
2
3use ghast_client::entity::{EntityClass, EntityType};
4use ghast_client::{BlockPos, GameVersion, TickContext, Vec3};
5
6use crate::{Bot, Error};
7
8/// A block state of the session's version, named with ghast-data.
9///
10/// ```
11/// use ghast_client::GameVersion;
12/// use ghast_ext::Block;
13///
14/// let ore = Block::new(GameVersion::V1_8_9, 56 << 4); // 1.8 diamond ore
15/// assert_eq!(ore.name(), "diamond_ore");
16/// assert!(ore.is_ore());
17/// assert!(Block::new(GameVersion::V1_8_9, 0).is_air());
18/// ```
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub struct Block {
21    version: GameVersion,
22    raw: u32,
23}
24
25impl Block {
26    /// The block for a raw state of `version` (1.8 `id << 4 | meta`, 1.16 the global
27    /// palette id), as [`ghast_client::WorldView::raw_block`] returns it.
28    ///
29    /// ```
30    /// # use ghast_client::GameVersion;
31    /// let b = ghast_ext::Block::new(GameVersion::V1_8_9, 1 << 4);
32    /// assert_eq!(b.name(), "stone");
33    /// ```
34    #[must_use]
35    pub const fn new(version: GameVersion, raw: u32) -> Self {
36        Block { version, raw }
37    }
38
39    /// The raw state.
40    ///
41    /// ```
42    /// # use ghast_client::GameVersion;
43    /// assert_eq!(ghast_ext::Block::new(GameVersion::V1_8_9, 17).raw(), 17);
44    /// ```
45    #[must_use]
46    pub const fn raw(self) -> u32 {
47        self.raw
48    }
49
50    /// The registry name without namespace (`"stone"`, `"oak_log"`; 1.8: `"log"`), or `""`
51    /// for an id this version does not know.
52    ///
53    /// ```
54    /// # use ghast_client::GameVersion;
55    /// assert_eq!(ghast_ext::Block::new(GameVersion::V1_8_9, 17 << 4).name(), "log");
56    /// ```
57    #[must_use]
58    pub fn name(self) -> &'static str {
59        match self.version {
60            #[cfg(feature = "v1_8")]
61            GameVersion::V1_8_9 => u8::try_from(self.raw >> 4)
62                .ok()
63                .and_then(ghast_data::v1_8::Block::from_id)
64                .map_or("", ghast_data::v1_8::Block::name),
65            #[cfg(feature = "v1_12_2")]
66            GameVersion::V1_12_2 => u8::try_from(self.raw >> 4)
67                .ok()
68                .and_then(ghast_data::v1_12::Block::from_id)
69                .map_or("", ghast_data::v1_12::Block::name),
70            #[cfg(feature = "v1_16_5")]
71            GameVersion::V1_16_5 => u16::try_from(self.raw)
72                .ok()
73                .and_then(ghast_data::v1_16_5::BlockState::from_id)
74                .map_or("", |s| s.block().name()),
75            #[cfg(feature = "v26_1")]
76            GameVersion::V26_1 => u16::try_from(self.raw)
77                .ok()
78                .and_then(ghast_data::v26_1::BlockState::from_id)
79                .map_or("", |s| s.block().name()),
80            #[cfg(feature = "v26_2")]
81            GameVersion::V26_2 => u16::try_from(self.raw)
82                .ok()
83                .and_then(ghast_data::v26_2::BlockState::from_id)
84                .map_or("", |s| s.block().name()),
85            _ => "",
86        }
87    }
88
89    /// The 1.8 / 1.12 metadata (`raw & 15`); 0 on 1.16 (use ghast-data's properties there).
90    ///
91    /// ```
92    /// # use ghast_client::GameVersion;
93    /// assert_eq!(ghast_ext::Block::new(GameVersion::V1_8_9, 59 << 4 | 7).meta(), 7); // ripe wheat
94    /// ```
95    #[must_use]
96    pub fn meta(self) -> u8 {
97        match self.version {
98            GameVersion::V1_8_9 | GameVersion::V1_12_2 => (self.raw & 15) as u8,
99            _ => 0,
100        }
101    }
102
103    /// Air (also cave / void air on 1.16).
104    ///
105    /// ```
106    /// # use ghast_client::GameVersion;
107    /// assert!(ghast_ext::Block::new(GameVersion::V1_16_5, 0).is_air());
108    /// ```
109    #[must_use]
110    pub fn is_air(self) -> bool {
111        matches!(self.name(), "air" | "cave_air" | "void_air")
112    }
113
114    /// An ore (`*_ore`, nether quartz / gold ore, ancient debris; not the lit redstone ore
115    /// variant's name difference on 1.8: `lit_redstone_ore` counts too).
116    ///
117    /// ```
118    /// # use ghast_client::GameVersion;
119    /// assert!(ghast_ext::Block::new(GameVersion::V1_8_9, 15 << 4).is_ore()); // iron ore
120    /// ```
121    #[must_use]
122    pub fn is_ore(self) -> bool {
123        let n = self.name();
124        n.ends_with("_ore") || n == "ancient_debris"
125    }
126
127    /// A log / stem / hyphae block (tree trunks).
128    ///
129    /// ```
130    /// # use ghast_client::GameVersion;
131    /// assert!(ghast_ext::Block::new(GameVersion::V1_8_9, 17 << 4).is_log());
132    /// ```
133    #[must_use]
134    pub fn is_log(self) -> bool {
135        let n = self.name();
136        n == "log"
137            || n == "log2"
138            || n.ends_with("_log")
139            || n.ends_with("_stem")
140            || n.ends_with("_hyphae")
141            || n.ends_with("_wood")
142    }
143
144    /// Water or lava.
145    ///
146    /// ```
147    /// # use ghast_client::GameVersion;
148    /// assert!(ghast_ext::Block::new(GameVersion::V1_8_9, 9 << 4).is_liquid());
149    /// ```
150    #[must_use]
151    pub fn is_liquid(self) -> bool {
152        matches!(
153            self.name(),
154            "water" | "flowing_water" | "lava" | "flowing_lava"
155        )
156    }
157}
158
159/// What [`Bot::find_blocks`] looks for: a name, several names, or a predicate.
160#[non_exhaustive]
161pub enum BlockMatch {
162    /// One registry name (`"diamond_ore"`, `"minecraft:chest"`).
163    Name(String),
164    /// Any of these names.
165    Names(Vec<String>),
166    /// A predicate on the block.
167    Pred(Box<dyn Fn(Block) -> bool + Send + Sync>),
168}
169
170impl std::fmt::Debug for BlockMatch {
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        match self {
173            BlockMatch::Name(n) => f.debug_tuple("Name").field(n).finish(),
174            BlockMatch::Names(n) => f.debug_tuple("Names").field(n).finish(),
175            BlockMatch::Pred(_) => f.write_str("Pred(..)"),
176        }
177    }
178}
179
180impl BlockMatch {
181    fn matches(&self, b: Block) -> bool {
182        match self {
183            BlockMatch::Name(n) => strip(n) == b.name(),
184            BlockMatch::Names(ns) => ns.iter().any(|n| strip(n) == b.name()),
185            BlockMatch::Pred(p) => p(b),
186        }
187    }
188}
189
190fn strip(n: &str) -> &str {
191    n.strip_prefix("minecraft:").unwrap_or(n)
192}
193
194impl From<&str> for BlockMatch {
195    fn from(n: &str) -> Self {
196        BlockMatch::Name(n.to_owned())
197    }
198}
199
200impl From<String> for BlockMatch {
201    fn from(n: String) -> Self {
202        BlockMatch::Name(n)
203    }
204}
205
206impl From<&[&str]> for BlockMatch {
207    fn from(ns: &[&str]) -> Self {
208        BlockMatch::Names(ns.iter().map(|s| (*s).to_owned()).collect())
209    }
210}
211
212impl<const N: usize> From<[&str; N]> for BlockMatch {
213    fn from(ns: [&str; N]) -> Self {
214        BlockMatch::Names(ns.iter().map(|s| (*s).to_owned()).collect())
215    }
216}
217
218impl<F: Fn(Block) -> bool + Send + Sync + 'static> From<F> for BlockMatch {
219    fn from(f: F) -> Self {
220        BlockMatch::Pred(Box::new(f))
221    }
222}
223
224/// Matching blocks within `max_distance` of `center` (block centres, Euclidean), nearest
225/// first, at most `count`. Unloaded columns are skipped; all-air sections are skipped
226/// unless air matches. The predicate runs once per distinct state.
227pub(crate) fn find_blocks(
228    ctx: &TickContext<'_>,
229    m: &BlockMatch,
230    center: Vec3,
231    max_distance: f64,
232    count: usize,
233) -> Vec<BlockPos> {
234    let v = ctx.version();
235    let w = ctx.world();
236    let r = max_distance.max(0.0);
237    let r2 = r * r;
238    // Per raw state: 0 unknown, 1 no, 2 yes.
239    let mut memo = vec![0u8; 1 << 16];
240    let mut test = |raw: u32| -> bool {
241        let i = (raw as usize) & 0xffff;
242        if memo[i] == 0 {
243            memo[i] = if m.matches(Block::new(v, raw)) { 2 } else { 1 };
244        }
245        memo[i] == 2
246    };
247    let air_matches = test(0);
248    let (min_y, max_y) = (
249        ((center.y - r).floor() as i32).max(0),
250        ((center.y + r).floor() as i32).min(255),
251    );
252    let (x0, x1) = ((center.x - r).floor() as i32, (center.x + r).floor() as i32);
253    let (z0, z1) = ((center.z - r).floor() as i32, (center.z + r).floor() as i32);
254    let mut found: Vec<(f64, BlockPos)> = Vec::new();
255    for cx in (x0 >> 4)..=(x1 >> 4) {
256        for cz in (z0 >> 4)..=(z1 >> 4) {
257            if !w.is_column_loaded(cx, cz) {
258                continue;
259            }
260            let col = w.column(cx, cz);
261            for sy in (min_y >> 4)..=(max_y >> 4) {
262                let section = col.map(|c| c.section(sy as usize));
263                if matches!(section, Some(None)) && !air_matches {
264                    continue; // all air
265                }
266                for y in (sy << 4).max(min_y)..=((sy << 4) + 15).min(max_y) {
267                    let dy = f64::from(y) + 0.5 - center.y;
268                    for z in ((cz << 4).max(z0))..=(((cz << 4) + 15).min(z1)) {
269                        let dz = f64::from(z) + 0.5 - center.z;
270                        for x in ((cx << 4).max(x0))..=(((cx << 4) + 15).min(x1)) {
271                            let dx = f64::from(x) + 0.5 - center.x;
272                            let d2 = dx * dx + dy * dy + dz * dz;
273                            if d2 > r2 {
274                                continue;
275                            }
276                            let raw = match col {
277                                Some(c) => u32::from(c.raw(x, y, z)),
278                                None => match w.raw_block(x, y, z) {
279                                    Some(r) => r,
280                                    None => continue,
281                                },
282                            };
283                            if test(raw) {
284                                found.push((d2, BlockPos::new(x, y, z)));
285                            }
286                        }
287                    }
288                }
289            }
290        }
291    }
292    found.sort_by(|a, b| a.0.total_cmp(&b.0));
293    found.truncate(count);
294    found.into_iter().map(|(_, p)| p).collect()
295}
296
297/// A snapshot of a tracked entity.
298#[derive(Debug, Clone, PartialEq)]
299#[non_exhaustive]
300pub struct EntityInfo {
301    /// Entity id.
302    pub id: i32,
303    /// Registry / minecraft-data name (`"player"`, `"zombie"`, `"item"`, `"arrow"`, ...;
304    /// 1.8 names as minecraft-data has them), `""` when unknown.
305    pub name: &'static str,
306    /// Broad class.
307    pub class: EntityClass,
308    /// Position (the server's, feet).
309    pub pos: Vec3,
310    /// A player's tab-list name ([`ghast_client::Interests::PLAYER_LIST`]).
311    pub player_name: Option<String>,
312    /// An item entity's stack: item id and count.
313    pub item: Option<(i32, i32)>,
314}
315
316/// The name of an entity type (1.8 and 1.12 share the legacy mob / object id spaces but not
317/// the names).
318fn entity_name(version: GameVersion, ty: EntityType) -> &'static str {
319    let info: Option<&'static ghast_data::EntityInfo> = match (ty, version) {
320        (EntityType::Player, _) => return "player",
321        #[cfg(feature = "v26_1")]
322        (EntityType::Registry(_), GameVersion::V26_1) => ghast_client::entity::v26_1::info(ty),
323        #[cfg(feature = "v26_2")]
324        (EntityType::Registry(_), GameVersion::V26_2) => ghast_client::entity::v26_2::info(ty),
325        #[cfg(feature = "v1_16_5")]
326        (EntityType::Registry(_), _) => ghast_client::entity::v1_16_5::info(ty),
327        #[cfg(feature = "v1_12_2")]
328        (_, GameVersion::V1_12_2) => ghast_client::entity::v1_12::info(ty),
329        #[cfg(feature = "v1_8")]
330        (_, GameVersion::V1_8_9) => ghast_client::entity::v1_8::info(ty),
331        _ => None,
332    };
333    info.map_or("", |i| i.name)
334}
335
336pub(crate) fn entity_info(ctx: &TickContext<'_>, id: i32) -> Option<EntityInfo> {
337    let es = ctx.entities()?;
338    let e = es.get(id)?;
339    let [x, y, z] = e.position();
340    Some(EntityInfo {
341        id,
342        name: entity_name(ctx.version(), e.entity_type()),
343        class: e.class(),
344        pos: Vec3::new(x, y, z),
345        player_name: es.player_name(id).map(str::to_owned),
346        item: e.item().map(|i| (i.id, i32::from(i.count))),
347    })
348}
349
350impl Bot {
351    /// The block at `pos`; `None` when its column is not loaded (never air by guess).
352    ///
353    /// ```no_run
354    /// use ghast_client::BlockPos;
355    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
356    /// if let Some(b) = bot.block_at(BlockPos::new(0, 63, 0)).await? {
357    ///     println!("{}", b.name());
358    /// }
359    /// # Ok(()) }
360    /// ```
361    pub async fn block_at(&self, pos: BlockPos) -> Result<Option<Block>, Error> {
362        self.with(move |ctx| {
363            let v = ctx.version();
364            ctx.world()
365                .raw_block(pos.x, pos.y, pos.z)
366                .map(|raw| Block::new(v, raw))
367        })
368        .await
369    }
370
371    /// Up to `count` blocks matching `what` within `max_distance` of the eyes, nearest first
372    /// (loaded columns only). `what` is a name, an array of names or a predicate on
373    /// [`Block`]. The search runs inside one tick: keep `max_distance` modest (32 blocks is
374    /// ~270k positions; all-air sections are skipped).
375    ///
376    /// ```no_run
377    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
378    /// let ores = bot.find_blocks(|b: ghast_ext::Block| b.is_ore(), 32.0, 10).await?;
379    /// let chests = bot.find_blocks("chest", 16.0, 1).await?;
380    /// let logs = bot.find_blocks(["log", "log2"], 24.0, 64).await?;
381    /// # Ok(()) }
382    /// ```
383    pub async fn find_blocks(
384        &self,
385        what: impl Into<BlockMatch>,
386        max_distance: f64,
387        count: usize,
388    ) -> Result<Vec<BlockPos>, Error> {
389        let m = what.into();
390        self.with(move |ctx| {
391            let eyes = ctx.eyes(ctx.pose());
392            find_blocks(ctx, &m, eyes, max_distance, count)
393        })
394        .await
395    }
396
397    /// The nearest block matching `what` within `max_distance` (see [`Bot::find_blocks`]).
398    ///
399    /// ```no_run
400    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
401    /// if let Some(chest) = bot.find_block("chest", 16.0).await? { /* ... */ }
402    /// # Ok(()) }
403    /// ```
404    pub async fn find_block(
405        &self,
406        what: impl Into<BlockMatch>,
407        max_distance: f64,
408    ) -> Result<Option<BlockPos>, Error> {
409        Ok(self
410            .find_blocks(what, max_distance, 1)
411            .await?
412            .into_iter()
413            .next())
414    }
415
416    /// Tracked entities (not the bot) within `radius` of the bot matching `pred`, nearest
417    /// first. Needs [`ghast_client::Interests::ENTITIES`] ([`crate::Ext::interests`]);
418    /// empty without it.
419    ///
420    /// ```no_run
421    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
422    /// let zombies = bot.find_entities(|e| e.name == "zombie", 16.0).await?;
423    /// # Ok(()) }
424    /// ```
425    pub async fn find_entities<F>(&self, pred: F, radius: f64) -> Result<Vec<EntityInfo>, Error>
426    where
427        F: Fn(&EntityInfo) -> bool + Send + 'static,
428    {
429        self.with(move |ctx| {
430            let me = ctx.pose().pos;
431            let Some(es) = ctx.entities() else {
432                return Vec::new();
433            };
434            let self_id = es.self_id();
435            let ids: Vec<i32> = es
436                .within([me.x, me.y, me.z], radius)
437                .map(|e| e.id())
438                .filter(|id| Some(*id) != self_id)
439                .collect();
440            let mut v: Vec<(f64, EntityInfo)> = ids
441                .into_iter()
442                .filter_map(|id| entity_info(ctx, id))
443                .filter(|e| pred(e))
444                .map(|e| {
445                    let d = (e.pos.x - me.x).powi(2)
446                        + (e.pos.y - me.y).powi(2)
447                        + (e.pos.z - me.z).powi(2);
448                    (d, e)
449                })
450                .collect();
451            v.sort_by(|a, b| a.0.total_cmp(&b.0));
452            v.into_iter().map(|(_, e)| e).collect()
453        })
454        .await
455    }
456
457    /// The nearest tracked entity within `radius` matching `pred` (see
458    /// [`Bot::find_entities`]).
459    ///
460    /// ```no_run
461    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
462    /// let player = bot.nearest_entity(|e| e.name == "player", 32.0).await?;
463    /// # Ok(()) }
464    /// ```
465    pub async fn nearest_entity<F>(&self, pred: F, radius: f64) -> Result<Option<EntityInfo>, Error>
466    where
467        F: Fn(&EntityInfo) -> bool + Send + 'static,
468    {
469        Ok(self.find_entities(pred, radius).await?.into_iter().next())
470    }
471
472    /// A tracked entity by id.
473    ///
474    /// ```no_run
475    /// # async fn f(bot: ghast_ext::Bot, id: i32) -> Result<(), ghast_ext::Error> {
476    /// if let Some(e) = bot.entity(id).await? { println!("{:?}", e.pos); }
477    /// # Ok(()) }
478    /// ```
479    pub async fn entity(&self, id: i32) -> Result<Option<EntityInfo>, Error> {
480        self.with(move |ctx| entity_info(ctx, id)).await
481    }
482
483    /// The player entity with this tab-list name (needs [`ghast_client::Interests::ENTITIES`]
484    /// and [`ghast_client::Interests::PLAYER_LIST`]).
485    ///
486    /// ```no_run
487    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
488    /// if let Some(p) = bot.player("Steve").await? { println!("Steve at {:?}", p.pos); }
489    /// # Ok(()) }
490    /// ```
491    pub async fn player(&self, name: &str) -> Result<Option<EntityInfo>, Error> {
492        let name = name.to_owned();
493        self.with(move |ctx| {
494            let es = ctx.entities()?;
495            let id = es
496                .iter()
497                .filter(|e| e.is_player())
498                .find(|e| {
499                    es.player_name(e.id())
500                        .is_some_and(|n| n.eq_ignore_ascii_case(&name))
501                })?
502                .id();
503            entity_info(ctx, id)
504        })
505        .await
506    }
507}