1use ghast_client::entity::{EntityClass, EntityType};
4use ghast_client::{BlockPos, GameVersion, TickContext, Vec3};
5
6use crate::{Bot, Error};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub struct Block {
21 version: GameVersion,
22 raw: u32,
23}
24
25impl Block {
26 #[must_use]
35 pub const fn new(version: GameVersion, raw: u32) -> Self {
36 Block { version, raw }
37 }
38
39 #[must_use]
46 pub const fn raw(self) -> u32 {
47 self.raw
48 }
49
50 #[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 #[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 #[must_use]
110 pub fn is_air(self) -> bool {
111 matches!(self.name(), "air" | "cave_air" | "void_air")
112 }
113
114 #[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 #[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 #[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#[non_exhaustive]
161pub enum BlockMatch {
162 Name(String),
164 Names(Vec<String>),
166 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
224pub(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 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; }
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#[derive(Debug, Clone, PartialEq)]
299#[non_exhaustive]
300pub struct EntityInfo {
301 pub id: i32,
303 pub name: &'static str,
306 pub class: EntityClass,
308 pub pos: Vec3,
310 pub player_name: Option<String>,
312 pub item: Option<(i32, i32)>,
314}
315
316fn 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 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 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 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 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 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 pub async fn entity(&self, id: i32) -> Result<Option<EntityInfo>, Error> {
480 self.with(move |ctx| entity_info(ctx, id)).await
481 }
482
483 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}