chore: move to crates folder
This commit is contained in:
1 parent
5d10c0d8a8
commit
cb3660bcd2
3393 files changed
+1270
-741
No files matched your search
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "pumpkin-inventory"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
pumpkin-protocol.workspace = true
|
||||
pumpkin-data = { workspace = true, features = [
|
||||
"item",
|
||||
"screen",
|
||||
"data_component",
|
||||
"recipes",
|
||||
"tag",
|
||||
"fuels",
|
||||
"enchantment",
|
||||
"potion",
|
||||
"statistic",
|
||||
] }
|
||||
|
||||
pumpkin-world.workspace = true
|
||||
pumpkin-util.workspace = true
|
||||
|
||||
rand.workspace = true
|
||||
tracing.workspace = true
|
||||
tokio.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,225 @@
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::{item_stack::ItemStack, screen::WindowType};
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour,
|
||||
ScreenHandlerFuture, offer_or_drop_stack,
|
||||
},
|
||||
slot::NormalSlot,
|
||||
window_property::{Anvil, WindowProperty},
|
||||
};
|
||||
|
||||
pub struct AnvilScreenHandler {
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
pub rename_text: String,
|
||||
pub repair_cost: i16,
|
||||
}
|
||||
|
||||
impl AnvilScreenHandler {
|
||||
#[expect(clippy::needless_pass_by_value)]
|
||||
pub fn new(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> Self {
|
||||
let mut handler = Self {
|
||||
inventory: inventory.clone(),
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(WindowType::Anvil)),
|
||||
rename_text: String::new(),
|
||||
repair_cost: 0,
|
||||
};
|
||||
|
||||
// Anvil specific slots: 2 input, 1 output
|
||||
for i in 0..3 {
|
||||
handler.add_slot(Arc::new(NormalSlot::new(inventory.clone(), i)));
|
||||
}
|
||||
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&player_inventory);
|
||||
|
||||
handler
|
||||
}
|
||||
|
||||
pub async fn update_item_name(&mut self, name: String) {
|
||||
self.rename_text = name;
|
||||
self.update_result_slot().await;
|
||||
self.send_content_updates().await;
|
||||
}
|
||||
|
||||
pub async fn update_result_slot(&mut self) {
|
||||
let input_a = {
|
||||
let lock = self.inventory.get_stack(0).await;
|
||||
lock.lock().await.clone()
|
||||
};
|
||||
|
||||
if input_a.is_empty() {
|
||||
self.inventory.set_stack(2, ItemStack::EMPTY.clone()).await;
|
||||
self.set_repair_cost(0).await;
|
||||
return;
|
||||
}
|
||||
|
||||
let mut result_item = input_a.clone();
|
||||
let mut cost = 0;
|
||||
|
||||
// Basic renaming logic for now
|
||||
if !self.rename_text.is_empty() {
|
||||
result_item.set_custom_name(self.rename_text.clone());
|
||||
cost += 1;
|
||||
}
|
||||
|
||||
// If combining with another item... we'll skip complex anvil logic for now
|
||||
// and just support renaming.
|
||||
if cost > 0 {
|
||||
self.inventory.set_stack(2, result_item).await;
|
||||
self.set_repair_cost(cost).await;
|
||||
} else {
|
||||
self.inventory.set_stack(2, ItemStack::EMPTY.clone()).await;
|
||||
self.set_repair_cost(0).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn set_repair_cost(&mut self, cost: i16) {
|
||||
self.repair_cost = cost;
|
||||
if let Some(sync_handler) = self.behaviour.sync_handler.as_ref() {
|
||||
let (property_id, property_value) =
|
||||
WindowProperty::new(Anvil::RepairCost, cost).into_tuple();
|
||||
sync_handler
|
||||
.update_property(&self.behaviour, property_id as i32, property_value as i32)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for AnvilScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
self.inventory.on_close().await;
|
||||
// Drop inputs from anvil
|
||||
for i in 0..2 {
|
||||
let stack = self.inventory.remove_stack(i).await;
|
||||
if !stack.is_empty() {
|
||||
offer_or_drop_stack(player, stack).await;
|
||||
}
|
||||
}
|
||||
self.inventory.set_stack(2, ItemStack::EMPTY.clone()).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if slot.has_stack().await {
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let slot_stack_guard = slot_stack_lock.lock().await;
|
||||
stack_left = slot_stack_guard.clone();
|
||||
drop(slot_stack_guard);
|
||||
|
||||
let mut slot_stack_mut = slot_stack_lock.lock().await;
|
||||
|
||||
if slot_index < 3 {
|
||||
// From anvil to player
|
||||
if !self
|
||||
.insert_item(
|
||||
&mut slot_stack_mut,
|
||||
3,
|
||||
self.get_behaviour().slots.len() as i32,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else {
|
||||
// From player to anvil input 0 and 1
|
||||
if !self.insert_item(&mut slot_stack_mut, 0, 2, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if slot_stack_mut.is_empty() {
|
||||
drop(slot_stack_mut);
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
drop(slot_stack_mut);
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
|
||||
fn on_slot_click<'a>(
|
||||
&'a mut self,
|
||||
slot_index: i32,
|
||||
button: i32,
|
||||
action_type: pumpkin_protocol::java::server::play::SlotActionType,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
if slot_index == 2 {
|
||||
// Taking from output slot
|
||||
let result_slot = self.get_behaviour().slots[2].clone();
|
||||
if result_slot.has_stack().await {
|
||||
let result_stack = result_slot.get_cloned_stack().await;
|
||||
if !result_stack.is_empty() {
|
||||
if player.experience_level() >= self.repair_cost as i32
|
||||
|| player.is_creative()
|
||||
{
|
||||
// Consume experience
|
||||
if !player.is_creative() {
|
||||
player
|
||||
.add_experience_levels(-(self.repair_cost as i32))
|
||||
.await;
|
||||
}
|
||||
|
||||
// Consume inputs
|
||||
self.inventory.set_stack(0, ItemStack::EMPTY.clone()).await;
|
||||
self.get_behaviour().slots[0].mark_dirty().await;
|
||||
} else {
|
||||
// Cancel click
|
||||
self.send_content_updates().await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.internal_on_slot_click(slot_index, button, action_type, player)
|
||||
.await;
|
||||
if slot_index == 0 || slot_index == 1 || slot_index == 2 {
|
||||
self.update_result_slot().await;
|
||||
self.send_content_updates().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod anvil_screen_handler;
|
||||
|
||||
pub use anvil_screen_handler::*;
|
||||
@@ -0,0 +1,136 @@
|
||||
use std::{any::Any, sync::Arc};
|
||||
|
||||
use pumpkin_data::{item_stack::ItemStack, screen::WindowType};
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour,
|
||||
ScreenHandlerFuture,
|
||||
},
|
||||
slot::NormalSlot,
|
||||
};
|
||||
|
||||
/// Creates a beacon container screen handler.
|
||||
///
|
||||
/// Beacons feature a single payment slot and a specialized UI for selecting status effects.
|
||||
pub async fn create_beacon_handler(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> BeaconScreenHandler {
|
||||
BeaconScreenHandler::new(sync_id, player_inventory, inventory).await
|
||||
}
|
||||
|
||||
/// Screen handler specifically for Beacon blocks.
|
||||
pub struct BeaconScreenHandler {
|
||||
/// The beacon's inventory (contains exactly 1 slot for payment).
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
/// Core screen handler behavior (slots, sync ID, listeners).
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
}
|
||||
|
||||
impl BeaconScreenHandler {
|
||||
/// Creates a new beacon screen handler.
|
||||
async fn new(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> Self {
|
||||
let mut handler = Self {
|
||||
inventory: inventory.clone(),
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(WindowType::Beacon)),
|
||||
};
|
||||
|
||||
inventory.on_open().await;
|
||||
|
||||
// Add the single payment slot for the beacon (slot 0)
|
||||
handler.add_slot(Arc::new(NormalSlot::new(handler.inventory.clone(), 0)));
|
||||
|
||||
// Add the player's inventory slots (27 slots + 9 hotbar)
|
||||
let player_inventory_arc: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&player_inventory_arc);
|
||||
|
||||
handler
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for BeaconScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
self.inventory.on_close().await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Quick move logic specifically for the beacon UI.
|
||||
///
|
||||
/// - From beacon payment slot (0): Move to player inventory
|
||||
/// - From player inventory (1+): Move to beacon payment slot
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if slot.has_stack().await {
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let slot_stack_guard = slot_stack_lock.lock().await;
|
||||
stack_left = slot_stack_guard.clone();
|
||||
drop(slot_stack_guard);
|
||||
|
||||
let mut slot_stack_mut = slot_stack_lock.lock().await;
|
||||
|
||||
if slot_index == 0 {
|
||||
// Move from the single beacon slot to the player inventory (slots 1 to end)
|
||||
if !self
|
||||
.insert_item(
|
||||
&mut slot_stack_mut,
|
||||
1,
|
||||
self.get_behaviour().slots.len() as i32,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else {
|
||||
// Move from player inventory into the beacon payment slot (slot 0)
|
||||
if !self.insert_item(&mut slot_stack_mut, 0, 1, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if slot_stack_mut.is_empty() {
|
||||
drop(slot_stack_mut);
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
drop(slot_stack_mut);
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
//! Brewing stand screen handler.
|
||||
//!
|
||||
//! This module implements the screen handler for brewing stands.
|
||||
//! Brewing stands have 5 slots:
|
||||
//! - Slots 0-2: Potion bottles (output/input)
|
||||
//! - Slot 3: Brewing ingredient
|
||||
//! - Slot 4: Fuel (blaze powder)
|
||||
//!
|
||||
//! The brewing stand has two tracked properties:
|
||||
//! - Brew time (0-400): Progress of the current brewing operation
|
||||
//! - Fuel time (0-20): Amount of fuel remaining
|
||||
|
||||
use std::{any::Any, pin::Pin, sync::Arc};
|
||||
|
||||
use pumpkin_data::tag::Taggable;
|
||||
use pumpkin_data::{screen::WindowType, tag};
|
||||
use pumpkin_world::{block::entities::PropertyDelegate, inventory::Inventory};
|
||||
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{ScreenHandler, ScreenHandlerBehaviour, ScreenHandlerFuture, ScreenProperty},
|
||||
};
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
|
||||
/// Screen handler for the brewing stand.
|
||||
///
|
||||
/// Manages the brewing stand's 5 slots and tracks brewing progress
|
||||
/// and fuel levels.
|
||||
pub struct BrewingScreenHandler {
|
||||
/// The brewing stand's inventory (5 slots: 0-2 potions, 3 ingredient, 4 fuel).
|
||||
inventory: Arc<dyn Inventory>,
|
||||
/// Core screen handler behavior (slots, sync ID, listeners).
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
/// Delegate for accessing brew time and fuel time properties.
|
||||
///
|
||||
/// Property 0: Brew time (0-400), Property 1: Fuel time (0-20).
|
||||
_property_delegate: Arc<dyn PropertyDelegate>,
|
||||
}
|
||||
|
||||
impl BrewingScreenHandler {
|
||||
/// Creates a new brewing stand screen handler.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `sync_id` - The sync ID for client-server matching
|
||||
/// - `player_inventory` - The player's inventory
|
||||
/// - `inventory` - The brewing stand's inventory (5 slots)
|
||||
/// - `property_delegate` - Delegate for accessing brew time and fuel properties
|
||||
pub async fn new(
|
||||
sync_id: u8,
|
||||
player_inventory: Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
property_delegate: Arc<dyn PropertyDelegate>,
|
||||
) -> Self {
|
||||
struct BrewingScreenListener;
|
||||
impl crate::screen_handler::ScreenHandlerListener for BrewingScreenListener {
|
||||
fn on_property_update<'a>(
|
||||
&'a self,
|
||||
screen_handler: &'a ScreenHandlerBehaviour,
|
||||
property: u8,
|
||||
value: i32,
|
||||
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
if let Some(sync_handler) = screen_handler.sync_handler.as_ref() {
|
||||
sync_handler
|
||||
.update_property(screen_handler, i32::from(property), value)
|
||||
.await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let mut handler = Self {
|
||||
inventory,
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(WindowType::BrewingStand)),
|
||||
_property_delegate: property_delegate.clone(),
|
||||
};
|
||||
|
||||
// BrewTime (index 0) and Fuel (index 1)
|
||||
handler.add_property(ScreenProperty::new(property_delegate.clone(), 0));
|
||||
handler.add_property(ScreenProperty::new(property_delegate.clone(), 1));
|
||||
|
||||
handler.add_listener(Arc::new(BrewingScreenListener)).await;
|
||||
|
||||
// Add all 5 brewing stand slots: 0-2 = potions, 3 = ingredient, 4 = fuel
|
||||
for i in 0..5 {
|
||||
handler.add_slot(Arc::new(crate::slot::NormalSlot::new(
|
||||
handler.inventory.clone(),
|
||||
i,
|
||||
)));
|
||||
}
|
||||
|
||||
// Add player slots
|
||||
let pi: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&pi);
|
||||
|
||||
handler
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for BrewingScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(
|
||||
&'a mut self,
|
||||
player: &'a dyn crate::screen_handler::InventoryPlayer,
|
||||
) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move { self.default_on_closed(player).await })
|
||||
}
|
||||
|
||||
/// Quick move logic for brewing stand.
|
||||
///
|
||||
/// - Potions (0-2) -> Player inventory
|
||||
/// - Ingredient (3) -> Player inventory
|
||||
/// - Fuel (4) -> Player inventory
|
||||
/// - From player: potions -> potion slots, fuel -> fuel slot, else -> ingredient slot
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn crate::screen_handler::InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> Pin<Box<dyn Future<Output = ItemStack> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if !slot.has_stack().await {
|
||||
return stack_left;
|
||||
}
|
||||
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let mut stack = slot_stack_lock.lock().await;
|
||||
stack_left = stack.clone();
|
||||
|
||||
let success = if slot_index < 5 {
|
||||
// Moving from brewing stand to player inventory
|
||||
self.insert_item(&mut stack, 5, self.get_behaviour().slots.len() as i32, true)
|
||||
.await
|
||||
} else {
|
||||
// Moving from player inventory to brewing stand
|
||||
// Check item type to determine target slot
|
||||
|
||||
// Check if item has potion contents (for slots 0-2)
|
||||
let has_potion_contents = stack
|
||||
.get_data_component::<pumpkin_data::data_component_impl::PotionContentsImpl>()
|
||||
.is_some();
|
||||
|
||||
// Check if item is brewing fuel (for slot 4)
|
||||
let is_fuel = stack.get_item().has_tag(&tag::Item::MINECRAFT_BREWING_FUEL);
|
||||
|
||||
if has_potion_contents {
|
||||
// Try to insert into potion slots (0-2)
|
||||
self.insert_item(&mut stack, 0, 3, false).await
|
||||
} else if is_fuel {
|
||||
// Try to insert into fuel slot (4)
|
||||
self.insert_item(&mut stack, 4, 5, false).await
|
||||
} else {
|
||||
// Try to insert into ingredient slot (3)
|
||||
self.insert_item(&mut stack, 3, 4, false).await
|
||||
}
|
||||
};
|
||||
|
||||
if !success {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
|
||||
if stack.is_empty() {
|
||||
drop(stack);
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new brewing stand screen handler.
|
||||
///
|
||||
/// Factory function used by the server when a player opens a brewing stand.
|
||||
pub async fn create_brewing(
|
||||
sync_id: u8,
|
||||
player_inventory: Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
property_delegate: Arc<dyn PropertyDelegate>,
|
||||
) -> Option<impl ScreenHandler> {
|
||||
let handler =
|
||||
BrewingScreenHandler::new(sync_id, player_inventory, inventory, property_delegate).await;
|
||||
Some(handler)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Brewing module.
|
||||
//!
|
||||
//! This module handles the brewing stand mechanics:
|
||||
//! - [`BrewingStandScreenHandler`] - Screen handler for the brewing stand UI
|
||||
//!
|
||||
//! The brewing stand allows players to brew potions by combining water bottles
|
||||
//! with various ingredients.
|
||||
|
||||
pub mod brewing_screen_handler;
|
||||
|
||||
pub use brewing_screen_handler::create_brewing;
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Container click handling.
|
||||
//!
|
||||
//! This module processes inventory click packets from the client and converts
|
||||
//! them into structured click events. It handles all click types:
|
||||
//! - Mouse clicks (left/right)
|
||||
//! - Shift-clicks
|
||||
//! - Hotbar key presses
|
||||
//! - Drop actions (Q key or clicking outside)
|
||||
//! - Drag operations (click and drag across slots)
|
||||
//! - Double-clicks (pickup all)
|
||||
//!
|
||||
//! # Click Types
|
||||
//!
|
||||
//! The client sends a mode and button value that are decoded into
|
||||
//! [`ClickType`] variants. See the Minecraft protocol documentation
|
||||
//! for packet format details.
|
||||
|
||||
use crate::InventoryError;
|
||||
use pumpkin_protocol::java::server::play::SlotActionType;
|
||||
|
||||
/// A parsed container click event.
|
||||
///
|
||||
/// Contains the slot being clicked and the type of click action.
|
||||
#[derive(Debug)]
|
||||
pub struct Click {
|
||||
/// The slot being clicked (or outside the inventory).
|
||||
pub slot: Slot,
|
||||
/// The type of click action (mouse click, shift-click, drag, etc.).
|
||||
pub click_type: ClickType,
|
||||
}
|
||||
|
||||
/// Button values for normal mouse clicks.
|
||||
const BUTTON_CLICK_LEFT: i8 = 0;
|
||||
const BUTTON_CLICK_RIGHT: i8 = 1;
|
||||
|
||||
/// Key code for offhand swap (F key by default).
|
||||
const KEY_CLICK_OFFHAND: i8 = 40;
|
||||
|
||||
/// Hotbar slot key range (1-9 keys).
|
||||
const KEY_CLICK_HOTBAR_START: i8 = 0;
|
||||
const KEY_CLICK_HOTBAR_END: i8 = 9;
|
||||
|
||||
/// Slot index indicating a click outside the inventory.
|
||||
const SLOT_INDEX_OUTSIDE: i16 = -999;
|
||||
|
||||
impl Click {
|
||||
/// Parses a slot action into a click event.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `mode` - The action type from the protocol
|
||||
/// - `button` - The button value from the protocol
|
||||
/// - `slot` - The slot index (-999 for outside)
|
||||
///
|
||||
/// # Returns
|
||||
/// The parsed click or an error if invalid.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`InventoryError::InvalidSlot`] or [`InventoryError::InvalidPacket`]
|
||||
/// for malformed input.
|
||||
pub fn new(mode: &SlotActionType, button: i8, slot: i16) -> Result<Self, InventoryError> {
|
||||
match mode {
|
||||
SlotActionType::Pickup => Self::new_normal_click(button, slot),
|
||||
// Both buttons do the same here, so we omit it
|
||||
SlotActionType::QuickMove => Self::new_shift_click(slot),
|
||||
SlotActionType::Swap => Self::new_key_click(button, slot),
|
||||
SlotActionType::Clone => Ok(Self {
|
||||
click_type: ClickType::CreativePickItem,
|
||||
slot: Slot::Normal(slot.try_into().or(Err(InventoryError::InvalidSlot))?),
|
||||
}),
|
||||
SlotActionType::Throw => Self::new_drop_item(button, slot),
|
||||
SlotActionType::QuickCraft => Self::new_drag_item(button, slot),
|
||||
SlotActionType::PickupAll => Ok(Self {
|
||||
click_type: ClickType::DoubleClick,
|
||||
slot: Slot::Normal(slot.try_into().or(Err(InventoryError::InvalidSlot))?),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_normal_click(button: i8, slot: i16) -> Result<Self, InventoryError> {
|
||||
let slot = if slot == SLOT_INDEX_OUTSIDE {
|
||||
Slot::OutsideInventory
|
||||
} else {
|
||||
let slot = slot.try_into().unwrap_or(0);
|
||||
Slot::Normal(slot)
|
||||
};
|
||||
let button = match button {
|
||||
BUTTON_CLICK_LEFT => MouseClick::Left,
|
||||
BUTTON_CLICK_RIGHT => MouseClick::Right,
|
||||
_ => Err(InventoryError::InvalidPacket)?,
|
||||
};
|
||||
Ok(Self {
|
||||
click_type: ClickType::MouseClick(button),
|
||||
slot,
|
||||
})
|
||||
}
|
||||
|
||||
fn new_shift_click(slot: i16) -> Result<Self, InventoryError> {
|
||||
Ok(Self {
|
||||
slot: Slot::Normal(slot.try_into().or(Err(InventoryError::InvalidSlot))?),
|
||||
click_type: ClickType::ShiftClick,
|
||||
})
|
||||
}
|
||||
|
||||
fn new_key_click(button: i8, slot: i16) -> Result<Self, InventoryError> {
|
||||
let key = match button {
|
||||
KEY_CLICK_HOTBAR_START..KEY_CLICK_HOTBAR_END => {
|
||||
KeyClick::Slot(button.try_into().or(Err(InventoryError::InvalidSlot))?)
|
||||
}
|
||||
KEY_CLICK_OFFHAND => KeyClick::Offhand,
|
||||
_ => Err(InventoryError::InvalidSlot)?,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
click_type: ClickType::KeyClick(key),
|
||||
slot: Slot::Normal(slot.try_into().or(Err(InventoryError::InvalidSlot))?),
|
||||
})
|
||||
}
|
||||
|
||||
fn new_drop_item(button: i8, slot: i16) -> Result<Self, InventoryError> {
|
||||
let drop_type = DropType::from_i8(button)?;
|
||||
let slot = if slot == SLOT_INDEX_OUTSIDE {
|
||||
Slot::OutsideInventory
|
||||
} else {
|
||||
let slot = slot.try_into().unwrap_or(0);
|
||||
Slot::Normal(slot)
|
||||
};
|
||||
Ok(Self {
|
||||
click_type: ClickType::DropType(drop_type),
|
||||
slot,
|
||||
})
|
||||
}
|
||||
|
||||
fn new_drag_item(button: i8, slot: i16) -> Result<Self, InventoryError> {
|
||||
let state = match button {
|
||||
0 => MouseDragState::Start(MouseDragType::Left),
|
||||
4 => MouseDragState::Start(MouseDragType::Right),
|
||||
8 => MouseDragState::Start(MouseDragType::Middle),
|
||||
1 | 5 | 9 => {
|
||||
MouseDragState::AddSlot(slot.try_into().or(Err(InventoryError::InvalidSlot))?)
|
||||
}
|
||||
2 | 6 | 10 => MouseDragState::End,
|
||||
_ => Err(InventoryError::InvalidPacket)?,
|
||||
};
|
||||
Ok(Self {
|
||||
slot: match &state {
|
||||
MouseDragState::AddSlot(slot) => Slot::Normal(*slot),
|
||||
_ => Slot::OutsideInventory,
|
||||
},
|
||||
click_type: ClickType::MouseDrag { drag_state: state },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of click action.
|
||||
#[derive(Debug)]
|
||||
pub enum ClickType {
|
||||
/// Normal mouse click (left or right).
|
||||
MouseClick(MouseClick),
|
||||
/// Shift-click to quick-move an item.
|
||||
ShiftClick,
|
||||
/// Hotbar key press (1-9 or offhand swap).
|
||||
KeyClick(KeyClick),
|
||||
/// Creative mode middle-click (pick block).
|
||||
CreativePickItem,
|
||||
/// Drop item (Q key or drop click).
|
||||
DropType(DropType),
|
||||
/// Drag items across multiple slots.
|
||||
MouseDrag { drag_state: MouseDragState },
|
||||
/// Double-click to gather items.
|
||||
DoubleClick,
|
||||
}
|
||||
|
||||
/// Normal mouse button clicks.
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub enum MouseClick {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Hotbar key clicks.
|
||||
#[derive(Debug)]
|
||||
pub enum KeyClick {
|
||||
/// Hotbar slot index (0-8).
|
||||
Slot(u8),
|
||||
/// Swap with offhand.
|
||||
Offhand,
|
||||
}
|
||||
|
||||
/// A slot reference - either a specific slot or outside the inventory.
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum Slot {
|
||||
Normal(usize),
|
||||
OutsideInventory,
|
||||
}
|
||||
|
||||
/// Drop action types.
|
||||
#[derive(Debug)]
|
||||
pub enum DropType {
|
||||
/// Drop a single item (Ctrl+Q).
|
||||
SingleItem,
|
||||
/// Drop the full stack (Q).
|
||||
FullStack,
|
||||
}
|
||||
|
||||
impl DropType {
|
||||
const fn from_i8(value: i8) -> Result<Self, InventoryError> {
|
||||
Ok(match value {
|
||||
0 => Self::SingleItem,
|
||||
1 => Self::FullStack,
|
||||
_ => return Err(InventoryError::InvalidPacket),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Mouse drag button types.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum MouseDragType {
|
||||
/// Left button drag - even distribution.
|
||||
Left,
|
||||
/// Right button drag - one item per slot.
|
||||
Right,
|
||||
/// Middle button drag - create full stacks (creative only).
|
||||
Middle,
|
||||
}
|
||||
|
||||
/// Drag operation state.
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
pub enum MouseDragState {
|
||||
/// Start of drag - button determines drag type.
|
||||
Start(MouseDragType),
|
||||
/// Adding a slot to the drag.
|
||||
AddSlot(usize),
|
||||
/// End of drag - apply to all selected slots.
|
||||
End,
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Crafting inventory implementation.
|
||||
//!
|
||||
//! This module provides a temporary inventory for crafting grids.
|
||||
//! Crafting inventories are used for:
|
||||
//! - The 2x2 crafting grid in the player inventory
|
||||
//! - The 3x3 crafting grid in crafting tables
|
||||
//! - Other recipe-based crafting mechanisms
|
||||
//!
|
||||
//! Unlike regular inventories, crafting grids are typically cleared when
|
||||
//! the container closes, and their contents are used up when crafting.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::{any::Any, pin::Pin};
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_world::inventory::split_stack;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use pumpkin_world::inventory::{Clearable, Inventory, InventoryFuture};
|
||||
|
||||
use super::recipes::RecipeInputInventory;
|
||||
|
||||
/// A temporary inventory for crafting grids.
|
||||
///
|
||||
/// Crafting inventories hold items arranged in a grid pattern for crafting recipes.
|
||||
/// The grid dimensions can vary (2x2 for player inventory, 3x3 for crafting table).
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// When a player places items in the crafting grid, they are stored here.
|
||||
/// When the crafting result is taken, the ingredients are consumed from this inventory.
|
||||
#[derive(Clone)]
|
||||
pub struct CraftingInventory {
|
||||
/// Width of the crafting grid (typically 2 or 3).
|
||||
pub width: u8,
|
||||
/// Height of the crafting grid (typically 2 or 3).
|
||||
pub height: u8,
|
||||
/// Items in the crafting grid, stored row by row.
|
||||
pub items: Vec<Arc<Mutex<ItemStack>>>,
|
||||
}
|
||||
|
||||
impl CraftingInventory {
|
||||
/// Creates a new crafting inventory with the given dimensions.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `width` - Grid width (e.g., 2 for player crafting, 3 for crafting table)
|
||||
/// - `height` - Grid height (e.g., 2 for player crafting, 3 for crafting table)
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// // 2x2 player inventory crafting grid
|
||||
/// let player_crafting = CraftingInventory::new(2, 2);
|
||||
///
|
||||
/// // 3x3 crafting table grid
|
||||
/// let table_crafting = CraftingInventory::new(3, 3);
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn new(width: u8, height: u8) -> Self {
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
items: {
|
||||
// Creates a Vec with different Mutexes for each slot
|
||||
let mut v = Vec::with_capacity(width as usize * height as usize);
|
||||
(0..width as usize * height as usize)
|
||||
.for_each(|_| v.push(Arc::new(Mutex::new(ItemStack::EMPTY.clone()))));
|
||||
v
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Inventory for CraftingInventory {
|
||||
fn size(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> InventoryFuture<'_, bool> {
|
||||
Box::pin(async move {
|
||||
for slot in &self.items {
|
||||
if !slot.lock().await.is_empty() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
fn get_stack(&self, slot: usize) -> InventoryFuture<'_, Arc<Mutex<ItemStack>>> {
|
||||
Box::pin(async move { self.items[slot].clone() })
|
||||
}
|
||||
|
||||
fn remove_stack(&self, slot: usize) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
let mut removed = ItemStack::EMPTY.clone();
|
||||
let mut guard = self.items[slot].lock().await;
|
||||
std::mem::swap(&mut removed, &mut *guard);
|
||||
removed
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_stack_specific(&self, slot: usize, amount: u8) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move { split_stack(&self.items, slot, amount).await })
|
||||
}
|
||||
|
||||
fn set_stack(&self, slot: usize, stack: ItemStack) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
*self.items[slot].lock().await = stack;
|
||||
})
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RecipeInputInventory for CraftingInventory {
|
||||
fn get_width(&self) -> usize {
|
||||
self.width as usize
|
||||
}
|
||||
|
||||
fn get_height(&self) -> usize {
|
||||
self.height as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl Clearable for CraftingInventory {
|
||||
fn clear(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
for item in &self.items {
|
||||
*item.lock().await = ItemStack::EMPTY.clone();
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,670 @@
|
||||
//! Crafting screen handler implementation.
|
||||
//!
|
||||
//! This module provides screen handlers for crafting mechanics:
|
||||
//! - [`CraftingScreenHandler`] - Trait for crafting screen handlers
|
||||
//! - [`CraftingTableScreenHandler`] - The 3x3 crafting table UI
|
||||
//! - [`ResultSlot`] - The special result slot that shows crafted items
|
||||
//!
|
||||
//! # Recipe Matching
|
||||
//!
|
||||
//! Crafting recipes are matched against the items in the crafting grid.
|
||||
//! The system supports:
|
||||
//! - Shaped recipes (specific patterns)
|
||||
//! - Shapeless recipes (any arrangement)
|
||||
//! - Transmute recipes (upgrading items)
|
||||
//! - Special recipes (like decorated pots)
|
||||
|
||||
use std::any::Any;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
|
||||
use super::recipe_provider::{GenericRecipe, RecipeProvider};
|
||||
use super::recipes::{RecipeFinderScreenHandler, RecipeInputInventory};
|
||||
use crate::crafting::crafting_inventory::CraftingInventory;
|
||||
use crate::player::player_inventory::PlayerInventory;
|
||||
use crate::screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour, ScreenHandlerFuture,
|
||||
ScreenHandlerListener,
|
||||
};
|
||||
use crate::slot::{BoxFuture, NormalSlot, Slot};
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::recipes::{CraftingRecipeTypes, RECIPES_CRAFTING};
|
||||
use pumpkin_data::screen::WindowType;
|
||||
use pumpkin_data::statistic::StatisticCategory;
|
||||
use pumpkin_data::tag;
|
||||
use pumpkin_data::tag::Taggable;
|
||||
use pumpkin_protocol::codec::recipe::{DynamicRecipe, OwnedCraftingRecipe};
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// The result slot in a crafting screen.
|
||||
pub struct ResultSlot {
|
||||
/// The crafting inventory (grid) that provides recipe input.
|
||||
pub inventory: Arc<dyn RecipeInputInventory>,
|
||||
/// Protocol ID for this slot (assigned by screen handler).
|
||||
pub id: AtomicU8,
|
||||
/// The cached result item stack.
|
||||
pub result: Arc<Mutex<ItemStack>>,
|
||||
/// Provider for dynamic recipes.
|
||||
pub recipe_provider: Option<Arc<dyn RecipeProvider>>,
|
||||
}
|
||||
|
||||
pub struct RecipeResult {
|
||||
pub item_id: String,
|
||||
pub count: u8,
|
||||
}
|
||||
|
||||
/// Checks if a recipe pattern is symmetrical horizontally.
|
||||
fn is_symmetrical_horizontally(pattern: &[&str]) -> bool {
|
||||
let width = pattern.first().map_or(0, |s| s.len());
|
||||
for row in pattern {
|
||||
if row.len() != width {
|
||||
return false;
|
||||
}
|
||||
for j in 0..width / 2 {
|
||||
if row.chars().nth(j) != row.chars().nth(width - j - 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Checks if a crafting recipe matches the current inventory state.
|
||||
#[expect(clippy::too_many_lines)]
|
||||
async fn recipe_matches(
|
||||
recipe: GenericRecipe<'_>,
|
||||
input_height: usize,
|
||||
input_width: usize,
|
||||
top_x: usize,
|
||||
top_y: usize,
|
||||
count: usize,
|
||||
inventory: &dyn RecipeInputInventory,
|
||||
) -> Option<RecipeResult> {
|
||||
match recipe {
|
||||
GenericRecipe::Vanilla(CraftingRecipeTypes::CraftingShaped {
|
||||
key,
|
||||
pattern,
|
||||
result,
|
||||
..
|
||||
}) => {
|
||||
if pattern.len() != input_height || pattern.first().unwrap().len() != input_width {
|
||||
return None;
|
||||
}
|
||||
|
||||
if count
|
||||
!= pattern
|
||||
.iter()
|
||||
.map(|l| l.chars().filter(|c| *c != ' ').count())
|
||||
.sum::<usize>()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let x_offset = top_x;
|
||||
let y_offset = top_y;
|
||||
|
||||
let mut matched = true;
|
||||
'outer: for (y, row_str) in pattern.iter().enumerate() {
|
||||
for (x, current_key) in row_str.chars().enumerate() {
|
||||
let slot = inventory
|
||||
.get_stack((y + y_offset) * inventory.get_width() + (x + x_offset))
|
||||
.await;
|
||||
if current_key == ' ' {
|
||||
if !slot.lock().await.is_empty() {
|
||||
matched = false;
|
||||
break 'outer;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let ingredient = key
|
||||
.iter()
|
||||
.find_map(|(k, v)| (*k == current_key).then_some(v))
|
||||
.expect("Crafting recipe used invalid key");
|
||||
|
||||
let slot = slot.lock().await;
|
||||
|
||||
if !ingredient.match_item(slot.item) {
|
||||
matched = false;
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !matched && !is_symmetrical_horizontally(pattern) {
|
||||
matched = true;
|
||||
'outer: for y in 0..pattern.len() {
|
||||
for x in 0..pattern[y].len() {
|
||||
let current_key = pattern[y].chars().nth(x).unwrap();
|
||||
let slot = inventory
|
||||
.get_stack(
|
||||
(y + y_offset) * inventory.get_height()
|
||||
+ (x_offset + input_width - 1 - x),
|
||||
)
|
||||
.await;
|
||||
if current_key == ' ' {
|
||||
if !slot.lock().await.is_empty() {
|
||||
matched = false;
|
||||
break 'outer;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let ingredient = key
|
||||
.iter()
|
||||
.find_map(|(k, v)| (*k == current_key).then_some(v))
|
||||
.expect("Crafting recipe used invalid key");
|
||||
let slot = slot.lock().await;
|
||||
if !ingredient.match_item(slot.item) {
|
||||
matched = false;
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
matched.then_some(RecipeResult {
|
||||
item_id: result.id.to_string(),
|
||||
count: result.count,
|
||||
})
|
||||
}
|
||||
GenericRecipe::Vanilla(CraftingRecipeTypes::CraftingShapeless {
|
||||
ingredients,
|
||||
result,
|
||||
..
|
||||
}) => {
|
||||
if count != ingredients.len() {
|
||||
return None;
|
||||
}
|
||||
let mut ingredient_used = vec![false; ingredients.len()];
|
||||
'next_slot: for i in 0..inventory.size() {
|
||||
let slot = inventory.get_stack(i).await;
|
||||
let slot = slot.lock().await;
|
||||
if slot.is_empty() {
|
||||
continue 'next_slot;
|
||||
}
|
||||
for i in 0..ingredients.len() {
|
||||
if !ingredient_used[i] && ingredients[i].match_item(slot.item) {
|
||||
ingredient_used[i] = true;
|
||||
continue 'next_slot;
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
Some(RecipeResult {
|
||||
item_id: result.id.to_string(),
|
||||
count: result.count,
|
||||
})
|
||||
}
|
||||
GenericRecipe::Vanilla(CraftingRecipeTypes::CraftingTransmute {
|
||||
input,
|
||||
material,
|
||||
result,
|
||||
..
|
||||
}) => {
|
||||
if count != 2 {
|
||||
return None;
|
||||
}
|
||||
'item_stack: for i in 0..inventory.size() {
|
||||
let slot = inventory.get_stack(i).await;
|
||||
let slot = slot.lock().await;
|
||||
if slot.is_empty() {
|
||||
continue 'item_stack;
|
||||
}
|
||||
if !material.match_item(slot.item) && !input.match_item(slot.item) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(RecipeResult {
|
||||
item_id: result.id.to_string(),
|
||||
count: result.count,
|
||||
})
|
||||
}
|
||||
GenericRecipe::Vanilla(CraftingRecipeTypes::CraftingDecoratedPot { .. }) => {
|
||||
if count != 4 || inventory.get_width() != 3 || inventory.get_height() != 3 {
|
||||
return None;
|
||||
}
|
||||
for position in (1..=7).step_by(2) {
|
||||
let slot = inventory.get_stack(position).await;
|
||||
let slot = slot.lock().await;
|
||||
if slot.is_empty()
|
||||
|| !slot
|
||||
.item
|
||||
.has_tag(&tag::Item::MINECRAFT_DECORATED_POT_INGREDIENTS)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(RecipeResult {
|
||||
item_id: "minecraft:decorated_pot".to_string(),
|
||||
count: 1,
|
||||
})
|
||||
}
|
||||
GenericRecipe::Dynamic(OwnedCraftingRecipe::Shaped {
|
||||
pattern,
|
||||
key,
|
||||
result,
|
||||
..
|
||||
}) => {
|
||||
if pattern.len() != input_height || pattern.first().unwrap().len() != input_width {
|
||||
return None;
|
||||
}
|
||||
if count
|
||||
!= pattern
|
||||
.iter()
|
||||
.map(|l| l.chars().filter(|c| *c != ' ').count())
|
||||
.sum::<usize>()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let x_offset = top_x;
|
||||
let y_offset = top_y;
|
||||
let mut matched = true;
|
||||
'outer: for (y, row_str) in pattern.iter().enumerate() {
|
||||
for (x, current_key) in row_str.chars().enumerate() {
|
||||
let slot = inventory
|
||||
.get_stack((y + y_offset) * inventory.get_width() + (x + x_offset))
|
||||
.await;
|
||||
if current_key == ' ' {
|
||||
if !slot.lock().await.is_empty() {
|
||||
matched = false;
|
||||
break 'outer;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let ingredient = key
|
||||
.iter()
|
||||
.find(|(k, _)| *k == current_key)
|
||||
.map(|(_, v)| v)
|
||||
.expect("Crafting recipe used invalid key");
|
||||
let slot = slot.lock().await;
|
||||
if !ingredient.match_item(slot.item) {
|
||||
matched = false;
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
matched.then_some(RecipeResult {
|
||||
item_id: result.item_id.clone(),
|
||||
count: result.count,
|
||||
})
|
||||
}
|
||||
GenericRecipe::Dynamic(OwnedCraftingRecipe::Shapeless {
|
||||
ingredients,
|
||||
result,
|
||||
..
|
||||
}) => {
|
||||
if count != ingredients.len() {
|
||||
return None;
|
||||
}
|
||||
let mut ingredient_used = vec![false; ingredients.len()];
|
||||
'next_slot: for i in 0..inventory.size() {
|
||||
let slot = inventory.get_stack(i).await;
|
||||
let slot = slot.lock().await;
|
||||
if slot.is_empty() {
|
||||
continue 'next_slot;
|
||||
}
|
||||
for i in 0..ingredients.len() {
|
||||
if !ingredient_used[i] && ingredients[i].match_item(slot.item) {
|
||||
ingredient_used[i] = true;
|
||||
continue 'next_slot;
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
Some(RecipeResult {
|
||||
item_id: result.item_id.clone(),
|
||||
count: result.count,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl ResultSlot {
|
||||
pub fn new(
|
||||
inventory: Arc<dyn RecipeInputInventory>,
|
||||
provider: Option<Arc<dyn RecipeProvider>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
id: AtomicU8::new(0),
|
||||
result: Arc::new(Mutex::new(ItemStack::EMPTY.clone())),
|
||||
recipe_provider: provider,
|
||||
}
|
||||
}
|
||||
|
||||
async fn match_recipe(&self) -> Option<RecipeResult> {
|
||||
let mut count: usize = 0;
|
||||
let inventory_width = self.inventory.get_width();
|
||||
let mut top_x = 9;
|
||||
let mut top_y = 9;
|
||||
let mut bottom_x = 0;
|
||||
let mut bottom_y = 0;
|
||||
for i in 0..self.inventory.size() {
|
||||
let x = i % inventory_width;
|
||||
let y = i / inventory_width;
|
||||
let slot = self.inventory.get_stack(i).await;
|
||||
let slot = slot.lock().await;
|
||||
if !slot.is_empty() {
|
||||
top_x = top_x.min(x);
|
||||
top_y = top_y.min(y);
|
||||
bottom_x = bottom_x.max(x);
|
||||
bottom_y = bottom_y.max(y);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return None;
|
||||
}
|
||||
let input_width = bottom_x + 1 - top_x;
|
||||
let input_height = bottom_y + 1 - top_y;
|
||||
|
||||
for recipe in RECIPES_CRAFTING {
|
||||
if let Some(result) = recipe_matches(
|
||||
GenericRecipe::Vanilla(recipe),
|
||||
input_height,
|
||||
input_width,
|
||||
top_x,
|
||||
top_y,
|
||||
count,
|
||||
&*self.inventory,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Some(result);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(provider) = &self.recipe_provider {
|
||||
let dynamic = provider.get_dynamic_recipes().await;
|
||||
for recipe in &dynamic {
|
||||
if let DynamicRecipe::Crafting(crafting) = recipe
|
||||
&& let Some(result) = recipe_matches(
|
||||
GenericRecipe::Dynamic(crafting),
|
||||
input_height,
|
||||
input_width,
|
||||
top_x,
|
||||
top_y,
|
||||
count,
|
||||
&*self.inventory,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Some(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn refill_output(&self) -> ItemStack {
|
||||
let result = if let Some(matched) = self.match_recipe().await {
|
||||
let key = matched
|
||||
.item_id
|
||||
.strip_prefix("minecraft:")
|
||||
.unwrap_or(&matched.item_id);
|
||||
let item = pumpkin_data::item::Item::from_registry_key(key)
|
||||
.unwrap_or(&pumpkin_data::item::Item::AIR);
|
||||
ItemStack::new(matched.count, item)
|
||||
} else {
|
||||
ItemStack::EMPTY.clone()
|
||||
};
|
||||
*self.result.lock().await = result.clone();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Slot for ResultSlot {
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory> {
|
||||
self.inventory.clone()
|
||||
}
|
||||
fn get_index(&self) -> usize {
|
||||
999
|
||||
}
|
||||
fn set_id(&self, id: usize) {
|
||||
self.id.store(id as u8, Ordering::Relaxed);
|
||||
}
|
||||
fn on_quick_move_crafted(
|
||||
&self,
|
||||
_stack: ItemStack,
|
||||
_stack_prev: ItemStack,
|
||||
) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.refill_output().await;
|
||||
})
|
||||
}
|
||||
fn on_take_item<'a>(
|
||||
&'a self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
stack: &'a ItemStack,
|
||||
) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
player
|
||||
.increment_stat(
|
||||
StatisticCategory::Crafted,
|
||||
stack.item.id as i32,
|
||||
stack.item_count as i32,
|
||||
)
|
||||
.await;
|
||||
for i in 0..self.inventory.size() {
|
||||
let slot = self.inventory.get_stack(i).await;
|
||||
let mut stack = slot.lock().await;
|
||||
if !stack.is_empty() {
|
||||
stack.item_count -= 1;
|
||||
}
|
||||
}
|
||||
self.mark_dirty().await;
|
||||
})
|
||||
}
|
||||
fn can_insert(&self, _stack: &ItemStack) -> BoxFuture<'_, bool> {
|
||||
Box::pin(async move { false })
|
||||
}
|
||||
fn get_stack(&self) -> BoxFuture<'_, Arc<Mutex<ItemStack>>> {
|
||||
Box::pin(async move { self.result.clone() })
|
||||
}
|
||||
fn get_cloned_stack(&self) -> BoxFuture<'_, ItemStack> {
|
||||
Box::pin(async move { self.result.lock().await.clone() })
|
||||
}
|
||||
fn has_stack(&self) -> BoxFuture<'_, bool> {
|
||||
Box::pin(async move { !self.result.lock().await.is_empty() })
|
||||
}
|
||||
fn set_stack(&self, _stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.refill_output().await;
|
||||
})
|
||||
}
|
||||
fn set_stack_prev(&self, _stack: ItemStack, _previous_stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.refill_output().await;
|
||||
})
|
||||
}
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.inventory.mark_dirty();
|
||||
})
|
||||
}
|
||||
fn get_max_item_count(&self) -> BoxFuture<'_, u8> {
|
||||
Box::pin(async move {
|
||||
let mut count = u8::MAX;
|
||||
for i in 0..self.inventory.size() {
|
||||
let slot = self.inventory.get_stack(i).await;
|
||||
let slot = slot.lock().await;
|
||||
if !slot.is_empty() {
|
||||
count = count.min(slot.item_count);
|
||||
}
|
||||
}
|
||||
count
|
||||
})
|
||||
}
|
||||
fn take_stack(&self, _amount: u8) -> BoxFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
if self.has_stack().await {
|
||||
self.result.lock().await.clone()
|
||||
} else {
|
||||
ItemStack::EMPTY.clone()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandlerListener for ResultSlot {
|
||||
fn on_slot_update<'a>(
|
||||
&'a self,
|
||||
screen_handler: &'a ScreenHandlerBehaviour,
|
||||
slot: u8,
|
||||
_stack: ItemStack,
|
||||
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
if (0..=(self.inventory.get_width() * self.inventory.get_height()))
|
||||
.contains(&(slot as usize))
|
||||
{
|
||||
let result = self.refill_output().await;
|
||||
let next_revision = screen_handler.next_revision();
|
||||
if let Some(sync_handler) = screen_handler.sync_handler.as_ref() {
|
||||
sync_handler
|
||||
.update_slot(screen_handler, 0, &result, next_revision)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub trait CraftingScreenHandler<I: RecipeInputInventory>:
|
||||
RecipeFinderScreenHandler + ScreenHandler
|
||||
{
|
||||
fn add_recipe_slots<'a>(
|
||||
&'a mut self,
|
||||
crafing_inventory: Arc<dyn RecipeInputInventory>,
|
||||
provider: Option<Arc<dyn RecipeProvider>>,
|
||||
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let result_slot = Arc::new(ResultSlot::new(crafing_inventory.clone(), provider));
|
||||
self.add_slot(result_slot.clone());
|
||||
let width = crafing_inventory.get_width();
|
||||
let height = crafing_inventory.get_height();
|
||||
for i in 0..width {
|
||||
for j in 0..height {
|
||||
let input_slot = NormalSlot::new(crafing_inventory.clone(), j + i * width);
|
||||
self.add_slot(Arc::new(input_slot));
|
||||
}
|
||||
}
|
||||
self.add_listener(result_slot).await;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CraftingTableScreenHandler {
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
crafting_inventory: Arc<dyn RecipeInputInventory>,
|
||||
}
|
||||
|
||||
impl CraftingTableScreenHandler {
|
||||
pub async fn new(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
provider: Option<Arc<dyn RecipeProvider>>,
|
||||
) -> Self {
|
||||
let crafting_inventory: Arc<dyn RecipeInputInventory> =
|
||||
Arc::new(CraftingInventory::new(3, 3));
|
||||
let mut crafting_table_handler = Self {
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(WindowType::Crafting)),
|
||||
crafting_inventory: crafting_inventory.clone(),
|
||||
};
|
||||
crafting_table_handler
|
||||
.add_recipe_slots(crafting_inventory, provider)
|
||||
.await;
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
crafting_table_handler.add_player_slots(&player_inventory);
|
||||
crafting_table_handler
|
||||
}
|
||||
}
|
||||
|
||||
impl RecipeFinderScreenHandler for CraftingTableScreenHandler {}
|
||||
|
||||
impl ScreenHandler for CraftingTableScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
self.drop_inventory(player, self.crafting_inventory.clone())
|
||||
.await;
|
||||
})
|
||||
}
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
if slot.has_stack().await {
|
||||
let slot_stack = slot.get_stack().await;
|
||||
let mut slot_stack = slot_stack.lock().await;
|
||||
let stack_prev = slot_stack.clone();
|
||||
if slot_index == 0 {
|
||||
if !self.insert_item(&mut slot_stack, 10, 46, true).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else if (1..=9).contains(&slot_index) {
|
||||
if !self.insert_item(&mut slot_stack, 10, 46, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else if (10..46).contains(&slot_index) {
|
||||
if !self.insert_item(&mut slot_stack, 1, 10, false).await {
|
||||
if slot_index < 37 {
|
||||
if !self.insert_item(&mut slot_stack, 37, 46, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else if !self.insert_item(&mut slot_stack, 10, 37, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
} else if !self.insert_item(&mut slot_stack, 10, 46, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
let stack = slot_stack.clone();
|
||||
drop(slot_stack);
|
||||
if stack.is_empty() {
|
||||
slot.set_stack_prev(ItemStack::EMPTY.clone(), stack_prev.clone())
|
||||
.await;
|
||||
} else {
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
if stack.item_count == stack_prev.item_count {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
|
||||
let mut taken_stack = stack_prev.clone();
|
||||
taken_stack.set_count(stack_prev.item_count - stack.item_count);
|
||||
slot.on_take_item(player, &taken_stack).await;
|
||||
|
||||
if slot_index == 0 {
|
||||
slot.on_quick_move_crafted(stack.clone(), stack_prev.clone())
|
||||
.await;
|
||||
if !stack.is_empty() {
|
||||
player.drop_item(stack, false).await;
|
||||
}
|
||||
}
|
||||
return stack_prev;
|
||||
}
|
||||
ItemStack::EMPTY.clone()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl CraftingScreenHandler<CraftingInventory> for CraftingTableScreenHandler {}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Crafting module.
|
||||
//!
|
||||
//! This module handles crafting mechanics including:
|
||||
//! - [`CraftingInventory`] - Temporary inventory for crafting slots
|
||||
//! - [`CraftingScreenHandler`] - Screen handler for crafting tables and inventory crafting
|
||||
//! - [`recipes`] - Recipe matching and crafting result calculation
|
||||
|
||||
pub mod crafting_inventory;
|
||||
pub mod crafting_screen_handler;
|
||||
pub mod recipe_provider;
|
||||
pub mod recipes;
|
||||
@@ -0,0 +1,26 @@
|
||||
use crate::slot::BoxFuture;
|
||||
use pumpkin_protocol::codec::recipe::DynamicRecipe;
|
||||
|
||||
pub trait RecipeProvider: Send + Sync {
|
||||
fn get_dynamic_recipes(&self) -> BoxFuture<'_, Vec<DynamicRecipe>>;
|
||||
}
|
||||
|
||||
pub enum GenericRecipe<'a> {
|
||||
Vanilla(&'a pumpkin_data::recipes::CraftingRecipeTypes),
|
||||
Dynamic(&'a pumpkin_protocol::codec::recipe::OwnedCraftingRecipe),
|
||||
}
|
||||
|
||||
pub enum IngredientRef<'a> {
|
||||
Vanilla(&'a pumpkin_data::recipes::RecipeIngredientTypes),
|
||||
Dynamic(&'a pumpkin_protocol::codec::recipe::OwnedRecipeIngredient),
|
||||
}
|
||||
|
||||
impl IngredientRef<'_> {
|
||||
#[must_use]
|
||||
pub fn match_item(&self, item: &pumpkin_data::item::Item) -> bool {
|
||||
match self {
|
||||
Self::Vanilla(v) => v.match_item(item),
|
||||
Self::Dynamic(d) => d.match_item(item),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Recipe-related types and traits.
|
||||
//!
|
||||
//! This module defines the interfaces for recipe handling in crafting systems.
|
||||
//! It provides traits for screen handlers that can find recipes and inventories
|
||||
//! that can serve as recipe input.
|
||||
//!
|
||||
//! # Recipe System
|
||||
//!
|
||||
//! The recipe system involves:
|
||||
//! - [`RecipeFinderScreenHandler`] - Screen handlers that can find matching recipes
|
||||
//! - [`RecipeInputInventory`] - Inventories that provide crafting input
|
||||
//! - [`RecipeMatcher`] - Helper for matching items to recipes
|
||||
//! - [`RecipeFinder`] - Helper for finding recipes
|
||||
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
/// Helper struct for matching recipe ingredients.
|
||||
// RecipeMatcher.java
|
||||
pub struct RecipeMatcher;
|
||||
|
||||
/// Helper struct for finding recipes.
|
||||
// RecipeFinder.java
|
||||
pub struct RecipeFinder;
|
||||
|
||||
/// Trait for screen handlers that can find crafting recipes.
|
||||
///
|
||||
/// Screen handlers implementing this trait can search for recipes
|
||||
/// that match the current input inventory state.
|
||||
// AbstractRecipeScreenHandle.java
|
||||
pub trait RecipeFinderScreenHandler {}
|
||||
|
||||
/// Trait for inventories that serve as recipe input.
|
||||
///
|
||||
/// Crafting grids implement this trait to provide their dimensions
|
||||
/// and item access for recipe matching.
|
||||
pub trait RecipeInputInventory: Inventory {
|
||||
/// Gets the width of the crafting grid.
|
||||
fn get_width(&self) -> usize;
|
||||
|
||||
/// Gets the height of the crafting grid.
|
||||
fn get_height(&self) -> usize;
|
||||
|
||||
// TODO: Additional methods for recipe input handling
|
||||
// fn get_held_stacks(), Get a lock on the inventory instead
|
||||
// createRecipeInput
|
||||
// createPositionedRecipeInput
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Double inventory implementation.
|
||||
//!
|
||||
//! This module provides a composite inventory that combines two inventories
|
||||
//! into one. This is used for large containers like double chests, which
|
||||
//! consist of two single chest inventories viewed as a single 54-slot inventory.
|
||||
//!
|
||||
//! The first inventory's slots come first, followed by the second inventory's
|
||||
//! slots. Operations are delegated to the appropriate underlying inventory
|
||||
//! based on the slot index.
|
||||
|
||||
use std::{any::Any, pin::Pin, sync::Arc};
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_world::inventory::{Clearable, Inventory, InventoryFuture};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// A composite inventory combining two inventories.
|
||||
///
|
||||
/// Used for double chests and other large containers that span
|
||||
/// multiple block entities. The combined inventory size is the sum
|
||||
/// of both inventories' sizes.
|
||||
pub struct DoubleInventory {
|
||||
/// The first inventory (lower slot indices, 0 to first.size()-1).
|
||||
first: Arc<dyn Inventory>,
|
||||
/// The second inventory (higher slot indices, `first.size()` to total-1).
|
||||
second: Arc<dyn Inventory>,
|
||||
}
|
||||
|
||||
impl DoubleInventory {
|
||||
/// Creates a new double inventory.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `first` - The first inventory (lower slot indices)
|
||||
/// - `second` - The second inventory (higher slot indices)
|
||||
///
|
||||
/// # Returns
|
||||
/// A shared reference to the new double inventory.
|
||||
pub fn new(first: Arc<dyn Inventory>, second: Arc<dyn Inventory>) -> Arc<Self> {
|
||||
Arc::new(Self { first, second })
|
||||
}
|
||||
}
|
||||
|
||||
impl Inventory for DoubleInventory {
|
||||
fn size(&self) -> usize {
|
||||
self.first.size() + self.second.size()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> InventoryFuture<'_, bool> {
|
||||
Box::pin(async move { self.first.is_empty().await && self.second.is_empty().await })
|
||||
}
|
||||
|
||||
fn get_stack(&self, slot: usize) -> InventoryFuture<'_, Arc<Mutex<ItemStack>>> {
|
||||
Box::pin(async move {
|
||||
if slot >= self.first.size() {
|
||||
self.second.get_stack(slot - self.first.size()).await
|
||||
} else {
|
||||
self.first.get_stack(slot).await
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_stack(&self, slot: usize) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
if slot >= self.first.size() {
|
||||
self.second.remove_stack(slot - self.first.size()).await
|
||||
} else {
|
||||
self.first.remove_stack(slot).await
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_stack_specific(&self, slot: usize, amount: u8) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
if slot >= self.first.size() {
|
||||
self.second
|
||||
.remove_stack_specific(slot - self.first.size(), amount)
|
||||
.await
|
||||
} else {
|
||||
self.first.remove_stack_specific(slot, amount).await
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn set_stack(&self, slot: usize, stack: ItemStack) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
if slot >= self.first.size() {
|
||||
self.second.set_stack(slot - self.first.size(), stack).await;
|
||||
} else {
|
||||
self.first.set_stack(slot, stack).await;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_open(&self) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.first.on_open().await;
|
||||
self.second.on_open().await;
|
||||
})
|
||||
}
|
||||
|
||||
fn on_close(&self) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.first.on_close().await;
|
||||
self.second.on_close().await;
|
||||
})
|
||||
}
|
||||
|
||||
fn get_max_count_per_stack(&self) -> u8 {
|
||||
self.first.get_max_count_per_stack()
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) {
|
||||
self.first.mark_dirty();
|
||||
self.second.mark_dirty();
|
||||
}
|
||||
|
||||
fn is_valid_slot_for(&self, slot: usize, stack: &ItemStack) -> bool {
|
||||
if slot >= self.first.size() {
|
||||
self.second
|
||||
.is_valid_slot_for(slot - self.first.size(), stack)
|
||||
} else {
|
||||
self.first.is_valid_slot_for(slot, stack)
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Clearable for DoubleInventory {
|
||||
fn clear(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
self.first.clear().await;
|
||||
self.second.clear().await;
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Item drag handler.
|
||||
//!
|
||||
//! This module handles the logic for dragging items across multiple inventory slots.
|
||||
//! When a player clicks and drags with an item, they can distribute it across
|
||||
//! multiple slots.
|
||||
//!
|
||||
//! Drag types:
|
||||
//! - Left click drag - Evenly distributes items across slots
|
||||
//! - Right click drag - Places one item in each slot
|
||||
//! - Middle click drag (creative) - Creates full stacks in each slot (creative only)
|
||||
//!
|
||||
//! Note: This implementation is currently disabled/commented out pending completion.
|
||||
|
||||
/*
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DragHandler(RwLock<HashMap<u64, Arc<Mutex<Drag>>>>);
|
||||
|
||||
impl DragHandler {
|
||||
pub fn new() -> Self {
|
||||
Self(RwLock::new(HashMap::new()))
|
||||
}
|
||||
pub async fn new_drag(
|
||||
&self,
|
||||
container_id: u64,
|
||||
player: i32,
|
||||
drag_type: MouseDragType,
|
||||
) -> Result<(), InventoryError> {
|
||||
let drag = Drag {
|
||||
player,
|
||||
drag_type,
|
||||
slots: vec![],
|
||||
};
|
||||
let mut drags = self.0.write().await;
|
||||
drags.insert(container_id, Arc::new(Mutex::new(drag)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn add_slot(
|
||||
&self,
|
||||
container_id: u64,
|
||||
player: i32,
|
||||
slot: usize,
|
||||
) -> Result<(), InventoryError> {
|
||||
let drags = self.0.read().await;
|
||||
match drags.get(&container_id) {
|
||||
Some(drag) => {
|
||||
let mut drag = drag.lock().await;
|
||||
if drag.player != player {
|
||||
Err(InventoryError::MultiplePlayersDragging)?
|
||||
}
|
||||
if !drag.slots.contains(&slot) {
|
||||
drag.slots.push(slot);
|
||||
}
|
||||
}
|
||||
None => Err(InventoryError::OutOfOrderDragging)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn apply_drag<T: Container>(
|
||||
&self,
|
||||
maybe_carried_item: &mut Option<ItemStack>,
|
||||
container: &mut T,
|
||||
container_id: &u64,
|
||||
player: i32,
|
||||
) -> Result<(), InventoryError> {
|
||||
// The Minecraft client does still send dragging packets when not carrying an item!
|
||||
if maybe_carried_item.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut drags = self.0.write().await;
|
||||
let Some((_, drag)) = drags.remove_entry(container_id) else {
|
||||
Err(InventoryError::OutOfOrderDragging)?
|
||||
};
|
||||
let drag = drag.lock().await;
|
||||
|
||||
if player != drag.player {
|
||||
Err(InventoryError::MultiplePlayersDragging)?
|
||||
}
|
||||
let mut slots = container.all_slots();
|
||||
let Some(carried_item) = maybe_carried_item else {
|
||||
return Ok(());
|
||||
};
|
||||
match drag.drag_type {
|
||||
// This is only valid in the Creative gamemode.
|
||||
// Checked in any function that uses this function.
|
||||
MouseDragType::Middle => {
|
||||
for slot in &drag.slots {
|
||||
*slots[*slot] = maybe_carried_item.clone();
|
||||
}
|
||||
}
|
||||
MouseDragType::Right => {
|
||||
let changing_slots =
|
||||
drag.possibly_changing_slots(slots.as_ref(), carried_item.item.id);
|
||||
changing_slots.into_iter().for_each(|slot| {
|
||||
if carried_item.item_count != 0 {
|
||||
carried_item.item_count -= 1;
|
||||
if let Some(stack) = &mut slots[slot] {
|
||||
// TODO: Check for stack max here
|
||||
if stack.item_count + 1 < stack.item.components.max_stack_size {
|
||||
stack.item_count += 1;
|
||||
} else {
|
||||
carried_item.item_count += 1;
|
||||
}
|
||||
} else {
|
||||
*slots[slot] = Some(ItemStack {
|
||||
item: carried_item.item.clone(),
|
||||
item_count: 1,
|
||||
})
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if carried_item.item_count == 0 {
|
||||
*maybe_carried_item = None
|
||||
}
|
||||
}
|
||||
MouseDragType::Left => {
|
||||
// TODO: Handle dragging a stack with a greater amount than the item allows as max unstackable.
|
||||
// In that specific case, follow `MouseDragType::Right` behaviours instead!
|
||||
|
||||
let changing_slots = drag.possibly_changing_slots(&slots, carried_item.item.id);
|
||||
let amount_of_slots = changing_slots.len();
|
||||
let (amount_per_slot, remainder) = if amount_of_slots == 0 {
|
||||
// TODO: please work lol
|
||||
(1, 0)
|
||||
} else {
|
||||
(
|
||||
carried_item.item_count.div_euclid(amount_of_slots as u8),
|
||||
carried_item.item_count.rem_euclid(amount_of_slots as u8),
|
||||
)
|
||||
};
|
||||
changing_slots.into_iter().for_each(|slot| {
|
||||
if let Some(stack) = slots[slot].as_mut() {
|
||||
debug_assert!(stack.item.id == carried_item.item.id);
|
||||
// TODO: Handle max stack size
|
||||
stack.item_count += amount_per_slot;
|
||||
}
|
||||
});
|
||||
|
||||
if remainder > 0 {
|
||||
carried_item.item_count = remainder;
|
||||
} else {
|
||||
*maybe_carried_item = None
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Drag {
|
||||
player: i32,
|
||||
drag_type: MouseDragType,
|
||||
slots: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Drag {
|
||||
fn possibly_changing_slots(
|
||||
&self,
|
||||
slots: &[&mut Option<ItemStack>],
|
||||
carried_item_id: u16,
|
||||
) -> Box<[usize]> {
|
||||
self.slots
|
||||
.iter()
|
||||
.filter_map(move |slot_index| {
|
||||
let slot = &slots[*slot_index];
|
||||
|
||||
match slot {
|
||||
Some(item_slot) => {
|
||||
if item_slot.item.id == carried_item_id {
|
||||
Some(*slot_index)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
None => Some(*slot_index),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,497 @@
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::Enchantment;
|
||||
use pumpkin_data::data_component_impl::EnchantableImpl;
|
||||
use pumpkin_data::item::Item;
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::screen::WindowType;
|
||||
use pumpkin_data::statistic::{CustomStatistic, StatisticCategory};
|
||||
use pumpkin_data::tag::{Enchantment as EnchantmentTag, Taggable};
|
||||
use pumpkin_util::random::{RandomImpl, legacy_rand::LegacyRand};
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour,
|
||||
ScreenHandlerFuture, offer_or_drop_stack,
|
||||
},
|
||||
slot::{BoxFuture, NormalSlot, Slot},
|
||||
window_property::{EnchantmentTable, WindowProperty},
|
||||
};
|
||||
|
||||
struct LapisSlot(NormalSlot);
|
||||
|
||||
fn is_lapis(stack: &ItemStack) -> bool {
|
||||
stack.item == &Item::LAPIS_LAZULI
|
||||
}
|
||||
|
||||
impl LapisSlot {
|
||||
fn new(inventory: Arc<dyn Inventory>) -> Self {
|
||||
Self(NormalSlot::new(inventory, 1))
|
||||
}
|
||||
}
|
||||
|
||||
impl Slot for LapisSlot {
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory> {
|
||||
self.0.get_inventory()
|
||||
}
|
||||
|
||||
fn get_index(&self) -> usize {
|
||||
self.0.get_index()
|
||||
}
|
||||
|
||||
fn set_id(&self, id: usize) {
|
||||
self.0.set_id(id);
|
||||
}
|
||||
|
||||
fn can_insert<'a>(&'a self, stack: &'a ItemStack) -> BoxFuture<'a, bool> {
|
||||
Box::pin(async move { is_lapis(stack) })
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()> {
|
||||
self.0.mark_dirty()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EnchantingTableScreenHandler {
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
pub level_requirements: [i32; 3],
|
||||
pub enchantment_id: [i32; 3],
|
||||
pub enchantment_level: [i32; 3],
|
||||
pub enchantment_seed: i32,
|
||||
pub bookshelf_count: i32,
|
||||
}
|
||||
|
||||
impl EnchantingTableScreenHandler {
|
||||
pub fn new(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: &Arc<dyn Inventory>,
|
||||
enchantment_seed: i32,
|
||||
bookshelf_count: i32,
|
||||
) -> Self {
|
||||
let mut handler = Self {
|
||||
inventory: inventory.clone(),
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(WindowType::Enchantment)),
|
||||
level_requirements: [0; 3],
|
||||
enchantment_id: [-1; 3],
|
||||
enchantment_level: [-1; 3],
|
||||
enchantment_seed,
|
||||
bookshelf_count,
|
||||
};
|
||||
|
||||
// Enchanting slots: 0 is item, 1 is lapis
|
||||
handler.add_slot(Arc::new(NormalSlot::new(inventory.clone(), 0)));
|
||||
handler.add_slot(Arc::new(LapisSlot::new(inventory.clone())));
|
||||
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&player_inventory);
|
||||
|
||||
handler
|
||||
}
|
||||
|
||||
pub async fn update_enchantments(&mut self, _player: &dyn InventoryPlayer) {
|
||||
let item = self.inventory.get_stack(0).await;
|
||||
let item = item.lock().await;
|
||||
|
||||
if item.is_empty() || item.has_enchantments() {
|
||||
for i in 0..3 {
|
||||
self.level_requirements[i] = 0;
|
||||
self.enchantment_id[i] = -1;
|
||||
self.enchantment_level[i] = -1;
|
||||
}
|
||||
} else {
|
||||
let enchantability = item
|
||||
.get_data_component::<EnchantableImpl>()
|
||||
.map_or(0, |e| e.value);
|
||||
|
||||
if enchantability <= 0 {
|
||||
for i in 0..3 {
|
||||
self.level_requirements[i] = 0;
|
||||
self.enchantment_id[i] = -1;
|
||||
self.enchantment_level[i] = -1;
|
||||
}
|
||||
} else {
|
||||
let mut random = LegacyRand::from_seed(self.enchantment_seed as u64);
|
||||
|
||||
for i in 0..3 {
|
||||
let level = self.calculate_level_requirement(&mut random, i, enchantability);
|
||||
self.level_requirements[i] = level;
|
||||
}
|
||||
|
||||
for i in 0..3 {
|
||||
if self.level_requirements[i] > 0 {
|
||||
let mut random = self.create_enchantment_random(i);
|
||||
let enchantments = Self::get_enchantment_list(
|
||||
&mut random,
|
||||
&item,
|
||||
i,
|
||||
self.level_requirements[i],
|
||||
);
|
||||
if enchantments.is_empty() {
|
||||
self.enchantment_id[i] = -1;
|
||||
self.enchantment_level[i] = -1;
|
||||
} else {
|
||||
let clue_index =
|
||||
random.next_bounded_i32(enchantments.len() as i32) as usize;
|
||||
let clue = enchantments[clue_index];
|
||||
self.enchantment_id[i] = clue.0.id as i32;
|
||||
self.enchantment_level[i] = clue.1;
|
||||
}
|
||||
} else {
|
||||
self.enchantment_id[i] = -1;
|
||||
self.enchantment_level[i] = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.send_property_updates().await;
|
||||
}
|
||||
|
||||
fn calculate_level_requirement(
|
||||
&self,
|
||||
random: &mut LegacyRand,
|
||||
slot: usize,
|
||||
_enchantability: i32,
|
||||
) -> i32 {
|
||||
let b = self.bookshelf_count;
|
||||
let level = random.next_bounded_i32(8) + 1 + (b >> 1) + random.next_bounded_i32(b + 1);
|
||||
|
||||
match slot {
|
||||
0 => (level / 3).max(1),
|
||||
1 => (level * 2 / 3 + 7).max(1),
|
||||
2 => level.max(b * 2).max(1),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
const fn create_enchantment_random(&self, slot: usize) -> LegacyRand {
|
||||
LegacyRand::from_seed(self.enchantment_seed.wrapping_add(slot as i32) as u64)
|
||||
}
|
||||
|
||||
fn get_enchantment_list(
|
||||
random: &mut LegacyRand,
|
||||
item: &ItemStack,
|
||||
_slot: usize,
|
||||
level: i32,
|
||||
) -> Vec<(&'static Enchantment, i32)> {
|
||||
let enchantability = item
|
||||
.get_data_component::<EnchantableImpl>()
|
||||
.map_or(0, |e| e.value);
|
||||
let mut enchant_level = level
|
||||
+ 1
|
||||
+ random.next_bounded_i32(enchantability / 4 + 1)
|
||||
+ random.next_bounded_i32(enchantability / 4 + 1);
|
||||
let bonus = (random.next_f32() + random.next_f32() - 1.0) * 0.15;
|
||||
enchant_level = (enchant_level as f32 * (1.0 + bonus)).round() as i32;
|
||||
enchant_level = enchant_level.max(1);
|
||||
|
||||
let mut available = Vec::new();
|
||||
for enchant in Enchantment::all() {
|
||||
if enchant.has_tag(&EnchantmentTag::MINECRAFT_IN_ENCHANTING_TABLE)
|
||||
&& enchant.can_enchant(item.item)
|
||||
{
|
||||
for l in (1..=enchant.max_level).rev() {
|
||||
if enchant_level >= enchant.min_cost.calculate(l)
|
||||
&& enchant_level <= enchant.max_cost.calculate(l)
|
||||
{
|
||||
available.push((*enchant, l));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if available.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let total_weight: i32 = available.iter().map(|(e, _)| e.weight).sum();
|
||||
if total_weight <= 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut weight = random.next_bounded_i32(total_weight);
|
||||
let mut selected = None;
|
||||
for (e, l) in &available {
|
||||
weight -= e.weight;
|
||||
if weight < 0 {
|
||||
selected = Some((*e, *l));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut result = Vec::new();
|
||||
if let Some(s) = selected {
|
||||
result.push(s);
|
||||
|
||||
// Add more?
|
||||
let mut current_level = enchant_level;
|
||||
while random.next_bounded_i32(50) <= (current_level + 1) / 2 {
|
||||
available.retain(|(e, _)| {
|
||||
for (se, _) in &result {
|
||||
if !e.are_compatible(se) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
if available.is_empty() {
|
||||
break;
|
||||
}
|
||||
|
||||
let total_weight: i32 = available.iter().map(|(e, _)| e.weight).sum();
|
||||
let mut weight = random.next_bounded_i32(total_weight);
|
||||
for (e, l) in &available {
|
||||
weight -= e.weight;
|
||||
if weight < 0 {
|
||||
result.push((*e, *l));
|
||||
break;
|
||||
}
|
||||
}
|
||||
current_level /= 2;
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn send_property_updates(&self) {
|
||||
if let Some(sync_handler) = self.behaviour.sync_handler.as_ref() {
|
||||
for i in 0..3 {
|
||||
let (id, val) = WindowProperty::new(
|
||||
EnchantmentTable::LevelRequirement { slot: i as u8 },
|
||||
self.level_requirements[i] as i16,
|
||||
)
|
||||
.into_tuple();
|
||||
sync_handler
|
||||
.update_property(&self.behaviour, id as i32, val as i32)
|
||||
.await;
|
||||
|
||||
let (id, val) = WindowProperty::new(
|
||||
EnchantmentTable::EnchantmentId { slot: i as u8 },
|
||||
self.enchantment_id[i] as i16,
|
||||
)
|
||||
.into_tuple();
|
||||
sync_handler
|
||||
.update_property(&self.behaviour, id as i32, val as i32)
|
||||
.await;
|
||||
|
||||
let (id, val) = WindowProperty::new(
|
||||
EnchantmentTable::EnchantmentLevel { slot: i as u8 },
|
||||
self.enchantment_level[i] as i16,
|
||||
)
|
||||
.into_tuple();
|
||||
sync_handler
|
||||
.update_property(&self.behaviour, id as i32, val as i32)
|
||||
.await;
|
||||
}
|
||||
|
||||
let (id, val) = WindowProperty::new(
|
||||
EnchantmentTable::EnchantmentSeed,
|
||||
(self.enchantment_seed & 0xFFFF) as i16,
|
||||
)
|
||||
.into_tuple();
|
||||
sync_handler
|
||||
.update_property(&self.behaviour, id as i32, val as i32)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for EnchantingTableScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
self.inventory.on_close().await;
|
||||
// Return items to player
|
||||
for i in 0..2 {
|
||||
let stack = self.inventory.remove_stack(i).await;
|
||||
if !stack.is_empty() {
|
||||
offer_or_drop_stack(player, stack).await;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_button_click<'a>(
|
||||
&'a mut self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
id: i32,
|
||||
) -> ScreenHandlerFuture<'a, bool> {
|
||||
Box::pin(async move {
|
||||
if !(0..3).contains(&id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let level_req = self.level_requirements[id as usize];
|
||||
if player.experience_level() < level_req && !player.is_creative() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let lapis_slot = self.inventory.get_stack(1).await;
|
||||
let mut lapis_stack = lapis_slot.lock().await;
|
||||
let lapis_cost = (id + 1) as u8;
|
||||
|
||||
if !player.is_creative()
|
||||
&& (lapis_stack.is_empty()
|
||||
|| !is_lapis(&lapis_stack)
|
||||
|| lapis_stack.item_count < lapis_cost)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Perform enchantment
|
||||
let item_slot = self.inventory.get_stack(0).await;
|
||||
let mut item_stack = item_slot.lock().await;
|
||||
|
||||
if item_stack.is_empty() || item_stack.has_enchantments() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut random = self.create_enchantment_random(id as usize);
|
||||
let enchantments =
|
||||
Self::get_enchantment_list(&mut random, &item_stack, id as usize, level_req);
|
||||
|
||||
if enchantments.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
if !player.is_creative() {
|
||||
player.add_experience_levels(-(id + 1)).await;
|
||||
lapis_stack.decrement(lapis_cost);
|
||||
}
|
||||
|
||||
for (enchant, level) in enchantments {
|
||||
item_stack.add_enchantment(enchant, level as u16);
|
||||
}
|
||||
|
||||
// CRITICAL FIX: Drop locks *before* calling `update_enchantments`
|
||||
// Otherwise, update_enchantments will try to lock slot 0 again and deadlock!
|
||||
drop(item_stack);
|
||||
drop(lapis_stack);
|
||||
|
||||
// Update seed
|
||||
player.set_enchantment_seed(rand::random()).await;
|
||||
self.enchantment_seed = player.enchantment_seed();
|
||||
|
||||
self.update_enchantments(player).await;
|
||||
self.send_content_updates().await;
|
||||
|
||||
player
|
||||
.increment_stat(
|
||||
StatisticCategory::Custom,
|
||||
CustomStatistic::EnchantItem as i32,
|
||||
1,
|
||||
)
|
||||
.await;
|
||||
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
player: &'a dyn InventoryPlayer, // FIX: Changed _player to player
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if slot.has_stack().await {
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let slot_stack_guard = slot_stack_lock.lock().await;
|
||||
stack_left = slot_stack_guard.clone();
|
||||
drop(slot_stack_guard);
|
||||
|
||||
let mut slot_stack_mut = slot_stack_lock.lock().await;
|
||||
|
||||
if slot_index < 2 {
|
||||
// From enchanting to player
|
||||
if !self
|
||||
.insert_item(
|
||||
&mut slot_stack_mut,
|
||||
2,
|
||||
self.get_behaviour().slots.len() as i32,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else {
|
||||
// From player to enchanting
|
||||
// Lapis check
|
||||
if slot_stack_mut.item == &Item::LAPIS_LAZULI {
|
||||
if !self.insert_item(&mut slot_stack_mut, 1, 2, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else if !self.insert_item(&mut slot_stack_mut, 0, 1, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if slot_stack_mut.is_empty() {
|
||||
drop(slot_stack_mut);
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
drop(slot_stack_mut);
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
|
||||
// CRITICAL FIX: Ensure the client is notified when shift-clicking items into the slots
|
||||
self.update_enchantments(player).await;
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
|
||||
fn on_slot_click<'a>(
|
||||
&'a mut self,
|
||||
slot_index: i32,
|
||||
button: i32,
|
||||
action_type: pumpkin_protocol::java::server::play::SlotActionType,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.internal_on_slot_click(slot_index, button, action_type, player)
|
||||
.await;
|
||||
if slot_index == 0 || slot_index == 1 {
|
||||
self.update_enchantments(player).await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lapis_slot_only_accepts_lapis_lazuli() {
|
||||
assert!(is_lapis(&ItemStack::new(1, &Item::LAPIS_LAZULI)));
|
||||
assert!(!is_lapis(&ItemStack::new(1, &Item::DIRT)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! Enchanting module.
|
||||
//!
|
||||
//! This module handles enchanting mechanics including:
|
||||
//! - [`EnchantingTableScreenHandler`] - Screen handler for enchanting tables
|
||||
|
||||
pub mod enchanting_screen_handler;
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Entity equipment management.
|
||||
//!
|
||||
//! This module handles the storage and management of entity equipment slots,
|
||||
//! such as armor (head, chest, legs, feet) and off-hand items.
|
||||
//!
|
||||
//! Equipment is stored separately from the main inventory and is visible on
|
||||
//! the entity model (armor is rendered on the player, held items are visible
|
||||
//! in hands).
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use pumpkin_data::data_component_impl::EquipmentSlot;
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// Equipment storage for an entity.
|
||||
///
|
||||
/// Stores items equipped in armor slots (head, chest, legs, feet) and
|
||||
/// the off-hand slot. Equipment is separate from the main inventory
|
||||
/// and affects entity appearance and stats.
|
||||
///
|
||||
/// See also: [`EquipmentSlot`](EquipmentSlot)
|
||||
// EntityEquipment.java
|
||||
#[derive(Clone)]
|
||||
pub struct EntityEquipment {
|
||||
/// Map of equipment slots to their equipped items.
|
||||
///
|
||||
/// Keys are equipment slot types (head, chest, legs, feet, off-hand).
|
||||
/// Values are mutex-protected item stacks for thread-safe access.
|
||||
pub equipment: HashMap<EquipmentSlot, Arc<Mutex<ItemStack>>>,
|
||||
}
|
||||
|
||||
impl Default for EntityEquipment {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl EntityEquipment {
|
||||
/// Creates a new empty equipment storage.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
equipment: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Equips an item in a slot, returning the previous item.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `slot` - The equipment slot
|
||||
/// - `stack` - The item to equip
|
||||
///
|
||||
/// # Returns
|
||||
/// The previously equipped item, or an empty stack if the slot was empty.
|
||||
pub async fn put(&mut self, slot: &EquipmentSlot, stack: ItemStack) -> ItemStack {
|
||||
self.equipment
|
||||
.insert(slot.clone(), Arc::new(Mutex::new(stack)))
|
||||
.unwrap_or(Arc::new(Mutex::new(ItemStack::EMPTY.clone())))
|
||||
.lock()
|
||||
.await
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Gets or inserts an empty stack for a slot.
|
||||
///
|
||||
/// If the slot doesn't exist, creates it with an empty stack.
|
||||
///
|
||||
/// # Returns
|
||||
/// A mutex-protected item stack for this slot.
|
||||
#[must_use]
|
||||
pub fn get_or_insert(&mut self, slot: &EquipmentSlot) -> Arc<Mutex<ItemStack>> {
|
||||
self.equipment
|
||||
.entry(slot.clone())
|
||||
.or_insert_with(|| Arc::new(Mutex::new(ItemStack::EMPTY.clone())))
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Gets the item in a slot.
|
||||
///
|
||||
/// # Returns
|
||||
/// The equipped item, or an empty stack if nothing is equipped.
|
||||
#[must_use]
|
||||
pub fn get(&self, slot: &EquipmentSlot) -> Arc<Mutex<ItemStack>> {
|
||||
self.equipment
|
||||
.get(slot)
|
||||
.cloned()
|
||||
.unwrap_or(Arc::new(Mutex::new(ItemStack::EMPTY.clone())))
|
||||
}
|
||||
|
||||
/// Checks if all equipment slots are empty.
|
||||
pub async fn is_empty(&self) -> bool {
|
||||
for stack in self.equipment.values() {
|
||||
if !stack.lock().await.is_empty() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Clears all equipped items.
|
||||
pub fn clear(&mut self) {
|
||||
self.equipment.clear();
|
||||
}
|
||||
|
||||
// TODO: tick - Equipment updates, durability damage, etc.
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use thiserror::Error;
|
||||
|
||||
/// Errors that can occur during inventory operations.
|
||||
///
|
||||
/// These errors represent various failure conditions when handling inventory
|
||||
/// interactions, such as invalid slot indices, permission issues, or protocol errors.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum InventoryError {
|
||||
/// Failed to acquire a lock on an inventory or slot.
|
||||
#[error("Unable to lock")]
|
||||
LockError,
|
||||
/// The specified slot index is invalid or out of bounds.
|
||||
#[error("Invalid slot")]
|
||||
InvalidSlot,
|
||||
/// A player attempted to interact with a container that is closed.
|
||||
///
|
||||
/// The parameter is the player's entity ID.
|
||||
#[error("Player '{0}' tried to interact with a closed container")]
|
||||
ClosedContainerInteract(i32),
|
||||
/// Multiple players attempted to drag items in the same container simultaneously.
|
||||
#[error("Multiple players dragging in a container at once")]
|
||||
MultiplePlayersDragging,
|
||||
/// Drag operation was performed out of order (e.g., end before start).
|
||||
#[error("Out of order dragging")]
|
||||
OutOfOrderDragging,
|
||||
/// The received inventory packet is malformed or invalid.
|
||||
#[error("Invalid inventory packet")]
|
||||
InvalidPacket,
|
||||
/// The player lacks permission to perform this inventory operation.
|
||||
#[error("Player does not have enough permissions")]
|
||||
PermissionError,
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Furnace-like screen handler.
|
||||
//!
|
||||
//! This module implements the screen handler for furnace-like blocks:
|
||||
//! - Furnace
|
||||
//! - Smoker
|
||||
//! - Blast Furnace
|
||||
//!
|
||||
//! All three share the same 3-slot layout:
|
||||
//! - Slot 0: Input (item to smelt/cook)
|
||||
//! - Slot 1: Fuel (coal, charcoal, etc.)
|
||||
//! - Slot 2: Output (smelted result)
|
||||
//!
|
||||
//! The screen handler tracks 4 properties:
|
||||
//! - Property 0: Fire icon animation (fuel burn time remaining)
|
||||
//! - Property 1: Maximum fuel burn time
|
||||
//! - Property 2: Progress arrow (cooking/smelt time)
|
||||
//! - Property 3: Maximum progress (typically 200 ticks for furnace)
|
||||
|
||||
use std::{any::Any, pin::Pin, sync::Arc};
|
||||
|
||||
use pumpkin_data::{fuels::is_fuel, item_stack::ItemStack, screen::WindowType};
|
||||
use pumpkin_world::{
|
||||
block::entities::{ExperienceContainer, PropertyDelegate},
|
||||
inventory::Inventory,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour,
|
||||
ScreenHandlerFuture, ScreenHandlerListener, ScreenProperty,
|
||||
},
|
||||
};
|
||||
use tracing::debug;
|
||||
|
||||
use super::furnace_like_slot::{FurnaceLikeSlot, FurnaceLikeSlotType, FurnaceOutputSlot};
|
||||
|
||||
/// Screen handler for furnace-like containers.
|
||||
///
|
||||
/// Handles the UI for furnaces, smokers, and blast furnaces.
|
||||
/// These all share the same slot layout and quick-move behavior.
|
||||
pub struct FurnaceLikeScreenHandler {
|
||||
/// The furnace's inventory (3 slots: 0 input, 1 fuel, 2 output).
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
/// Container that tracks accumulated smelting experience.
|
||||
///
|
||||
/// Experience is awarded to the player when they take items from the output slot.
|
||||
experience_container: Arc<dyn ExperienceContainer>,
|
||||
/// Core screen handler behavior (slots, sync ID, properties, listeners).
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
}
|
||||
|
||||
impl FurnaceLikeScreenHandler {
|
||||
/// Creates a new furnace-like screen handler.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `sync_id` - The sync ID for client-server matching
|
||||
/// - `player_inventory` - The player's inventory
|
||||
/// - `inventory` - The furnace's inventory (3 slots)
|
||||
/// - `property_delegate` - Delegate for accessing furnace properties
|
||||
/// - `experience_container` - Container that tracks smelting experience
|
||||
/// - `window_type` - The window type (Furnace, Smoker, or `BlastFurnace`)
|
||||
pub async fn new(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
property_delegate: Arc<dyn PropertyDelegate>,
|
||||
experience_container: Arc<dyn ExperienceContainer>,
|
||||
window_type: WindowType,
|
||||
) -> Self {
|
||||
struct FurnaceLikeScreenListener;
|
||||
impl ScreenHandlerListener for FurnaceLikeScreenListener {
|
||||
fn on_property_update<'a>(
|
||||
&'a self,
|
||||
screen_handler: &'a ScreenHandlerBehaviour,
|
||||
property: u8,
|
||||
value: i32,
|
||||
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
if let Some(sync_handler) = screen_handler.sync_handler.as_ref() {
|
||||
sync_handler
|
||||
.update_property(screen_handler, i32::from(property), value)
|
||||
.await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
let mut handler = Self {
|
||||
inventory,
|
||||
experience_container,
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(window_type)),
|
||||
};
|
||||
|
||||
// 0: Fire icon (fuel left) counting from fuel burn time down to 0 (in-game ticks)
|
||||
// 1: Maximum fuel burn time fuel burn time or 0 (in-game ticks)
|
||||
// 2: Progress arrow counting from 0 to maximum progress (in-game ticks)
|
||||
// 3: Maximum progress always 200 on the vanilla server
|
||||
for i in 0..4 {
|
||||
handler.add_property(ScreenProperty::new(property_delegate.clone(), i));
|
||||
}
|
||||
|
||||
handler
|
||||
.add_listener(Arc::new(FurnaceLikeScreenListener))
|
||||
.await;
|
||||
handler.add_inventory_slots();
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&player_inventory);
|
||||
|
||||
handler
|
||||
}
|
||||
|
||||
/// Adds the 3 furnace inventory slots.
|
||||
///
|
||||
/// - Slot 0: Input (top)
|
||||
/// - Slot 1: Fuel (bottom)
|
||||
/// - Slot 2: Output
|
||||
fn add_inventory_slots(&mut self) {
|
||||
self.add_slot(Arc::new(FurnaceLikeSlot::new(
|
||||
self.inventory.clone(),
|
||||
FurnaceLikeSlotType::Top,
|
||||
)));
|
||||
self.add_slot(Arc::new(FurnaceLikeSlot::new(
|
||||
self.inventory.clone(),
|
||||
FurnaceLikeSlotType::Bottom,
|
||||
)));
|
||||
// Output slot awards experience when items are taken
|
||||
self.add_slot(Arc::new(FurnaceOutputSlot::new(
|
||||
self.inventory.clone(),
|
||||
self.experience_container.clone(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for FurnaceLikeScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
// TODO: self.inventory.on_closed(player).await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Quick move logic for furnace-like containers.
|
||||
///
|
||||
/// - From furnace slots (0-2): Move to player inventory
|
||||
/// - Fuel items: Move to fuel slot (1)
|
||||
/// - Other items: Move to input slot (0)
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
const FUEL_SLOT: i32 = 1; // Note: Slots 0, 1, 2 are Furnace slots.
|
||||
const OUTPUT_SLOT: i32 = 2;
|
||||
|
||||
debug!("FurnaceLikeScreenHandler::quick_move slot_index={slot_index}");
|
||||
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if !slot.has_stack().await {
|
||||
return stack_left;
|
||||
}
|
||||
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
|
||||
// Acquire the lock to read/clone the stack
|
||||
let mut stack = slot_stack_lock.lock().await;
|
||||
stack_left = stack.clone();
|
||||
|
||||
let success = if slot_index < 3 {
|
||||
// If clicked slot is one of the Furnace slots (0, 1, 2):
|
||||
// Try to move to player inventory (slots 3 onwards, starting from the end)
|
||||
self.insert_item(&mut stack, 3, self.get_behaviour().slots.len() as i32, true)
|
||||
.await
|
||||
} else if is_fuel(stack.item.id) {
|
||||
// If clicked slot is in the player inventory (3+) and contains fuel:
|
||||
// Try to move to the Furnace's Fuel slot (slot 1)
|
||||
self.insert_item(&mut stack, FUEL_SLOT, 3, false).await
|
||||
} else {
|
||||
// If clicked slot is in the player inventory (3+) and NOT fuel (must be a smeltable item):
|
||||
// Try to move to the Furnace's Input/Smelting slot (slot 0)
|
||||
self.insert_item(&mut stack, 0, 3, false).await
|
||||
};
|
||||
|
||||
if !success {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
|
||||
if stack.is_empty() {
|
||||
drop(stack); // Release lock before awaiting
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
|
||||
// Award XP when taking from output slot (slot 2)
|
||||
if slot_index == OUTPUT_SLOT {
|
||||
debug!("quick_move: taking from output slot, calling on_take_item");
|
||||
slot.on_take_item(player, &stack_left).await;
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Furnace-like slot implementations.
|
||||
//!
|
||||
//! This module provides specialized slot types for furnace-like containers.
|
||||
//! Furnaces have three slots with specific behaviors:
|
||||
//! - Input slot (top): Accepts any smeltable item
|
||||
//! - Fuel slot (bottom): Only accepts fuel items (coal, charcoal, etc.)
|
||||
//! - Output slot: Cannot receive items, awards experience when items are taken
|
||||
|
||||
use std::sync::{Arc, atomic::AtomicU8};
|
||||
|
||||
use pumpkin_data::{fuels::is_fuel, item::Item, statistic::StatisticCategory};
|
||||
use pumpkin_world::{block::entities::ExperienceContainer, inventory::Inventory};
|
||||
|
||||
use tracing::debug;
|
||||
|
||||
use crate::{
|
||||
screen_handler::InventoryPlayer,
|
||||
slot::{BoxFuture, Slot},
|
||||
};
|
||||
|
||||
/// Type of furnace slot.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum FurnaceLikeSlotType {
|
||||
/// Input slot (top) - accepts items to smelt.
|
||||
Top = 0,
|
||||
/// Fuel slot (bottom) - accepts fuel items.
|
||||
Bottom = 1,
|
||||
}
|
||||
|
||||
/// Slot for furnace input or fuel.
|
||||
///
|
||||
/// The input slot accepts any item, while the fuel slot only accepts
|
||||
/// valid fuel items (and empty buckets for lava fuel).
|
||||
pub struct FurnaceLikeSlot {
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
pub slot_type: FurnaceLikeSlotType,
|
||||
pub index: usize,
|
||||
pub id: AtomicU8,
|
||||
}
|
||||
|
||||
impl FurnaceLikeSlot {
|
||||
/// Creates a new furnace slot.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `inventory` - The furnace's inventory
|
||||
/// - `slot_type` - Whether this is the input (Top) or fuel (Bottom) slot
|
||||
pub fn new(inventory: Arc<dyn Inventory>, slot_type: FurnaceLikeSlotType) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
slot_type,
|
||||
index: slot_type as usize,
|
||||
id: AtomicU8::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Slot for FurnaceLikeSlot {
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory> {
|
||||
self.inventory.clone()
|
||||
}
|
||||
|
||||
fn get_index(&self) -> usize {
|
||||
self.index
|
||||
}
|
||||
|
||||
fn set_id(&self, id: usize) {
|
||||
self.id
|
||||
.store(id as u8, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Restricts inserts based on slot type.
|
||||
///
|
||||
/// - Top slot: accepts any item (smeltables)
|
||||
/// - Bottom slot: only accepts fuel items and buckets
|
||||
fn can_insert<'a>(
|
||||
&'a self,
|
||||
stack: &'a pumpkin_data::item_stack::ItemStack,
|
||||
) -> BoxFuture<'a, bool> {
|
||||
Box::pin(async move {
|
||||
match self.slot_type {
|
||||
FurnaceLikeSlotType::Top => true,
|
||||
FurnaceLikeSlotType::Bottom => {
|
||||
is_fuel(stack.item.id) || stack.item.id == Item::BUCKET.id
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.inventory.mark_dirty();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Output slot for furnace-like containers.
|
||||
///
|
||||
/// This slot cannot receive items directly (items are placed here by smelting).
|
||||
/// When items are taken from this slot, the player receives experience
|
||||
/// based on the smelting recipes used.
|
||||
pub struct FurnaceOutputSlot {
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
pub experience_container: Arc<dyn ExperienceContainer>,
|
||||
pub id: AtomicU8,
|
||||
}
|
||||
|
||||
impl FurnaceOutputSlot {
|
||||
/// Creates a new furnace output slot.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `inventory` - The furnace's inventory
|
||||
/// - `experience_container` - Container that tracks accumulated experience
|
||||
pub fn new(
|
||||
inventory: Arc<dyn Inventory>,
|
||||
experience_container: Arc<dyn ExperienceContainer>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
experience_container,
|
||||
id: AtomicU8::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Slot for FurnaceOutputSlot {
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory> {
|
||||
self.inventory.clone()
|
||||
}
|
||||
|
||||
fn get_index(&self) -> usize {
|
||||
2 // Output slot is always index 2
|
||||
}
|
||||
|
||||
fn set_id(&self, id: usize) {
|
||||
self.id
|
||||
.store(id as u8, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Awards experience when items are taken from this slot.
|
||||
fn on_take_item<'a>(
|
||||
&'a self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
stack: &'a pumpkin_data::item_stack::ItemStack,
|
||||
) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
debug!("FurnaceOutputSlot: on_take_item called");
|
||||
player
|
||||
.increment_stat(
|
||||
StatisticCategory::Crafted,
|
||||
stack.item.id as i32,
|
||||
stack.item_count as i32,
|
||||
)
|
||||
.await;
|
||||
// Extract accumulated experience and award to player
|
||||
let experience = self.experience_container.extract_experience();
|
||||
debug!("FurnaceOutputSlot: extracted experience = {experience}");
|
||||
if experience > 0 {
|
||||
debug!("FurnaceOutputSlot: awarding {experience} xp to player");
|
||||
player.award_experience(experience).await;
|
||||
}
|
||||
self.mark_dirty().await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Output slot cannot receive inserted items.
|
||||
fn can_insert<'a>(
|
||||
&'a self,
|
||||
_stack: &'a pumpkin_data::item_stack::ItemStack,
|
||||
) -> BoxFuture<'a, bool> {
|
||||
// Cannot insert items into the output slot
|
||||
Box::pin(async move { false })
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.inventory.mark_dirty();
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Furnace-like containers module.
|
||||
//!
|
||||
//! This module handles screen handlers for furnace-like blocks:
|
||||
//! - Furnace
|
||||
//! - Smoker
|
||||
//! - Blast Furnace
|
||||
//!
|
||||
//! These containers share the same slot layout and behavior:
|
||||
//! - Slot 0: Input (item to smelt/cook)
|
||||
//! - Slot 1: Fuel (coal, charcoal, etc.)
|
||||
//! - Slot 2: Output (smelted/cooked result)
|
||||
//!
|
||||
//! # Properties
|
||||
//!
|
||||
/// Furnace-like containers track four properties:
|
||||
/// - Property 0: Fire icon (fuel remaining)
|
||||
/// - Property 1: Maximum fuel burn time
|
||||
/// - Property 2: Progress arrow (smelting progress)
|
||||
/// - Property 3: Maximum progress (typically 200 ticks)
|
||||
pub mod furnace_like_screen_handler;
|
||||
pub mod furnace_like_slot;
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Generic container screen handler.
|
||||
//!
|
||||
//! This module provides a generic screen handler for simple containers like:
|
||||
//! - Chests (single, double, ender chest)
|
||||
//! - Hoppers
|
||||
//! - Dispensers/Droppers
|
||||
//! - Barrels
|
||||
//!
|
||||
//! These containers have a simple grid layout with no special behaviors
|
||||
//! (no smelting, no crafting, just item storage).
|
||||
|
||||
use std::{any::Any, sync::Arc};
|
||||
|
||||
use pumpkin_data::{item_stack::ItemStack, screen::WindowType};
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour,
|
||||
ScreenHandlerFuture,
|
||||
},
|
||||
slot::NormalSlot,
|
||||
};
|
||||
|
||||
/// Creates a generic 9x3 container (single chest).
|
||||
///
|
||||
/// Used for single chests, ender chests, and similar containers.
|
||||
pub async fn create_generic_9x3(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> GenericContainerScreenHandler {
|
||||
GenericContainerScreenHandler::new(
|
||||
WindowType::Generic9x3,
|
||||
sync_id,
|
||||
player_inventory,
|
||||
inventory,
|
||||
3,
|
||||
9,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Creates a generic 9x6 container (double chest).
|
||||
///
|
||||
/// Used for double chests and similar large containers.
|
||||
pub async fn create_generic_9x6(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> GenericContainerScreenHandler {
|
||||
GenericContainerScreenHandler::new(
|
||||
WindowType::Generic9x6,
|
||||
sync_id,
|
||||
player_inventory,
|
||||
inventory,
|
||||
6,
|
||||
9,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Creates a generic 3x3 container.
|
||||
///
|
||||
/// Used for dispensers, droppers, and similar containers.
|
||||
pub async fn create_generic_3x3(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> GenericContainerScreenHandler {
|
||||
GenericContainerScreenHandler::new(
|
||||
WindowType::Generic3x3,
|
||||
sync_id,
|
||||
player_inventory,
|
||||
inventory,
|
||||
3,
|
||||
3,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Creates a crafter container (9 slots, 3x3 layout).
|
||||
pub async fn create_crafter_3x3(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> GenericContainerScreenHandler {
|
||||
GenericContainerScreenHandler::new(
|
||||
WindowType::Crafter3x3,
|
||||
sync_id,
|
||||
player_inventory,
|
||||
inventory,
|
||||
3,
|
||||
3,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Creates a hopper container (5 slots).
|
||||
///
|
||||
/// Hoppers have a single row of 5 slots.
|
||||
pub async fn create_hopper(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
) -> GenericContainerScreenHandler {
|
||||
GenericContainerScreenHandler::new(
|
||||
WindowType::Hopper,
|
||||
sync_id,
|
||||
player_inventory,
|
||||
inventory,
|
||||
1,
|
||||
5,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Generic container screen handler.
|
||||
///
|
||||
/// Handles simple grid-based containers without special behaviors.
|
||||
/// The container grid is followed by the player's inventory (27 slots + 9 hotbar).
|
||||
pub struct GenericContainerScreenHandler {
|
||||
/// The container's inventory.
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
/// Number of rows in the container grid.
|
||||
pub rows: u8,
|
||||
/// Number of columns in the container grid.
|
||||
pub columns: u8,
|
||||
/// Core screen handler behavior (slots, sync ID, listeners).
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
}
|
||||
|
||||
impl GenericContainerScreenHandler {
|
||||
/// Creates a new generic container screen handler.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `screen_type` - The window type for this container
|
||||
/// - `sync_id` - The sync ID for client-server matching
|
||||
/// - `player_inventory` - The player's inventory
|
||||
/// - `inventory` - The container's inventory
|
||||
/// - `rows` - Number of rows in the container
|
||||
/// - `columns` - Number of columns in the container
|
||||
async fn new(
|
||||
screen_type: WindowType,
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
rows: u8,
|
||||
columns: u8,
|
||||
) -> Self {
|
||||
let mut handler = Self {
|
||||
inventory: inventory.clone(),
|
||||
rows,
|
||||
columns,
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(screen_type)),
|
||||
};
|
||||
|
||||
// TODO: Add player entity as a parameter
|
||||
inventory.on_open().await;
|
||||
|
||||
handler.add_inventory_slots();
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&player_inventory);
|
||||
|
||||
handler
|
||||
}
|
||||
|
||||
/// Adds slots for the container's inventory grid.
|
||||
fn add_inventory_slots(&mut self) {
|
||||
for i in 0..self.rows {
|
||||
for j in 0..self.columns {
|
||||
self.add_slot(Arc::new(NormalSlot::new(
|
||||
self.inventory.clone(),
|
||||
(j + i * self.columns) as usize,
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for GenericContainerScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
self.inventory.on_close().await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Quick move logic for generic containers.
|
||||
///
|
||||
/// - From container: Move to player inventory (end first)
|
||||
/// - From player inventory: Move to container (start first)
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
// Assuming bounds check passed for slot_index by caller or within quick_move spec
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if slot.has_stack().await {
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let slot_stack_guard = slot_stack_lock.lock().await;
|
||||
stack_left = slot_stack_guard.clone();
|
||||
// Release the guard before calling insert_item which needs its own lock
|
||||
drop(slot_stack_guard);
|
||||
|
||||
// Re-acquire lock for insert_item (which expects &mut ItemStack)
|
||||
let mut slot_stack_mut = slot_stack_lock.lock().await;
|
||||
|
||||
if slot_index < i32::from(self.rows * 9) {
|
||||
// Move from inventory to player area (end)
|
||||
if !self
|
||||
.insert_item(
|
||||
&mut slot_stack_mut,
|
||||
(self.rows * 9).into(),
|
||||
self.get_behaviour().slots.len() as i32,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else if !self
|
||||
.insert_item(&mut slot_stack_mut, 0, (self.rows * 9).into(), false)
|
||||
.await
|
||||
{
|
||||
// Move from player area to inventory (start)
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
|
||||
// Check the resulting state of the slot stack after insert_item
|
||||
if slot_stack_mut.is_empty() {
|
||||
drop(slot_stack_mut); // Release lock
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
drop(slot_stack_mut); // Release lock
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour,
|
||||
ScreenHandlerFuture,
|
||||
},
|
||||
slot::NormalSlot,
|
||||
};
|
||||
use pumpkin_data::{item_stack::ItemStack, screen::WindowType};
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
use std::{any::Any, sync::Arc};
|
||||
|
||||
/// Builder for custom GUIs.
|
||||
pub struct GUIBuilder {
|
||||
screen_type: WindowType,
|
||||
rows: u8,
|
||||
columns: u8,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
allow_grab_items: bool,
|
||||
allow_put_items: bool,
|
||||
}
|
||||
|
||||
impl GUIBuilder {
|
||||
/// Creates a new `GUIBuilder` with a basic 9x3 layout.
|
||||
pub fn new(screen_type: WindowType, inventory: Arc<dyn Inventory>) -> Self {
|
||||
let (rows, columns) = match screen_type {
|
||||
WindowType::Generic9x1 => (1, 9),
|
||||
WindowType::Generic9x2 => (2, 9),
|
||||
WindowType::Generic9x4 => (4, 9),
|
||||
WindowType::Generic9x5 => (5, 9),
|
||||
WindowType::Generic9x6 => (6, 9),
|
||||
WindowType::Generic3x3 | WindowType::Crafter3x3 => (3, 3),
|
||||
WindowType::Hopper => (1, 5),
|
||||
_ => (3, 9), // Default to 9x3
|
||||
};
|
||||
|
||||
Self {
|
||||
screen_type,
|
||||
rows,
|
||||
columns,
|
||||
inventory,
|
||||
allow_grab_items: true,
|
||||
allow_put_items: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets whether players can grab items out of the inventory.
|
||||
#[must_use]
|
||||
pub const fn allow_grab_items(mut self, allow: bool) -> Self {
|
||||
self.allow_grab_items = allow;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether players can put items into the inventory from their own.
|
||||
#[must_use]
|
||||
pub const fn allow_put_items(mut self, allow: bool) -> Self {
|
||||
self.allow_put_items = allow;
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds the `GUIScreenHandler`.
|
||||
pub async fn build(
|
||||
self,
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
) -> GUIScreenHandler {
|
||||
let mut behaviour = ScreenHandlerBehaviour::new(sync_id, Some(self.screen_type));
|
||||
behaviour.allow_grab_items = self.allow_grab_items;
|
||||
behaviour.allow_put_items = self.allow_put_items;
|
||||
behaviour.container_slots = (self.rows * self.columns) as usize;
|
||||
|
||||
let mut handler = GUIScreenHandler {
|
||||
inventory: self.inventory.clone(),
|
||||
rows: self.rows,
|
||||
columns: self.columns,
|
||||
behaviour,
|
||||
};
|
||||
|
||||
self.inventory.on_open().await;
|
||||
|
||||
handler.add_inventory_slots();
|
||||
let player_inventory_trait: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&player_inventory_trait);
|
||||
|
||||
handler
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GUIScreenHandler {
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
pub rows: u8,
|
||||
pub columns: u8,
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
}
|
||||
|
||||
impl GUIScreenHandler {
|
||||
fn add_inventory_slots(&mut self) {
|
||||
for i in 0..self.rows {
|
||||
for j in 0..self.columns {
|
||||
self.add_slot(Arc::new(NormalSlot::new(
|
||||
self.inventory.clone(),
|
||||
(j + i * self.columns) as usize,
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for GUIScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
self.inventory.on_close().await;
|
||||
})
|
||||
}
|
||||
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if slot.has_stack().await {
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let slot_stack_guard = slot_stack_lock.lock().await;
|
||||
stack_left = slot_stack_guard.clone();
|
||||
drop(slot_stack_guard);
|
||||
|
||||
let mut slot_stack_mut = slot_stack_lock.lock().await;
|
||||
let container_slots = i32::from(self.rows * self.columns);
|
||||
|
||||
if slot_index < container_slots {
|
||||
// From container to player
|
||||
if !self.get_behaviour().allow_grab_items {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
if !self
|
||||
.insert_item(
|
||||
&mut slot_stack_mut,
|
||||
container_slots,
|
||||
self.get_behaviour().slots.len() as i32,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else {
|
||||
// From player to container
|
||||
if !self.get_behaviour().allow_put_items {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
if !self
|
||||
.insert_item(&mut slot_stack_mut, 0, container_slots, false)
|
||||
.await
|
||||
{
|
||||
// Move from player area to inventory (start)
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if slot_stack_mut.is_empty() {
|
||||
drop(slot_stack_mut);
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
drop(slot_stack_mut);
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour, ScreenHandlerFuture,
|
||||
ScreenProperty, offer_or_drop_stack,
|
||||
};
|
||||
use crate::slot::NormalSlot;
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::screen::WindowType;
|
||||
use pumpkin_world::block::entities::PropertyDelegate;
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
/// Callbacks into the lectern block so page turns and book removal can drive
|
||||
/// block-state changes (redstone pulse, `has_book`) that live outside this crate.
|
||||
pub trait LecternController: Send + Sync {
|
||||
/// The page currently displayed.
|
||||
fn current_page(&self) -> i32;
|
||||
|
||||
/// Clamps and persists `page`, emitting a redstone pulse when it changes.
|
||||
fn set_page(&self, page: i32) -> ScreenHandlerFuture<'_, ()>;
|
||||
|
||||
/// Restores the bookless block state after the book was taken.
|
||||
fn on_book_taken(&self) -> ScreenHandlerFuture<'_, ()>;
|
||||
}
|
||||
|
||||
/// Exposes the current page as container property 0 (see `window_property::Lectern`).
|
||||
struct PageDelegate(Arc<dyn LecternController>);
|
||||
|
||||
impl PropertyDelegate for PageDelegate {
|
||||
fn get_property(&self, index: i32) -> i32 {
|
||||
if index == 0 { self.0.current_page() } else { 0 }
|
||||
}
|
||||
|
||||
fn set_property(&self, _index: i32, _value: i32) {}
|
||||
|
||||
fn get_properties_size(&self) -> i32 {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
/// Vanilla `LecternScreenHandler`: a single book slot, no player slots and the
|
||||
/// current page synced as property 0. Page navigation and taking the book are
|
||||
/// plain button clicks sent by the client.
|
||||
pub struct LecternScreenHandler {
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
controller: Arc<dyn LecternController>,
|
||||
}
|
||||
|
||||
impl LecternScreenHandler {
|
||||
const PREVIOUS_PAGE_BUTTON_ID: i32 = 1;
|
||||
const NEXT_PAGE_BUTTON_ID: i32 = 2;
|
||||
const TAKE_BOOK_BUTTON_ID: i32 = 3;
|
||||
/// Button ids at or above this jump directly to `id - JUMP_TO_PAGE_OFFSET`.
|
||||
const JUMP_TO_PAGE_OFFSET: i32 = 100;
|
||||
|
||||
pub fn new(
|
||||
sync_id: u8,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
controller: Arc<dyn LecternController>,
|
||||
) -> Self {
|
||||
let mut handler = Self {
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(WindowType::Lectern)),
|
||||
inventory: inventory.clone(),
|
||||
controller: controller.clone(),
|
||||
};
|
||||
|
||||
handler.add_slot(Arc::new(NormalSlot::new(inventory, 0)));
|
||||
handler.add_property(ScreenProperty::new(Arc::new(PageDelegate(controller)), 0));
|
||||
|
||||
handler
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for LecternScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_button_click<'a>(
|
||||
&'a mut self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
id: i32,
|
||||
) -> ScreenHandlerFuture<'a, bool> {
|
||||
Box::pin(async move {
|
||||
match id {
|
||||
Self::PREVIOUS_PAGE_BUTTON_ID => {
|
||||
self.controller
|
||||
.set_page(self.controller.current_page() - 1)
|
||||
.await;
|
||||
true
|
||||
}
|
||||
Self::NEXT_PAGE_BUTTON_ID => {
|
||||
self.controller
|
||||
.set_page(self.controller.current_page() + 1)
|
||||
.await;
|
||||
true
|
||||
}
|
||||
Self::TAKE_BOOK_BUTTON_ID => {
|
||||
let stack = self.inventory.remove_stack(0).await;
|
||||
if stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
self.inventory.mark_dirty();
|
||||
self.controller.on_book_taken().await;
|
||||
offer_or_drop_stack(player, stack).await;
|
||||
self.send_content_updates().await;
|
||||
true
|
||||
}
|
||||
_ if id >= Self::JUMP_TO_PAGE_OFFSET => {
|
||||
self.controller
|
||||
.set_page(id - Self::JUMP_TO_PAGE_OFFSET)
|
||||
.await;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
_slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
// The lectern screen has no player slots, so nothing can be shift-clicked.
|
||||
Box::pin(async move { ItemStack::EMPTY.clone() })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Pumpkin inventory system.
|
||||
//!
|
||||
//! This crate provides the inventory management system for the Pumpkin Minecraft server.
|
||||
//! It handles player inventories, container screens (like chests, furnaces, crafting tables),
|
||||
//! slot interactions, item dragging, and inventory synchronization between server and client.
|
||||
//!
|
||||
//! # Core Concepts
|
||||
//!
|
||||
//! - [`Inventory`] - A trait representing any item storage (player inventory, chest, furnace, etc.)
|
||||
//! - [`ScreenHandler`] - Manages the UI screen for a container, handling slot layout and interactions
|
||||
//! - [`Slot`] - Represents a single slot in an inventory that can hold items
|
||||
//! - [`PlayerInventory`] - The player's 36-slot main inventory plus equipment slots
|
||||
//! - [`SyncHandler`] - Synchronizes inventory state between server and client
|
||||
//!
|
||||
//! # Module Structure
|
||||
//!
|
||||
//! - [`player`] - Player inventory and screen handler implementations
|
||||
//! - [`crafting`] - Crafting table and inventory crafting mechanics
|
||||
//! - [`furnace_like`] - Furnace, smoker, and blast furnace screen handlers
|
||||
//! - [`brewing`] - Brewing stand handling
|
||||
//! - [`slot`] - Slot trait and implementations (normal slots, armor slots)
|
||||
//! - [`container_click`] - Mouse and keyboard click handling
|
||||
//! - [`drag_handler`] - Item dragging across multiple slots
|
||||
//! - [`sync_handler`] - Client-server inventory synchronization
|
||||
//! - [`window_property`] - Container UI properties (furnace progress, enchantment levels, etc.)
|
||||
//!
|
||||
//! [`Inventory`]: pumpkin_world::inventory::Inventory
|
||||
//! [`ScreenHandler`]: screen_handler::ScreenHandler
|
||||
//! [`Slot`]: slot::Slot
|
||||
//! [`PlayerInventory`]: PlayerInventory
|
||||
//! [`SyncHandler`]: sync_handler::SyncHandler
|
||||
|
||||
pub mod anvil;
|
||||
pub mod beacon_screen_handler;
|
||||
pub mod brewing;
|
||||
pub mod container_click;
|
||||
pub mod crafting;
|
||||
pub mod double;
|
||||
pub mod drag_handler;
|
||||
pub mod enchanting;
|
||||
pub mod entity_equipment;
|
||||
mod error;
|
||||
pub mod furnace_like;
|
||||
pub mod generic_container_screen_handler;
|
||||
pub mod gui_builder;
|
||||
pub mod lectern_screen_handler;
|
||||
pub mod merchant;
|
||||
pub mod player;
|
||||
pub mod screen_handler;
|
||||
pub mod slot;
|
||||
pub mod stonecutter_screen_handler;
|
||||
pub mod sync_handler;
|
||||
pub mod window_property;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub use error::InventoryError;
|
||||
use pumpkin_data::data_component_impl::EquipmentSlot;
|
||||
|
||||
use crate::player::player_inventory::PlayerInventory;
|
||||
|
||||
/// Builds a map of slot indices to equipment slots for the player's inventory.
|
||||
///
|
||||
/// This creates the mapping between UI slot indices and equipment slots
|
||||
/// (head, chest, legs, feet, off-hand) used by the player screen handler.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `HashMap` where keys are slot indices and values are the corresponding [`EquipmentSlot`]s.
|
||||
#[must_use]
|
||||
pub fn build_equipment_slots() -> HashMap<usize, EquipmentSlot> {
|
||||
let mut equipment_slots = HashMap::new();
|
||||
equipment_slots.insert(
|
||||
EquipmentSlot::FEET.get_offset_entity_slot_id(PlayerInventory::MAIN_SIZE as i32) as usize,
|
||||
EquipmentSlot::FEET,
|
||||
);
|
||||
equipment_slots.insert(
|
||||
EquipmentSlot::LEGS.get_offset_entity_slot_id(PlayerInventory::MAIN_SIZE as i32) as usize,
|
||||
EquipmentSlot::LEGS,
|
||||
);
|
||||
equipment_slots.insert(
|
||||
EquipmentSlot::CHEST.get_offset_entity_slot_id(PlayerInventory::MAIN_SIZE as i32) as usize,
|
||||
EquipmentSlot::CHEST,
|
||||
);
|
||||
equipment_slots.insert(
|
||||
EquipmentSlot::HEAD.get_offset_entity_slot_id(PlayerInventory::MAIN_SIZE as i32) as usize,
|
||||
EquipmentSlot::HEAD,
|
||||
);
|
||||
|
||||
equipment_slots.insert(PlayerInventory::OFF_HAND_SLOT, EquipmentSlot::OFF_HAND);
|
||||
equipment_slots.insert(PlayerInventory::OFF_HAND_SLOT, EquipmentSlot::OFF_HAND);
|
||||
equipment_slots
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::{item_stack::ItemStack, screen::WindowType};
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
|
||||
use crate::{
|
||||
player::player_inventory::PlayerInventory,
|
||||
screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour,
|
||||
ScreenHandlerFuture, offer_or_drop_stack,
|
||||
},
|
||||
slot::NormalSlot,
|
||||
};
|
||||
|
||||
pub struct MerchantScreenHandler {
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
selected_offer: usize,
|
||||
pub offers: Vec<pumpkin_protocol::java::client::play::MerchantOffer>,
|
||||
pub on_trade: Option<Box<dyn Fn(usize) + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl MerchantScreenHandler {
|
||||
pub async fn new(
|
||||
sync_id: u8,
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
inventory: Arc<dyn Inventory>,
|
||||
offers: Vec<pumpkin_protocol::java::client::play::MerchantOffer>,
|
||||
) -> Self {
|
||||
let mut handler = Self {
|
||||
inventory: inventory.clone(),
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, Some(WindowType::Merchant)),
|
||||
selected_offer: 0,
|
||||
offers,
|
||||
on_trade: None,
|
||||
};
|
||||
|
||||
inventory.on_open().await;
|
||||
|
||||
// Merchant specific slots: 2 input, 1 output
|
||||
for i in 0..3 {
|
||||
handler.add_slot(Arc::new(NormalSlot::new(inventory.clone(), i)));
|
||||
}
|
||||
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
handler.add_player_slots(&player_inventory);
|
||||
|
||||
handler
|
||||
}
|
||||
|
||||
pub async fn set_selected_offer(&mut self, index: usize) {
|
||||
self.selected_offer = index;
|
||||
self.update_result_slot().await;
|
||||
self.send_content_updates().await;
|
||||
}
|
||||
|
||||
pub async fn update_result_slot(&mut self) {
|
||||
if self.selected_offer >= self.offers.len() {
|
||||
self.inventory.set_stack(2, ItemStack::EMPTY.clone()).await;
|
||||
return;
|
||||
}
|
||||
|
||||
let offer = &self.offers[self.selected_offer];
|
||||
let input_a = self.inventory.get_stack(0).await;
|
||||
let input_a = input_a.lock().await;
|
||||
let input_b = self.inventory.get_stack(1).await;
|
||||
let input_b = input_b.lock().await;
|
||||
|
||||
let match_a = input_a.are_items_and_components_equal(&offer.base_cost_a.0)
|
||||
&& input_a.item_count >= offer.base_cost_a.0.item_count;
|
||||
|
||||
let match_b = offer.cost_b.as_ref().map_or_else(
|
||||
|| input_b.is_empty(),
|
||||
|cost_b| {
|
||||
input_b.are_items_and_components_equal(&cost_b.0)
|
||||
&& input_b.item_count >= cost_b.0.item_count
|
||||
},
|
||||
);
|
||||
|
||||
if match_a && match_b {
|
||||
self.inventory.set_stack(2, (*offer.output.0).clone()).await;
|
||||
} else {
|
||||
self.inventory.set_stack(2, ItemStack::EMPTY.clone()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for MerchantScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
self.inventory.on_close().await;
|
||||
// Vanilla drops items from merchant container on close
|
||||
for i in 0..2 {
|
||||
// Drop inputs only, output is virtual/ghost in some sense or just cleared
|
||||
let stack = self.inventory.remove_stack(i).await;
|
||||
if !stack.is_empty() {
|
||||
offer_or_drop_stack(player, stack).await;
|
||||
}
|
||||
}
|
||||
// Clear output slot
|
||||
self.inventory.set_stack(2, ItemStack::EMPTY.clone()).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let mut stack_left = ItemStack::EMPTY.clone();
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
if slot.has_stack().await {
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let slot_stack_guard = slot_stack_lock.lock().await;
|
||||
stack_left = slot_stack_guard.clone();
|
||||
drop(slot_stack_guard);
|
||||
|
||||
let mut slot_stack_mut = slot_stack_lock.lock().await;
|
||||
|
||||
if slot_index < 3 {
|
||||
// From merchant slots to player inventory
|
||||
if !self
|
||||
.insert_item(
|
||||
&mut slot_stack_mut,
|
||||
3,
|
||||
self.get_behaviour().slots.len() as i32,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
} else {
|
||||
// From player inventory to merchant inputs (0 and 1)
|
||||
if !self.insert_item(&mut slot_stack_mut, 0, 2, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if slot_stack_mut.is_empty() {
|
||||
drop(slot_stack_mut);
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
drop(slot_stack_mut);
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
}
|
||||
|
||||
stack_left
|
||||
})
|
||||
}
|
||||
|
||||
fn on_slot_click<'a>(
|
||||
&'a mut self,
|
||||
slot_index: i32,
|
||||
button: i32,
|
||||
action_type: pumpkin_protocol::java::server::play::SlotActionType,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
if slot_index == 2 {
|
||||
// Special handling for taking from output slot
|
||||
let result_slot = self.get_behaviour().slots[2].clone();
|
||||
if result_slot.has_stack().await {
|
||||
let result_stack = result_slot.get_cloned_stack().await;
|
||||
if !result_stack.is_empty() {
|
||||
// Consume inputs
|
||||
let (count_a, count_b, offer_xp) = {
|
||||
let offer = &mut self.offers[self.selected_offer];
|
||||
offer.uses += 1;
|
||||
let count_b = offer.cost_b.as_ref().map(|c| c.0.item_count);
|
||||
(offer.base_cost_a.0.item_count, count_b, offer.xp)
|
||||
};
|
||||
|
||||
let input_a = self.inventory.get_stack(0).await;
|
||||
let mut input_a = input_a.lock().await;
|
||||
input_a.decrement(count_a);
|
||||
if input_a.is_empty() {
|
||||
*input_a = ItemStack::EMPTY.clone();
|
||||
}
|
||||
drop(input_a);
|
||||
self.get_behaviour().slots[0].mark_dirty().await;
|
||||
|
||||
if let Some(count_b) = count_b {
|
||||
let input_b = self.inventory.get_stack(1).await;
|
||||
let mut input_b = input_b.lock().await;
|
||||
input_b.decrement(count_b);
|
||||
if input_b.is_empty() {
|
||||
*input_b = ItemStack::EMPTY.clone();
|
||||
}
|
||||
drop(input_b);
|
||||
self.get_behaviour().slots[1].mark_dirty().await;
|
||||
}
|
||||
|
||||
// Award XP
|
||||
player.award_experience(offer_xp).await;
|
||||
|
||||
if let Some(on_trade) = &self.on_trade {
|
||||
on_trade(self.selected_offer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.internal_on_slot_click(slot_index, button, action_type, player)
|
||||
.await;
|
||||
if slot_index == 0 || slot_index == 1 || slot_index == 2 {
|
||||
self.update_result_slot().await;
|
||||
self.send_content_updates().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod merchant_screen_handler;
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Ender chest inventory implementation.
|
||||
//!
|
||||
//! Ender chests are player-specific storage that persist across dimensions.
|
||||
//! Each player has their own ender chest contents that is accessible from
|
||||
//! any ender chest block. The inventory syncs across all ender chests
|
||||
//! for that player.
|
||||
//!
|
||||
//! # Viewer Tracking
|
||||
//!
|
||||
//! Ender chests track when players open and close them to properly
|
||||
//! manage the viewer count for animation purposes.
|
||||
|
||||
use std::{any::Any, array::from_fn, pin::Pin, sync::Arc};
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_world::{
|
||||
block::viewer::ViewerCountTracker,
|
||||
inventory::{Clearable, Inventory, InventoryFuture, split_stack},
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// A player's ender chest inventory.
|
||||
///
|
||||
/// Stores 27 slots (like a single chest) that are private to each player.
|
||||
/// Contents persist across dimensions and are accessible from any
|
||||
/// ender chest block.
|
||||
pub struct EnderChestInventory {
|
||||
/// The 27 item slots in the ender chest.
|
||||
pub items: [Arc<Mutex<ItemStack>>; Self::INVENTORY_SIZE],
|
||||
/// Viewer count tracker for lid animation.
|
||||
///
|
||||
/// Tracks how many players have the ender chest open to animate the lid.
|
||||
pub tracker: Mutex<Option<Arc<ViewerCountTracker>>>,
|
||||
}
|
||||
|
||||
impl Default for EnderChestInventory {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl EnderChestInventory {
|
||||
/// The size of an ender chest inventory (27 slots).
|
||||
pub const INVENTORY_SIZE: usize = 27;
|
||||
|
||||
/// Creates a new empty ender chest inventory.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
items: from_fn(|_| Arc::new(Mutex::new(ItemStack::EMPTY.clone()))),
|
||||
tracker: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the viewer count tracker for this inventory.
|
||||
///
|
||||
/// Used to animate the ender chest lid based on viewers.
|
||||
pub async fn set_tracker(&self, tracker: Arc<ViewerCountTracker>) {
|
||||
self.tracker.lock().await.replace(tracker);
|
||||
}
|
||||
|
||||
/// Checks if this inventory has a tracker set.
|
||||
pub async fn has_tracker(&self) -> bool {
|
||||
self.tracker.lock().await.is_some()
|
||||
}
|
||||
|
||||
/// Checks if the given tracker is associated with this inventory.
|
||||
pub async fn is_tracker(&self, tracker: &Arc<ViewerCountTracker>) -> bool {
|
||||
if let Some(value) = self.tracker.lock().await.as_ref() {
|
||||
return Arc::ptr_eq(value, tracker);
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl Inventory for EnderChestInventory {
|
||||
fn size(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> InventoryFuture<'_, bool> {
|
||||
Box::pin(async move {
|
||||
for slot in &self.items {
|
||||
if !slot.lock().await.is_empty() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
fn get_stack(&self, slot: usize) -> InventoryFuture<'_, Arc<Mutex<ItemStack>>> {
|
||||
Box::pin(async move { self.items[slot].clone() })
|
||||
}
|
||||
|
||||
fn remove_stack(&self, slot: usize) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
let mut removed = ItemStack::EMPTY.clone();
|
||||
let mut guard = self.items[slot].lock().await;
|
||||
std::mem::swap(&mut removed, &mut *guard);
|
||||
removed
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_stack_specific(&self, slot: usize, amount: u8) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move { split_stack(&self.items, slot, amount).await })
|
||||
}
|
||||
|
||||
fn set_stack(&self, slot: usize, stack: ItemStack) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
*self.items[slot].lock().await = stack;
|
||||
})
|
||||
}
|
||||
|
||||
fn on_open(&self) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
if let Some(tracker) = self.tracker.lock().await.as_ref() {
|
||||
tracker.open_container();
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_close(&self) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
if let Some(tracker) = self.tracker.lock().await.as_ref() {
|
||||
tracker.close_container();
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) {}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Clearable for EnderChestInventory {
|
||||
fn clear(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
for item in &self.items {
|
||||
*item.lock().await = ItemStack::EMPTY.clone();
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! Player inventory module.
|
||||
//!
|
||||
//! This module contains the player's inventory implementation, including:
|
||||
//! - [`PlayerInventory`] - The 36-slot main inventory plus equipment slots
|
||||
//! - [`PlayerScreenHandler`] - The screen handler for the player's inventory UI
|
||||
//! - [`EnderChestInventory`] - The ender chest storage
|
||||
|
||||
pub mod ender_chest_inventory;
|
||||
pub mod player_inventory;
|
||||
pub mod player_screen_handler;
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Player inventory implementation.
|
||||
//!
|
||||
//! This module implements the player's inventory, which consists of:
|
||||
//! - 36 main inventory slots (3 rows of 9 + hotbar)
|
||||
//! - Equipment slots (armor + off-hand)
|
||||
//!
|
||||
//! The first 9 slots of the main inventory are the hotbar (accessible with number keys).
|
||||
//! Slots 0-35 are the main inventory, with slot 40 being the off-hand slot.
|
||||
|
||||
use crate::entity_equipment::EntityEquipment;
|
||||
use crate::screen_handler::InventoryPlayer;
|
||||
|
||||
use pumpkin_data::data_component_impl::EquipmentSlot;
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_protocol::java::client::play::CSetPlayerInventory;
|
||||
use pumpkin_util::Hand;
|
||||
use pumpkin_world::inventory::split_stack;
|
||||
use pumpkin_world::inventory::{Clearable, Inventory, InventoryFuture};
|
||||
use std::any::Any;
|
||||
use std::array::from_fn;
|
||||
use std::collections::HashMap;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::warn;
|
||||
|
||||
/// The player's inventory.
|
||||
///
|
||||
/// Contains 36 main inventory slots (hotbar + main storage) plus
|
||||
/// equipment slots accessed through [`EntityEquipment`].
|
||||
pub struct PlayerInventory {
|
||||
/// The 36 main inventory slots (slots 0-35).
|
||||
///
|
||||
/// The first 9 slots (0-8) are the hotbar, the remaining 27 (9-35) are the main storage.
|
||||
pub main_inventory: [Arc<Mutex<ItemStack>>; Self::MAIN_SIZE],
|
||||
/// Mapping of slot indices to equipment slot types.
|
||||
///
|
||||
/// Used to identify which slots correspond to armor and off-hand equipment.
|
||||
pub equipment_slots: Arc<HashMap<usize, EquipmentSlot>>,
|
||||
/// The currently selected hotbar slot index (0-8).
|
||||
selected_slot: AtomicU8,
|
||||
/// The entity equipment storage for armor and off-hand items.
|
||||
///
|
||||
/// This is separate from the main inventory and is rendered on the player model.
|
||||
pub entity_equipment: Arc<Mutex<EntityEquipment>>,
|
||||
}
|
||||
|
||||
impl PlayerInventory {
|
||||
/// Size of the main inventory (36 slots: 27 storage + 9 hotbar).
|
||||
pub const MAIN_SIZE: usize = 36;
|
||||
/// Size of the hotbar (9 slots).
|
||||
const HOTBAR_SIZE: usize = 9;
|
||||
/// Slot index for the off-hand (40).
|
||||
pub const OFF_HAND_SLOT: usize = 40;
|
||||
|
||||
/// Creates a new player inventory.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `entity_equipment` - The entity equipment storage for armor/off-hand
|
||||
/// - `equipment_slots` - Mapping of slot indices to equipment slots
|
||||
// TODO: Add inventory load from nbt
|
||||
pub fn new(
|
||||
entity_equipment: Arc<Mutex<EntityEquipment>>,
|
||||
equipment_slots: Arc<HashMap<usize, EquipmentSlot>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
// Normal syntax can't be used here because Arc doesn't implement Copy
|
||||
main_inventory: from_fn(|_| Arc::new(Mutex::new(ItemStack::EMPTY.clone()))),
|
||||
equipment_slots,
|
||||
selected_slot: AtomicU8::new(0),
|
||||
entity_equipment,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the item in the currently selected hotbar slot.
|
||||
///
|
||||
/// This is the item the player is currently holding in their main hand.
|
||||
///
|
||||
/// Mojang name: `getSelectedStack`
|
||||
pub fn held_item(&self) -> Arc<Mutex<ItemStack>> {
|
||||
self.main_inventory
|
||||
.get(self.get_selected_slot() as usize)
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Gets the item in the specified hand.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `hand` - Which hand to get the item from
|
||||
pub async fn get_stack_in_hand(&self, hand: Hand) -> Arc<Mutex<ItemStack>> {
|
||||
match hand {
|
||||
Hand::Left => self.off_hand_item().await,
|
||||
Hand::Right => self.held_item(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if the given item Arc already points to the target equipment slot's stack.
|
||||
///
|
||||
/// Use before attempting to re-equip an item to prevent self-deadlock:
|
||||
/// Tokio's `Mutex` is not reentrant, so locking an `Arc<Mutex<T>>` that
|
||||
/// you already hold will deadlock forever.
|
||||
pub async fn is_already_equipped(
|
||||
&self,
|
||||
item_arc: &Arc<Mutex<ItemStack>>,
|
||||
slot: &EquipmentSlot,
|
||||
) -> bool {
|
||||
match slot {
|
||||
EquipmentSlot::OffHand(_) => Arc::ptr_eq(item_arc, &self.off_hand_item().await),
|
||||
EquipmentSlot::MainHand(_) => Arc::ptr_eq(item_arc, &self.held_item()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the item in the off-hand.
|
||||
///
|
||||
/// Mojang name: `getOffHandStack`
|
||||
pub async fn off_hand_item(&self) -> Arc<Mutex<ItemStack>> {
|
||||
let slot = self.equipment_slots.get(&Self::OFF_HAND_SLOT).unwrap();
|
||||
self.entity_equipment.lock().await.get(slot)
|
||||
}
|
||||
|
||||
/// Swaps the items between main hand and off-hand.
|
||||
///
|
||||
/// # Returns
|
||||
/// The new main hand item and new off-hand item.
|
||||
pub async fn swap_item(&self) -> (ItemStack, ItemStack) {
|
||||
let slot = self.equipment_slots.get(&Self::OFF_HAND_SLOT).unwrap();
|
||||
let mut equipment = self.entity_equipment.lock().await;
|
||||
let binding = self.held_item();
|
||||
let mut main_hand_item = binding.lock().await;
|
||||
let off_hand_item = main_hand_item.clone();
|
||||
*main_hand_item = equipment.put(slot, off_hand_item.clone()).await;
|
||||
(main_hand_item.clone(), off_hand_item)
|
||||
}
|
||||
|
||||
/// Checks if a slot index is a valid hotbar slot.
|
||||
#[must_use]
|
||||
pub const fn is_valid_hotbar_index(slot: usize) -> bool {
|
||||
slot < Self::HOTBAR_SIZE
|
||||
}
|
||||
|
||||
/// Adds a stack to any available slot, prioritizing stacking with existing items.
|
||||
async fn add_stack(&self, stack: ItemStack) -> usize {
|
||||
let mut slot_index = self.get_occupied_slot_with_room_for_stack(&stack).await;
|
||||
|
||||
if slot_index == -1 {
|
||||
slot_index = self.get_empty_slot().await;
|
||||
}
|
||||
|
||||
if slot_index == -1 {
|
||||
stack.item_count as usize
|
||||
} else {
|
||||
self.add_stack_to_slot(slot_index as usize, stack).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a stack to a specific slot.
|
||||
///
|
||||
/// Returns the number of items that couldn't fit.
|
||||
async fn add_stack_to_slot(&self, slot: usize, stack: ItemStack) -> usize {
|
||||
let mut stack_count = stack.item_count;
|
||||
let binding = self.get_stack(slot).await;
|
||||
let mut self_stack = binding.lock().await;
|
||||
|
||||
if self_stack.is_empty() {
|
||||
*self_stack = stack.copy_with_count(0);
|
||||
//self.set_stack(slot, self_stack).await;
|
||||
}
|
||||
|
||||
let count_left = self_stack.get_max_stack_size() - self_stack.item_count;
|
||||
let count_min = stack_count.min(count_left);
|
||||
|
||||
if count_min != 0 {
|
||||
stack_count -= count_min;
|
||||
self_stack.increment(count_min);
|
||||
}
|
||||
stack_count as usize
|
||||
}
|
||||
|
||||
/// Finds an empty slot in the inventory.
|
||||
///
|
||||
/// # Returns
|
||||
/// The slot index or -1 if inventory is full.
|
||||
async fn get_empty_slot(&self) -> i16 {
|
||||
for i in 0..Self::MAIN_SIZE {
|
||||
if self.main_inventory[i].lock().await.is_empty() {
|
||||
return i as i16;
|
||||
}
|
||||
}
|
||||
|
||||
-1
|
||||
}
|
||||
|
||||
/// Checks if a stack can be added to an existing stack.
|
||||
fn can_stack_add_more(existing_stack: &ItemStack, stack: &ItemStack) -> bool {
|
||||
!existing_stack.is_empty()
|
||||
&& existing_stack.are_items_and_components_equal(stack)
|
||||
&& existing_stack.is_stackable()
|
||||
&& existing_stack.item_count < existing_stack.get_max_stack_size()
|
||||
}
|
||||
|
||||
/// Finds a slot with the same item type that has room for more items.
|
||||
///
|
||||
/// Checks selected slot, off-hand, then other slots.
|
||||
async fn get_occupied_slot_with_room_for_stack(&self, stack: &ItemStack) -> i16 {
|
||||
if Self::can_stack_add_more(
|
||||
&*self
|
||||
.get_stack(self.get_selected_slot() as usize)
|
||||
.await
|
||||
.lock()
|
||||
.await,
|
||||
stack,
|
||||
) {
|
||||
i16::from(self.get_selected_slot())
|
||||
} else if Self::can_stack_add_more(
|
||||
&*self.get_stack(Self::OFF_HAND_SLOT).await.lock().await,
|
||||
stack,
|
||||
) {
|
||||
Self::OFF_HAND_SLOT as i16
|
||||
} else {
|
||||
for i in 0..Self::MAIN_SIZE {
|
||||
if Self::can_stack_add_more(&*self.main_inventory[i].lock().await, stack) {
|
||||
return i as i16;
|
||||
}
|
||||
}
|
||||
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a stack into any available slot.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `stack` - The stack to insert (modified in place)
|
||||
///
|
||||
/// # Returns
|
||||
/// `true` if any items were inserted, `false` otherwise.
|
||||
pub async fn insert_stack_anywhere(&self, stack: &mut ItemStack) -> bool {
|
||||
self.insert_stack(-1, stack).await
|
||||
}
|
||||
|
||||
/// Inserts a stack into a specific slot or any slot.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `slot` - The slot index, or -1 for any slot
|
||||
/// - `stack` - The stack to insert (modified in place)
|
||||
///
|
||||
/// # Returns
|
||||
/// `true` if any items were inserted, `false` otherwise.
|
||||
pub async fn insert_stack(&self, slot: i16, stack: &mut ItemStack) -> bool {
|
||||
if stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO: if (stack.isDamaged()) {
|
||||
|
||||
let mut i;
|
||||
|
||||
loop {
|
||||
i = stack.item_count;
|
||||
if slot == -1 {
|
||||
stack.set_count(self.add_stack(stack.clone()).await as u8);
|
||||
} else {
|
||||
stack.set_count(self.add_stack_to_slot(slot as usize, stack.clone()).await as u8);
|
||||
}
|
||||
|
||||
if stack.is_empty() || stack.item_count >= i {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Creative mode check
|
||||
|
||||
stack.item_count < i
|
||||
}
|
||||
|
||||
/// Finds the first slot containing a matching stack.
|
||||
///
|
||||
/// # Returns
|
||||
/// The slot index or -1 if not found.
|
||||
pub async fn get_slot_with_stack(&self, stack: &ItemStack) -> i16 {
|
||||
for i in 0..Self::MAIN_SIZE {
|
||||
if !self.main_inventory[i].lock().await.is_empty()
|
||||
&& self.main_inventory[i]
|
||||
.lock()
|
||||
.await
|
||||
.are_items_and_components_equal(stack)
|
||||
{
|
||||
return i as i16;
|
||||
}
|
||||
}
|
||||
|
||||
-1
|
||||
}
|
||||
|
||||
/// Finds an empty hotbar slot to swap an item to.
|
||||
///
|
||||
/// First looks for empty slots, then slots without enchantments.
|
||||
async fn get_swappable_hotbar_slot(&self) -> usize {
|
||||
let selected_slot = self.get_selected_slot() as usize;
|
||||
for i in 0..Self::HOTBAR_SIZE {
|
||||
let check_index = (i + selected_slot) % 9;
|
||||
if self.main_inventory[check_index].lock().await.is_empty() {
|
||||
return check_index;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(i) = (0..Self::HOTBAR_SIZE).next() {
|
||||
let check_index = (i + selected_slot) % 9;
|
||||
return check_index;
|
||||
}
|
||||
|
||||
self.get_selected_slot() as usize
|
||||
}
|
||||
|
||||
/// Swaps an item stack with an item on the hotbar.
|
||||
///
|
||||
/// Finds an empty hotbar slot and places the stack there.
|
||||
pub async fn swap_stack_with_hotbar(&self, stack: ItemStack) {
|
||||
self.set_selected_slot(self.get_swappable_hotbar_slot().await as u8);
|
||||
|
||||
if !self.main_inventory[self.get_selected_slot() as usize]
|
||||
.lock()
|
||||
.await
|
||||
.is_empty()
|
||||
{
|
||||
let empty_slot = self.get_empty_slot().await;
|
||||
if empty_slot != -1 {
|
||||
self.set_stack(
|
||||
empty_slot as usize,
|
||||
self.main_inventory[self.get_selected_slot() as usize]
|
||||
.lock()
|
||||
.await
|
||||
.clone(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
self.set_stack(self.get_selected_slot() as usize, stack)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Swaps the items at two slot indices.
|
||||
pub async fn swap_slot_with_hotbar(&self, slot: usize) {
|
||||
self.set_selected_slot(self.get_swappable_hotbar_slot().await as u8);
|
||||
let stack = self.main_inventory[self.get_selected_slot() as usize]
|
||||
.lock()
|
||||
.await
|
||||
.clone();
|
||||
self.set_stack(
|
||||
self.get_selected_slot() as usize,
|
||||
self.main_inventory[slot].lock().await.clone(),
|
||||
)
|
||||
.await;
|
||||
self.set_stack(slot, stack).await;
|
||||
}
|
||||
|
||||
/// Gives a stack to the player or drops it if inventory is full.
|
||||
pub async fn offer_or_drop_stack(&self, stack: ItemStack, player: &dyn InventoryPlayer) {
|
||||
self.offer(stack, true, player).await;
|
||||
}
|
||||
|
||||
/// Gives a stack to the player, optionally notifying the client.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `stack` - The stack to give
|
||||
/// - `notify_client` - Whether to send inventory update packets
|
||||
/// - `player` - The player to give the stack to
|
||||
pub async fn offer(&self, stack: ItemStack, notify_client: bool, player: &dyn InventoryPlayer) {
|
||||
let mut stack = stack;
|
||||
while !stack.is_empty() {
|
||||
let mut room_for_stack = self.get_occupied_slot_with_room_for_stack(&stack).await;
|
||||
if room_for_stack == -1 {
|
||||
room_for_stack = self.get_empty_slot().await;
|
||||
}
|
||||
|
||||
if room_for_stack == -1 {
|
||||
player.drop_item(stack, false).await;
|
||||
break;
|
||||
}
|
||||
|
||||
let items_fit = stack.get_max_stack_size()
|
||||
- self
|
||||
.get_stack(room_for_stack as usize)
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.item_count;
|
||||
if self
|
||||
.insert_stack(room_for_stack, &mut stack.split(items_fit))
|
||||
.await
|
||||
&& notify_client
|
||||
{
|
||||
player
|
||||
.enqueue_slot_set_packet(&CSetPlayerInventory::new(
|
||||
i32::from(room_for_stack).into(),
|
||||
&self
|
||||
.get_stack(room_for_stack as usize)
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.clone()
|
||||
.into(),
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clearable for PlayerInventory {
|
||||
fn clear(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
for item in &self.main_inventory {
|
||||
*item.lock().await = ItemStack::EMPTY.clone();
|
||||
}
|
||||
|
||||
self.entity_equipment.lock().await.clear();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Inventory for PlayerInventory {
|
||||
fn size(&self) -> usize {
|
||||
self.main_inventory.len() + self.equipment_slots.len()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> InventoryFuture<'_, bool> {
|
||||
Box::pin(async move {
|
||||
for item in &self.main_inventory {
|
||||
if !item.lock().await.is_empty() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for slot in self.equipment_slots.values() {
|
||||
if !self
|
||||
.entity_equipment
|
||||
.lock()
|
||||
.await
|
||||
.get(slot)
|
||||
.lock()
|
||||
.await
|
||||
.is_empty()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
fn get_stack(&self, slot: usize) -> InventoryFuture<'_, Arc<Mutex<ItemStack>>> {
|
||||
Box::pin(async move {
|
||||
if slot < self.main_inventory.len() {
|
||||
self.main_inventory[slot].clone()
|
||||
} else {
|
||||
let slot = self.equipment_slots.get(&slot).unwrap();
|
||||
self.entity_equipment.lock().await.get(slot)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_stack(&self, slot: usize) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
if slot < self.main_inventory.len() {
|
||||
let mut removed = ItemStack::EMPTY.clone();
|
||||
let mut guard = self.main_inventory[slot].lock().await;
|
||||
std::mem::swap(&mut removed, &mut *guard);
|
||||
removed
|
||||
} else {
|
||||
let slot = self.equipment_slots.get(&slot).unwrap();
|
||||
self.entity_equipment
|
||||
.lock()
|
||||
.await
|
||||
.put(slot, ItemStack::EMPTY.clone())
|
||||
.await
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_stack_specific(&self, slot: usize, amount: u8) -> InventoryFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
if slot < self.main_inventory.len() {
|
||||
split_stack(&self.main_inventory, slot, amount).await
|
||||
} else {
|
||||
let slot = self.equipment_slots.get(&slot).unwrap();
|
||||
|
||||
let equipment = self.entity_equipment.lock().await.get(slot);
|
||||
let mut stack = equipment.lock().await;
|
||||
|
||||
if !stack.is_empty() {
|
||||
return stack.split(amount);
|
||||
}
|
||||
|
||||
ItemStack::EMPTY.clone()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn set_stack(&self, slot: usize, stack: ItemStack) -> InventoryFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
if slot < self.main_inventory.len() {
|
||||
*self.main_inventory[slot].lock().await = stack;
|
||||
} else if let Some(slot) = self.equipment_slots.get(&slot) {
|
||||
self.entity_equipment.lock().await.put(slot, stack).await;
|
||||
} else {
|
||||
warn!("Failed to get Equipment Slot at {slot}");
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) {}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl PlayerInventory {
|
||||
/// Sets the selected hotbar slot.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if the slot index is not a valid hotbar index.
|
||||
pub fn set_selected_slot(&self, slot: u8) {
|
||||
if Self::is_valid_hotbar_index(slot as usize) {
|
||||
self.selected_slot.store(slot, Ordering::Relaxed);
|
||||
} else {
|
||||
panic!("Invalid hotbar slot: {slot}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the currently selected hotbar slot index.
|
||||
pub fn get_selected_slot(&self) -> u8 {
|
||||
self.selected_slot.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Player inventory screen handler.
|
||||
//!
|
||||
//! This module handles the player's inventory screen (opened with E key).
|
||||
//! It includes:
|
||||
//! - The 2x2 crafting grid (inventory crafting)
|
||||
//! - Armor slots (head, chest, legs, feet)
|
||||
//! - Main inventory (27 slots)
|
||||
//! - Hotbar (9 slots)
|
||||
//! - Offhand slot
|
||||
//!
|
||||
//! # Slot Layout
|
||||
//!
|
||||
//! The player screen handler uses the following slot indices:
|
||||
//! - 0: Crafting result
|
||||
//! - 1-4: Crafting grid (2x2)
|
||||
//! - 5-8: Armor slots (head, chest, legs, feet)
|
||||
//! - 9-35: Main inventory
|
||||
//! - 36-44: Hotbar
|
||||
//! - 45: Offhand
|
||||
|
||||
use super::player_inventory::PlayerInventory;
|
||||
use crate::crafting::crafting_inventory::CraftingInventory;
|
||||
use crate::crafting::crafting_screen_handler::CraftingScreenHandler;
|
||||
use crate::crafting::recipes::{RecipeFinderScreenHandler, RecipeInputInventory};
|
||||
use crate::screen_handler::{
|
||||
InventoryPlayer, ItemStackFuture, ScreenHandler, ScreenHandlerBehaviour, ScreenHandlerFuture,
|
||||
};
|
||||
use crate::slot::{ArmorSlot, NormalSlot, Slot};
|
||||
use pumpkin_data::data_component_impl::{EquipmentSlot, EquipmentType, EquippableImpl};
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::screen::WindowType;
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Screen handler for the player's inventory.
|
||||
///
|
||||
/// Manages the player's inventory UI including crafting, armor, and
|
||||
/// the main inventory. This is the default screen shown when pressing E.
|
||||
pub struct PlayerScreenHandler {
|
||||
/// Core screen handler behavior (slots, sync ID, listeners).
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
/// The 2x2 crafting grid inventory.
|
||||
crafting_inventory: Arc<dyn RecipeInputInventory>,
|
||||
}
|
||||
|
||||
impl RecipeFinderScreenHandler for PlayerScreenHandler {}
|
||||
|
||||
impl CraftingScreenHandler<CraftingInventory> for PlayerScreenHandler {}
|
||||
|
||||
// TODO: Fully implement this
|
||||
impl PlayerScreenHandler {
|
||||
/// Equipment slot order for armor display.
|
||||
const EQUIPMENT_SLOT_ORDER: [EquipmentSlot; 4] = [
|
||||
EquipmentSlot::HEAD,
|
||||
EquipmentSlot::CHEST,
|
||||
EquipmentSlot::LEGS,
|
||||
EquipmentSlot::FEET,
|
||||
];
|
||||
|
||||
/// Checks if a slot index is in the hotbar.
|
||||
///
|
||||
/// Hotbar slots are 36-44 in the protocol (0-indexed 36-44).
|
||||
#[must_use]
|
||||
pub fn is_in_hotbar(slot: u8) -> bool {
|
||||
(36..=45).contains(&slot)
|
||||
}
|
||||
|
||||
/// Gets a slot by its index.
|
||||
pub fn get_slot(&self, slot: usize) -> Arc<dyn Slot> {
|
||||
self.behaviour.slots[slot].clone()
|
||||
}
|
||||
|
||||
/// Creates a new player screen handler.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `player_inventory` - The player's inventory
|
||||
/// - `window_type` - The window type (usually None for player inventory)
|
||||
/// - `sync_id` - The synchronization ID
|
||||
pub async fn new(
|
||||
player_inventory: &Arc<PlayerInventory>,
|
||||
window_type: Option<WindowType>,
|
||||
sync_id: u8,
|
||||
provider: Option<Arc<dyn crate::crafting::recipe_provider::RecipeProvider>>,
|
||||
) -> Self {
|
||||
let crafting_inventory: Arc<dyn RecipeInputInventory> =
|
||||
Arc::new(CraftingInventory::new(2, 2));
|
||||
|
||||
let mut player_screen_handler = Self {
|
||||
behaviour: ScreenHandlerBehaviour::new(sync_id, window_type),
|
||||
crafting_inventory: crafting_inventory.clone(),
|
||||
};
|
||||
|
||||
player_screen_handler
|
||||
.add_recipe_slots(crafting_inventory, provider)
|
||||
.await;
|
||||
|
||||
// Add armor slots (head, chest, legs, feet)
|
||||
for i in 0..4 {
|
||||
player_screen_handler.add_slot(Arc::new(ArmorSlot::new(
|
||||
player_inventory.clone(),
|
||||
39 - i,
|
||||
Self::EQUIPMENT_SLOT_ORDER[i].clone(),
|
||||
)));
|
||||
}
|
||||
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
|
||||
// Add main inventory and hotbar
|
||||
player_screen_handler.add_player_slots(&player_inventory);
|
||||
|
||||
// Offhand slot (index 40 in player inventory, 45 in screen handler)
|
||||
// TODO: onEquipStack callback for offhand
|
||||
player_screen_handler.add_slot(Arc::new(NormalSlot::new(player_inventory.clone(), 40)));
|
||||
|
||||
player_screen_handler
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for PlayerScreenHandler {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn on_closed<'a>(&'a mut self, player: &'a dyn InventoryPlayer) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.default_on_closed(player).await;
|
||||
//TODO: this.craftingResultInventory.clear();
|
||||
self.drop_inventory(player, self.crafting_inventory.clone())
|
||||
.await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Performs quick move (shift-click) for the given slot.
|
||||
///
|
||||
/// The quick move logic depends on the source slot:
|
||||
/// - Crafting result (0) -> Player inventory (from end)
|
||||
/// - Crafting grid (1-4) -> Player inventory (from start)
|
||||
/// - Armor slots (5-8) -> Player inventory, unequips
|
||||
/// - Armor items -> Armor slots if empty
|
||||
/// - Offhand items -> Offhand slot if empty
|
||||
/// - Main inventory (9-35) -> Hotbar
|
||||
/// - Hotbar (36-44) -> Main inventory
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ItemStackFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let slot = self.get_behaviour().slots[slot_index as usize].clone();
|
||||
|
||||
// TODO: Equippable component
|
||||
|
||||
if slot.has_stack().await {
|
||||
let slot_stack_lock = slot.get_stack().await;
|
||||
let mut slot_stack = slot_stack_lock.lock().await;
|
||||
let stack_prev = slot_stack.clone();
|
||||
|
||||
let equipment_slot = slot_stack
|
||||
.get_data_component::<EquippableImpl>()
|
||||
.map_or(&EquipmentSlot::MAIN_HAND, |equippable| equippable.slot);
|
||||
|
||||
// Quick move logic based on source slot
|
||||
let success = if slot_index == 0 {
|
||||
// From crafting result slot (0) -> Player Inventory (9-45, from end)
|
||||
self.insert_item(&mut slot_stack, 9, 45, true).await
|
||||
} else if (1..5).contains(&slot_index) {
|
||||
// From craft ingredient slots (1-4) -> Player Inventory (9-45, from start)
|
||||
self.insert_item(&mut slot_stack, 9, 45, false).await
|
||||
} else if (5..9).contains(&slot_index) {
|
||||
// From armour slots (5-8) -> Player Inventory (9-45, from start)
|
||||
let result = self.insert_item(&mut slot_stack, 9, 45, false).await;
|
||||
|
||||
if result {
|
||||
player
|
||||
.enqueue_equipment_change(equipment_slot, ItemStack::EMPTY)
|
||||
.await;
|
||||
}
|
||||
result
|
||||
} else if equipment_slot.slot_type() == EquipmentType::HumanoidArmor
|
||||
&& self
|
||||
.get_slot((8 - equipment_slot.get_entity_slot_id()) as usize)
|
||||
.get_cloned_stack()
|
||||
.await
|
||||
.is_empty()
|
||||
{
|
||||
// Into empty armour slots (5-8)
|
||||
let index = 8 - equipment_slot.get_entity_slot_id();
|
||||
let result = self
|
||||
.insert_item(&mut slot_stack, index, index + 1, false)
|
||||
.await;
|
||||
|
||||
if result {
|
||||
player
|
||||
.enqueue_equipment_change(equipment_slot, &stack_prev)
|
||||
.await;
|
||||
}
|
||||
result
|
||||
} else if matches!(equipment_slot, EquipmentSlot::OffHand(_))
|
||||
&& slot_index != 45
|
||||
&& self.get_slot(45).get_cloned_stack().await.is_empty()
|
||||
{
|
||||
// Into empty offhand slot (45)
|
||||
let index = 45;
|
||||
self.insert_item(&mut slot_stack, index, index + 1, false)
|
||||
.await
|
||||
} else if (9..36).contains(&slot_index) {
|
||||
// From main inventory (9-35) -> Hotbar (36-44)
|
||||
self.insert_item(&mut slot_stack, 36, 45, false).await
|
||||
} else if (36..45).contains(&slot_index) {
|
||||
// From hotbar (36-44) -> Main inventory (9-35)
|
||||
self.insert_item(&mut slot_stack, 9, 36, false).await
|
||||
} else {
|
||||
// Fallback to moving into the player inventory area
|
||||
self.insert_item(&mut slot_stack, 9, 45, false).await
|
||||
};
|
||||
|
||||
if !success {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
|
||||
let stack = slot_stack.clone();
|
||||
drop(slot_stack); // release the lock before calling other methods
|
||||
|
||||
if stack.is_empty() {
|
||||
slot.set_stack_prev(ItemStack::EMPTY.clone(), stack_prev.clone())
|
||||
.await;
|
||||
} else {
|
||||
slot.mark_dirty().await;
|
||||
}
|
||||
|
||||
if stack.item_count == stack_prev.item_count {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
|
||||
let mut taken_stack = stack_prev.clone();
|
||||
taken_stack.set_count(stack_prev.item_count - stack.item_count);
|
||||
slot.on_take_item(player, &taken_stack).await;
|
||||
|
||||
if slot_index == 0 {
|
||||
// From crafting result slot (0)
|
||||
// Notify the result slot to refill
|
||||
slot.on_quick_move_crafted(stack.clone(), stack_prev.clone())
|
||||
.await;
|
||||
// For crafting result slot, drop any remaining items
|
||||
if !stack.is_empty() {
|
||||
player.drop_item(stack, false).await;
|
||||
}
|
||||
}
|
||||
|
||||
return stack_prev;
|
||||
}
|
||||
|
||||
// Nothing changed
|
||||
ItemStack::EMPTY.clone()
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,463 @@
|
||||
//! Inventory slot implementations.
|
||||
//!
|
||||
//! This module defines the [`Slot`] trait and its implementations. Slots represent
|
||||
//! individual positions in an inventory that can hold items.
|
||||
//!
|
||||
//! # Slot Types
|
||||
//!
|
||||
//! - [`NormalSlot`] - A basic inventory slot with no restrictions
|
||||
//! - [`ArmorSlot`] - An armor slot that only accepts appropriate item types
|
||||
//! (helmets in head slot, chestplates in chest slot, etc.)
|
||||
//!
|
||||
//! # Slot Operations
|
||||
//!
|
||||
//! Slots support various operations:
|
||||
//! - Getting/setting the item stack
|
||||
//! - Checking if items can be inserted
|
||||
//! - Taking items from the slot
|
||||
//! - Marking the slot as changed (dirty)
|
||||
//! - Callbacks for slot interaction events
|
||||
|
||||
use std::{
|
||||
pin::Pin,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU8, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::screen_handler::InventoryPlayer;
|
||||
|
||||
use pumpkin_data::data_component_impl::EquipmentSlot;
|
||||
use pumpkin_data::item::Item;
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
use tokio::{sync::Mutex, time::timeout};
|
||||
|
||||
/// Type alias for async slot operations.
|
||||
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// A slot in an inventory.
|
||||
///
|
||||
/// The slot trait defines how individual inventory positions behave.
|
||||
/// Different slot types (normal, armor, result slots) implement this
|
||||
/// trait to enforce their specific restrictions.
|
||||
// Slot.java
|
||||
pub trait Slot: Send + Sync {
|
||||
/// Returns the inventory containing this slot.
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory>;
|
||||
|
||||
/// Returns the index of this slot within its inventory.
|
||||
fn get_index(&self) -> usize;
|
||||
|
||||
/// Sets the protocol ID of this slot.
|
||||
fn set_id(&self, index: usize);
|
||||
|
||||
/// Callback for when an item is quick-moved from this slot.
|
||||
///
|
||||
/// Used to notify result slots (like crafting output) that they
|
||||
/// need to refill their contents.
|
||||
///
|
||||
/// # Note
|
||||
/// You **MUST** call this after changing the stack and releasing
|
||||
/// any locks to avoid deadlocks.
|
||||
///
|
||||
/// Also see: [`ScreenHandler::quick_move`](crate::screen_handler::ScreenHandler::quick_move)
|
||||
fn on_quick_move_crafted(
|
||||
&self,
|
||||
_stack: ItemStack,
|
||||
_stack_prev: ItemStack,
|
||||
) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async {}) // Default implementation
|
||||
}
|
||||
|
||||
/// Callback for when an item is taken from this slot.
|
||||
///
|
||||
/// Also see: [`safe_take`]
|
||||
fn on_take_item<'a>(
|
||||
&'a self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
_stack: &'a ItemStack,
|
||||
) -> BoxFuture<'a, ()> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
self.mark_dirty().await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Plugin callback for slot clicks.
|
||||
///
|
||||
/// Called when a player clicks on this slot. Can be used by
|
||||
/// plugins to intercept or modify click behavior.
|
||||
fn on_click(&self, _player: &dyn InventoryPlayer) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async {}) // Default implementation
|
||||
}
|
||||
|
||||
/// Checks if the given stack can be inserted into this slot.
|
||||
fn can_insert<'a>(&'a self, _stack: &'a ItemStack) -> BoxFuture<'a, bool> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move { true })
|
||||
}
|
||||
|
||||
/// Gets the stack in this slot.
|
||||
fn get_stack(&self) -> BoxFuture<'_, Arc<Mutex<ItemStack>>> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move { self.get_inventory().get_stack(self.get_index()).await })
|
||||
}
|
||||
|
||||
/// Gets a copy of the stack in this slot.
|
||||
///
|
||||
/// Acquires a lock and returns a clone of the stack.
|
||||
fn get_cloned_stack(&self) -> BoxFuture<'_, ItemStack> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
let stack = self.get_stack().await;
|
||||
let lock = timeout(Duration::from_secs(5), stack.lock())
|
||||
.await
|
||||
.expect("Timed out while trying to acquire lock");
|
||||
|
||||
lock.clone()
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks if this slot has a non-empty stack.
|
||||
fn has_stack(&self) -> BoxFuture<'_, bool> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
let inv = self.get_inventory();
|
||||
!inv.get_stack(self.get_index())
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.is_empty()
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the stack in this slot.
|
||||
///
|
||||
/// # Note
|
||||
/// Make sure to drop any locks to the slot stack before calling this.
|
||||
fn set_stack(&self, stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
self.set_stack_no_callbacks(stack).await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the stack with previous stack reference.
|
||||
///
|
||||
/// Some slots (like armor) need to know the previous stack for callbacks.
|
||||
fn set_stack_prev(&self, stack: ItemStack, _previous_stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
self.set_stack_no_callbacks(stack).await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the stack without calling callbacks.
|
||||
fn set_stack_no_callbacks(&self, stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
let inv = self.get_inventory();
|
||||
inv.set_stack(self.get_index(), stack).await;
|
||||
self.mark_dirty().await;
|
||||
})
|
||||
}
|
||||
|
||||
/// Marks this slot as changed.
|
||||
///
|
||||
/// Must be implemented by concrete types.
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()>;
|
||||
|
||||
/// Gets the maximum item count for this slot.
|
||||
fn get_max_item_count(&self) -> BoxFuture<'_, u8> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move { self.get_inventory().get_max_count_per_stack() })
|
||||
}
|
||||
|
||||
/// Gets the maximum item count for the given stack in this slot.
|
||||
fn get_max_item_count_for_stack<'a>(&'a self, stack: &'a ItemStack) -> BoxFuture<'a, u8> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
self.get_max_item_count()
|
||||
.await
|
||||
.min(stack.get_max_stack_size())
|
||||
})
|
||||
}
|
||||
|
||||
/// Removes a specific amount of items from this slot.
|
||||
///
|
||||
/// Mojang name: `remove`
|
||||
fn take_stack(&self, amount: u8) -> BoxFuture<'_, ItemStack> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
let inv = self.get_inventory();
|
||||
inv.remove_stack_specific(self.get_index(), amount).await
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks if the player can take items from this slot.
|
||||
///
|
||||
/// Mojang name: `mayPickup`
|
||||
fn can_take_items(&self, _player: &dyn InventoryPlayer) -> BoxFuture<'_, bool> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move { true })
|
||||
}
|
||||
|
||||
/// Checks if this slot can be modified by the player.
|
||||
///
|
||||
/// Mojang name: `allowModification`
|
||||
fn allow_modification<'a>(&'a self, player: &'a dyn InventoryPlayer) -> BoxFuture<'a, bool> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
self.can_insert(&self.get_cloned_stack().await).await
|
||||
&& self.can_take_items(player).await
|
||||
})
|
||||
}
|
||||
|
||||
/// Tries to take a stack in the given range.
|
||||
///
|
||||
/// Returns `None` if can't take items or if slot is empty.
|
||||
/// For result slots, cannot take partial stacks.
|
||||
///
|
||||
/// Mojang name: `tryRemove`
|
||||
fn try_take_stack_range<'a>(
|
||||
&'a self,
|
||||
min: u8,
|
||||
max: u8,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
) -> BoxFuture<'a, Option<ItemStack>> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
if !self.can_take_items(player).await {
|
||||
return None;
|
||||
}
|
||||
if !self.allow_modification(player).await
|
||||
&& self.get_cloned_stack().await.item_count > max
|
||||
{
|
||||
// If the slot is not allowed to be modified, we cannot take a partial stack from it.
|
||||
return None;
|
||||
}
|
||||
let min = min.min(max);
|
||||
let stack = self.take_stack(min).await;
|
||||
|
||||
if stack.is_empty() {
|
||||
None
|
||||
} else {
|
||||
if self.get_cloned_stack().await.is_empty() {
|
||||
self.set_stack_prev(ItemStack::EMPTY.clone(), stack.clone())
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(stack)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Safely tries to take a stack of items from the slot.
|
||||
///
|
||||
/// Returns an empty stack if can't take. Triggers callbacks.
|
||||
///
|
||||
/// Mojang name: `safeTake`
|
||||
fn safe_take<'a>(
|
||||
&'a self,
|
||||
min: u8,
|
||||
max: u8,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
) -> BoxFuture<'a, ItemStack> {
|
||||
Box::pin(async move {
|
||||
let stack = self.try_take_stack_range(min, max, player).await;
|
||||
|
||||
if let Some(stack) = &stack {
|
||||
self.on_take_item(player, stack).await;
|
||||
}
|
||||
|
||||
stack.unwrap_or_else(|| ItemStack::EMPTY.clone())
|
||||
})
|
||||
}
|
||||
|
||||
/// Inserts a stack into this slot.
|
||||
///
|
||||
/// Returns any leftover items that couldn't fit.
|
||||
fn insert_stack(&self, stack: ItemStack) -> BoxFuture<'_, ItemStack> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
let stack_item_count = stack.item_count;
|
||||
self.insert_stack_count(stack, stack_item_count).await
|
||||
})
|
||||
}
|
||||
|
||||
/// Inserts a specific count from a stack.
|
||||
///
|
||||
/// Returns any leftover items.
|
||||
fn insert_stack_count(&self, mut stack: ItemStack, count: u8) -> BoxFuture<'_, ItemStack> {
|
||||
// Default implementation logic:
|
||||
Box::pin(async move {
|
||||
if !stack.is_empty() && self.can_insert(&stack).await {
|
||||
let stack_mutex = self.get_stack().await;
|
||||
let mut stack_self = stack_mutex.lock().await;
|
||||
let min_count = count
|
||||
.min(stack.item_count)
|
||||
.min(self.get_max_item_count_for_stack(&stack).await - stack_self.item_count);
|
||||
|
||||
if min_count != 0 {
|
||||
if stack_self.is_empty() {
|
||||
drop(stack_self);
|
||||
self.set_stack(stack.split(min_count)).await;
|
||||
} else if stack.are_items_and_components_equal(&stack_self) {
|
||||
stack.decrement(min_count);
|
||||
stack_self.increment(min_count);
|
||||
let cloned_stack = stack_self.clone();
|
||||
drop(stack_self);
|
||||
self.set_stack(cloned_stack).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
if stack.is_empty() {
|
||||
ItemStack::EMPTY.clone()
|
||||
} else {
|
||||
stack
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A normal inventory slot.
|
||||
///
|
||||
/// Just called `Slot` in vanilla Minecraft. This is the basic
|
||||
/// slot implementation with no special restrictions.
|
||||
pub struct NormalSlot {
|
||||
/// The inventory containing this slot.
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
/// Index of this slot within its inventory.
|
||||
pub index: usize,
|
||||
/// Protocol ID for this slot (assigned by screen handler).
|
||||
pub id: AtomicU8,
|
||||
}
|
||||
|
||||
impl NormalSlot {
|
||||
/// Creates a new normal slot.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `inventory` - The containing inventory
|
||||
/// - `index` - The slot index within the inventory
|
||||
pub fn new(inventory: Arc<dyn Inventory>, index: usize) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
index,
|
||||
id: AtomicU8::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Slot for NormalSlot {
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory> {
|
||||
self.inventory.clone()
|
||||
}
|
||||
|
||||
fn get_index(&self) -> usize {
|
||||
self.index
|
||||
}
|
||||
|
||||
fn set_id(&self, id: usize) {
|
||||
self.id.store(id as u8, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.inventory.mark_dirty();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An armor equipment slot.
|
||||
///
|
||||
/// Restricts which items can be placed based on the equipment slot type:
|
||||
/// - Head: Helmets, skulls, carved pumpkins
|
||||
/// - Chest: Chestplates, elytra
|
||||
/// - Legs: Leggings
|
||||
/// - Feet: Boots
|
||||
// ArmorSlot.java
|
||||
pub struct ArmorSlot {
|
||||
/// The inventory containing this slot (usually player inventory).
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
/// Index of this slot within its inventory.
|
||||
pub index: usize,
|
||||
/// Protocol ID for this slot (assigned by screen handler).
|
||||
pub id: AtomicU8,
|
||||
/// The equipment slot type (head, chest, legs, feet, or off-hand).
|
||||
pub equipment_slot: EquipmentSlot,
|
||||
}
|
||||
|
||||
impl ArmorSlot {
|
||||
/// Creates a new armor slot.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `inventory` - The containing inventory
|
||||
/// - `index` - The slot index
|
||||
/// - `equipment_slot` - The equipment slot type (head, chest, legs, feet)
|
||||
pub fn new(inventory: Arc<dyn Inventory>, index: usize, equipment_slot: EquipmentSlot) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
index,
|
||||
id: AtomicU8::new(0),
|
||||
equipment_slot,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Slot for ArmorSlot {
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory> {
|
||||
self.inventory.clone()
|
||||
}
|
||||
|
||||
fn get_index(&self) -> usize {
|
||||
self.index
|
||||
}
|
||||
|
||||
fn set_id(&self, id: usize) {
|
||||
self.id.store(id as u8, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Restricts inserts to appropriate armor types.
|
||||
fn can_insert<'a>(&'a self, stack: &'a ItemStack) -> BoxFuture<'a, bool> {
|
||||
Box::pin(async move {
|
||||
match self.equipment_slot {
|
||||
EquipmentSlot::Head(_) => {
|
||||
stack.is_helmet() || stack.is_skull() || stack.item == &Item::CARVED_PUMPKIN
|
||||
}
|
||||
EquipmentSlot::Chest(_) => stack.is_chestplate() || stack.item == &Item::ELYTRA,
|
||||
EquipmentSlot::Legs(_) => stack.is_leggings(),
|
||||
EquipmentSlot::Feet(_) => stack.is_boots(),
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn set_stack_prev(&self, stack: ItemStack, _previous_stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
//TODO: this.entity.onEquipStack(this.equipmentSlot, previousStack, stack);
|
||||
self.set_stack_no_callbacks(stack).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.inventory.mark_dirty();
|
||||
})
|
||||
}
|
||||
|
||||
/// Armor slots can only hold one item.
|
||||
fn get_max_item_count(&self) -> BoxFuture<'_, u8> {
|
||||
Box::pin(async move { 1 })
|
||||
}
|
||||
|
||||
/// TODO: Check for curse of binding enchantment.
|
||||
fn can_take_items(&self, _player: &dyn InventoryPlayer) -> BoxFuture<'_, bool> {
|
||||
Box::pin(async move {
|
||||
// TODO: Check enchantments
|
||||
true
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::player::player_inventory::PlayerInventory;
|
||||
use crate::screen_handler::{
|
||||
InventoryPlayer, ScreenHandler, ScreenHandlerBehaviour, ScreenHandlerFuture,
|
||||
};
|
||||
use crate::slot::{BoxFuture, NormalSlot, Slot};
|
||||
|
||||
use pumpkin_data::item::Item;
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::recipes::{RECIPES_STONECUTTING, StonecutterRecipe};
|
||||
use pumpkin_data::screen::WindowType;
|
||||
use pumpkin_data::statistic::StatisticCategory;
|
||||
use pumpkin_protocol::java::server::play::SlotActionType;
|
||||
use pumpkin_world::inventory::Inventory;
|
||||
use pumpkin_world::inventory::SimpleInventory;
|
||||
|
||||
pub struct StonecutterScreenHandler {
|
||||
behaviour: ScreenHandlerBehaviour,
|
||||
pub input_inventory: Arc<SimpleInventory>,
|
||||
pub output_inventory: Arc<SimpleInventory>,
|
||||
pub selected_recipe: AtomicU8,
|
||||
}
|
||||
|
||||
impl StonecutterScreenHandler {
|
||||
pub fn new(sync_id: u8, player_inventory: &Arc<PlayerInventory>) -> Self {
|
||||
let behaviour = ScreenHandlerBehaviour::new(sync_id, Some(WindowType::Stonecutter));
|
||||
let input_inventory = Arc::new(SimpleInventory::new(1));
|
||||
let output_inventory = Arc::new(SimpleInventory::new(1));
|
||||
|
||||
let mut handler = Self {
|
||||
behaviour,
|
||||
input_inventory: input_inventory.clone(),
|
||||
output_inventory: output_inventory.clone(),
|
||||
selected_recipe: AtomicU8::new(u8::MAX),
|
||||
};
|
||||
|
||||
handler.add_slot(Arc::new(NormalSlot::new(
|
||||
input_inventory.clone() as Arc<dyn Inventory>,
|
||||
0,
|
||||
)));
|
||||
handler.add_slot(Arc::new(StonecutterOutputSlot::new(
|
||||
output_inventory as Arc<dyn Inventory>,
|
||||
input_inventory as Arc<dyn Inventory>,
|
||||
0,
|
||||
)));
|
||||
|
||||
let player_inventory: Arc<dyn Inventory> = player_inventory.clone();
|
||||
|
||||
handler.add_player_slots(&player_inventory);
|
||||
|
||||
handler
|
||||
}
|
||||
|
||||
async fn update_output(&self) {
|
||||
let input_stack = self.input_inventory.get_stack(0).await;
|
||||
let input_lock = input_stack.lock().await;
|
||||
|
||||
if input_lock.is_empty() {
|
||||
self.output_inventory
|
||||
.set_stack(0, ItemStack::EMPTY.clone())
|
||||
.await;
|
||||
self.selected_recipe.store(u8::MAX, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
|
||||
let available_recipes = Self::get_available_recipes(&input_lock);
|
||||
let recipe_index = self.selected_recipe.load(Ordering::Relaxed);
|
||||
|
||||
if recipe_index != u8::MAX && (recipe_index as usize) < available_recipes.len() {
|
||||
let recipe = available_recipes[recipe_index as usize];
|
||||
let item =
|
||||
Item::from_registry_key(recipe.result.id).expect("Invalid recipe result item");
|
||||
let result = ItemStack::new(recipe.result.count, item);
|
||||
self.output_inventory.set_stack(0, result).await;
|
||||
} else {
|
||||
self.output_inventory
|
||||
.set_stack(0, ItemStack::EMPTY.clone())
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_available_recipes(input: &ItemStack) -> Vec<&'static StonecutterRecipe> {
|
||||
let item = input.item;
|
||||
RECIPES_STONECUTTING
|
||||
.iter()
|
||||
.filter(|r| r.ingredient.match_item(item))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenHandler for StonecutterScreenHandler {
|
||||
fn get_behaviour(&self) -> &ScreenHandlerBehaviour {
|
||||
&self.behaviour
|
||||
}
|
||||
|
||||
fn get_behaviour_mut(&mut self) -> &mut ScreenHandlerBehaviour {
|
||||
&mut self.behaviour
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn on_slot_click<'a>(
|
||||
&'a mut self,
|
||||
slot_index: i32,
|
||||
button: i32,
|
||||
action_type: SlotActionType,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
) -> ScreenHandlerFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
self.internal_on_slot_click(slot_index, button, action_type, player)
|
||||
.await;
|
||||
if slot_index == 0 {
|
||||
self.update_output().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn quick_move<'a>(
|
||||
&'a mut self,
|
||||
_player: &'a dyn InventoryPlayer,
|
||||
slot_index: i32,
|
||||
) -> ScreenHandlerFuture<'a, ItemStack> {
|
||||
Box::pin(async move {
|
||||
let mut stack = ItemStack::EMPTY.clone();
|
||||
let slot = self.get_behaviour().slots.get(slot_index as usize).cloned();
|
||||
|
||||
if let Some(slot) = slot {
|
||||
let mut slot_stack = slot.get_cloned_stack().await;
|
||||
if !slot_stack.is_empty() {
|
||||
stack = slot_stack.clone();
|
||||
if slot_index < 2 {
|
||||
// From Stonecutter to Player
|
||||
if !self.insert_item(&mut slot_stack, 2, 38, true).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
slot.on_quick_move_crafted(slot_stack.clone(), stack.clone())
|
||||
.await;
|
||||
} else {
|
||||
// From Player to Stonecutter
|
||||
// Try input slot (0)
|
||||
if !self.insert_item(&mut slot_stack, 0, 1, false).await {
|
||||
return ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if slot_stack.is_empty() {
|
||||
slot.set_stack(ItemStack::EMPTY.clone()).await;
|
||||
} else {
|
||||
slot.set_stack(slot_stack).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
stack
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct StonecutterOutputSlot {
|
||||
pub inventory: Arc<dyn Inventory>,
|
||||
pub input_inventory: Arc<dyn Inventory>,
|
||||
pub index: usize,
|
||||
pub id: AtomicU8,
|
||||
}
|
||||
|
||||
impl StonecutterOutputSlot {
|
||||
pub fn new(
|
||||
inventory: Arc<dyn Inventory>,
|
||||
input_inventory: Arc<dyn Inventory>,
|
||||
index: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
input_inventory,
|
||||
index,
|
||||
id: AtomicU8::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Slot for StonecutterOutputSlot {
|
||||
fn get_inventory(&self) -> Arc<dyn Inventory> {
|
||||
self.inventory.clone()
|
||||
}
|
||||
|
||||
fn get_index(&self) -> usize {
|
||||
self.index
|
||||
}
|
||||
|
||||
fn set_id(&self, id: usize) {
|
||||
self.id.store(id as u8, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn on_take_item<'a>(
|
||||
&'a self,
|
||||
player: &'a dyn InventoryPlayer,
|
||||
stack: &'a ItemStack,
|
||||
) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
player
|
||||
.increment_stat(
|
||||
StatisticCategory::Crafted,
|
||||
stack.item.id as i32,
|
||||
stack.item_count as i32,
|
||||
)
|
||||
.await;
|
||||
let input_stack = self.input_inventory.get_stack(0).await;
|
||||
let mut input_lock = input_stack.lock().await;
|
||||
if !input_lock.is_empty() {
|
||||
input_lock.item_count -= 1;
|
||||
if input_lock.item_count == 0 {
|
||||
*input_lock = ItemStack::EMPTY.clone();
|
||||
}
|
||||
}
|
||||
self.mark_dirty().await;
|
||||
})
|
||||
}
|
||||
|
||||
fn can_insert(&self, _stack: &ItemStack) -> BoxFuture<'_, bool> {
|
||||
Box::pin(async move { false })
|
||||
}
|
||||
|
||||
fn get_stack(&self) -> BoxFuture<'_, Arc<Mutex<ItemStack>>> {
|
||||
Box::pin(async move { self.inventory.get_stack(self.index).await })
|
||||
}
|
||||
|
||||
fn get_cloned_stack(&self) -> BoxFuture<'_, ItemStack> {
|
||||
Box::pin(async move {
|
||||
let stack = self.inventory.get_stack(self.index).await;
|
||||
stack.lock().await.clone()
|
||||
})
|
||||
}
|
||||
|
||||
fn has_stack(&self) -> BoxFuture<'_, bool> {
|
||||
Box::pin(async move {
|
||||
let stack = self.inventory.get_stack(self.index).await;
|
||||
!stack.lock().await.is_empty()
|
||||
})
|
||||
}
|
||||
|
||||
fn set_stack(&self, stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.inventory.set_stack(self.index, stack).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn set_stack_prev(&self, _stack: ItemStack, _previous_stack: ItemStack) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
// Do nothing
|
||||
})
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.inventory.mark_dirty();
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Inventory synchronization handler.
|
||||
//!
|
||||
//! This module handles the synchronization of inventory state between the server
|
||||
//! and connected clients. It ensures that players see the correct items in slots,
|
||||
//! cursor items, and container properties (like furnace progress).
|
||||
//!
|
||||
//! # Synchronization
|
||||
//!
|
||||
//! The sync handler manages:
|
||||
//! - Full container content updates (sent when opening a container or on major changes)
|
||||
//! - Individual slot updates (sent when a single slot changes)
|
||||
//! - Cursor item updates (the item being held by the mouse cursor)
|
||||
//! - Property updates (container-specific data like furnace burn time)
|
||||
//!
|
||||
//! # Revision Tracking
|
||||
//!
|
||||
//! Each synchronization message includes a revision number to ensure the client
|
||||
//! and server stay in sync. If the client detects a desync, it can request a full
|
||||
//! resynchronization.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_protocol::{
|
||||
codec::{
|
||||
item_stack_seralizer::{ItemStackSerializer, OptionalItemStackHash},
|
||||
var_int::VarInt,
|
||||
},
|
||||
java::client::play::{
|
||||
CSetContainerContent, CSetContainerProperty, CSetContainerSlot, CSetCursorItem,
|
||||
},
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::screen_handler::{InventoryPlayer, ScreenHandlerBehaviour};
|
||||
|
||||
/// Handles inventory synchronization to a specific player.
|
||||
///
|
||||
/// The sync handler stores a reference to the player and sends inventory
|
||||
/// update packets when container state changes. It manages:
|
||||
/// - Full content synchronization
|
||||
/// - Incremental slot updates
|
||||
/// - Cursor item tracking
|
||||
/// - Property (UI element) updates
|
||||
pub struct SyncHandler {
|
||||
/// The player to synchronize inventory updates with.
|
||||
///
|
||||
/// None until `store_player` is called to attach a player.
|
||||
player: Mutex<Option<Arc<dyn InventoryPlayer>>>,
|
||||
}
|
||||
|
||||
impl Default for SyncHandler {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncHandler {
|
||||
/// Creates a new sync handler with no player attached.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
player: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores the player to synchronize with.
|
||||
///
|
||||
/// Must be called before any sync operations.
|
||||
pub async fn store_player(&self, player: Arc<dyn InventoryPlayer>) {
|
||||
self.player.lock().await.replace(player);
|
||||
}
|
||||
|
||||
/// Sends a full container content update.
|
||||
///
|
||||
/// This sends all slots, the cursor item, and properties to the client.
|
||||
/// Used for initial sync and recovery from desync.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `screen_handler` - The screen handler to sync
|
||||
/// - `stacks` - All slot contents
|
||||
/// - `cursor_stack` - The item held by the cursor
|
||||
/// - `properties` - Container property values
|
||||
/// - `next_revision` - The new revision number
|
||||
pub async fn update_state(
|
||||
&self,
|
||||
screen_handler: &ScreenHandlerBehaviour,
|
||||
stacks: &[ItemStack],
|
||||
cursor_stack: &ItemStack,
|
||||
properties: Vec<i32>,
|
||||
next_revision: u32,
|
||||
) {
|
||||
if let Some(player) = self.player.lock().await.as_ref() {
|
||||
player
|
||||
.enqueue_inventory_packet(&CSetContainerContent::new(
|
||||
VarInt(screen_handler.sync_id.into()),
|
||||
VarInt(next_revision as i32),
|
||||
stacks
|
||||
.iter()
|
||||
.map(|stack| ItemStackSerializer::from(stack.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
.as_slice(),
|
||||
&ItemStackSerializer::from(cursor_stack.clone()),
|
||||
))
|
||||
.await;
|
||||
|
||||
for (i, property) in properties.iter().enumerate() {
|
||||
player
|
||||
.enqueue_property_packet(&CSetContainerProperty::new(
|
||||
VarInt(screen_handler.sync_id.into()),
|
||||
i as i16,
|
||||
*property as i16,
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates a single slot on the client.
|
||||
///
|
||||
/// More efficient than full sync for single-slot changes.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `screen_handler` - The screen handler
|
||||
/// - `slot` - The slot index that changed
|
||||
/// - `stack` - The new stack in that slot
|
||||
/// - `next_revision` - The new revision number
|
||||
pub async fn update_slot(
|
||||
&self,
|
||||
screen_handler: &ScreenHandlerBehaviour,
|
||||
slot: usize,
|
||||
stack: &ItemStack,
|
||||
next_revision: u32,
|
||||
) {
|
||||
if let Some(player) = self.player.lock().await.as_ref() {
|
||||
player
|
||||
.enqueue_slot_packet(&CSetContainerSlot::new(
|
||||
screen_handler.sync_id as i8,
|
||||
next_revision as i32,
|
||||
slot as i16,
|
||||
&ItemStackSerializer::from(stack.clone()),
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the cursor item on the client.
|
||||
///
|
||||
/// Sent when the player's held (cursor) item changes.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `screen_handler` - The screen handler
|
||||
/// - `stack` - The new cursor item
|
||||
pub async fn update_cursor_stack(
|
||||
&self,
|
||||
_screen_handler: &ScreenHandlerBehaviour,
|
||||
stack: &ItemStack,
|
||||
) {
|
||||
if let Some(player) = self.player.lock().await.as_ref() {
|
||||
player
|
||||
.enqueue_cursor_packet(&CSetCursorItem::new(&ItemStackSerializer::from(
|
||||
stack.clone(),
|
||||
)))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates a container property on the client.
|
||||
///
|
||||
/// Used for UI elements like furnace progress bars.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `screen_handler` - The screen handler
|
||||
/// - `property` - The property index
|
||||
/// - `value` - The new property value
|
||||
pub async fn update_property(
|
||||
&self,
|
||||
screen_handler: &ScreenHandlerBehaviour,
|
||||
property: i32,
|
||||
value: i32,
|
||||
) {
|
||||
if let Some(player) = self.player.lock().await.as_ref() {
|
||||
player
|
||||
.enqueue_property_packet(&CSetContainerProperty::new(
|
||||
VarInt(screen_handler.sync_id.into()),
|
||||
property as i16,
|
||||
value as i16,
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks the last known state of a slot for sync purposes.
|
||||
///
|
||||
/// Used to detect when a slot has changed and needs to be synced to the client.
|
||||
/// Stores either the full stack or a hash for comparison.
|
||||
#[derive(Clone)]
|
||||
pub struct TrackedStack {
|
||||
/// The full item stack last sent to the client.
|
||||
///
|
||||
/// Set when sending full stack data. Cleared when only sending a hash.
|
||||
pub received_stack: Option<ItemStack>,
|
||||
/// The hash of the item stack last sent to the client.
|
||||
///
|
||||
/// Used for lightweight comparison to detect changes.
|
||||
pub received_hash: Option<OptionalItemStackHash>,
|
||||
}
|
||||
|
||||
impl TrackedStack {
|
||||
/// An empty tracked stack with no known state.
|
||||
pub const EMPTY: Self = Self {
|
||||
received_stack: None,
|
||||
received_hash: None,
|
||||
};
|
||||
|
||||
/// Records that we sent this stack to the client.
|
||||
pub fn set_received_stack(&mut self, stack: ItemStack) {
|
||||
self.received_stack = Some(stack);
|
||||
self.received_hash = None;
|
||||
}
|
||||
|
||||
/// Records that we sent this hash to the client.
|
||||
pub fn set_received_hash(&mut self, hash: OptionalItemStackHash) {
|
||||
self.received_hash = Some(hash);
|
||||
self.received_stack = None;
|
||||
}
|
||||
|
||||
/// Checks if the actual stack matches our tracked state.
|
||||
///
|
||||
/// Updates the tracked state to the actual stack if they match.
|
||||
//FIX Methods named `is_*` normally take self by reference or no self. Consider choosing a less ambiguous name.
|
||||
pub fn is_in_sync(&mut self, actual_stack: &ItemStack) -> bool {
|
||||
if let Some(stack) = &self.received_stack {
|
||||
return stack.are_equal(actual_stack);
|
||||
} else if let Some(hash) = &self.received_hash
|
||||
&& hash.hash_equals(actual_stack)
|
||||
{
|
||||
self.received_stack = Some(actual_stack.clone());
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Window property definitions.
|
||||
//!
|
||||
//! This module defines container-specific UI properties that need to be synchronized
|
||||
//! between server and client. These include progress bars, fuel indicators, and
|
||||
//! other visual elements in container screens.
|
||||
//!
|
||||
//! # Window Properties
|
||||
//!
|
||||
//! Properties are identified by a unique ID and sent to the client to update
|
||||
//! the container's visual state:
|
||||
//! - Furnace: Fire icon animation, smelting progress
|
||||
//! - Enchantment table: Level requirements, available enchantments
|
||||
//! - Brewing stand: Brew time, fuel level
|
||||
//! - Anvil: Repair cost
|
||||
//!
|
||||
//! See the Minecraft wiki for property ID mappings.
|
||||
|
||||
/// Trait for types that can be converted to window property IDs.
|
||||
pub trait WindowPropertyTrait {
|
||||
/// Converts this property to its protocol ID.
|
||||
fn to_id(self) -> i16;
|
||||
}
|
||||
|
||||
/// A window property with a specific value.
|
||||
///
|
||||
/// Used to send property updates to the client (e.g., furnace progress bar).
|
||||
pub struct WindowProperty<T: WindowPropertyTrait> {
|
||||
/// The property type being tracked (e.g., furnace fire icon, progress arrow).
|
||||
window_property: T,
|
||||
/// The current value of the property.
|
||||
value: i16,
|
||||
}
|
||||
|
||||
impl<T: WindowPropertyTrait> WindowProperty<T> {
|
||||
/// Creates a new window property.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `window_property` - The property type
|
||||
/// - `value` - The property value
|
||||
#[must_use]
|
||||
pub const fn new(window_property: T, value: i16) -> Self {
|
||||
Self {
|
||||
window_property,
|
||||
value,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this property to a tuple of (id, value).
|
||||
#[must_use]
|
||||
pub fn into_tuple(self) -> (i16, i16) {
|
||||
(self.window_property.to_id(), self.value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Furnace window properties.
|
||||
pub enum Furnace {
|
||||
/// Fire icon animation level (0-250).
|
||||
FireIcon,
|
||||
/// Maximum fuel burn time.
|
||||
MaximumFuelBurnTime,
|
||||
/// Arrow progress animation (0-250).
|
||||
ProgressArrow,
|
||||
/// Maximum smelting progress time.
|
||||
MaximumProgress,
|
||||
}
|
||||
|
||||
/// Enchantment table window properties.
|
||||
pub enum EnchantmentTable {
|
||||
/// Experience level requirement for a specific slot.
|
||||
LevelRequirement { slot: u8 },
|
||||
/// Random seed for enchantment generation.
|
||||
EnchantmentSeed,
|
||||
/// Enchantment ID for a specific slot.
|
||||
EnchantmentId { slot: u8 },
|
||||
/// Enchantment level for a specific slot.
|
||||
EnchantmentLevel { slot: u8 },
|
||||
}
|
||||
|
||||
// TODO: No more magic numbers
|
||||
impl WindowPropertyTrait for EnchantmentTable {
|
||||
fn to_id(self) -> i16 {
|
||||
use EnchantmentTable::{
|
||||
EnchantmentId, EnchantmentLevel, EnchantmentSeed, LevelRequirement,
|
||||
};
|
||||
|
||||
i16::from(match self {
|
||||
LevelRequirement { slot } => slot,
|
||||
EnchantmentSeed => 3,
|
||||
EnchantmentId { slot } => 4 + slot,
|
||||
EnchantmentLevel { slot } => 7 + slot,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Beacon window properties.
|
||||
pub enum Beacon {
|
||||
/// Effect power level (1-4).
|
||||
PowerLevel,
|
||||
/// First selected potion effect ID.
|
||||
FirstPotionEffect,
|
||||
/// Second selected potion effect ID.
|
||||
SecondPotionEffect,
|
||||
}
|
||||
|
||||
/// Anvil window properties.
|
||||
pub enum Anvil {
|
||||
/// Total repair cost in experience levels.
|
||||
RepairCost,
|
||||
}
|
||||
|
||||
impl WindowPropertyTrait for Anvil {
|
||||
fn to_id(self) -> i16 {
|
||||
match self {
|
||||
Self::RepairCost => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Brewing stand window properties.
|
||||
pub enum BrewingStand {
|
||||
/// Brewing progress (0-400).
|
||||
BrewTime,
|
||||
/// Fuel time remaining (0-20).
|
||||
FuelTime,
|
||||
}
|
||||
|
||||
/// Stonecutter window properties.
|
||||
pub enum Stonecutter {
|
||||
/// ID of the selected recipe.
|
||||
SelectedRecipe,
|
||||
}
|
||||
|
||||
/// Loom window properties.
|
||||
pub enum Loom {
|
||||
/// ID of the selected pattern.
|
||||
SelectedPattern,
|
||||
}
|
||||
|
||||
/// Lectern window properties.
|
||||
pub enum Lectern {
|
||||
/// Current page number being viewed.
|
||||
PageNumber,
|
||||
}
|
||||
Reference in new issue
Block a user