Skip to main content

azalea_client/plugins/client_inventory/
mod.rs

1pub mod equipment_effects;
2
3use azalea_chat::FormattedText;
4use azalea_core::tick::GameTick;
5use azalea_entity::{PlayerAbilities, inventory::Inventory};
6use azalea_inventory::{Menu, operations::ClickOperation};
7use azalea_protocol::packets::game::{
8    s_container_click::{HashedStack, ServerboundContainerClick},
9    s_container_close::ServerboundContainerClose,
10    s_set_carried_item::ServerboundSetCarriedItem,
11};
12use azalea_registry::{builtin::MenuKind, item::ItemStack};
13use bevy_app::{App, Plugin};
14use bevy_ecs::prelude::*;
15use indexmap::IndexMap;
16use tracing::{error, warn};
17
18use crate::{
19    client_inventory::equipment_effects::{collect_equipment_changes, handle_equipment_changes},
20    packet::game::SendGamePacketEvent,
21};
22
23pub struct InventoryPlugin;
24impl Plugin for InventoryPlugin {
25    fn build(&self, app: &mut App) {
26        app.add_systems(
27            GameTick,
28            (
29                ensure_has_sent_carried_item.after(super::mining::handle_mining_queued),
30                collect_equipment_changes
31                    .after(super::interact::handle_start_use_item_queued)
32                    .before(azalea_physics::ai_step),
33            ),
34        )
35        .add_observer(handle_client_side_close_container_trigger)
36        .add_observer(handle_menu_opened_trigger)
37        .add_observer(handle_container_close_event)
38        .add_observer(handle_set_container_content_trigger)
39        .add_observer(handle_container_click_event)
40        // number keys are checked on tick but scrolling can happen outside of ticks, therefore
41        // this is fine
42        .add_observer(handle_set_selected_hotbar_slot_event)
43        .add_observer(handle_equipment_changes);
44    }
45}
46
47#[derive(Clone, Debug, Eq, Hash, PartialEq, SystemSet)]
48pub struct InventorySystems;
49
50/// A Bevy trigger that's fired when our client should show a new screen (like a
51/// chest or crafting table).
52///
53/// To watch for the menu being closed, you could use
54/// [`ClientsideCloseContainerEvent`]. To close it manually, use
55/// [`CloseContainerEvent`].
56#[derive(Clone, Debug, EntityEvent)]
57pub struct MenuOpenedEvent {
58    pub entity: Entity,
59    pub window_id: i32,
60    pub menu_type: MenuKind,
61    pub title: FormattedText,
62}
63fn handle_menu_opened_trigger(event: On<MenuOpenedEvent>, mut query: Query<&mut Inventory>) {
64    let mut inventory = query.get_mut(event.entity).unwrap();
65    inventory.id = event.window_id;
66    inventory.container_menu = Some(Box::new(Menu::from_kind(event.menu_type)));
67    inventory.container_menu_title = Some(Box::new(event.title.clone()));
68}
69
70/// Tell the server that we want to close a container.
71///
72/// Note that this is also sent when the client closes its own inventory, even
73/// though there is no packet for opening its inventory.
74#[derive(EntityEvent)]
75pub struct CloseContainerEvent {
76    pub entity: Entity,
77    /// The ID of the container to close. 0 for the player's inventory.
78    ///
79    /// If this is not the same as the currently open inventory, nothing will
80    /// happen.
81    pub id: i32,
82}
83fn handle_container_close_event(
84    close_container: On<CloseContainerEvent>,
85    mut commands: Commands,
86    query: Query<(Entity, &Inventory)>,
87) {
88    let (entity, inventory) = query.get(close_container.entity).unwrap();
89    if close_container.id != inventory.id {
90        warn!(
91            "Tried to close container with ID {}, but the current container ID is {}",
92            close_container.id, inventory.id
93        );
94        return;
95    }
96
97    commands.trigger(SendGamePacketEvent::new(
98        entity,
99        ServerboundContainerClose {
100            container_id: inventory.id,
101        },
102    ));
103    commands.trigger(ClientsideCloseContainerEvent {
104        entity: close_container.entity,
105    });
106}
107
108/// A Bevy event that's fired when our client closed a container.
109///
110/// This can also be triggered directly to close a container silently without
111/// sending any packets to the server. You probably don't want that though, and
112/// should instead use [`CloseContainerEvent`].
113///
114/// If you want to watch for a container being opened, you should use
115/// [`MenuOpenedEvent`].
116#[derive(Clone, EntityEvent)]
117pub struct ClientsideCloseContainerEvent {
118    pub entity: Entity,
119}
120pub fn handle_client_side_close_container_trigger(
121    event: On<ClientsideCloseContainerEvent>,
122    mut query: Query<&mut Inventory>,
123) {
124    let mut inventory = query.get_mut(event.entity).unwrap();
125
126    // copy the Player part of the container_menu to the inventory_menu
127    if let Some(inventory_menu) = inventory.container_menu.take() {
128        // this isn't the same as what vanilla does. i believe vanilla
129        // synchronizes the slots between inventoryMenu and containerMenu by
130        // just having the player slots point to the same ItemStack in memory,
131        // but emulating this in rust would require us to wrap our `ItemStack`s
132        // as `Arc<Mutex<ItemStack>>` which would have kinda terrible
133        // ergonomics.
134
135        // the simpler solution i chose to go with here is to only copy the
136        // player slots when the container is closed. this is perfectly fine for
137        // vanilla, but it might cause issues if a server modifies id 0 while we
138        // have a container open...
139
140        // if we do encounter this issue in the wild then the simplest solution
141        // would probably be to just add logic for updating the container_menu
142        // when the server tries to modify id 0 for slots within `inventory`.
143        // not implemented for now because i'm not sure if that's worth worrying
144        // about.
145
146        let new_inventory = inventory_menu.slots()[inventory_menu.player_slots_range()].to_vec();
147        let new_inventory = <[ItemStack; 36]>::try_from(new_inventory).unwrap();
148        *inventory.inventory_menu.as_player_mut().inventory = new_inventory;
149    }
150
151    inventory.id = 0;
152    inventory.container_menu_title = None;
153}
154
155#[derive(Debug, EntityEvent)]
156pub struct ContainerClickEvent {
157    pub entity: Entity,
158    pub window_id: i32,
159    pub operation: ClickOperation,
160}
161pub fn handle_container_click_event(
162    container_click: On<ContainerClickEvent>,
163    mut commands: Commands,
164    mut query: Query<(Entity, &mut Inventory, Option<&PlayerAbilities>)>,
165) {
166    let (entity, mut inventory, player_abilities) = query.get_mut(container_click.entity).unwrap();
167    if inventory.id != container_click.window_id {
168        error!(
169            "Tried to click container with ID {}, but the current container ID is {}. Click packet won't be sent.",
170            container_click.window_id, inventory.id
171        );
172        return;
173    }
174
175    let old_slots = inventory.menu().slots();
176    inventory.simulate_click(
177        &container_click.operation,
178        player_abilities.unwrap_or(&PlayerAbilities::default()),
179    );
180    let new_slots = inventory.menu().slots();
181
182    // see which slots changed after clicking and put them in the map the server
183    // uses this to check if we desynced
184    let mut changed_slots: IndexMap<u16, HashedStack> = IndexMap::new();
185    for (slot_index, old_slot) in old_slots.iter().enumerate() {
186        let new_slot = &new_slots[slot_index];
187        if old_slot != new_slot {
188            changed_slots.insert(slot_index as u16, HashedStack::from_item_stack(new_slot));
189        }
190    }
191
192    commands.trigger(SendGamePacketEvent::new(
193        entity,
194        ServerboundContainerClick {
195            container_id: container_click.window_id,
196            state_id: inventory.state_id,
197            slot_num: container_click
198                .operation
199                .slot_num()
200                .map(|n| n as i16)
201                .unwrap_or(-999),
202            button_num: container_click.operation.button_num(),
203            click_type: container_click.operation.click_type(),
204            changed_slots,
205            carried_item: HashedStack::from_item_stack(&inventory.carried),
206        },
207    ));
208}
209
210/// Sent from the server when the contents of a container are replaced.
211///
212/// Usually triggered by the `ContainerSetContent` packet.
213#[derive(EntityEvent)]
214pub struct SetContainerContentEvent {
215    pub entity: Entity,
216    pub slots: Vec<ItemStack>,
217    pub container_id: i32,
218}
219pub fn handle_set_container_content_trigger(
220    set_container_content: On<SetContainerContentEvent>,
221    mut query: Query<&mut Inventory>,
222) {
223    let mut inventory = query.get_mut(set_container_content.entity).unwrap();
224
225    if set_container_content.container_id != inventory.id {
226        warn!(
227            "Got SetContainerContentEvent for container with ID {}, but the current container ID is {}",
228            set_container_content.container_id, inventory.id
229        );
230        return;
231    }
232
233    let menu = inventory.menu_mut();
234    for (i, slot) in set_container_content.slots.iter().enumerate() {
235        if let Some(slot_mut) = menu.slot_mut(i) {
236            *slot_mut = slot.clone();
237        }
238    }
239}
240
241/// An ECS message to switch our hand to a different hotbar slot.
242///
243/// This is equivalent to using the scroll wheel or number keys in Minecraft.
244#[derive(EntityEvent)]
245pub struct SetSelectedHotbarSlotEvent {
246    pub entity: Entity,
247    /// The hotbar slot to select. This should be in the range 0..=8.
248    pub slot: u8,
249}
250pub fn handle_set_selected_hotbar_slot_event(
251    set_selected_hotbar_slot: On<SetSelectedHotbarSlotEvent>,
252    mut query: Query<&mut Inventory>,
253) {
254    let mut inventory = query.get_mut(set_selected_hotbar_slot.entity).unwrap();
255    inventory.selected_hotbar_slot = set_selected_hotbar_slot.slot;
256}
257
258/// The item slot that the server thinks we have selected.
259///
260/// See [`ensure_has_sent_carried_item`].
261#[derive(Component)]
262pub struct LastSentSelectedHotbarSlot {
263    pub slot: u8,
264}
265/// A system that makes sure that [`LastSentSelectedHotbarSlot`] is in sync with
266/// [`Inventory::selected_hotbar_slot`].
267///
268/// This is necessary to make sure that [`ServerboundSetCarriedItem`] is sent in
269/// the right order, since it's not allowed to happen outside of a tick.
270pub fn ensure_has_sent_carried_item(
271    mut commands: Commands,
272    query: Query<(Entity, &Inventory, Option<&LastSentSelectedHotbarSlot>)>,
273) {
274    for (entity, inventory, last_sent) in query.iter() {
275        if let Some(last_sent) = last_sent {
276            if last_sent.slot == inventory.selected_hotbar_slot {
277                continue;
278            }
279
280            commands.trigger(SendGamePacketEvent::new(
281                entity,
282                ServerboundSetCarriedItem {
283                    slot: inventory.selected_hotbar_slot as u16,
284                },
285            ));
286        }
287
288        commands.entity(entity).insert(LastSentSelectedHotbarSlot {
289            slot: inventory.selected_hotbar_slot,
290        });
291    }
292}