1use std::sync::Arc;
4
5use ghast_client::inventory::{Click, ClickError, ClickOutcome, Stack, WindowKind};
6#[cfg(any(
7 feature = "v1_8",
8 feature = "v1_12_2",
9 feature = "v1_16_5",
10 feature = "v26_1",
11 feature = "v26_2",
12 feature = "v26_3"
13))]
14use ghast_client::version::DataSet;
15use ghast_client::{BlockPos, ClickRefused, GameVersion, TickContext};
16
17use crate::{Bot, Error};
18
19const CLICK_WAIT: u64 = 100;
21
22#[derive(Clone)]
25#[non_exhaustive]
26pub enum ItemMatch {
27 Name(String),
29 Id(i32),
31 Pred(Arc<dyn Fn(&Stack) -> bool + Send + Sync>),
33}
34
35impl std::fmt::Debug for ItemMatch {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 match self {
38 ItemMatch::Name(n) => f.debug_tuple("Name").field(n).finish(),
39 ItemMatch::Id(i) => f.debug_tuple("Id").field(i).finish(),
40 ItemMatch::Pred(_) => f.write_str("Pred(..)"),
41 }
42 }
43}
44
45impl std::fmt::Display for ItemMatch {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 match self {
48 ItemMatch::Name(n) => f.write_str(n),
49 ItemMatch::Id(i) => write!(f, "item id {i}"),
50 ItemMatch::Pred(_) => f.write_str("matching item"),
51 }
52 }
53}
54
55impl From<&str> for ItemMatch {
56 fn from(n: &str) -> Self {
57 ItemMatch::Name(n.to_owned())
58 }
59}
60
61impl From<String> for ItemMatch {
62 fn from(n: String) -> Self {
63 ItemMatch::Name(n)
64 }
65}
66
67impl From<i32> for ItemMatch {
68 fn from(id: i32) -> Self {
69 ItemMatch::Id(id)
70 }
71}
72
73impl<F: Fn(&Stack) -> bool + Send + Sync + 'static> From<F> for ItemMatch {
74 fn from(f: F) -> Self {
75 ItemMatch::Pred(Arc::new(f))
76 }
77}
78
79#[must_use]
88pub fn item_id(version: GameVersion, name: &str) -> Option<i32> {
89 let n = name.strip_prefix("minecraft:").unwrap_or(name);
90 match version.caps().data {
92 #[cfg(feature = "v1_8")]
93 DataSet::V1_8 => ghast_data::v1_8::Item::from_name(n).map(|i| i32::from(i.id())),
94 #[cfg(feature = "v1_12_2")]
95 DataSet::V1_12 => ghast_data::v1_12::Item::from_name(n).map(|i| i32::from(i.id())),
96 #[cfg(feature = "v1_16_5")]
97 DataSet::V1_16_5 => ghast_data::v1_16_5::Item::from_name(n).map(|i| i32::from(i.id())),
98 #[cfg(feature = "v26_1")]
99 DataSet::V26_1 => ghast_data::v26_1::Item::from_name(n).map(|i| i32::from(i.id())),
100 #[cfg(feature = "v26_2")]
101 DataSet::V26_2 => ghast_data::v26_2::Item::from_name(n).map(|i| i32::from(i.id())),
102 #[cfg(feature = "v26_3")]
103 DataSet::V26_3 => ghast_data::v26_3::Item::from_name(n).map(|i| i32::from(i.id())),
104 _ => None,
105 }
106}
107
108#[must_use]
115pub fn item_name(version: GameVersion, id: i32) -> &'static str {
116 let Ok(id) = u16::try_from(id) else {
117 return "";
118 };
119 match version.caps().data {
121 #[cfg(feature = "v1_8")]
122 DataSet::V1_8 => ghast_data::v1_8::Item::from_id(id).map_or("", |i| i.info().name),
123 #[cfg(feature = "v1_12_2")]
124 DataSet::V1_12 => ghast_data::v1_12::Item::from_id(id).map_or("", |i| i.info().name),
125 #[cfg(feature = "v1_16_5")]
126 DataSet::V1_16_5 => ghast_data::v1_16_5::Item::from_id(id).map_or("", |i| i.info().name),
127 #[cfg(feature = "v26_1")]
128 DataSet::V26_1 => ghast_data::v26_1::Item::from_id(id).map_or("", |i| i.name()),
129 #[cfg(feature = "v26_2")]
130 DataSet::V26_2 => ghast_data::v26_2::Item::from_id(id).map_or("", |i| i.name()),
131 #[cfg(feature = "v26_3")]
132 DataSet::V26_3 => ghast_data::v26_3::Item::from_id(id).map_or("", |i| i.name()),
133 _ => "",
134 }
135}
136
137#[derive(Clone)]
139pub(crate) struct Matcher(ItemMatchInner);
140
141#[derive(Clone)]
142enum ItemMatchInner {
143 Id(i32),
144 Pred(Arc<dyn Fn(&Stack) -> bool + Send + Sync>),
145}
146
147impl Matcher {
148 pub(crate) fn resolve(m: &ItemMatch, version: GameVersion) -> Result<Matcher, Error> {
149 Ok(Matcher(match m {
150 ItemMatch::Name(n) => ItemMatchInner::Id(
151 item_id(version, n).ok_or_else(|| Error::UnknownItem(n.clone()))?,
152 ),
153 ItemMatch::Id(i) => ItemMatchInner::Id(*i),
154 ItemMatch::Pred(p) => ItemMatchInner::Pred(p.clone()),
155 }))
156 }
157
158 pub(crate) fn matches(&self, s: &Stack) -> bool {
159 if s.count() <= 0 && s.id() <= 0 {
160 return false;
161 }
162 match &self.0 {
163 ItemMatchInner::Id(i) => s.id() == *i,
164 ItemMatchInner::Pred(p) => p(s),
165 }
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct Container {
173 pub id: i32,
175 pub kind: WindowKind,
177 pub slots: usize,
179}
180
181fn find_player(ctx: &TickContext<'_>, m: &Matcher) -> Option<usize> {
184 (0..36).find(|&k| ctx.inventory().player(k).is_some_and(|s| m.matches(s)))
185}
186
187impl Bot {
188 pub async fn count(&self, item: impl Into<ItemMatch>) -> Result<i32, Error> {
197 let item = item.into();
198 self.with(move |ctx| {
199 let m = Matcher::resolve(&item, ctx.version())?;
200 Ok(ctx.inventory().count(|s| m.matches(s)))
201 })
202 .await?
203 }
204
205 pub async fn find_item(
216 &self,
217 item: impl Into<ItemMatch>,
218 ) -> Result<Option<(usize, Stack)>, Error> {
219 let item = item.into();
220 self.with(move |ctx| {
221 let m = Matcher::resolve(&item, ctx.version())?;
222 Ok(
223 find_player(ctx, &m)
224 .and_then(|k| ctx.inventory().player(k).map(|s| (k, s.clone()))),
225 )
226 })
227 .await?
228 }
229
230 pub async fn held_item(&self) -> Result<Option<Stack>, Error> {
238 self.with(|ctx| ctx.inventory().held().cloned()).await
239 }
240
241 pub fn select_slot(&self, slot: u8) {
249 self.act(move |ctx| ctx.select_slot(slot));
250 }
251
252 pub async fn equip(&self, item: impl Into<ItemMatch>) -> Result<u8, Error> {
264 let item = item.into();
265 let label = item.to_string();
266 let found = self
267 .with(move |ctx| -> Result<Option<(usize, u8)>, Error> {
268 let m = Matcher::resolve(&item, ctx.version())?;
269 let Some(k) = find_player(ctx, &m) else {
270 return Ok(None);
271 };
272 if k < 9 {
273 ctx.select_slot(k as u8);
274 return Ok(Some((k, k as u8)));
275 }
276 let inv = ctx.inventory();
277 let hotbar = (0..9u8)
278 .find(|h| inv.hotbar(usize::from(*h)).is_none())
279 .unwrap_or(ctx.held_slot());
280 Ok(Some((k, hotbar)))
281 })
282 .await??;
283 let Some((index, hotbar)) = found else {
284 return Err(Error::NoSuchItem(label));
285 };
286 if index < 9 {
287 return Ok(hotbar);
288 }
289 self.swap_to_hotbar(index, hotbar).await?;
290 self.select_slot(hotbar);
291 self.next_tick().await;
292 Ok(hotbar)
293 }
294
295 pub async fn equip_for_block(&self, pos: BlockPos) -> Result<u8, Error> {
307 let plan = self
308 .with(move |ctx| -> Result<(u8, Option<usize>), Error> {
309 if ctx.world().raw_block(pos.x, pos.y, pos.z).is_none() {
310 return Err(Error::NotLoaded(pos));
311 }
312 let (slot, hot) = crate::actions::best_hotbar_tool(ctx, pos);
313 let main = (9..36)
314 .filter_map(|k| {
315 let s = ctx.dig_speed(pos, ctx.inventory().player(k))?;
316 (s > hot).then_some((k, s))
317 })
318 .max_by(|a, b| a.1.total_cmp(&b.1))
319 .map(|(k, _)| k);
320 if main.is_none() {
321 ctx.select_slot(slot);
322 }
323 Ok((slot, main))
324 })
325 .await??;
326 match plan {
327 (slot, None) => Ok(slot),
328 (_, Some(k)) => {
329 let hotbar = self.with(|ctx| ctx.held_slot()).await?;
330 self.swap_to_hotbar(k, hotbar).await?;
331 self.select_slot(hotbar);
332 self.next_tick().await;
333 Ok(hotbar)
334 }
335 }
336 }
337
338 pub async fn swap_to_hotbar(&self, index: usize, hotbar: u8) -> Result<(), Error> {
348 let opened = self.ensure_screen().await?;
349 let r = async {
350 let slot = self
351 .with(move |ctx| ctx.inventory().slot_of_player(index))
352 .await?
353 .ok_or(Error::Click(ClickError::InvalidSlot))?;
354 self.click(Click::Swap { slot, hotbar }).await
355 }
356 .await;
357 if opened {
358 self.close_window().await?;
359 }
360 r
361 }
362
363 pub async fn drop_slot(&self, index: usize, all: bool) -> Result<(), Error> {
372 let opened = self.ensure_screen().await?;
373 let r = async {
374 let slot = self
375 .with(move |ctx| ctx.inventory().slot_of_player(index))
376 .await?
377 .ok_or(Error::Click(ClickError::InvalidSlot))?;
378 self.click(Click::Drop { slot, all }).await
379 }
380 .await;
381 if opened {
382 self.close_window().await?;
383 }
384 r
385 }
386
387 pub async fn toss(&self, item: impl Into<ItemMatch>) -> Result<i32, Error> {
396 let item = item.into();
397 let m = {
398 let item = item.clone();
399 self.with(move |ctx| Matcher::resolve(&item, ctx.version()))
400 .await??
401 };
402 let opened = self.ensure_screen().await?;
403 let r = async {
404 let mut dropped = 0;
405 loop {
406 let m2 = m.clone();
407 let next = self
408 .with(move |ctx| {
409 let k = find_player(ctx, &m2)?;
410 let n = ctx.inventory().player(k)?.count();
411 Some((ctx.inventory().slot_of_player(k)?, n))
412 })
413 .await?;
414 let Some((slot, n)) = next else { break };
415 self.click(Click::Drop { slot, all: true }).await?;
416 dropped += n;
417 }
418 Ok(dropped)
419 }
420 .await;
421 if opened {
422 self.close_window().await?;
423 }
424 r
425 }
426
427 async fn ensure_screen(&self) -> Result<bool, Error> {
429 let need = self.with(|ctx| !ctx.inventory().gui_open()).await?;
430 if !need {
431 return Ok(false);
432 }
433 for _ in 0..CLICK_WAIT {
434 match self.with(|ctx| ctx.open_inventory()).await? {
435 Ok(()) => {
436 self.next_tick().await;
438 return Ok(true);
439 }
440 Err(ClickRefused::Inventory(ClickError::SameTick | ClickError::Pending)) => {}
441 Err(ClickRefused::Inventory(e)) => return Err(Error::Click(e)),
442 Err(_) => {}
443 }
444 self.next_tick().await;
445 }
446 Err(Error::Timeout)
447 }
448
449 pub async fn click(&self, click: Click) -> Result<(), Error> {
462 let start = self.tick();
463 let ticket = loop {
464 match self.with(move |ctx| ctx.click(click)).await? {
465 Ok(t) => break t,
466 Err(ClickRefused::Inventory(
467 e @ (ClickError::NoScreen
468 | ClickError::InvalidSlot
469 | ClickError::InvalidButton
470 | ClickError::Unpredictable
471 | ClickError::WindowOpen),
472 )) => return Err(Error::Click(e)),
473 Err(ClickRefused::Dead) => return Err(Error::Died),
474 Err(_) => {}
475 }
476 if self.tick().saturating_sub(start) > CLICK_WAIT {
477 return Err(Error::Timeout);
478 }
479 self.next_tick().await;
480 };
481 if ticket.window_id < 0 {
482 return Ok(());
484 }
485 loop {
487 self.next_tick().await;
488 let r = self
489 .with(move |ctx| {
490 ctx.events()
491 .inventory
492 .clicks
493 .iter()
494 .find(|r| ticket.matches(r))
495 .map(|r| r.outcome)
496 })
497 .await?;
498 match r {
499 Some(ClickOutcome::Accepted) => return Ok(()),
500 Some(ClickOutcome::Rejected) => return Err(Error::ClickRejected),
501 Some(_) => return Err(Error::ClickTimedOut),
502 None => {}
503 }
504 if self.tick().saturating_sub(start) > CLICK_WAIT + 60 {
505 return Err(Error::ClickTimedOut);
506 }
507 }
508 }
509
510 pub async fn close_window(&self) -> Result<(), Error> {
518 for _ in 0..CLICK_WAIT {
519 match self
520 .with(|ctx| {
521 if !ctx.inventory().gui_open() {
522 return Ok(());
523 }
524 ctx.close_window()
525 })
526 .await?
527 {
528 Ok(()) => return Ok(()),
529 Err(ClickRefused::Inventory(ClickError::SameTick | ClickError::Pending)) => {}
530 Err(ClickRefused::Inventory(e)) => return Err(Error::Click(e)),
531 Err(_) => {}
532 }
533 self.next_tick().await;
534 }
535 Err(Error::Timeout)
536 }
537
538 pub async fn open_container(&self, pos: BlockPos) -> Result<Container, Error> {
550 let mark = self.mark();
551 if self.with(|ctx| ctx.inventory().gui_open()).await? {
552 self.close_window().await?;
553 }
554 self.activate_block(pos).await?;
555 for _ in 0..40 {
556 self.next_tick().await;
557 self.check(mark)?;
558 let w = self
559 .with(|ctx| {
560 let inv = ctx.inventory();
561 inv.window().map(|w| Container {
562 id: w.id(),
563 kind: w.kind(),
564 slots: inv.container_len(),
565 })
566 })
567 .await?;
568 if let Some(c) = w {
569 self.next_tick().await;
571 return Ok(c);
572 }
573 }
574 Err(Error::Timeout)
575 }
576
577 pub async fn container_items(&self) -> Result<Vec<(usize, Stack)>, Error> {
587 self.with(|ctx| {
588 let inv = ctx.inventory();
589 if inv.window().is_none() {
590 return Err(Error::NoWindow);
591 }
592 Ok((0..inv.container_len())
593 .filter_map(|i| inv.slot(i).map(|s| (i, s.clone())))
594 .collect())
595 })
596 .await?
597 }
598
599 pub async fn deposit(
609 &self,
610 item: impl Into<ItemMatch>,
611 max: Option<i32>,
612 ) -> Result<i32, Error> {
613 self.transfer(item.into(), max, true).await
614 }
615
616 pub async fn withdraw(
626 &self,
627 item: impl Into<ItemMatch>,
628 max: Option<i32>,
629 ) -> Result<i32, Error> {
630 self.transfer(item.into(), max, false).await
631 }
632
633 async fn transfer(
634 &self,
635 item: ItemMatch,
636 max: Option<i32>,
637 deposit: bool,
638 ) -> Result<i32, Error> {
639 let m = self
640 .with(move |ctx| -> Result<(Matcher, i32), Error> {
641 let m = Matcher::resolve(&item, ctx.version())?;
642 if ctx.inventory().window().is_none() {
643 return Err(Error::NoWindow);
644 }
645 let n = ctx.inventory().count(|s| m.matches(s));
646 Ok((m, n))
647 })
648 .await??;
649 let (m, start) = m;
650 let mut moved = 0;
651 let mut tried: Vec<i16> = Vec::new();
652 while max.is_none_or(|x| moved < x) {
653 let m2 = m.clone();
654 let skip = tried.clone();
655 let slot = self
656 .with(move |ctx| -> Result<Option<i16>, Error> {
657 let inv = ctx.inventory();
658 if inv.window().is_none() {
659 return Err(Error::NoWindow);
660 }
661 let n = inv.container_len();
662 let range = if deposit { n..inv.slot_count() } else { 0..n };
663 Ok(range
664 .map(|i| i as i16)
665 .filter(|i| !skip.contains(i))
666 .find(|&i| inv.slot(i as usize).is_some_and(|s| m2.matches(s))))
667 })
668 .await??;
669 let Some(slot) = slot else { break };
670 self.click(Click::QuickMove { slot, right: false }).await?;
671 tried.push(slot);
672 let m3 = m.clone();
673 let now = self
674 .with(move |ctx| ctx.inventory().count(|s| m3.matches(s)))
675 .await?;
676 let delta = if deposit { start - now } else { now - start };
677 if delta == moved {
678 break; }
680 moved = delta;
681 }
682 Ok(moved)
683 }
684}
685
686#[cfg(all(test, feature = "v1_12_2", feature = "v1_16_5"))]
687mod tests {
688 use super::*;
689
690 #[test]
691 fn sub_versions_use_their_rows_tables() {
692 for (sub, row) in [
693 (GameVersion::V1_12_1, GameVersion::V1_12_2),
694 (GameVersion::V1_16_2, GameVersion::V1_16_5),
695 (GameVersion::V1_16_3, GameVersion::V1_16_5),
696 ] {
697 let id = item_id(row, "diamond_pickaxe");
698 assert!(id.is_some());
699 assert_eq!(item_id(sub, "diamond_pickaxe"), id);
700 assert_eq!(item_name(sub, id.unwrap()), "diamond_pickaxe");
701 assert_eq!(
702 crate::Block::new(sub, 1 << 4).name(),
703 crate::Block::new(row, 1 << 4).name()
704 );
705 }
706 }
707}
708
709#[cfg(all(test, feature = "v26_3"))]
710mod tests_26_3 {
711 use super::*;
712
713 #[test]
715 fn new_items_and_blocks_resolve() {
716 let v = GameVersion::V26_3;
717 for name in ["poplar_planks", "poplar_door", "diamond_pickaxe", "stone"] {
718 let id = item_id(v, name).unwrap_or_else(|| panic!("{name}: no 26.3 item"));
719 assert_eq!(item_name(v, id), name);
720 assert_eq!(
721 id,
722 i32::from(ghast_data::v26_3::Item::from_name(name).unwrap().id())
723 );
724 }
725 for spec in [
726 "poplar_door",
727 "poplar_fence_gate",
728 "shelf_mushroom",
729 "stone",
730 ] {
731 let s = ghast_data::v26_3::BlockState::parse(spec).expect(spec);
732 assert_eq!(crate::Block::new(v, u32::from(s.id())).name(), spec);
733 }
734 }
735
736 #[cfg(feature = "v26_2")]
737 #[test]
738 fn ids_differ_from_26_2() {
739 let a = item_id(GameVersion::V26_2, "diamond_pickaxe");
741 let b = item_id(GameVersion::V26_3, "diamond_pickaxe");
742 assert!(a.is_some() && b.is_some());
743 assert_eq!(item_id(GameVersion::V26_2, "poplar_planks"), None);
744 }
745}