1use ghast_client::entity::{EntityClass, EntityType};
4use ghast_client::version::DataSet;
5use ghast_client::{BlockPos, GameVersion, TickContext, Vec3};
6
7use crate::{Bot, Error};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct Block {
22 version: GameVersion,
23 raw: u32,
24}
25
26impl Block {
27 #[must_use]
36 pub const fn new(version: GameVersion, raw: u32) -> Self {
37 Block { version, raw }
38 }
39
40 #[must_use]
47 pub const fn raw(self) -> u32 {
48 self.raw
49 }
50
51 #[must_use]
59 pub fn name(self) -> &'static str {
60 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 #[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 #[must_use]
117 pub fn is_air(self) -> bool {
118 matches!(self.name(), "air" | "cave_air" | "void_air")
119 }
120
121 #[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 #[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 #[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#[non_exhaustive]
168pub enum BlockMatch {
169 Name(String),
171 Names(Vec<String>),
173 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
231pub(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 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; }
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#[derive(Debug, Clone, PartialEq)]
306#[non_exhaustive]
307pub struct EntityInfo {
308 pub id: i32,
310 pub name: &'static str,
313 pub class: EntityClass,
315 pub pos: Vec3,
317 pub player_name: Option<String>,
319 pub item: Option<(i32, i32)>,
321 pub alive: bool,
324}
325
326fn 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
363fn 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 #[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 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 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 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 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 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 pub async fn entity(&self, id: i32) -> Result<Option<EntityInfo>, Error> {
520 self.with(move |ctx| entity_info(ctx, id)).await
521 }
522
523 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}