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