diff --git a/Cargo.lock b/Cargo.lock index 5cc64d4ba..4408dc4a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -806,7 +806,11 @@ name = "feather-inventory" version = "0.6.0" dependencies = [ "feather-items", + "fecs", + "legion", + "maplit", "once_cell", + "parking_lot", "smallvec", "thiserror", ] @@ -2332,18 +2336,18 @@ dependencies = [ [[package]] name = "pin-project" -version = "0.4.16" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81d480cb4e89522ccda96d0eed9af94180b7a5f93fb28f66e1fd7d68431663d1" +checksum = "edc93aeee735e60ecb40cf740eb319ff23eab1c5748abfdb5c180e4ce49f7791" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "0.4.16" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82996f11efccb19b685b14b5df818de31c1edcee3daa256ab5775dd98e72feb" +checksum = "e58db2081ba5b4c93bd6be09c40fd36cb9193a8336c384f3b40012e531aa7e40" dependencies = [ "proc-macro2 1.0.13", "quote 1.0.1", diff --git a/core/anvil/src/player.rs b/core/anvil/src/player.rs index 225108fb7..cf958a278 100644 --- a/core/anvil/src/player.rs +++ b/core/anvil/src/player.rs @@ -1,6 +1,6 @@ use crate::entity::BaseEntityData; -use feather_inventory::{ - SlotIndex, HOTBAR_SIZE, INVENTORY_SIZE, SLOT_ARMOR_MAX, SLOT_ARMOR_MIN, SLOT_HOTBAR_OFFSET, +use feather_inventory::player_constants::{ + HOTBAR_SIZE, INVENTORY_SIZE, SLOT_ARMOR_MAX, SLOT_ARMOR_MIN, SLOT_HOTBAR_OFFSET, SLOT_INVENTORY_OFFSET, SLOT_OFFHAND, }; use feather_items::{Item, ItemStack}; @@ -45,7 +45,7 @@ impl InventorySlot { /// Converts a network protocol index, item, and count /// to an `InventorySlot`. - pub fn from_network_index(network: SlotIndex, stack: ItemStack) -> Self { + pub fn from_network_index(network: usize, stack: ItemStack) -> Option { let slot = if SLOT_HOTBAR_OFFSET <= network && network < SLOT_HOTBAR_OFFSET + HOTBAR_SIZE { // Hotbar (network - SLOT_HOTBAR_OFFSET) as i8 @@ -58,19 +58,19 @@ impl InventorySlot { { network as i8 } else { - panic!("Invalid slot index {} on server", network); + return None; }; - Self { + Some(Self { count: stack.amount as i8, slot, item: stack.ty.identifier().to_string(), - } + }) } /// Converts an NBT inventory index to a network protocol index. /// Returns None if the index is invalid. - pub fn convert_index(&self) -> Option { + pub fn convert_index(&self) -> Option { if 0 <= self.slot && self.slot <= 8 { // Hotbar Some(SLOT_HOTBAR_OFFSET + (self.slot as usize)) @@ -131,6 +131,9 @@ fn file_path(world_dir: &Path, uuid: Uuid) -> PathBuf { #[cfg(test)] mod tests { use super::*; + use feather_inventory::player_constants::{ + SLOT_ARMOR_CHEST, SLOT_ARMOR_FEET, SLOT_ARMOR_HEAD, SLOT_ARMOR_LEGS, + }; use feather_util::Gamemode; use std::collections::HashMap; use std::io::Cursor; @@ -173,15 +176,15 @@ mod tests { let mut map: HashMap = HashMap::new(); // Equipment - map.insert(103, feather_inventory::SLOT_ARMOR_HEAD); - map.insert(102, feather_inventory::SLOT_ARMOR_CHEST); - map.insert(101, feather_inventory::SLOT_ARMOR_LEGS); - map.insert(100, feather_inventory::SLOT_ARMOR_FEET); - map.insert(-106, feather_inventory::SLOT_OFFHAND); + map.insert(103, SLOT_ARMOR_HEAD); + map.insert(102, SLOT_ARMOR_CHEST); + map.insert(101, SLOT_ARMOR_LEGS); + map.insert(100, SLOT_ARMOR_FEET); + map.insert(-106, SLOT_OFFHAND); // Hotbar for x in 0..9 { - map.insert(x, feather_inventory::SLOT_HOTBAR_OFFSET + (x as usize)); + map.insert(x, SLOT_HOTBAR_OFFSET + (x as usize)); } // Rest of inventory @@ -199,7 +202,7 @@ mod tests { assert_eq!(slot.convert_index().unwrap(), expected); assert_eq!( InventorySlot::from_network_index(expected, ItemStack::new(Item::Stone, 1)), - slot + Some(slot), ); } diff --git a/core/inventory/Cargo.toml b/core/inventory/Cargo.toml index 44224f89c..44a0ea7ec 100644 --- a/core/inventory/Cargo.toml +++ b/core/inventory/Cargo.toml @@ -6,6 +6,11 @@ edition = "2018" [dependencies] feather-items = { path = "../items" } -smallvec = "1.3" -once_cell = "1.3" + +fecs = { git = "https://github.com/feather-rs/fecs", rev = "fed8bcb516941b12cb980e354e77b699be075a89" } +legion = { git = "https://github.com/TomGillen/legion", rev = "bd441f4811e7a9e877a0f479a674bbdbf4e4cda3" } thiserror = "1.0" +parking_lot = "0.10" +maplit = "1.0" +smallvec = "1.4" +once_cell = "1.3" diff --git a/core/inventory/src/lib.rs b/core/inventory/src/lib.rs index ed1ef3893..8aa091f20 100644 --- a/core/inventory/src/lib.rs +++ b/core/inventory/src/lib.rs @@ -1,304 +1,221 @@ -//! Module for creating and modifying inventories of any type. +//! An implementation of inventory handling. +//! +//! # Key types +//! * `Area`: an area in an inventory, e.g. hotbar, storage, crafting +//! * `Inventory`: stores the items inside an inventory, associated +//! with their respective areas +//! * `Window`: handles mapping from protocol inventory indices +//! to internal indices used for `Inventory`. + +use feather_items::ItemStack; +use maplit::btreemap; +use parking_lot::{RwLock, RwLockWriteGuard}; +use std::collections::BTreeMap; +use std::iter::repeat_with; +use thiserror::Error; + +mod window; -use feather_items::{Item, ItemStack}; use once_cell::sync::Lazy; use smallvec::{Array, SmallVec}; use std::cmp::min; -use thiserror::Error; - -pub type SlotIndex = usize; - -#[derive(Debug, Error)] -#[error("slot index out of bounds")] -pub struct IndexOutOfBounds; - -// Constants representing various standard inventory slot indices - -pub const SLOT_CRAFTING_OUTPUT: SlotIndex = 0; -pub const SLOT_CRAFTING_INPUT_X0_Y0: SlotIndex = 1; -pub const SLOT_CRAFTING_INPUT_X1_Y0: SlotIndex = 2; -pub const SLOT_CRAFTING_INPUT_X0_Y1: SlotIndex = 3; -pub const SLOT_CRAFTING_INPUT_X1_Y1: SlotIndex = 4; +pub use window::{constants as player_constants, Error as WindowError, Window, WindowAccessor}; -pub const SLOT_ARMOR_MIN: SlotIndex = 5; -pub const SLOT_ARMOR_MAX: SlotIndex = 8; - -pub const SLOT_ARMOR_HEAD: SlotIndex = 5; -pub const SLOT_ARMOR_CHEST: SlotIndex = 6; -pub const SLOT_ARMOR_LEGS: SlotIndex = 7; -pub const SLOT_ARMOR_FEET: SlotIndex = 8; - -pub const SLOT_OFFHAND: SlotIndex = 45; - -pub const SLOT_INVENTORY_OFFSET: SlotIndex = 9; -pub const SLOT_HOTBAR_OFFSET: SlotIndex = 36; - -pub const HOTBAR_SIZE: SlotIndex = 9; -pub const INVENTORY_SIZE: SlotIndex = 27; - -pub const SLOT_ENTITY_EQUIPMENT_MAIN_HAND: SlotIndex = 0; -pub const SLOT_ENTITY_EQUIPMENT_OFF_HAND: SlotIndex = 1; -pub const SLOT_ENTITY_EQUIPMENT_BOOTS: SlotIndex = 2; -pub const SLOT_ENTITY_EQUIPMENT_LEGGINGS: SlotIndex = 3; -pub const SLOT_ENTITY_EQUIPMENT_CHESTPLATE: SlotIndex = 4; -pub const SLOT_ENTITY_EQUIPMENT_HELMET: SlotIndex = 5; - -pub type Slot = Option; - -static COLLECT_SEARCH_ORDER: Lazy> = Lazy::new(|| { +static COLLECT_SEARCH_ORDER: Lazy> = Lazy::new(|| { let mut result = vec![]; - for x in SLOT_HOTBAR_OFFSET..SLOT_HOTBAR_OFFSET + HOTBAR_SIZE { - result.push(x); + // TODO: move to constants + for x in 0..9 { + result.push((Area::Hotbar, x)); } - for x in SLOT_INVENTORY_OFFSET..SLOT_INVENTORY_OFFSET + INVENTORY_SIZE { - result.push(x); + for x in 0..27 { + result.push((Area::Main, x)); } result }); -pub fn armor_slot_to_entity_equipment(slot: SlotIndex) -> SlotIndex { - assert!(slot >= 5 && slot <= 8); - match slot { - SLOT_ARMOR_HEAD => SLOT_ENTITY_EQUIPMENT_HELMET, - SLOT_ARMOR_CHEST => SLOT_ENTITY_EQUIPMENT_CHESTPLATE, - SLOT_ARMOR_LEGS => SLOT_ENTITY_EQUIPMENT_LEGGINGS, - SLOT_ARMOR_FEET => SLOT_ENTITY_EQUIPMENT_BOOTS, - _ => unreachable!(), - } +/// An area inside an inventory, used to differentiate between +/// different parts. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Area { + /// A player's hotbar (9 slots total) + Hotbar, + /// The crafting output slot inside either a player's + /// inventory or a crafting table. (1 slot total) + CraftingOutput, + /// Crafting input slots. (Total depends on window: + /// 4 slots for `Player` and 9 slots for `Crafting`) + CraftingInput, + + // armor + Head, + /// A player's chestplate + Torso, + Legs, + Feet, + Offhand, + + /// Main part of a player's inventory (27 slots total) + Main, + + /// Chest storage (27 or 54 slots total, depending on whether + /// chest is single or large) + /// + /// Note that this is not the chestplate slot; use `Torso` instead. + Chest, } -/// Returns the max size of a stack with the given -/// type. -pub fn max_size(item: Item) -> u8 { - match item { - Item::WoodenSword - | Item::GoldenSword - | Item::StoneSword - | Item::IronSword - | Item::DiamondSword - | Item::WoodenAxe - | Item::GoldenAxe - | Item::StoneAxe - | Item::IronAxe - | Item::DiamondAxe - | Item::WoodenHoe - | Item::GoldenHoe - | Item::StoneHoe - | Item::IronHoe - | Item::DiamondHoe - | Item::WoodenPickaxe - | Item::GoldenPickaxe - | Item::StonePickaxe - | Item::IronPickaxe - | Item::DiamondPickaxe - | Item::WoodenShovel - | Item::GoldenShovel - | Item::StoneShovel - | Item::IronShovel - | Item::DiamondShovel - | Item::LeatherChestplate - | Item::GoldenChestplate - | Item::ChainmailChestplate - | Item::IronChestplate - | Item::DiamondChestplate - | Item::LeatherLeggings - | Item::GoldenLeggings - | Item::ChainmailLeggings - | Item::IronLeggings - | Item::DiamondLeggings - | Item::LeatherBoots - | Item::GoldenBoots - | Item::ChainmailBoots - | Item::IronBoots - | Item::DiamondBoots - | Item::LeatherHelmet - | Item::GoldenHelmet - | Item::ChainmailHelmet - | Item::IronHelmet - | Item::DiamondHelmet - | Item::Bow - | Item::WritableBook - | Item::FlintAndSteel - | Item::WhiteBed - | Item::OrangeBed - | Item::MagentaBed - | Item::LightBlueBed - | Item::YellowBed - | Item::LimeBed - | Item::PinkBed - | Item::GrayBed - | Item::LightGrayBed - | Item::CyanBed - | Item::PurpleBed - | Item::BlueBed - | Item::BrownBed - | Item::GreenBed - | Item::RedBed - | Item::BlackBed - | Item::ShulkerBox - | Item::TurtleEgg - | Item::TurtleHelmet - | Item::FishingRod - | Item::EnchantedBook - | Item::Potion - | Item::LingeringPotion - | Item::SplashPotion - | Item::WaterBucket - | Item::LavaBucket - | Item::TropicalFishBucket - | Item::CodBucket - | Item::MilkBucket - | Item::PufferfishBucket - | Item::SalmonBucket - | Item::CarrotOnAStick - | Item::Elytra - | Item::Shield - | Item::Trident - | Item::MusicDisc13 - | Item::MusicDiscCat - | Item::MusicDiscBlocks - | Item::MusicDiscChirp - | Item::MusicDiscFar - | Item::MusicDiscMall - | Item::MusicDiscMellohi - | Item::MusicDiscStal - | Item::MusicDiscStrad - | Item::MusicDiscWard - | Item::MusicDisc11 - | Item::MusicDiscWait - | Item::TotemOfUndying - | Item::Shears - | Item::AcaciaBoat - | Item::DarkOakBoat - | Item::OakBoat - | Item::SpruceBoat - | Item::BirchBoat - | Item::JungleBoat - | Item::MushroomStew - | Item::BeetrootSoup - | Item::RabbitStew - | Item::Cake - | Item::Minecart - | Item::ChestMinecart - | Item::CommandBlockMinecart - | Item::FurnaceMinecart - | Item::HopperMinecart - | Item::TntMinecart - | Item::DiamondHorseArmor - | Item::GoldenHorseArmor - | Item::Saddle - | Item::KnowledgeBook - | Item::DebugStick - | Item::IronHorseArmor => 1, - Item::EnderPearl - | Item::Snowball - | Item::WhiteBanner - | Item::OrangeBanner - | Item::MagentaBanner - | Item::LightBlueBanner - | Item::YellowBanner - | Item::LimeBanner - | Item::PinkBanner - | Item::GrayBanner - | Item::LightGrayBanner - | Item::CyanBanner - | Item::PurpleBanner - | Item::BlueBanner - | Item::BrownBanner - | Item::GreenBanner - | Item::RedBanner - | Item::BlackBanner - | Item::Sign - | Item::ArmorStand - | Item::Bucket - | Item::WrittenBook - | Item::Egg => 16, - _ => 64, - } +/// Index into a slot. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct SlotIndex { + pub area: Area, + pub slot: usize, } -/// The various types of inventories ("windows"). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum InventoryType { - Player, - Container, - Chest, - CraftingTable, - Furnace, - Dispenser, - EnchantingTable, - BrewingStand, - Villager, - Beacon, - Anvil, - Hopper, - Dropper, - ShulkerBox, - Horse, +/// Creates a `SlotIndex`. +pub fn slot(area: Area, slot: usize) -> SlotIndex { + SlotIndex { area, slot } +} + +/// A slot in an inventory. This is an `Option`; +/// if set to `None`, then there is no item in this slot. +pub type Slot = Option; + +/// An error emitted when accessing an item +/// fails. +#[derive(Debug, Error)] +pub enum Error { + #[error("index {0} for area {1:?} out of bounds")] + OutOfBounds(usize, Area), + #[error("area {0:?} does not exist in this inventory")] + NoSuchArea(Area), + #[error("invalid protocol index {0}")] + InvalidProtocolIndex(usize), } -/// An inventory, consisting of a vector -/// of `Slot`s and a type. -#[derive(Debug, Clone)] +/// Stores items in some inventory. +/// +/// Internally, items are each wrapped in a `RwLock`. +/// This allows for convenient access and shared +/// references to an `Inventory` without using +/// `RefCell`. The overhead from the use of locks +/// should be minimal. +/// +/// # Structure +/// `Inventory` uses a composition-based design. It +/// stores a vector of items for each `Area` which it contains. +/// +/// # Initialization +/// `Inventory` provides assorted functions to initialize inventories +/// of some kind. For example, `Inventory::large_chest()` creates an +/// empty inventory for a large chest. +/// +/// # Indexing conventions +/// When an area consists of a rectangle +/// of slots on the client GUI, then indexing +/// starts at 0 with the top-left corner and proceeds +/// horizontally, then vertically. +#[derive(Default, Debug)] pub struct Inventory { - /// The item vector. + /// Associative array from `Area` => items + /// contained within the `Area`. /// - /// The vector always contains an entry - /// for each slot in the inventory, indexed - /// by the slot IDs. When an entry is set to - /// `None`, there is no item in the slot. s - items: Vec>, - /// The type of this inventory. - pub ty: InventoryType, + /// Might switch to another, more efficient map + /// type at some point, but we have no profile + /// results which indicate inventory handling + /// is a bottleneck. + slots: BTreeMap>>, } impl Inventory { - /// Creates a new inventory of the given - /// type and number of slots. - pub fn new(ty: InventoryType, num_slots: u32) -> Self { - Self { - items: vec![None; num_slots as usize], - ty, - } + /// Creates an inventory for a player, i.e. + /// one with hotbar, main storage, armor, offhand, survival + /// crafting slots. + pub fn player() -> Self { + let slots = btreemap! { + Area::Hotbar => empty(9), + Area::Main => empty(27), + + Area::Head => empty(1), + Area::Torso => empty(1), + Area::Legs => empty(1), + Area::Feet => empty(1), + Area::Offhand => empty(1), + + Area::CraftingInput => empty(4), + Area::CraftingOutput => empty(1), + }; + + Self { slots } } - /// Retrieves a reference to the item at the given slot index. - /// - /// This function returns a "double option": the first layer - /// is `None` if the index is out of bounds, and the second - /// is `None` if there is no item in the slot. - pub fn item_at(&self, index: SlotIndex) -> Result, IndexOutOfBounds> { - self.items.get(index).copied().ok_or(IndexOutOfBounds) + /// Creates an inventory for a crafting table. + /// Contains `CraftingInput` and `CraftingOutput` + /// areas. + pub fn crafting_table() -> Self { + let slots = btreemap! { + Area::CraftingInput => empty(9), + Area::CraftingOutput => empty(9), + }; + + Self { slots } } - pub fn item_at_mut(&mut self, index: SlotIndex) -> Option<&mut ItemStack> { - self.items[index].as_mut() + /// Returns the item at the given + /// index inside some area. + pub fn item_at(&self, area: Area, index: usize) -> Result { + self.slot(area, index).map(RwLock::read).map(|guard| *guard) } - /// Sets the item at the given slot index. - pub fn set_item_at(&mut self, index: SlotIndex, item: ItemStack) { - self.try_set_item_at(index, item) - .expect("slot index out of bounds") + /// Returns a mutable guard for an item + /// at the given slot. + pub fn item_at_mut(&self, area: Area, index: usize) -> Result, Error> { + self.slot(area, index).map(RwLock::write) } - /// Tries to set the item at the given - /// index. Returns `None` if the slot - /// index is out of bouds. - pub fn try_set_item_at(&mut self, index: SlotIndex, item: ItemStack) -> Option<()> { - if item.amount == 0 { - *self.items.get_mut(index)? = None; + /// Sets the item at the given index inside some area. + /// + /// Returns the old item in the slot. + pub fn set_item_at(&self, area: Area, index: usize, stack: ItemStack) -> Result { + let mut slot = self.item_at_mut(area, index)?; + let old = *slot; + *slot = if stack.amount == 0 { + Slot::None } else { - *self.items.get_mut(index)? = Some(item); - } - Some(()) + Slot::Some(stack) + }; + Ok(old) + } + + /// Removes the item at the given position. Returns + /// the removed item. + pub fn remove_item_at(&self, area: Area, index: usize) -> Result { + let mut item = self.item_at_mut(area, index)?; + + Ok(item.take()) + } + + /// Returns an iterator over mutable references to all + /// items in this inventory. + pub fn iter_mut(&self) -> impl Iterator> { + self.slots + .values() + .flat_map(Vec::as_slice) + .map(RwLock::write) } - /// Clears the item at the given slot index, returning - /// the old item. - pub fn clear_item_at(&mut self, index: SlotIndex) -> Option { - self.items.get_mut(index).map(|item| item.take()).flatten() + /// Returns an iterator over items + indices. + pub fn enumerate<'a>(&'a self) -> impl Iterator + 'a { + self.slots + .iter() + .flat_map(|(area, slots)| std::iter::repeat(*area).zip(slots.iter().enumerate())) + .map(|(area, (index, slot))| (SlotIndex { area, slot: index }, *slot.read())) + } + + /// Returns an iterator over the areas in this inventory. + pub fn areas<'a>(&'a self) -> impl Iterator + 'a { + self.slots.keys().copied() } /// Attempts to insert the given item into a player @@ -306,14 +223,24 @@ impl Inventory { /// /// Returns the affected slots and the number of remaining /// items which were not added to the inventory. - pub fn collect_item(&mut self, mut item: ItemStack) -> (SmallVec<[SlotIndex; 2]>, u8) { + /// + /// TODO: replace with inventory query API + pub fn collect_item(&self, mut item: ItemStack) -> (SmallVec<[SlotIndex; 2]>, u8) { let mut affected_slots = SmallVec::new(); // First, look for slots already having the type. - for slot in COLLECT_SEARCH_ORDER.iter() { - if let Some(slot_item) = self.item_at(*slot).expect("index out of bounds") { + for (area, slot) in COLLECT_SEARCH_ORDER.iter() { + if let Some(slot_item) = self.item_at(*area, *slot).expect("index out of bounds") { if slot_item.ty == item.ty { - self.add_to_stack(&mut item, slot_item, *slot, &mut affected_slots); + self.add_to_stack( + &mut item, + slot_item, + SlotIndex { + area: *area, + slot: *slot, + }, + &mut affected_slots, + ); if item.amount == 0 { return (affected_slots, 0); @@ -322,11 +249,19 @@ impl Inventory { } } - for slot in COLLECT_SEARCH_ORDER.iter() { - let slot_item = self.item_at(*slot).unwrap(); + for (area, slot) in COLLECT_SEARCH_ORDER.iter() { + let slot_item = self.item_at(*area, *slot).unwrap(); if slot_item.is_none() { let fake = ItemStack::new(item.ty, 0); - self.add_to_stack(&mut item, fake, *slot, &mut affected_slots); + self.add_to_stack( + &mut item, + fake, + SlotIndex { + area: *area, + slot: *slot, + }, + &mut affected_slots, + ); if item.amount == 0 { return (affected_slots, 0); } @@ -334,7 +269,15 @@ impl Inventory { if let Some(slot_item) = slot_item { if slot_item.ty == item.ty { - self.add_to_stack(&mut item, slot_item, *slot, &mut affected_slots); + self.add_to_stack( + &mut item, + slot_item, + SlotIndex { + area: *area, + slot: *slot, + }, + &mut affected_slots, + ); if item.amount == 0 { return (affected_slots, 0); @@ -348,101 +291,37 @@ impl Inventory { /// Adds an item to a stack. fn add_to_stack>( - &mut self, + &self, item: &mut ItemStack, slot_item: ItemStack, slot: SlotIndex, affected_slots: &mut SmallVec, ) { - let added = min(item.amount, max_size(item.ty) - slot_item.amount); + let added = min(item.amount, item.ty.stack_size() as u8 - slot_item.amount); item.amount -= added; - self.set_item_at(slot, ItemStack::new(slot_item.ty, slot_item.amount + added)); + self.set_item_at( + slot.area, + slot.slot, + ItemStack::new(slot_item.ty, slot_item.amount + added), + ) + .unwrap(); affected_slots.push(slot); } - /// Returns the number of slots in this inventory. - pub fn slot_count(&self) -> u16 { - self.items.len() as u16 + fn slot(&self, area: Area, index: usize) -> Result<&RwLock, Error> { + let slots = self.slots(area)?; + slots.get(index).ok_or(Error::OutOfBounds(index, area)) } - /// Returns a reference to this inventory's items. - pub fn items(&self) -> &[Option] { - &self.items + fn slots(&self, area: Area) -> Result<&[RwLock], Error> { + self.slots + .get(&area) + .ok_or(Error::NoSuchArea(area)) + .map(Vec::as_slice) } } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_inventory() { - let mut inv = Inventory::new(InventoryType::Chest, 36); - assert_eq!(inv.slot_count(), 36); - - inv.set_item_at(0, ItemStack::new(Item::Air, 1)); - - let item = inv.item_at(0).unwrap().unwrap(); - assert_eq!(item.ty, Item::Air); - assert_eq!(item.amount, 1); - - let item = inv.item_at_mut(0).unwrap(); - item.ty = Item::Sponge; - assert_eq!(inv.item_at(0).unwrap().unwrap().ty, Item::Sponge); - - inv.clear_item_at(0); - assert!(inv.item_at(0).unwrap().is_none()); - } - - #[test] - fn test_collect_item_basic() { - let mut inv = Inventory::new(InventoryType::Player, 46); - let item = ItemStack::new(Item::Cobblestone, 32); - inv.collect_item(item); - assert_eq!(inv.item_at(SLOT_HOTBAR_OFFSET).unwrap().unwrap(), item); - } - - #[test] - fn test_collect_item_full() { - let mut inv = Inventory::new(InventoryType::Player, 46); - let item = ItemStack::new(Item::DriedKelpBlock, 64); - - for i in 0..46 { - inv.set_item_at(i, item); - } - - inv.collect_item(ItemStack::new(Item::Cobblestone, 16)); - for i in 0..46 { - assert_eq!(inv.item_at(i).unwrap().unwrap(), item); - } - } - - #[test] - fn test_collect_item_type_already_in() { - let mut inv = Inventory::new(InventoryType::Player, 46); - let item = ItemStack::new(Item::Cobblestone, 33); - inv.set_item_at(31, item); - - inv.collect_item(item); - assert_eq!( - inv.item_at(31).unwrap().unwrap(), - ItemStack::new(item.ty, 64) - ); - assert_eq!( - inv.item_at(SLOT_HOTBAR_OFFSET).unwrap().unwrap(), - ItemStack::new(item.ty, 2) - ); - } - - #[test] - fn test_collect_item_overstack() { - let mut inv = Inventory::new(InventoryType::Player, 46); - let item = ItemStack::new(Item::DiamondSword, 1); - inv.set_item_at(SLOT_HOTBAR_OFFSET, item); - - inv.collect_item(item); - assert_eq!(inv.item_at(SLOT_HOTBAR_OFFSET).unwrap().unwrap(), item); - assert_eq!(inv.item_at(SLOT_HOTBAR_OFFSET + 1).unwrap().unwrap(), item); - } +fn empty(n: usize) -> Vec> { + repeat_with(|| RwLock::new(None)).take(n).collect() } diff --git a/core/inventory/src/window.rs b/core/inventory/src/window.rs new file mode 100644 index 000000000..44432a1be --- /dev/null +++ b/core/inventory/src/window.rs @@ -0,0 +1,261 @@ +//! Window management. Used to map inventory slot indices +//! in the protocol to `(Area, usize)` indices into an `Inventory`. +//! +//! See https://wiki.vg/Inventory for more information. + +use crate::{Area, Inventory, Slot, SlotIndex}; +use feather_items::ItemStack; +use fecs::{Entity, World}; +use legion::borrow::Ref; +use smallvec::{smallvec, SmallVec}; +use thiserror::Error; + +pub mod constants { + // Constants representing various standard inventory slot indices + // for the `Player` window + // Deprecated; mainly for interop with world saves. + + pub const SLOT_CRAFTING_OUTPUT: usize = 0; + pub const SLOT_CRAFTING_INPUT_X0_Y0: usize = 1; + pub const SLOT_CRAFTING_INPUT_X1_Y0: usize = 2; + pub const SLOT_CRAFTING_INPUT_X0_Y1: usize = 3; + pub const SLOT_CRAFTING_INPUT_X1_Y1: usize = 4; + + pub const SLOT_ARMOR_MIN: usize = 5; + pub const SLOT_ARMOR_MAX: usize = 8; + + pub const SLOT_ARMOR_HEAD: usize = 5; + pub const SLOT_ARMOR_CHEST: usize = 6; + pub const SLOT_ARMOR_LEGS: usize = 7; + pub const SLOT_ARMOR_FEET: usize = 8; + + pub const SLOT_OFFHAND: usize = 45; + + pub const SLOT_INVENTORY_OFFSET: usize = 9; + pub const SLOT_HOTBAR_OFFSET: usize = 36; + + pub const HOTBAR_SIZE: usize = 9; + pub const INVENTORY_SIZE: usize = 27; + + pub const SLOT_ENTITY_EQUIPMENT_MAIN_HAND: usize = 0; + pub const SLOT_ENTITY_EQUIPMENT_OFF_HAND: usize = 1; + pub const SLOT_ENTITY_EQUIPMENT_BOOTS: usize = 2; + pub const SLOT_ENTITY_EQUIPMENT_LEGGINGS: usize = 3; + pub const SLOT_ENTITY_EQUIPMENT_CHESTPLATE: usize = 4; + pub const SLOT_ENTITY_EQUIPMENT_HELMET: usize = 5; +} + +/// Converted from of a protocol index, used +/// to access inventories directly. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct Index { + /// The index into `Window.inventories`, used + /// when the window consists of multiple inventories. + pub inventory: usize, + /// The area inside the inventory. + pub area: Area, + /// The index inside the area. + pub slot: usize, +} + +impl From for SlotIndex { + fn from(idx: Index) -> Self { + SlotIndex { + area: idx.area, + slot: idx.slot, + } + } +} + +/// Error returned when a `Window` fails to create +/// a `WindowAccessor` +#[derive(Debug, Error)] +pub enum Error { + #[error("no inventory component for entity")] + MissingComponent, +} + +/// A window represents the current context of a player's GUI. +/// It defines the functions to convert slot indices in the protocol +/// to those used for `Inventory`. +/// +/// Critically, a window may wrap over multiple inventories. For example, +/// if a player is inside a chest, then their context is `Window::chest(player, chest)`. +/// The `Window` then delegates raw `usize`s from the protocol to either +/// `player` or `chest` depending on the value of said `usize`. +#[derive(Debug, Clone)] +pub struct Window { + /// Mapping from `usize` in the protocol + /// to indices into the inventory. + protocol_to_slot: fn(usize) -> Option, + /// Inverse of `protocol_to_slot`. + slot_to_protocol: fn(Index) -> usize, + /// Inventories wrapped over by this `Window`. + /// + /// Internally, we store the `Entity` handles. + /// When accessing inventories, we retrieve the `Inventory` + /// component. + inventories: SmallVec<[Entity; 2]>, +} + +impl Window { + /// Creates a new `Window` for a normal player, + /// i.e. a player's own inventory without any + /// crafting tables, chests, furnaces, etc. open. + /// + /// https://wiki.vg/Inventory#Player_Inventory + pub fn player(player: Entity) -> Self { + Self { + protocol_to_slot: player_to_slot, + slot_to_protocol: player_from_slot, + inventories: smallvec![player], + } + } + + /// Retrieves a `WindowAccessor` which may be used + /// to access the underlying inventories. + /// + /// Returns an error if the `Entity`s stored in the `Window` + /// do not exist in the `World` or have no inventory components. + pub fn accessor<'a>(&'a self, world: &'a World) -> Result, Error> { + let inventories = self + .inventories + .iter() + .map(|entity| world.try_get::(*entity)) + .collect::>() + .ok_or(Error::MissingComponent)?; + + Ok(WindowAccessor { + window: self, + inventories, + }) + } + + /// Converts a network index to a `SlotIndex`. + pub fn convert_network(&self, network: usize) -> Option { + let protocol_to_slot = self.protocol_to_slot; + protocol_to_slot(network) + } + + /// Converts a `SlotIndex` and the entity whose + /// inventory the `SlotIndex` belongs to to a network index. + pub fn convert_slot(&self, slot: SlotIndex, entity: Entity) -> Option { + let slot_to_protocol = self.slot_to_protocol; + let inventory = self.inventories.iter().position(|e| *e == entity)?; + let index = Index { + area: slot.area, + inventory, + slot: slot.slot, + }; + Some(slot_to_protocol(index)) + } + + // TODO: more mappings as the need arises +} + +/// Accessor to a set of inventories returned by `Window::accessor`. +/// +/// This stores references to the wrapped `Inventory`s +/// and allows for direct inventory access through protocol +/// indices. +pub struct WindowAccessor<'a> { + window: &'a Window, + inventories: SmallVec<[Ref<'a, Inventory>; 2]>, +} + +impl<'a> WindowAccessor<'a> { + /// Retrieves the item at the given protocol index. + pub fn item_at(&self, index: usize) -> Result { + self.with_inv(index, |inv, idx| inv.item_at(idx.area, idx.slot)) + } + + /// Sets the slot (`Option`) at the given protocol + /// index. + /// + /// Returns the old slot. + pub fn set_slot_at(&self, index: usize, slot: Slot) -> Result { + self.with_inv(index, |inv, idx| { + inv.item_at_mut(idx.area, idx.slot).map(|mut guard| { + let old = *guard; + *guard = slot; + old + }) + }) + } + + /// Sets the item at the given protocol index. + /// + /// Returns the old item. + pub fn set_item_at(&self, index: usize, stack: ItemStack) -> Result { + self.with_inv(index, |inv, idx| inv.set_item_at(idx.area, idx.slot, stack)) + } + + /// Removes the item at the given index. + /// + /// Returns the removed item. + pub fn remove_item_at(&self, index: usize) -> Result { + self.with_inv(index, |inv, idx| inv.remove_item_at(idx.area, idx.slot)) + } + + fn with_inv( + &self, + index: usize, + f: impl FnOnce(&Inventory, Index) -> Result, + ) -> Result { + let protocol_to_slot = self.window.protocol_to_slot; + let index = protocol_to_slot(index).ok_or(crate::Error::InvalidProtocolIndex(index))?; + let inventory = &self.inventories[index.inventory]; + + f(inventory, index) + } +} + +/// https://wiki.vg/Inventory#Player_Inventory +fn player_to_slot(x: usize) -> Option { + Some(match x { + 0 => index(0, Area::CraftingOutput, 0), + 1..=4 => index(0, Area::CraftingInput, x - 1), + 5 => index(0, Area::Head, 0), + 6 => index(0, Area::Torso, 0), + 7 => index(0, Area::Legs, 0), + 8 => index(0, Area::Feet, 0), + 9..=35 => index(0, Area::Main, x - 9), + 36..=44 => index(0, Area::Hotbar, x - 36), + 45 => index(0, Area::Offhand, 0), + _ => return None, + }) +} + +fn player_from_slot(slot: Index) -> usize { + use Area::*; + match slot.area { + CraftingOutput => 0, + CraftingInput => slot.slot + 1, + Head => 5, + Torso => 6, + Legs => 7, + Feet => 8, + Main => 9 + slot.slot, + Hotbar => 36 + slot.slot, + Offhand => 45, + x => panic!("unreachable area {:?} for player window", x), + } +} + +fn index(inventory: usize, area: Area, slot: usize) -> Index { + Index { + inventory, + area, + slot, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn player_roundtrip() { + (0..=45).for_each(|i| assert_eq!(i, player_from_slot(player_to_slot(i).unwrap()))); + } +} diff --git a/server/chunk/src/save.rs b/server/chunk/src/save.rs index 91c3e27aa..78179b3a4 100644 --- a/server/chunk/src/save.rs +++ b/server/chunk/src/save.rs @@ -3,7 +3,7 @@ use crate::{chunk_manager, ChunkWorkerHandle}; use feather_core::anvil::entity::BaseEntityData; use feather_core::anvil::player::{InventorySlot, PlayerData}; -use feather_core::inventory::Inventory; +use feather_core::inventory::{Inventory, Window}; use feather_core::util::{ChunkPosition, Gamemode, Position, Vec3d}; use feather_server_types::{ ChunkLoadEvent, ChunkUnloadEvent, ComponentSerializer, Game, PlayerLeaveEvent, Uuid, @@ -152,14 +152,13 @@ pub fn on_player_leave_save_data(event: &PlayerLeaveEvent, game: &Game, world: & pub fn save_player_data(game: &Game, world: &World, player: Entity) { let inventory = world .get::(player) - .items() - .iter() .enumerate() - .filter_map(|(i, item)| item.map(|item| (i, item))) - .map(|(slot, item)| InventorySlot { - count: item.amount as i8, - slot: slot as i8, - item: item.ty.identifier().to_owned(), + .filter_map(|(index, slot)| slot.map(move |slot| (index, slot))) + .filter_map(|(index, slot)| { + InventorySlot::from_network_index( + Window::player(player).convert_slot(index, player).unwrap(), + slot, + ) }) .collect(); diff --git a/server/entity/src/broadcasters/inventory.rs b/server/entity/src/broadcasters/inventory.rs index c76f10a97..ca6430856 100644 --- a/server/entity/src/broadcasters/inventory.rs +++ b/server/entity/src/broadcasters/inventory.rs @@ -1,7 +1,7 @@ //! Broadcasting of inventory-related events. use crate::inventory::Equipment; -use feather_core::inventory::{Inventory, SlotIndex, SLOT_HOTBAR_OFFSET}; +use feather_core::inventory::{Area, Inventory, SlotIndex, Window}; use feather_core::network::packets::{EntityEquipment, SetSlot}; use feather_server_types::{ EntitySendEvent, Game, HeldItem, InventoryUpdateEvent, Network, NetworkId, @@ -23,7 +23,9 @@ pub fn on_inventory_update_broadcast_equipment_update( // Skip this slot if it is not an equipment update. if let Ok(equipment) = is_equipment_update(held_item.0, *slot) { let slot = equipment.slot_index(held_item.0); - let item = inv.item_at(slot).expect("slot index out of bounds"); + let item = inv + .item_at(slot.area, slot.slot) + .expect("invalid InventoryUpdateEvent"); let packet = EntityEquipment { entity_id: world.get::(event.player).0, @@ -65,7 +67,7 @@ pub fn on_entity_send_send_equipment(event: &EntitySendEvent, world: &mut World) for equipment in equipments.iter() { let item = { let slot = equipment.slot_index(held_item.0); - match inventory.item_at(slot).unwrap() { + match inventory.item_at(slot.area, slot.slot).unwrap() { Some(item) => item, None => continue, // don't send equipment if it doesn't exist } @@ -88,12 +90,14 @@ pub fn on_entity_send_send_equipment(event: &EntitySendEvent, world: &mut World) pub fn on_inventory_update_send_set_slot(event: &InventoryUpdateEvent, world: &mut World) { let inv = world.get::(event.player); let network = world.get::(event.player); + let window = world.get::(event.player); for slot in &event.slots { + let converted = window.convert_slot(*slot, event.player).unwrap_or(0); let packet = SetSlot { window_id: 0, - slot: *slot as i16, - slot_data: inv.item_at(*slot as usize).unwrap(), + slot: converted as i16, + slot_data: inv.item_at(slot.area, slot.slot).unwrap(), }; network.send(packet); @@ -102,10 +106,10 @@ pub fn on_inventory_update_send_set_slot(event: &InventoryUpdateEvent, world: &m /// Returns whether the given update to an inventory /// is an equipment update. -fn is_equipment_update(held_item: SlotIndex, slot: SlotIndex) -> Result { - if slot >= SLOT_HOTBAR_OFFSET && slot - SLOT_HOTBAR_OFFSET == held_item { +fn is_equipment_update(held_item: usize, slot: SlotIndex) -> Result { + if slot.area == Area::Hotbar && slot.slot == held_item { Ok(Equipment::MainHand) - } else if let Some(equipment) = Equipment::from_slot_index(slot) { + } else if let Some(equipment) = Equipment::from_slot_index(slot, held_item) { Ok(equipment) } else { Err(()) @@ -115,9 +119,6 @@ fn is_equipment_update(held_item: SlotIndex, slot: SlotIndex) -> Result(player1).0 = 2; test.world - .get_mut::(player1) - .set_item_at(slot, stack); + .get::(player1) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); test.handle( InventoryUpdateEvent { @@ -156,8 +161,9 @@ mod tests { // now do player3 test.world.get_mut::(player3).0 = 2; test.world - .get_mut::(player3) - .set_item_at(slot, stack); + .get::(player3) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); test.handle( InventoryUpdateEvent { @@ -177,12 +183,16 @@ mod tests { let mut test = Test::new(); let stack = ItemStack::new(Item::EnderPearl, 15); - let slot = SLOT_HOTBAR_OFFSET; + let slot = SlotIndex { + area: Area::Hotbar, + slot: 0, + }; let (packet, player) = test.broadcast_routine::( |test, player1, player2| { test.world - .get_mut::(player1) - .set_item_at(slot, stack); + .get::(player1) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); EntitySendEvent { entity: player1, client: player2, @@ -202,14 +212,18 @@ mod tests { let mut test = Test::new(); let stack = ItemStack::new(Item::RedstoneOre, 4); - let slot = SLOT_INVENTORY_OFFSET + 4; + let slot = SlotIndex { + area: Area::Main, + slot: 4, + }; let player1 = test.player("", position!(0.0, 74.0, 0.0)); let player2 = test.player("", position!(0.0, 50.0, 1.5)); test.world - .get_mut::(player1) - .set_item_at(slot, stack); + .get::(player1) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); test.handle( InventoryUpdateEvent { @@ -220,33 +234,12 @@ mod tests { ); let packet = test.sent::(player1).unwrap(); - assert_eq!(packet.slot, slot as i16); + assert_eq!( + packet.slot, + Window::player(player1).convert_slot(slot, player1).unwrap() as i16 + ); assert_eq!(packet.slot_data, Some(stack)); assert!(test.sent::(player2).is_none()); } - - #[test] - fn test_is_equipment_update() { - let results = vec![ - (1, SLOT_HOTBAR_OFFSET + 1, Ok(Equipment::MainHand)), - (4, SLOT_HOTBAR_OFFSET + 4, Ok(Equipment::MainHand)), - (2, SLOT_INVENTORY_OFFSET, Err(())), - (0, SLOT_ARMOR_CHEST, Ok(Equipment::Chestplate)), - (0, SLOT_ARMOR_FEET, Ok(Equipment::Boots)), - (0, SLOT_ARMOR_LEGS, Ok(Equipment::Leggings)), - (0, SLOT_ARMOR_HEAD, Ok(Equipment::Helmet)), - (0, 10000, Err(())), - ]; - - for (held_item, slot, expected) in results { - assert_eq!( - is_equipment_update(held_item, slot), - expected, - "failed at {} {}", - held_item, - slot - ); - } - } } diff --git a/server/entity/src/inventory.rs b/server/entity/src/inventory.rs index 9c0ac4870..bbcb705e6 100644 --- a/server/entity/src/inventory.rs +++ b/server/entity/src/inventory.rs @@ -1,7 +1,4 @@ -use feather_core::inventory::{ - SlotIndex, SLOT_ARMOR_CHEST, SLOT_ARMOR_FEET, SLOT_ARMOR_HEAD, SLOT_ARMOR_LEGS, - SLOT_HOTBAR_OFFSET, SLOT_OFFHAND, -}; +use feather_core::inventory::{slot, Area, SlotIndex}; use feather_core::items::ItemStack; use feather_server_types::{HeldItem, Inventory}; use fecs::{Entity, World}; @@ -15,7 +12,7 @@ pub trait InventoryExt { impl InventoryExt for Inventory { fn item_in_main_hand(&self, entity: Entity, world: &World) -> Option { let held_item = world.get::(entity).0; - self.item_at(SLOT_HOTBAR_OFFSET + held_item).unwrap() + self.item_at(Area::Hotbar, held_item).unwrap() } } @@ -33,25 +30,34 @@ pub enum Equipment { } impl Equipment { - pub fn from_slot_index(index: SlotIndex) -> Option { - match index { - SLOT_OFFHAND => Some(Equipment::OffHand), - SLOT_ARMOR_FEET => Some(Equipment::Boots), - SLOT_ARMOR_LEGS => Some(Equipment::Leggings), - SLOT_ARMOR_CHEST => Some(Equipment::Chestplate), - SLOT_ARMOR_HEAD => Some(Equipment::Helmet), + pub fn from_slot_index(index: SlotIndex, held_item: usize) -> Option { + use feather_core::inventory::Area::*; + match index.area { + Offhand => Some(Equipment::OffHand), + Feet => Some(Equipment::Boots), + Legs => Some(Equipment::Leggings), + Torso => Some(Equipment::Chestplate), + Head => Some(Equipment::Helmet), + Hotbar => { + if index.slot == held_item { + Some(Equipment::MainHand) + } else { + None + } + } _ => None, } } - pub fn slot_index(self, held_item: SlotIndex) -> SlotIndex { + pub fn slot_index(self, held_item: usize) -> SlotIndex { + use feather_core::inventory::Area::*; match self { - Equipment::MainHand => held_item + SLOT_HOTBAR_OFFSET, - Equipment::OffHand => SLOT_OFFHAND, - Equipment::Boots => SLOT_ARMOR_FEET, - Equipment::Leggings => SLOT_ARMOR_LEGS, - Equipment::Chestplate => SLOT_ARMOR_CHEST, - Equipment::Helmet => SLOT_ARMOR_HEAD, + Equipment::MainHand => slot(Hotbar, held_item), + Equipment::OffHand => slot(Offhand, 0), + Equipment::Boots => slot(Feet, 0), + Equipment::Leggings => slot(Legs, 0), + Equipment::Chestplate => slot(Torso, 0), + Equipment::Helmet => slot(Head, 0), } } } diff --git a/server/player/src/lib.rs b/server/player/src/lib.rs index 1776fe9a8..9d7f88314 100644 --- a/server/player/src/lib.rs +++ b/server/player/src/lib.rs @@ -8,7 +8,7 @@ mod join; mod packet_handlers; mod view; -use feather_core::inventory::{Inventory, InventoryType}; +use feather_core::inventory::{Area, Inventory, SlotIndex, Window}; use feather_core::items::{Item, ItemStack}; use feather_core::network::packets::{PlayerInfo, PlayerInfoAction, SpawnPlayer}; use feather_core::network::Packet; @@ -31,8 +31,6 @@ pub use packet_handlers::*; use std::sync::atomic::Ordering; pub use view::*; -pub const PLAYER_INVENTORY_SIZE: u32 = 46; - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ItemTimedUse { pub tick_start: u64, @@ -74,19 +72,39 @@ pub fn create(game: &mut Game, world: &mut World, info: NewClientInfo) -> Entity let items = info.data.inventory.iter().map(|slot| { ( - slot.slot as usize, + slot.convert_index().unwrap_or_default(), ItemStack::new( Item::from_identifier(&slot.item).unwrap_or(Item::Air), slot.count as u8, ), ) }); - let slots = info.data.inventory.iter().map(|slot| slot.slot as usize); - - let mut inventory = Inventory::new(InventoryType::Player, PLAYER_INVENTORY_SIZE); - items.for_each(|(index, item)| inventory.set_item_at(index, item)); - world.add(entity, inventory).unwrap(); + let (window, slots) = { + let inventory = Inventory::player(); + let window = Window::player(entity); + world.add(entity, inventory).unwrap(); + + let accessor = window.accessor(world).unwrap(); + items.for_each(|(index, item)| { + let _ = accessor.set_item_at(index, item); + }); + + let window2 = window.clone(); + let slots = info.data.inventory.iter().map(move |slot| { + window2 + .convert_network(slot.convert_index().unwrap_or_default()) + .map(SlotIndex::from) + .unwrap_or(SlotIndex { + area: Area::Hotbar, + slot: 0, + }) + }); + + drop(accessor); + (window, slots) + }; + world.add(entity, window).unwrap(); world.add(entity, HeldItem(0)).unwrap(); // todo: load from player data world.add(entity, Player).unwrap(); diff --git a/server/player/src/packet_handlers/digging.rs b/server/player/src/packet_handlers/digging.rs index 7b914af6d..f0e4421f5 100644 --- a/server/player/src/packet_handlers/digging.rs +++ b/server/player/src/packet_handlers/digging.rs @@ -7,7 +7,7 @@ use crate::{ItemTimedUse, IteratorExt}; use entity::InventoryExt; use feather_core::blocks::BlockId; -use feather_core::inventory::{Inventory, SlotIndex, SLOT_HOTBAR_OFFSET, SLOT_OFFHAND}; +use feather_core::inventory::{slot, Area, Inventory, Slot, SlotIndex}; use feather_core::items::{Item, ItemStack}; use feather_core::network::packets::{PlayerDigging, PlayerDiggingStatus}; use feather_core::util::{BlockPosition, Position}; @@ -165,8 +165,9 @@ pub fn advance_dig_progress(game: &mut Game, world: &mut World) { let best_tool = block.kind().best_tool(); let best_tool_required = block.kind().best_tool_required(); - let item_in_main_hand: Option = - inventory.item_at(SLOT_HOTBAR_OFFSET + held_item.0).unwrap(); + let item_in_main_hand: Slot = inventory + .item_at(Area::Hotbar, held_item.0) + .expect("held item out of bounds"); let held_tool = item_in_main_hand.map(|item| item.ty.tool()).flatten(); let multiplier = if best_tool == held_tool && best_tool.is_some() { @@ -268,12 +269,10 @@ fn handle_drop_item_stack( ); let held_item = world.get::(player).0; - let mut inventory = world.get_mut::(player); - - let slot = held_item + SLOT_HOTBAR_OFFSET; + let inventory = world.get::(player); let stack = { - if let Some(item) = inventory.item_at(slot).unwrap() { + if let Some(item) = inventory.item_at(Area::Hotbar, held_item).unwrap() { item } else { // Silently fail - no item stack to drop @@ -284,18 +283,24 @@ fn handle_drop_item_stack( let amnt = match packet.status { PlayerDiggingStatus::DropItem => { if stack.amount == 0 { - inventory.clear_item_at(slot); + inventory.remove_item_at(Area::Hotbar, held_item).unwrap(); 0 } else if stack.amount == 1 { - inventory.clear_item_at(slot); + inventory.remove_item_at(Area::Hotbar, held_item).unwrap(); 1 } else { - inventory.set_item_at(slot, ItemStack::new(stack.ty, stack.amount - 1)); + inventory + .set_item_at( + Area::Hotbar, + held_item, + ItemStack::new(stack.ty, stack.amount - 1), + ) + .unwrap(); 1 } } PlayerDiggingStatus::DropItemStack => { - inventory.clear_item_at(slot); + inventory.remove_item_at(Area::Hotbar, held_item).unwrap(); stack.amount } _ => unreachable!(), // Assertion above @@ -303,15 +308,19 @@ fn handle_drop_item_stack( drop(inventory); + let idx = SlotIndex { + area: Area::Hotbar, + slot: held_item, + }; let inv_update = InventoryUpdateEvent { - slots: smallvec![slot], + slots: smallvec![idx], player, }; game.handle(world, inv_update); if amnt != 0 { let item_drop = ItemDropEvent { - slot: Some(slot), + slot: Some(idx), stack: ItemStack::new(stack.ty, amnt), player, }; @@ -420,24 +429,24 @@ fn handle_shoot_bow(game: &mut Game, world: &mut World, player: Entity) { fn find_arrow(inventory: &Inventory) -> Option<(SlotIndex, ItemStack)> { // Order of priority is: off-hand, hotbar (0 to 8), rest of inventory - if let Some(offhand) = inventory.item_at(SLOT_OFFHAND).unwrap() { + if let Some(offhand) = inventory.item_at(Area::Hotbar, 0).unwrap() { if is_arrow_item(offhand.ty) { - return Some((SLOT_OFFHAND, offhand)); + return Some((slot(Area::Offhand, 0), offhand)); } } for hotbar_slot in 0..9 { - if let Some(hotbar_stack) = inventory.item_at(SLOT_HOTBAR_OFFSET + hotbar_slot).unwrap() { + if let Some(hotbar_stack) = inventory.item_at(Area::Hotbar, hotbar_slot).unwrap() { if is_arrow_item(hotbar_stack.ty) { - return Some((SLOT_HOTBAR_OFFSET + hotbar_slot, hotbar_stack)); + return Some((slot(Area::Hotbar, hotbar_slot), hotbar_stack)); } } } - for inv_slot in 9..=35 { - if let Some(inv_stack) = inventory.item_at(inv_slot).unwrap() { + for inv_slot in 0..=27 { + if let Some(inv_stack) = inventory.item_at(Area::Main, inv_slot).unwrap() { if is_arrow_item(inv_stack.ty) { - return Some((inv_slot, inv_stack)); + return Some((slot(Area::Main, inv_slot), inv_stack)); } } } diff --git a/server/player/src/packet_handlers/inventory.rs b/server/player/src/packet_handlers/inventory.rs index b88827d51..4758e5a24 100644 --- a/server/player/src/packet_handlers/inventory.rs +++ b/server/player/src/packet_handlers/inventory.rs @@ -3,7 +3,7 @@ //! Change, and the venerable Click Window. use crate::IteratorExt; -use feather_core::inventory::{Inventory, SlotIndex, HOTBAR_SIZE, SLOT_HOTBAR_OFFSET}; +use feather_core::inventory::{Area, Inventory, SlotIndex, Window}; use feather_core::items::ItemStack; use feather_core::network::packets::{ ClickWindow, ConfirmTransactionClientbound, CreativeInventoryAction, HeldItemChangeServerbound, @@ -61,31 +61,32 @@ pub fn handle_creative_inventory_action( } let inventory = world.get::(player); - let slot_count = inventory.slot_count() as i16; - drop(inventory); + let window = world.get::(player); - if packet.slot >= slot_count || packet.slot < -1 { - game.disconnect(player, world, "Slot index out of bounds"); - return; - } + let accessor = match window.accessor(world) { + Ok(a) => a, + Err(_) => return, // silently fail + }; - let mut inventory = world.get_mut::(player); + let slot = packet.clicked_item; - match packet.clicked_item.as_ref() { - Some(item) => { - inventory.set_item_at(packet.slot as usize, *item); - } - None => { - inventory.clear_item_at(packet.slot as usize); - } + if let Err(e) = accessor.set_slot_at(packet.slot as usize, slot) { + drop(inventory); + drop(accessor); + drop(window); + game.disconnect(player, world, format!("Slot index out of bounds: {}", e)); + return; } // Trigger inventory update event + let index = window.convert_network(packet.slot as usize).unwrap(); // already checked above let event = InventoryUpdateEvent { - slots: std::iter::once(packet.slot as usize).collect(), + slots: smallvec![index.into()], player, }; drop(inventory); + drop(accessor); + drop(window); game.handle(world, event); }); } @@ -100,7 +101,7 @@ pub fn handle_held_item_change( packet_buffers .received::() .for_each_valid(world, |world, (player, packet)| { - if packet.slot as usize >= HOTBAR_SIZE { + if packet.slot as usize >= 9 { game.disconnect(player, world, "Hotbar index out of bounds"); return; } @@ -110,7 +111,10 @@ pub fn handle_held_item_change( // Trigger event let event = InventoryUpdateEvent { - slots: std::iter::once(held_item.0 as usize + SLOT_HOTBAR_OFFSET).collect(), + slots: smallvec![SlotIndex { + area: Area::Hotbar, + slot: held_item.0 + }], player, }; drop(held_item); @@ -329,10 +333,10 @@ fn handle_single_click( // type in the slot, then the picked up item and // the item in the slot are swapped. - let inv = world.get::(player); - let current_item = inv.item_at(packet.slot as SlotIndex)?; + let window = world.get::(player); + let accessor = window.accessor(world)?; + let current_item = accessor.item_at(packet.slot as usize)?; - drop(inv); if let Some(current_item) = current_item.and_then(|item| { if item.ty == picked.0.ty { None @@ -341,10 +345,10 @@ fn handle_single_click( } }) { // Different items - swap + accessor.set_item_at(packet.slot as usize, picked.0)?; + drop(accessor); + drop(window); world.get_mut::(player).0 = current_item; - world - .get_mut::(player) - .set_item_at(packet.slot as SlotIndex, picked.0); } else { // Place item on slot let count = match button { @@ -355,10 +359,11 @@ fn handle_single_click( let current_count = current_item.map(|stack| stack.amount).unwrap_or(0); let new_count = (count + current_count).min(picked.0.ty.stack_size() as u8); - world.get_mut::(player).set_item_at( - packet.slot as SlotIndex, - ItemStack::new(picked.0.ty, new_count), - ); + accessor.set_item_at(packet.slot as usize, ItemStack::new(picked.0.ty, new_count))?; + + drop(accessor); + drop(window); + world.get_mut::(player).0.amount -= new_count - current_count; if world.get::(player).0.amount == 0 { @@ -366,34 +371,36 @@ fn handle_single_click( } } } else { + let window = world.get::(player); + let accessor = window.accessor(world)?; + // Pick up the item in the slot - let picked_up = world - .get::(player) - .item_at(packet.slot as SlotIndex)?; + let picked_up = accessor.item_at(packet.slot as usize)?; let mut count = picked_up.map(|item| item.amount).unwrap_or(0); if button == MouseButton::Right { count = (count + 1) / 2; } if let Some(item) = picked_up { + accessor.set_item_at( + packet.slot as usize, + ItemStack::new(item.ty, item.amount - count), + )?; + + drop(accessor); + drop(window); world .add(player, PickedItem(ItemStack::new(item.ty, count))) .unwrap(); - - let mut inv = world.get_mut::(player); - inv.set_item_at( - packet.slot as SlotIndex, - ItemStack::new(item.ty, item.amount - count), - ) } } - game.handle( - world, - InventoryUpdateEvent { - player, - slots: smallvec![packet.slot as SlotIndex], - }, - ); + let window = world.get::(player); + let slots = smallvec![window + .convert_network(packet.slot as usize) + .ok_or_else(|| anyhow::anyhow!("invalid slot index"))? + .into()]; + drop(window); + game.handle(world, InventoryUpdateEvent { player, slots }); Ok(()) } diff --git a/server/player/src/packet_handlers/placement.rs b/server/player/src/packet_handlers/placement.rs index 93ad3e338..f9ba12c90 100644 --- a/server/player/src/packet_handlers/placement.rs +++ b/server/player/src/packet_handlers/placement.rs @@ -3,13 +3,14 @@ use crate::IteratorExt; use entity::InventoryExt; use feather_core::blocks::BlockKind; -use feather_core::inventory::{Inventory, SLOT_HOTBAR_OFFSET}; +use feather_core::inventory::{slot, Area, Inventory}; use feather_core::item_block::ItemToBlock; use feather_core::items::ItemStack; use feather_core::network::packets::PlayerBlockPlacement; use feather_core::util::Gamemode; use feather_server_types::{BlockUpdateCause, Game, HeldItem, InventoryUpdateEvent, PacketBuffers}; use fecs::World; +use smallvec::smallvec; use std::sync::Arc; /// System for handling Player Block Placement packets @@ -58,7 +59,7 @@ pub fn handle_player_block_placement( game.set_block_at(world, pos, block, BlockUpdateCause::Entity(player)); let held_item = world.get::(player).0; - let mut inventory = world.get_mut::(player); + let inventory = world.get::(player); // Update player's inventory if in survival if gamemode == Gamemode::Survival { @@ -73,10 +74,12 @@ pub fn handle_player_block_placement( } let item = ItemStack::new(item.ty, item.amount - 1); - inventory.set_item_at(held_item, item); + inventory + .set_item_at(Area::Hotbar, held_item, item) + .unwrap(); let event = InventoryUpdateEvent { - slots: std::iter::once(SLOT_HOTBAR_OFFSET + held_item).collect(), + slots: smallvec![slot(Area::Hotbar, held_item)], player, }; drop(inventory); diff --git a/server/types/src/components.rs b/server/types/src/components.rs index 6e53ac217..932fb96d5 100644 --- a/server/types/src/components.rs +++ b/server/types/src/components.rs @@ -13,13 +13,15 @@ pub use uuid::Uuid; use ahash::AHashSet; use dashmap::DashMap; -use feather_core::inventory::SlotIndex; use feather_core::util::{ChunkPosition, Position}; use fecs::Entity; /// The item an entity is currently holding. +/// +/// This is the index inside the `Hotbar` area +/// of the inventory. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default)] -pub struct HeldItem(pub SlotIndex); +pub struct HeldItem(pub usize); /// An entity's name. #[derive(Debug, Clone, Default)]