aboutsummaryrefslogtreecommitdiff
path: root/azalea/src/container.rs
blob: 0016caad3a53a6e30ad593e2d66279da4b07abf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::fmt::Formatter;

use azalea_client::{
    inventory::{CloseContainerEvent, ContainerClickEvent, InventoryComponent},
    packet_handling::PacketEvent,
    Client, TickBroadcast,
};
use azalea_core::BlockPos;
use azalea_inventory::{operations::ClickOperation, ItemSlot, Menu};
use azalea_protocol::packets::game::ClientboundGamePacket;
use bevy_app::{App, Plugin};
use bevy_ecs::{component::Component, prelude::EventReader, system::Commands};
use std::fmt::Debug;

pub struct ContainerPlugin;
impl Plugin for ContainerPlugin {
    fn build(&self, app: &mut App) {
        app.add_system(handle_menu_opened_event);
    }
}

pub trait ContainerClientExt {
    async fn open_container(&mut self, pos: BlockPos) -> Option<ContainerHandle>;
}

impl ContainerClientExt for Client {
    /// Open a container in the world, like a chest.
    ///
    /// ```
    /// # use azalea::prelude::*;
    /// # async fn example(mut bot: azalea::Client) {
    /// let target_pos = bot
    ///     .world()
    ///     .read()
    ///     .find_block(bot.position(), &azalea::Block::Chest.into());
    /// let Some(target_pos) = target_pos else {
    ///     bot.chat("no chest found");
    ///     return;
    /// };
    /// let container = bot.open_container(target_pos).await;
    /// # }
    /// ```
    async fn open_container(&mut self, pos: BlockPos) -> Option<ContainerHandle> {
        self.ecs
            .lock()
            .entity_mut(self.entity)
            .insert(WaitingForInventoryOpen);
        self.block_interact(pos);

        let mut receiver = {
            let ecs = self.ecs.lock();
            let tick_broadcast = ecs.resource::<TickBroadcast>();
            tick_broadcast.subscribe()
        };
        while receiver.recv().await.is_ok() {
            let ecs = self.ecs.lock();
            if ecs.get::<WaitingForInventoryOpen>(self.entity).is_none() {
                break;
            }
        }

        let ecs = self.ecs.lock();
        let inventory = ecs
            .get::<InventoryComponent>(self.entity)
            .expect("no inventory");
        if inventory.id == 0 {
            None
        } else {
            Some(ContainerHandle {
                id: inventory.id,
                client: self.clone(),
            })
        }
    }
}

/// A handle to the open container. The container will be closed once this is
/// dropped.
pub struct ContainerHandle {
    pub id: u8,
    client: Client,
}
impl Drop for ContainerHandle {
    fn drop(&mut self) {
        self.client.ecs.lock().send_event(CloseContainerEvent {
            entity: self.client.entity,
            id: self.id,
        });
    }
}
impl Debug for ContainerHandle {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContainerHandle")
            .field("id", &self.id)
            .finish()
    }
}
impl ContainerHandle {
    /// Returns the menu of the container. If the container is closed, this
    /// will return `None`.
    pub fn menu(&self) -> Option<Menu> {
        let ecs = self.client.ecs.lock();
        let inventory = ecs
            .get::<InventoryComponent>(self.client.entity)
            .expect("no inventory");
        if inventory.id == self.id {
            Some(inventory.container_menu.clone().unwrap())
        } else {
            None
        }
    }

    /// Returns the item slots in the container, not including the player's
    /// inventory. If the container is closed, this will return `None`.
    pub fn contents(&self) -> Option<Vec<ItemSlot>> {
        self.menu().map(|menu| menu.contents())
    }

    pub fn click(&self, operation: impl Into<ClickOperation>) {
        let operation = operation.into();
        self.client.ecs.lock().send_event(ContainerClickEvent {
            entity: self.client.entity,
            window_id: self.id,
            operation,
        });
    }
}

#[derive(Component, Debug)]
pub struct WaitingForInventoryOpen;

fn handle_menu_opened_event(mut commands: Commands, mut events: EventReader<PacketEvent>) {
    for event in events.iter() {
        if let ClientboundGamePacket::ContainerSetContent { .. } = event.packet {
            commands
                .entity(event.entity)
                .remove::<WaitingForInventoryOpen>();
        }
    }
}