1use std::sync::Arc;
4
5use ghast_client::inventory::{Click, ClickError, ClickOutcome, Stack, WindowKind};
6use ghast_client::{BlockPos, ClickRefused, GameVersion, TickContext};
7
8use crate::{Bot, Error};
9
10const CLICK_WAIT: u64 = 100;
12
13#[derive(Clone)]
16#[non_exhaustive]
17pub enum ItemMatch {
18 Name(String),
20 Id(i32),
22 Pred(Arc<dyn Fn(&Stack) -> bool + Send + Sync>),
24}
25
26impl std::fmt::Debug for ItemMatch {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 match self {
29 ItemMatch::Name(n) => f.debug_tuple("Name").field(n).finish(),
30 ItemMatch::Id(i) => f.debug_tuple("Id").field(i).finish(),
31 ItemMatch::Pred(_) => f.write_str("Pred(..)"),
32 }
33 }
34}
35
36impl std::fmt::Display for ItemMatch {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 match self {
39 ItemMatch::Name(n) => f.write_str(n),
40 ItemMatch::Id(i) => write!(f, "item id {i}"),
41 ItemMatch::Pred(_) => f.write_str("matching item"),
42 }
43 }
44}
45
46impl From<&str> for ItemMatch {
47 fn from(n: &str) -> Self {
48 ItemMatch::Name(n.to_owned())
49 }
50}
51
52impl From<String> for ItemMatch {
53 fn from(n: String) -> Self {
54 ItemMatch::Name(n)
55 }
56}
57
58impl From<i32> for ItemMatch {
59 fn from(id: i32) -> Self {
60 ItemMatch::Id(id)
61 }
62}
63
64impl<F: Fn(&Stack) -> bool + Send + Sync + 'static> From<F> for ItemMatch {
65 fn from(f: F) -> Self {
66 ItemMatch::Pred(Arc::new(f))
67 }
68}
69
70#[must_use]
79pub fn item_id(version: GameVersion, name: &str) -> Option<i32> {
80 let n = name.strip_prefix("minecraft:").unwrap_or(name);
81 match version {
82 #[cfg(feature = "v1_8")]
83 GameVersion::V1_8_9 => ghast_data::v1_8::Item::from_name(n).map(|i| i32::from(i.id())),
84 #[cfg(feature = "v1_12_2")]
85 GameVersion::V1_12_2 => ghast_data::v1_12::Item::from_name(n).map(|i| i32::from(i.id())),
86 #[cfg(feature = "v1_16_5")]
87 GameVersion::V1_16_5 => ghast_data::v1_16_5::Item::from_name(n).map(|i| i32::from(i.id())),
88 #[cfg(feature = "v26_1")]
89 GameVersion::V26_1 => ghast_data::v26_1::Item::from_name(n).map(|i| i32::from(i.id())),
90 #[cfg(feature = "v26_2")]
91 GameVersion::V26_2 => ghast_data::v26_2::Item::from_name(n).map(|i| i32::from(i.id())),
92 _ => None,
93 }
94}
95
96#[must_use]
103pub fn item_name(version: GameVersion, id: i32) -> &'static str {
104 let Ok(id) = u16::try_from(id) else {
105 return "";
106 };
107 match version {
108 #[cfg(feature = "v1_8")]
109 GameVersion::V1_8_9 => ghast_data::v1_8::Item::from_id(id).map_or("", |i| i.info().name),
110 #[cfg(feature = "v1_12_2")]
111 GameVersion::V1_12_2 => ghast_data::v1_12::Item::from_id(id).map_or("", |i| i.info().name),
112 #[cfg(feature = "v1_16_5")]
113 GameVersion::V1_16_5 => {
114 ghast_data::v1_16_5::Item::from_id(id).map_or("", |i| i.info().name)
115 }
116 #[cfg(feature = "v26_1")]
117 GameVersion::V26_1 => ghast_data::v26_1::Item::from_id(id).map_or("", |i| i.name()),
118 #[cfg(feature = "v26_2")]
119 GameVersion::V26_2 => ghast_data::v26_2::Item::from_id(id).map_or("", |i| i.name()),
120 _ => "",
121 }
122}
123
124#[derive(Clone)]
126pub(crate) struct Matcher(ItemMatchInner);
127
128#[derive(Clone)]
129enum ItemMatchInner {
130 Id(i32),
131 Pred(Arc<dyn Fn(&Stack) -> bool + Send + Sync>),
132}
133
134impl Matcher {
135 pub(crate) fn resolve(m: &ItemMatch, version: GameVersion) -> Result<Matcher, Error> {
136 Ok(Matcher(match m {
137 ItemMatch::Name(n) => ItemMatchInner::Id(
138 item_id(version, n).ok_or_else(|| Error::UnknownItem(n.clone()))?,
139 ),
140 ItemMatch::Id(i) => ItemMatchInner::Id(*i),
141 ItemMatch::Pred(p) => ItemMatchInner::Pred(p.clone()),
142 }))
143 }
144
145 pub(crate) fn matches(&self, s: &Stack) -> bool {
146 if s.count() <= 0 && s.id() <= 0 {
147 return false;
148 }
149 match &self.0 {
150 ItemMatchInner::Id(i) => s.id() == *i,
151 ItemMatchInner::Pred(p) => p(s),
152 }
153 }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct Container {
160 pub id: i32,
162 pub kind: WindowKind,
164 pub slots: usize,
166}
167
168fn find_player(ctx: &TickContext<'_>, m: &Matcher) -> Option<usize> {
171 (0..36).find(|&k| ctx.inventory().player(k).is_some_and(|s| m.matches(s)))
172}
173
174impl Bot {
175 pub async fn count(&self, item: impl Into<ItemMatch>) -> Result<i32, Error> {
184 let item = item.into();
185 self.with(move |ctx| {
186 let m = Matcher::resolve(&item, ctx.version())?;
187 Ok(ctx.inventory().count(|s| m.matches(s)))
188 })
189 .await?
190 }
191
192 pub async fn find_item(
203 &self,
204 item: impl Into<ItemMatch>,
205 ) -> Result<Option<(usize, Stack)>, Error> {
206 let item = item.into();
207 self.with(move |ctx| {
208 let m = Matcher::resolve(&item, ctx.version())?;
209 Ok(
210 find_player(ctx, &m)
211 .and_then(|k| ctx.inventory().player(k).map(|s| (k, s.clone()))),
212 )
213 })
214 .await?
215 }
216
217 pub async fn held_item(&self) -> Result<Option<Stack>, Error> {
225 self.with(|ctx| ctx.inventory().held().cloned()).await
226 }
227
228 pub fn select_slot(&self, slot: u8) {
236 self.act(move |ctx| ctx.select_slot(slot));
237 }
238
239 pub async fn equip(&self, item: impl Into<ItemMatch>) -> Result<u8, Error> {
251 let item = item.into();
252 let label = item.to_string();
253 let found = self
254 .with(move |ctx| -> Result<Option<(usize, u8)>, Error> {
255 let m = Matcher::resolve(&item, ctx.version())?;
256 let Some(k) = find_player(ctx, &m) else {
257 return Ok(None);
258 };
259 if k < 9 {
260 ctx.select_slot(k as u8);
261 return Ok(Some((k, k as u8)));
262 }
263 let inv = ctx.inventory();
264 let hotbar = (0..9u8)
265 .find(|h| inv.hotbar(usize::from(*h)).is_none())
266 .unwrap_or(ctx.held_slot());
267 Ok(Some((k, hotbar)))
268 })
269 .await??;
270 let Some((index, hotbar)) = found else {
271 return Err(Error::NoSuchItem(label));
272 };
273 if index < 9 {
274 return Ok(hotbar);
275 }
276 self.swap_to_hotbar(index, hotbar).await?;
277 self.select_slot(hotbar);
278 self.next_tick().await;
279 Ok(hotbar)
280 }
281
282 pub async fn equip_for_block(&self, pos: BlockPos) -> Result<u8, Error> {
294 let plan = self
295 .with(move |ctx| -> Result<(u8, Option<usize>), Error> {
296 if ctx.world().raw_block(pos.x, pos.y, pos.z).is_none() {
297 return Err(Error::NotLoaded(pos));
298 }
299 let (slot, hot) = crate::actions::best_hotbar_tool(ctx, pos);
300 let main = (9..36)
301 .filter_map(|k| {
302 let s = ctx.dig_speed(pos, ctx.inventory().player(k))?;
303 (s > hot).then_some((k, s))
304 })
305 .max_by(|a, b| a.1.total_cmp(&b.1))
306 .map(|(k, _)| k);
307 if main.is_none() {
308 ctx.select_slot(slot);
309 }
310 Ok((slot, main))
311 })
312 .await??;
313 match plan {
314 (slot, None) => Ok(slot),
315 (_, Some(k)) => {
316 let hotbar = self.with(|ctx| ctx.held_slot()).await?;
317 self.swap_to_hotbar(k, hotbar).await?;
318 self.select_slot(hotbar);
319 self.next_tick().await;
320 Ok(hotbar)
321 }
322 }
323 }
324
325 pub async fn swap_to_hotbar(&self, index: usize, hotbar: u8) -> Result<(), Error> {
335 let opened = self.ensure_screen().await?;
336 let r = async {
337 let slot = self
338 .with(move |ctx| ctx.inventory().slot_of_player(index))
339 .await?
340 .ok_or(Error::Click(ClickError::InvalidSlot))?;
341 self.click(Click::Swap { slot, hotbar }).await
342 }
343 .await;
344 if opened {
345 self.close_window().await?;
346 }
347 r
348 }
349
350 pub async fn drop_slot(&self, index: usize, all: bool) -> Result<(), Error> {
359 let opened = self.ensure_screen().await?;
360 let r = async {
361 let slot = self
362 .with(move |ctx| ctx.inventory().slot_of_player(index))
363 .await?
364 .ok_or(Error::Click(ClickError::InvalidSlot))?;
365 self.click(Click::Drop { slot, all }).await
366 }
367 .await;
368 if opened {
369 self.close_window().await?;
370 }
371 r
372 }
373
374 pub async fn toss(&self, item: impl Into<ItemMatch>) -> Result<i32, Error> {
383 let item = item.into();
384 let m = {
385 let item = item.clone();
386 self.with(move |ctx| Matcher::resolve(&item, ctx.version()))
387 .await??
388 };
389 let opened = self.ensure_screen().await?;
390 let r = async {
391 let mut dropped = 0;
392 loop {
393 let m2 = m.clone();
394 let next = self
395 .with(move |ctx| {
396 let k = find_player(ctx, &m2)?;
397 let n = ctx.inventory().player(k)?.count();
398 Some((ctx.inventory().slot_of_player(k)?, n))
399 })
400 .await?;
401 let Some((slot, n)) = next else { break };
402 self.click(Click::Drop { slot, all: true }).await?;
403 dropped += n;
404 }
405 Ok(dropped)
406 }
407 .await;
408 if opened {
409 self.close_window().await?;
410 }
411 r
412 }
413
414 async fn ensure_screen(&self) -> Result<bool, Error> {
416 let need = self.with(|ctx| !ctx.inventory().gui_open()).await?;
417 if !need {
418 return Ok(false);
419 }
420 for _ in 0..CLICK_WAIT {
421 match self.with(|ctx| ctx.open_inventory()).await? {
422 Ok(()) => {
423 self.next_tick().await;
425 return Ok(true);
426 }
427 Err(ClickRefused::Inventory(ClickError::SameTick | ClickError::Pending)) => {}
428 Err(ClickRefused::Inventory(e)) => return Err(Error::Click(e)),
429 Err(_) => {}
430 }
431 self.next_tick().await;
432 }
433 Err(Error::Timeout)
434 }
435
436 pub async fn click(&self, click: Click) -> Result<(), Error> {
449 let start = self.tick();
450 let ticket = loop {
451 match self.with(move |ctx| ctx.click(click)).await? {
452 Ok(t) => break t,
453 Err(ClickRefused::Inventory(
454 e @ (ClickError::NoScreen
455 | ClickError::InvalidSlot
456 | ClickError::InvalidButton
457 | ClickError::Unpredictable
458 | ClickError::WindowOpen),
459 )) => return Err(Error::Click(e)),
460 Err(_) => {}
461 }
462 if self.tick().saturating_sub(start) > CLICK_WAIT {
463 return Err(Error::Timeout);
464 }
465 self.next_tick().await;
466 };
467 loop {
469 self.next_tick().await;
470 let r = self
471 .with(move |ctx| {
472 ctx.events()
473 .inventory
474 .clicks
475 .iter()
476 .find(|r| ticket.matches(r))
477 .map(|r| r.outcome)
478 })
479 .await?;
480 match r {
481 Some(ClickOutcome::Accepted) => return Ok(()),
482 Some(ClickOutcome::Rejected) => return Err(Error::ClickRejected),
483 Some(_) => return Err(Error::ClickTimedOut),
484 None => {}
485 }
486 if self.tick().saturating_sub(start) > CLICK_WAIT + 60 {
487 return Err(Error::ClickTimedOut);
488 }
489 }
490 }
491
492 pub async fn close_window(&self) -> Result<(), Error> {
500 for _ in 0..CLICK_WAIT {
501 match self
502 .with(|ctx| {
503 if !ctx.inventory().gui_open() {
504 return Ok(());
505 }
506 ctx.close_window()
507 })
508 .await?
509 {
510 Ok(()) => return Ok(()),
511 Err(ClickRefused::Inventory(ClickError::SameTick | ClickError::Pending)) => {}
512 Err(ClickRefused::Inventory(e)) => return Err(Error::Click(e)),
513 Err(_) => {}
514 }
515 self.next_tick().await;
516 }
517 Err(Error::Timeout)
518 }
519
520 pub async fn open_container(&self, pos: BlockPos) -> Result<Container, Error> {
532 let mark = self.mark();
533 if self.with(|ctx| ctx.inventory().gui_open()).await? {
534 self.close_window().await?;
535 }
536 self.activate_block(pos).await?;
537 for _ in 0..40 {
538 self.next_tick().await;
539 self.check(mark)?;
540 let w = self
541 .with(|ctx| {
542 let inv = ctx.inventory();
543 inv.window().map(|w| Container {
544 id: w.id(),
545 kind: w.kind(),
546 slots: inv.container_len(),
547 })
548 })
549 .await?;
550 if let Some(c) = w {
551 self.next_tick().await;
553 return Ok(c);
554 }
555 }
556 Err(Error::Timeout)
557 }
558
559 pub async fn container_items(&self) -> Result<Vec<(usize, Stack)>, Error> {
569 self.with(|ctx| {
570 let inv = ctx.inventory();
571 if inv.window().is_none() {
572 return Err(Error::NoWindow);
573 }
574 Ok((0..inv.container_len())
575 .filter_map(|i| inv.slot(i).map(|s| (i, s.clone())))
576 .collect())
577 })
578 .await?
579 }
580
581 pub async fn deposit(
591 &self,
592 item: impl Into<ItemMatch>,
593 max: Option<i32>,
594 ) -> Result<i32, Error> {
595 self.transfer(item.into(), max, true).await
596 }
597
598 pub async fn withdraw(
608 &self,
609 item: impl Into<ItemMatch>,
610 max: Option<i32>,
611 ) -> Result<i32, Error> {
612 self.transfer(item.into(), max, false).await
613 }
614
615 async fn transfer(
616 &self,
617 item: ItemMatch,
618 max: Option<i32>,
619 deposit: bool,
620 ) -> Result<i32, Error> {
621 let m = self
622 .with(move |ctx| -> Result<(Matcher, i32), Error> {
623 let m = Matcher::resolve(&item, ctx.version())?;
624 if ctx.inventory().window().is_none() {
625 return Err(Error::NoWindow);
626 }
627 let n = ctx.inventory().count(|s| m.matches(s));
628 Ok((m, n))
629 })
630 .await??;
631 let (m, start) = m;
632 let mut moved = 0;
633 let mut tried: Vec<i16> = Vec::new();
634 while max.is_none_or(|x| moved < x) {
635 let m2 = m.clone();
636 let skip = tried.clone();
637 let slot = self
638 .with(move |ctx| -> Result<Option<i16>, Error> {
639 let inv = ctx.inventory();
640 if inv.window().is_none() {
641 return Err(Error::NoWindow);
642 }
643 let n = inv.container_len();
644 let range = if deposit { n..inv.slot_count() } else { 0..n };
645 Ok(range
646 .map(|i| i as i16)
647 .filter(|i| !skip.contains(i))
648 .find(|&i| inv.slot(i as usize).is_some_and(|s| m2.matches(s))))
649 })
650 .await??;
651 let Some(slot) = slot else { break };
652 self.click(Click::QuickMove { slot, right: false }).await?;
653 tried.push(slot);
654 let m3 = m.clone();
655 let now = self
656 .with(move |ctx| ctx.inventory().count(|s| m3.matches(s)))
657 .await?;
658 let delta = if deposit { start - now } else { now - start };
659 if delta == moved {
660 break; }
662 moved = delta;
663 }
664 Ok(moved)
665 }
666}