From 679cb1620ff420760761341c90115c70f2b8d824 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Mon, 11 May 2020 23:02:14 -0600 Subject: [PATCH 1/5] Draft new inventory API --- Cargo.lock | 11 +- core/inventory/Cargo.toml | 8 +- core/inventory/src/lib.rs | 573 ++++++++++------------------------- core/inventory/src/window.rs | 158 ++++++++++ 4 files changed, 333 insertions(+), 417 deletions(-) create mode 100644 core/inventory/src/window.rs diff --git a/Cargo.lock b/Cargo.lock index 2e8b58686..dd8ba6db0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -805,13 +805,13 @@ dependencies = [ "indexmap", "itertools 0.9.0", "once_cell", - "proc-macro2 1.0.10", + "proc-macro2 1.0.12", "quote 1.0.1", "regex", "ron", "serde", "serde_json", - "syn 1.0.18", + "syn 1.0.19", "walkdir", ] @@ -850,7 +850,10 @@ name = "feather-inventory" version = "0.6.0" dependencies = [ "feather-items", - "once_cell", + "fecs", + "legion", + "maplit", + "parking_lot 0.10.2", "smallvec 1.4.0", "thiserror", ] @@ -2723,7 +2726,7 @@ name = "ron" version = "0.5.2" source = "git+https://github.com/ron-rs/ron?rev=0a7d83da66a4009f169967c5d2ac382a446bb76e#0a7d83da66a4009f169967c5d2ac382a446bb76e" dependencies = [ - "base64 0.12.0", + "base64 0.12.1", "bitflags", "serde", ] diff --git a/core/inventory/Cargo.toml b/core/inventory/Cargo.toml index 44224f89c..a64d206ae 100644 --- a/core/inventory/Cargo.toml +++ b/core/inventory/Cargo.toml @@ -6,6 +6,10 @@ 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" diff --git a/core/inventory/src/lib.rs b/core/inventory/src/lib.rs index ed1ef3893..e5a4553eb 100644 --- a/core/inventory/src/lib.rs +++ b/core/inventory/src/lib.rs @@ -1,448 +1,199 @@ -//! Module for creating and modifying inventories of any type. - -use feather_items::{Item, ItemStack}; -use once_cell::sync::Lazy; -use smallvec::{Array, SmallVec}; -use std::cmp::min; +//! 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; -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 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(|| { - let mut result = vec![]; - for x in SLOT_HOTBAR_OFFSET..SLOT_HOTBAR_OFFSET + HOTBAR_SIZE { - result.push(x); - } - - for x in SLOT_INVENTORY_OFFSET..SLOT_INVENTORY_OFFSET + INVENTORY_SIZE { - result.push(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!(), - } +mod window; + +pub use window::{Error as WindowError, Window, WindowAccessor}; + +/// 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, - } -} +/// 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; -/// 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, +/// 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), - /// 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) - } - - pub fn item_at_mut(&mut self, index: SlotIndex) -> Option<&mut ItemStack> { - self.items[index].as_mut() - } + Area::Head => empty(1), + Area::Torso => empty(1), + Area::Legs => empty(1), + Area::Feet => empty(1), + Area::Offhand => empty(1), - /// 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") - } - - /// 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; - } else { - *self.items.get_mut(index)? = Some(item); - } - Some(()) - } + Area::CraftingInput => empty(4), + Area::CraftingOutput => empty(1), + }; - /// 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() + Self { slots } } - /// Attempts to insert the given item into a player - /// 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) { - 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") { - if slot_item.ty == item.ty { - self.add_to_stack(&mut item, slot_item, *slot, &mut affected_slots); - - if item.amount == 0 { - return (affected_slots, 0); - } - } - } - } - - for slot in COLLECT_SEARCH_ORDER.iter() { - let slot_item = self.item_at(*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); - if item.amount == 0 { - return (affected_slots, 0); - } - } - - 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); - - if item.amount == 0 { - return (affected_slots, 0); - } - } - } - } + /// 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), + }; - (affected_slots, item.amount) + Self { slots } } - /// Adds an item to a stack. - fn add_to_stack>( - &mut 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); - item.amount -= added; - - self.set_item_at(slot, ItemStack::new(slot_item.ty, slot_item.amount + added)); - affected_slots.push(slot); + /// 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) } - /// Returns the number of slots in this inventory. - pub fn slot_count(&self) -> u16 { - self.items.len() as u16 + /// 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) } - /// Returns a reference to this inventory's items. - pub fn items(&self) -> &[Option] { - &self.items + /// 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 { + Slot::Some(stack) + }; + Ok(old) } -} - -#[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); + /// 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)?; - 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()); + Ok(item.take()) } - #[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); + /// 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) } - #[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); - } + /// Returns an iterator over the areas in this inventory. + pub fn areas<'a>(&'a self) -> impl Iterator + 'a { + self.slots.keys().copied() } - #[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) - ); + fn slot(&self, area: Area, index: usize) -> Result<&RwLock, Error> { + let slots = self.slots(area)?; + slots.get(index).ok_or(Error::OutOfBounds(index, area)) } - #[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 slots(&self, area: Area) -> Result<&[RwLock], Error> { + self.slots + .get(&area) + .ok_or(Error::NoSuchArea(area)) + .map(Vec::as_slice) } } + +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..d6b6b2a55 --- /dev/null +++ b/core/inventory/src/window.rs @@ -0,0 +1,158 @@ +//! 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}; +use feather_items::ItemStack; +use fecs::{Entity, World}; +use legion::borrow::Ref; +use smallvec::{smallvec, SmallVec}; +use thiserror::Error; + +/// Converted from of a protocol index, used +/// to access inventories directly. +#[derive(Copy, Clone, Debug)] +struct Index { + /// The index into `Window.inventories`, used + /// when the window consists of multiple inventories. + inventory: usize, + /// The area inside the inventory. + area: Area, + /// The index inside the area. + slot: usize, +} + +/// 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 inventory. + /// + mapping: fn(usize) -> Option, + /// 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 { + mapping: player_mapping, + 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, + }) + } + + // 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 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)) + } + + /// Removes the item at the given index + + fn with_inv( + &self, + index: usize, + f: impl FnOnce(&Inventory, Index) -> Result, + ) -> Result { + let mapping = self.window.mapping; + let index = mapping(index).ok_or(crate::Error::InvalidProtocolIndex(index))?; + let inventory = &self.inventories[index.inventory]; + + f(inventory, index) + } +} + +/// https://wiki.vg/Inventory#Player_Inventory +fn player_mapping(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 index(inventory: usize, area: Area, slot: usize) -> Index { + Index { + inventory, + area, + slot, + } +} From 1ddc953cee7fc28f9718dfdfc7647cca0513b986 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Tue, 12 May 2020 21:05:51 -0600 Subject: [PATCH 2/5] Convert feather-server-entity to new inventory API --- Cargo.lock | 1 + core/anvil/src/player.rs | 23 ++-- core/inventory/Cargo.toml | 1 + core/inventory/src/lib.rs | 129 +++++++++++++++++++- core/inventory/src/window.rs | 102 ++++++++++++++-- server/chunk/src/save.rs | 5 +- server/entity/src/broadcasters/inventory.rs | 28 +++-- server/entity/src/inventory.rs | 44 ++++--- server/types/src/components.rs | 6 +- 9 files changed, 281 insertions(+), 58 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dd8ba6db0..1a5b69c87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -853,6 +853,7 @@ dependencies = [ "fecs", "legion", "maplit", + "once_cell", "parking_lot 0.10.2", "smallvec 1.4.0", "thiserror", diff --git a/core/anvil/src/player.rs b/core/anvil/src/player.rs index 225108fb7..3d630f8f4 100644 --- a/core/anvil/src/player.rs +++ b/core/anvil/src/player.rs @@ -1,7 +1,8 @@ use crate::entity::BaseEntityData; -use feather_inventory::{ - SlotIndex, HOTBAR_SIZE, INVENTORY_SIZE, SLOT_ARMOR_MAX, SLOT_ARMOR_MIN, SLOT_HOTBAR_OFFSET, - SLOT_INVENTORY_OFFSET, SLOT_OFFHAND, +use feather_inventory::player_constants::{ + HOTBAR_SIZE, INVENTORY_SIZE, SLOT_ARMOR_CHEST, SLOT_ARMOR_FEET, SLOT_ARMOR_HEAD, + SLOT_ARMOR_LEGS, SLOT_ARMOR_MAX, SLOT_ARMOR_MIN, SLOT_HOTBAR_OFFSET, SLOT_INVENTORY_OFFSET, + SLOT_OFFHAND, }; use feather_items::{Item, ItemStack}; use serde::{Deserialize, Serialize}; @@ -45,7 +46,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) -> Self { let slot = if SLOT_HOTBAR_OFFSET <= network && network < SLOT_HOTBAR_OFFSET + HOTBAR_SIZE { // Hotbar (network - SLOT_HOTBAR_OFFSET) as i8 @@ -70,7 +71,7 @@ impl InventorySlot { /// 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)) @@ -173,15 +174,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 diff --git a/core/inventory/Cargo.toml b/core/inventory/Cargo.toml index a64d206ae..44a0ea7ec 100644 --- a/core/inventory/Cargo.toml +++ b/core/inventory/Cargo.toml @@ -13,3 +13,4 @@ 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 e5a4553eb..63fe8bd45 100644 --- a/core/inventory/src/lib.rs +++ b/core/inventory/src/lib.rs @@ -16,7 +16,24 @@ use thiserror::Error; mod window; -pub use window::{Error as WindowError, Window, WindowAccessor}; +use once_cell::sync::Lazy; +use smallvec::{Array, SmallVec}; +use std::cmp::min; +pub use window::{constants as player_constants, Error as WindowError, Window, WindowAccessor}; + +static COLLECT_SEARCH_ORDER: Lazy> = Lazy::new(|| { + let mut result = vec![]; + // TODO: move to constants + for x in 0..9 { + result.push((Area::Hotbar, x)); + } + + for x in 0..27 { + result.push((Area::Main, x)); + } + + result +}); /// An area inside an inventory, used to differentiate between /// different parts. @@ -49,6 +66,18 @@ pub enum Area { Chest, } +/// Index into a slot. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct SlotIndex { + pub area: Area, + pub slot: usize, +} + +/// 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; @@ -176,11 +205,109 @@ impl Inventory { .map(RwLock::write) } + /// 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 + /// inventory. + /// + /// Returns the affected slots and the number of remaining + /// items which were not added to the inventory. + /// + /// 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 (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, + SlotIndex { + area: *area, + slot: *slot, + }, + &mut affected_slots, + ); + + if item.amount == 0 { + return (affected_slots, 0); + } + } + } + } + + 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, + SlotIndex { + area: *area, + slot: *slot, + }, + &mut affected_slots, + ); + if item.amount == 0 { + return (affected_slots, 0); + } + } + + if let Some(slot_item) = slot_item { + if slot_item.ty == item.ty { + self.add_to_stack( + &mut item, + slot_item, + SlotIndex { + area: *area, + slot: *slot, + }, + &mut affected_slots, + ); + + if item.amount == 0 { + return (affected_slots, 0); + } + } + } + } + + (affected_slots, item.amount) + } + + /// Adds an item to a stack. + fn add_to_stack>( + &self, + item: &mut ItemStack, + slot_item: ItemStack, + slot: SlotIndex, + affected_slots: &mut SmallVec, + ) { + let added = min(item.amount, item.ty.stack_size() as u8 - slot_item.amount); + item.amount -= added; + + self.set_item_at( + slot.area, + slot.slot, + ItemStack::new(slot_item.ty, slot_item.amount + added), + ); + affected_slots.push(slot); + } + fn slot(&self, area: Area, index: usize) -> Result<&RwLock, Error> { let slots = self.slots(area)?; slots.get(index).ok_or(Error::OutOfBounds(index, area)) diff --git a/core/inventory/src/window.rs b/core/inventory/src/window.rs index d6b6b2a55..8b1d8bb16 100644 --- a/core/inventory/src/window.rs +++ b/core/inventory/src/window.rs @@ -3,17 +3,52 @@ //! //! See https://wiki.vg/Inventory for more information. -use crate::{Area, Inventory, Slot}; +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)] -struct Index { +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct Index { /// The index into `Window.inventories`, used /// when the window consists of multiple inventories. inventory: usize, @@ -42,9 +77,10 @@ pub enum Error { #[derive(Debug, Clone)] pub struct Window { /// Mapping from `usize` in the protocol - /// to indices into inventory. - /// - mapping: fn(usize) -> Option, + /// 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. @@ -61,7 +97,8 @@ impl Window { /// https://wiki.vg/Inventory#Player_Inventory pub fn player(player: Entity) -> Self { Self { - mapping: player_mapping, + protocol_to_slot: player_to_slot, + slot_to_protocol: player_from_slot, inventories: smallvec![player], } } @@ -85,6 +122,25 @@ impl Window { }) } + /// 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 } @@ -125,8 +181,8 @@ impl<'a> WindowAccessor<'a> { index: usize, f: impl FnOnce(&Inventory, Index) -> Result, ) -> Result { - let mapping = self.window.mapping; - let index = mapping(index).ok_or(crate::Error::InvalidProtocolIndex(index))?; + 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) @@ -134,7 +190,7 @@ impl<'a> WindowAccessor<'a> { } /// https://wiki.vg/Inventory#Player_Inventory -fn player_mapping(x: usize) -> Option { +fn player_to_slot(x: usize) -> Option { Some(match x { 0 => index(0, Area::CraftingOutput, 0), 1..=4 => index(0, Area::CraftingInput, x - 1), @@ -149,6 +205,22 @@ fn player_mapping(x: usize) -> Option { }) } +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, @@ -156,3 +228,13 @@ fn index(inventory: usize, area: Area, slot: usize) -> Index { 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..22d7f8dd6 100644 --- a/server/chunk/src/save.rs +++ b/server/chunk/src/save.rs @@ -152,10 +152,9 @@ 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() + .iter_mut() .enumerate() - .filter_map(|(i, item)| item.map(|item| (i, item))) + .filter_map(|(i, item)| (*item).map(|item| (i, item))) .map(|(slot, item)| InventorySlot { count: item.amount as i8, slot: slot as i8, diff --git a/server/entity/src/broadcasters/inventory.rs b/server/entity/src/broadcasters/inventory.rs index c76f10a97..e2c696668 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(()) @@ -135,7 +139,7 @@ mod tests { test.world.get_mut::(player1).0 = 2; test.world .get_mut::(player1) - .set_item_at(slot, stack); + .set_item_at(slot.area, slot.slot, stack); test.handle( InventoryUpdateEvent { @@ -157,7 +161,7 @@ mod tests { test.world.get_mut::(player3).0 = 2; test.world .get_mut::(player3) - .set_item_at(slot, stack); + .set_item_at(slot.area, slot.slot, stack); test.handle( InventoryUpdateEvent { @@ -182,7 +186,7 @@ mod tests { |test, player1, player2| { test.world .get_mut::(player1) - .set_item_at(slot, stack); + .set_item_at(slot.area, slot.slot, stack); EntitySendEvent { entity: player1, client: player2, @@ -209,7 +213,7 @@ mod tests { test.world .get_mut::(player1) - .set_item_at(slot, stack); + .set_item_at(slot.area, slot.slot, stack); test.handle( InventoryUpdateEvent { diff --git a/server/entity/src/inventory.rs b/server/entity/src/inventory.rs index 9c0ac4870..23e233fa2 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(Legs, 0), + Equipment::Leggings => slot(Legs, 0), + Equipment::Chestplate => slot(Torso, 0), + Equipment::Helmet => slot(Head, 0), } } } 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)] From 9ba7a3a1575e99b7d080b2df33db2043d9d198b4 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Fri, 15 May 2020 23:33:49 -0600 Subject: [PATCH 3/5] Lots more refactoring work... there are bugs. --- core/anvil/src/player.rs | 8 +- core/inventory/src/lib.rs | 3 +- core/inventory/src/window.rs | 15 ++- server/chunk/src/save.rs | 14 +-- server/entity/src/broadcasters/inventory.rs | 67 ++++++------- server/player/src/lib.rs | 34 +++++-- server/player/src/packet_handlers/digging.rs | 49 ++++++---- .../player/src/packet_handlers/inventory.rs | 95 ++++++++++--------- .../player/src/packet_handlers/placement.rs | 11 ++- 9 files changed, 167 insertions(+), 129 deletions(-) diff --git a/core/anvil/src/player.rs b/core/anvil/src/player.rs index 3d630f8f4..a6dedc76f 100644 --- a/core/anvil/src/player.rs +++ b/core/anvil/src/player.rs @@ -1,8 +1,7 @@ use crate::entity::BaseEntityData; use feather_inventory::player_constants::{ - HOTBAR_SIZE, INVENTORY_SIZE, SLOT_ARMOR_CHEST, SLOT_ARMOR_FEET, SLOT_ARMOR_HEAD, - SLOT_ARMOR_LEGS, SLOT_ARMOR_MAX, SLOT_ARMOR_MIN, SLOT_HOTBAR_OFFSET, SLOT_INVENTORY_OFFSET, - SLOT_OFFHAND, + HOTBAR_SIZE, INVENTORY_SIZE, SLOT_ARMOR_MAX, SLOT_ARMOR_MIN, SLOT_HOTBAR_OFFSET, + SLOT_INVENTORY_OFFSET, SLOT_OFFHAND, }; use feather_items::{Item, ItemStack}; use serde::{Deserialize, Serialize}; @@ -132,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; diff --git a/core/inventory/src/lib.rs b/core/inventory/src/lib.rs index 63fe8bd45..8aa091f20 100644 --- a/core/inventory/src/lib.rs +++ b/core/inventory/src/lib.rs @@ -304,7 +304,8 @@ impl Inventory { slot.area, slot.slot, ItemStack::new(slot_item.ty, slot_item.amount + added), - ); + ) + .unwrap(); affected_slots.push(slot); } diff --git a/core/inventory/src/window.rs b/core/inventory/src/window.rs index 8b1d8bb16..4cd83bce6 100644 --- a/core/inventory/src/window.rs +++ b/core/inventory/src/window.rs @@ -51,11 +51,20 @@ pub mod constants { pub struct Index { /// The index into `Window.inventories`, used /// when the window consists of multiple inventories. - inventory: usize, + pub inventory: usize, /// The area inside the inventory. - area: Area, + pub area: Area, /// The index inside the area. - slot: usize, + 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 diff --git a/server/chunk/src/save.rs b/server/chunk/src/save.rs index 22d7f8dd6..550fe1780 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,13 +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) - .iter_mut() .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))) + .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 e2c696668..ca6430856 100644 --- a/server/entity/src/broadcasters/inventory.rs +++ b/server/entity/src/broadcasters/inventory.rs @@ -119,9 +119,6 @@ fn is_equipment_update(held_item: usize, slot: SlotIndex) -> Result(player1).0 = 2; test.world - .get_mut::(player1) - .set_item_at(slot.area, slot.slot, stack); + .get::(player1) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); test.handle( InventoryUpdateEvent { @@ -160,8 +161,9 @@ mod tests { // now do player3 test.world.get_mut::(player3).0 = 2; test.world - .get_mut::(player3) - .set_item_at(slot.area, slot.slot, stack); + .get::(player3) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); test.handle( InventoryUpdateEvent { @@ -181,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.area, slot.slot, stack); + .get::(player1) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); EntitySendEvent { entity: player1, client: player2, @@ -206,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.area, slot.slot, stack); + .get::(player1) + .set_item_at(slot.area, slot.slot, stack) + .unwrap(); test.handle( InventoryUpdateEvent { @@ -224,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/player/src/lib.rs b/server/player/src/lib.rs index b3ec61ad9..b5ce9d014 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; @@ -30,8 +30,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, @@ -80,12 +78,32 @@ pub fn create(game: &mut Game, world: &mut World, info: NewClientInfo) -> Entity ), ) }); - 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.slot as usize) + .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..483a5c554 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_item_at(packet.slot as usize, slot.unwrap_or_default()) { + 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); From d1a7b335e6b87886594084ec059cc336cb94ad88 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Sun, 17 May 2020 23:38:05 -0600 Subject: [PATCH 4/5] Fix a few bugs --- core/anvil/src/player.rs | 10 +++++----- server/chunk/src/save.rs | 5 ++++- server/player/src/lib.rs | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/core/anvil/src/player.rs b/core/anvil/src/player.rs index a6dedc76f..cf958a278 100644 --- a/core/anvil/src/player.rs +++ b/core/anvil/src/player.rs @@ -45,7 +45,7 @@ impl InventorySlot { /// Converts a network protocol index, item, and count /// to an `InventorySlot`. - pub fn from_network_index(network: usize, 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,14 +58,14 @@ 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. @@ -202,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/server/chunk/src/save.rs b/server/chunk/src/save.rs index 550fe1780..514133a7b 100644 --- a/server/chunk/src/save.rs +++ b/server/chunk/src/save.rs @@ -154,7 +154,7 @@ pub fn save_player_data(game: &Game, world: &World, player: Entity) { .get::(player) .enumerate() .filter_map(|(index, slot)| slot.map(move |slot| (index, slot))) - .map(|(index, slot)| { + .filter_map(|(index, slot)| { InventorySlot::from_network_index( Window::player(player).convert_slot(index, player).unwrap(), slot, @@ -162,6 +162,9 @@ pub fn save_player_data(game: &Game, world: &World, player: Entity) { }) .collect(); + dbg!(&inventory); + dbg!(&*world.get::(player)); + let data = PlayerData { entity: BaseEntityData::new(*world.get::(player), Vec3d::broadcast(0.0)), gamemode: world.get::(player).id() as i32, diff --git a/server/player/src/lib.rs b/server/player/src/lib.rs index b5ce9d014..a96b9afa3 100644 --- a/server/player/src/lib.rs +++ b/server/player/src/lib.rs @@ -71,7 +71,7 @@ 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, @@ -92,7 +92,7 @@ pub fn create(game: &mut Game, world: &mut World, info: NewClientInfo) -> Entity let window2 = window.clone(); let slots = info.data.inventory.iter().map(move |slot| { window2 - .convert_network(slot.slot as usize) + .convert_network(slot.convert_index().unwrap_or_default()) .map(SlotIndex::from) .unwrap_or(SlotIndex { area: Area::Hotbar, From e00b7cd5707e34df956e0ba3c5b1ade15c2f2e43 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Mon, 18 May 2020 11:49:39 -0600 Subject: [PATCH 5/5] Fix remaining issues with creative mode inventory interaction --- core/inventory/src/window.rs | 16 ++++++++++++++-- server/chunk/src/save.rs | 3 --- server/entity/src/inventory.rs | 2 +- server/player/src/packet_handlers/inventory.rs | 2 +- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/core/inventory/src/window.rs b/core/inventory/src/window.rs index 4cd83bce6..44432a1be 100644 --- a/core/inventory/src/window.rs +++ b/core/inventory/src/window.rs @@ -169,6 +169,20 @@ impl<'a> WindowAccessor<'a> { 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. @@ -183,8 +197,6 @@ impl<'a> WindowAccessor<'a> { self.with_inv(index, |inv, idx| inv.remove_item_at(idx.area, idx.slot)) } - /// Removes the item at the given index - fn with_inv( &self, index: usize, diff --git a/server/chunk/src/save.rs b/server/chunk/src/save.rs index 514133a7b..78179b3a4 100644 --- a/server/chunk/src/save.rs +++ b/server/chunk/src/save.rs @@ -162,9 +162,6 @@ pub fn save_player_data(game: &Game, world: &World, player: Entity) { }) .collect(); - dbg!(&inventory); - dbg!(&*world.get::(player)); - let data = PlayerData { entity: BaseEntityData::new(*world.get::(player), Vec3d::broadcast(0.0)), gamemode: world.get::(player).id() as i32, diff --git a/server/entity/src/inventory.rs b/server/entity/src/inventory.rs index 23e233fa2..bbcb705e6 100644 --- a/server/entity/src/inventory.rs +++ b/server/entity/src/inventory.rs @@ -54,7 +54,7 @@ impl Equipment { match self { Equipment::MainHand => slot(Hotbar, held_item), Equipment::OffHand => slot(Offhand, 0), - Equipment::Boots => slot(Legs, 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/packet_handlers/inventory.rs b/server/player/src/packet_handlers/inventory.rs index 483a5c554..4758e5a24 100644 --- a/server/player/src/packet_handlers/inventory.rs +++ b/server/player/src/packet_handlers/inventory.rs @@ -70,7 +70,7 @@ pub fn handle_creative_inventory_action( let slot = packet.clicked_item; - if let Err(e) = accessor.set_item_at(packet.slot as usize, slot.unwrap_or_default()) { + if let Err(e) = accessor.set_slot_at(packet.slot as usize, slot) { drop(inventory); drop(accessor); drop(window);