Skip to main content

ghast_inventory/inventory/
read.rs

1//! Read access to the inventory: cursor, player slots, hands, the open window and its slots,
2//! searches, and whether a click may be sent now.
3
4use super::*;
5
6impl Inventory {
7    // ------------------------------------------------------------------ reading
8
9    /// The cursor ("carried") stack.
10    #[must_use]
11    pub fn cursor(&self) -> Option<&Stack> {
12        self.m.cursor.as_ref()
13    }
14
15    /// `PlayerInventory` slot by vanilla index: 0..=8 hotbar, 9..=35 main, 36..=39 armor
16    /// (feet, legs, chest, head), 40 offhand (1.12 / 1.16.5).
17    #[must_use]
18    pub fn player(&self, index: usize) -> Option<&Stack> {
19        self.m.player.get(index)?.as_ref()
20    }
21
22    /// Hotbar slot 0..=8.
23    #[must_use]
24    pub fn hotbar(&self, k: usize) -> Option<&Stack> {
25        if k < 9 { self.player(k) } else { None }
26    }
27
28    /// The selected hotbar slot.
29    #[must_use]
30    pub fn selected(&self) -> u8 {
31        self.m.selected
32    }
33
34    /// How many times the server wrote the selected hotbar slot (`set_slot`, `window_items`;
35    /// 1.8 – 1.16.5), whether the stack changed or not, wrapping. A 1.8 client's item use ends
36    /// when the held stack is replaced, even by an equal one.
37    #[must_use]
38    pub fn held_writes(&self) -> u16 {
39        self.hotbar_writes[usize::from(self.m.selected.min(8))]
40    }
41
42    /// [`Inventory::held_writes`] for the off-hand slot (1.12 / 1.16.5).
43    #[must_use]
44    pub fn offhand_writes(&self) -> u16 {
45        self.hotbar_writes[9]
46    }
47
48    /// Whether the player slots or the selected hotbar slot may have changed since the last
49    /// call (and since the inventory was made); clears the flag. Conservative: any write sets
50    /// it, changed or not. For a caller that keeps something derived from the hands (or any
51    /// player slot) and re-reads only when this is `true`; there must be one such caller.
52    #[inline]
53    pub fn take_player_touched(&mut self) -> bool {
54        self.m.player.take_touched()
55    }
56
57    /// The stack in the selected hotbar slot.
58    #[must_use]
59    pub fn held(&self) -> Option<&Stack> {
60        self.player(usize::from(self.m.selected))
61    }
62
63    /// Armor piece: 0 head, 1 chest, 2 legs, 3 feet.
64    #[must_use]
65    pub fn armor(&self, a: usize) -> Option<&Stack> {
66        if a < 4 { self.player(39 - a) } else { None }
67    }
68
69    /// The offhand stack (1.12 / 1.16.5).
70    #[must_use]
71    pub fn offhand(&self) -> Option<&Stack> {
72        self.player(40)
73    }
74
75    /// The open container window, if any.
76    #[must_use]
77    pub fn window(&self) -> Option<&Window> {
78        match &self.screen {
79            ScreenState::Window(w) => Some(w),
80            _ => None,
81        }
82    }
83
84    /// Whether a GUI is open (a container window or the player inventory).
85    #[must_use]
86    pub fn gui_open(&self) -> bool {
87        self.screen != ScreenState::None
88    }
89
90    /// Whether the player inventory GUI is open (no container window).
91    #[must_use]
92    pub fn inventory_open(&self) -> bool {
93        self.screen == ScreenState::Inventory
94    }
95
96    pub(super) fn layout(&self) -> Layout {
97        let screen = match &self.screen {
98            ScreenState::Window(w) => Screen::Container(w.kind),
99            _ => Screen::Player,
100        };
101        Layout::new(self.version, screen)
102    }
103
104    /// Number of slots of the current screen (window 0 when no container is open: 45 on 1.8,
105    /// 46 on 1.12 / 1.16.5).
106    #[must_use]
107    pub fn slot_count(&self) -> usize {
108        self.layout().len
109    }
110
111    /// Container slots of the open window (before the player's 36), 0 for window 0.
112    #[must_use]
113    pub fn container_len(&self) -> usize {
114        self.layout().n
115    }
116
117    /// Slot `i` of the current screen (window 0 layout when no container is open).
118    #[must_use]
119    pub fn slot(&self, i: usize) -> Option<&Stack> {
120        let l = self.layout().loc(i)?;
121        self.m.at(l).as_ref()
122    }
123
124    /// Slot `i` of window 0 (`PlayerScreenHandler` numbering), whatever is open.
125    #[must_use]
126    pub fn window0_slot(&self, i: usize) -> Option<&Stack> {
127        let l = Layout::new(self.version, Screen::Player).loc(i)?;
128        self.m.at(l).as_ref()
129    }
130
131    /// Kind of slot `i` of the current screen.
132    #[must_use]
133    pub fn slot_kind(&self, i: usize) -> Option<SlotKind> {
134        let lay = self.layout();
135        (i < lay.len).then(|| lay.kind(i))
136    }
137
138    /// The current screen's slot that shows `PlayerInventory` index `k` (e.g. hotbar 0 is
139    /// window 0 slot 36 and slot 54 of a 3-row chest).
140    #[must_use]
141    pub fn slot_of_player(&self, k: usize) -> Option<i16> {
142        self.layout().slot_of_player(k).map(|i| i as i16)
143    }
144
145    /// First slot of the current screen whose stack matches.
146    pub fn find(&self, mut pred: impl FnMut(&Stack) -> bool) -> Option<i16> {
147        let lay = self.layout();
148        (0..lay.len)
149            .find(|&i| {
150                lay.loc(i)
151                    .and_then(|l| self.m.at(l).as_ref())
152                    .is_some_and(&mut pred)
153            })
154            .map(|i| i as i16)
155    }
156
157    /// Total count of matching stacks in the player inventory (hotbar, main, armor, offhand).
158    pub fn count(&self, mut pred: impl FnMut(&Stack) -> bool) -> i32 {
159        self.m
160            .player
161            .iter()
162            .flatten()
163            .filter(|s| pred(s))
164            .map(|s| s.count)
165            .sum()
166    }
167
168    /// Whether the current screen's crafting result (window 0 slot 0, crafting table slot 0)
169    /// is what the vanilla client shows. The 1.8 client computes results from its recipe book
170    /// (ghast does not) and the server never sends them except in `window_items`; on 1.16.5 the
171    /// server sends each new result as `set_slot`. The 1.12 client never computes results: the
172    /// slot always holds what the server last sent (taking a result whose grid changed since is
173    /// refused, its remainders depend on the recipes). While unknown, result clicks are
174    /// [`ClickError::Unpredictable`]. 1.8 – 1.16.5 anvil and grindstone: whether ghast could
175    /// compute the output like the client (false for inputs it cannot read, until the server's
176    /// `set_slot`).
177    #[must_use]
178    pub fn result_known(&self) -> bool {
179        match &self.screen {
180            ScreenState::Window(w) if w.kind == WindowKind::Crafting => {
181                self.m.container_result_known
182            }
183            // 1.8 – 1.16.5 anvil: the output the client computed after an input change
184            ScreenState::Window(w)
185                if matches!(w.kind, WindowKind::Anvil | WindowKind::Grindstone)
186                    && !self.version.is_modern() =>
187            {
188                self.m.container_result_known
189            }
190            ScreenState::Window(_) => true,
191            _ => self.m.craft_result_known,
192        }
193    }
194
195    /// Whether the current screen's crafting result belongs to the grid as it is now. 1.12: the
196    /// server sent it and the grid has not changed since (a click that changes the grid leaves
197    /// the old result in the slot until the server's `set_slot`; taking such a stale result is
198    /// [`ClickError::Unpredictable`]). 1.8 / 1.16.5: the same as
199    /// [`result_known`](Inventory::result_known).
200    #[must_use]
201    pub fn result_current(&self) -> bool {
202        if self.version != Version::V1_12 {
203            return self.result_known();
204        }
205        match &self.screen {
206            ScreenState::Window(w) if w.kind == WindowKind::Crafting => self.m.container_fresh,
207            ScreenState::Window(_) => true,
208            _ => self.m.craft_fresh,
209        }
210    }
211
212    /// Whether a click waits for its confirm.
213    #[must_use]
214    pub fn pending(&self) -> bool {
215        self.pending.is_some()
216    }
217
218    /// Whether the inventory waits for the server's resync after a rejected click.
219    #[must_use]
220    pub fn resyncing(&self) -> bool {
221        self.resync.is_some()
222    }
223
224    /// Whether [`click`](Inventory::click) would currently refuse for a reason other than the
225    /// click itself.
226    pub fn can_click(&self) -> Result<(), ClickError> {
227        if self.pending.is_some() {
228            return Err(ClickError::Pending);
229        }
230        if self.resync.is_some() {
231            return Err(ClickError::Resyncing);
232        }
233        if self.flags.clicked || self.flags.opened {
234            return Err(ClickError::SameTick);
235        }
236        if self.screen == ScreenState::None {
237            return Err(ClickError::NoScreen);
238        }
239        Ok(())
240    }
241}