ghast-inventory 0.5.5

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! Client-side changes to the held stacks without a click: consuming, damaging, finishing into
//! a container, exchanging, equipping, dropping and selecting the hotbar slot.

use super::*;

impl Inventory {
    /// Client-side use of the held stack (no packet): `n` items off the selected hotbar stack,
    /// the slot emptied when nothing is left. Vanilla does this when a right click places a block
    /// or plants seeds (1.8 `BlockItem` / `SeedItem.use`, 1.16.5 `BlockItem.place`) or
    /// when eating finishes, before the server's `set_slot`; call it then (not in creative,
    /// where vanilla keeps the count). Returns whether there was a stack.
    pub fn consume_held(&mut self, n: u8) -> bool {
        self.consume(usize::from(self.m.selected.min(8)), n)
    }

    /// Client-side durability loss of the held stack (no packet; 1.8 / 1.12 `ItemStack.damage`
    /// without Unbreaking, which rolls a random number): the damage goes up by `amount`; past
    /// the durability the stack breaks (one item less, damage 0). Vanilla does this when a hit
    /// lands on a living entity (a sword 1, a tool 2), before the server's `set_slot`. Returns
    /// whether the stack took the damage (1.16.5 / 26.x keep the damage in NBT / components:
    /// `false`, nothing changes).
    pub fn damage_held(&mut self, amount: u16) -> bool {
        if !matches!(self.version, Version::V1_8 | Version::V1_12) {
            return false;
        }
        let v = self.version;
        let k = usize::from(self.m.selected.min(8));
        let slot = &mut self.m.player[k];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        let Some(max) = s.max_damage(v).filter(|&m| m > 0) else {
            return false;
        };
        if !s.is_damageable(v) {
            return false;
        }
        let d = i32::from(s.damage) + i32::from(amount);
        if d > max {
            s.count -= 1;
            s.damage = 0;
            if s.count <= 0 {
                *slot = None;
            }
        } else {
            s.damage = d as i16;
        }
        self.events.player_changed = true;
        true
    }

    /// [`consume_held`](Inventory::consume_held) for the offhand stack (1.12 / 1.16.5; no-op on
    /// 1.8).
    pub fn consume_offhand(&mut self, n: u8) -> bool {
        self.version != Version::V1_8 && self.consume(40, n)
    }

    /// Client-side end of a drink or a stew (`onItemUseFinish`, no packet): the last item of
    /// the stack in the main hand (or the off hand, 1.12+) becomes `container` (a glass bottle,
    /// a bucket, a bowl; one of it); a stack of more loses one item. Returns whether there
    /// was a stack.
    pub fn finish_into(&mut self, off_hand: bool, container: i32) -> bool {
        if off_hand && self.version == Version::V1_8 {
            return false;
        }
        let k = if off_hand {
            40
        } else {
            usize::from(self.m.selected.min(8))
        };
        let slot = &mut self.m.player[k];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        if s.count > 1 {
            s.count -= 1;
        } else {
            *slot = Some(Stack::new(container, 1, 0));
        }
        self.events.player_changed = true;
        true
    }

    /// 1.16.5 `ItemUsage.exchangeStack` (Yarn `method_30270`) on the client, after an item use
    /// in the air of the main hand (or the off hand) turned one item into `output` (a bucket
    /// filled, a bottle filled, a map drawn; no packet): outside creative one item is used up;
    /// the last one becomes `output`, else `output` goes into the inventory
    /// (`PlayerInventory.insertStack`). In creative with `creative_keeps` the hand keeps its
    /// stack and `output` goes in only when no stack of its item is there yet; in creative what
    /// does not fit is gone. Returns whether `output` did not fit outside creative (vanilla drops
    /// it: the client swings its main hand).
    pub fn exchange_hand(
        &mut self,
        off_hand: bool,
        output: Stack,
        creative: bool,
        creative_keeps: bool,
    ) -> bool {
        let k = if off_hand {
            40
        } else {
            usize::from(self.m.selected.min(8))
        };
        self.events.player_changed = true;
        if creative && creative_keeps {
            let id = output.id;
            if !self.m.player.iter().flatten().any(|s| s.id == id) {
                let _ = self.insert_player(output);
            }
            return false;
        }
        if !creative {
            let _ = self.consume(k, 1);
        }
        if self.m.player[k].is_none() {
            self.m.player[k] = Some(output);
            return false;
        }
        self.insert_player(output) > 0 && !creative
    }

    /// Sets the main hand's (or the off hand's) stack on the client (no packet).
    pub fn set_hand(&mut self, off_hand: bool, stack: Option<Stack>) {
        let k = if off_hand {
            40
        } else {
            usize::from(self.m.selected.min(8))
        };
        self.m.player[k] = stack;
        self.events.player_changed = true;
    }

    /// `PlayerInventory.insertStack` into the player's own inventory; returns the count left.
    pub(super) fn insert_player(&mut self, s: Stack) -> i32 {
        let lay = Layout::new(self.version, Screen::Player);
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut self.m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        sim.insert_stack(s)
    }

    pub(super) fn consume(&mut self, k: usize, n: u8) -> bool {
        let slot = &mut self.m.player[k];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        s.count -= i32::from(n);
        if s.count <= 0 {
            *slot = None;
        }
        self.events.player_changed = true;
        true
    }

    /// What a right-click use of the stack in the main hand (or the off hand, 1.12+) does to
    /// the armor on the client (no packet; vanilla's item `use`): `true` when it equips the
    /// stack. 1.8 / 1.12.2 / 1.16.5 (`ArmorItem` / `ElytraItem`): only into an empty armor
    /// slot. 26.x (a swappable `equippable`): also swaps with the piece worn, unless that is
    /// the same item with the same components or carries the binding curse outside creative.
    /// `creative` is the game mode.
    #[must_use]
    pub fn use_equips(&self, off_hand: bool, creative: bool) -> bool {
        self.use_equip_plan(off_hand, creative).is_some()
    }

    /// The hand's player index and the armor index its use equips.
    pub(super) fn use_equip_plan(&self, off_hand: bool, creative: bool) -> Option<(usize, usize)> {
        let hand = if off_hand {
            if self.version == Version::V1_8 {
                return None;
            }
            40
        } else {
            usize::from(self.m.selected.min(8))
        };
        let s = self.m.player[hand].as_ref().filter(|s| s.count > 0)?;
        let a = self.version.use_equip_target(s)?;
        let worn_k = 39 - usize::from(a);
        match &self.m.player[worn_k] {
            None => Some((hand, worn_k)),
            Some(_)
                if !matches!(
                    self.version,
                    Version::V26_1 | Version::V26_2 | Version::V26_3
                ) =>
            {
                None
            }
            // Equippable.swapWithEquipmentSlot: FAIL for the same item or a cursed piece.
            Some(w) => (!w.same_item(s)
                && (creative || self.enchantment_level(w, "binding_curse") == 0))
                .then_some((hand, worn_k)),
        }
    }

    /// Applies the right-click equip of [`Inventory::use_equips`] like the vanilla client,
    /// before the server's slot updates: 1.8 – 1.16.5 the stack moves into the armor slot and
    /// the hand empties (creative too); 26.x a single item swaps with the worn piece (in
    /// creative a copy goes on and the hand keeps its stack when the slot was empty), a larger
    /// stack puts one on and keeps the rest (not predicted when a worn piece would have to go
    /// into the inventory). Returns whether the use equips (the server's answer then follows).
    pub fn equip_from_hand(&mut self, off_hand: bool, creative: bool) -> bool {
        let Some((hand, worn_k)) = self.use_equip_plan(off_hand, creative) else {
            return false;
        };
        let modern = matches!(
            self.version,
            Version::V26_1 | Version::V26_2 | Version::V26_3
        );
        let worn = self.m.player[worn_k].take();
        let held = self.m.player[hand].take().expect("planned with a stack");
        if !modern {
            self.m.player[worn_k] = Some(held);
        } else if held.count <= 1 {
            let to_hand = match (&worn, creative) {
                (None, true) => Some(held.clone()),
                _ => worn,
            };
            self.m.player[worn_k] = Some(held);
            self.m.player[hand] = to_hand;
        } else if worn.is_some() {
            // Inventory.add of the old piece: left to the server's updates.
            self.m.player[worn_k] = worn;
            self.m.player[hand] = Some(held);
            return true;
        } else {
            let mut one = held.clone();
            one.count = 1;
            self.m.player[worn_k] = Some(one);
            let mut rest = held;
            if !creative {
                rest.count -= 1;
            }
            self.m.player[hand] = Some(rest);
        }
        self.events.player_changed = true;
        true
    }

    /// Client-side drop of the held stack (no packet): one item off the selected hotbar stack,
    /// or all of it with `whole_stack`, the slot emptied when nothing is left. The 1.16.5 / 26.1
    /// drop key does this before the server's `set_slot` (`ClientPlayerEntity.dropSelectedItem`,
    /// `LocalPlayer.drop`: `removeStack(selected, whole ? count : 1)`); 1.8 / 1.12 do not.
    /// Returns whether there was a stack (vanilla then swings the arm).
    pub fn drop_held(&mut self, whole_stack: bool) -> bool {
        let slot = &mut self.m.player[usize::from(self.m.selected.min(8))];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        if s.count <= 0 {
            return false;
        }
        if whole_stack || s.count == 1 {
            *slot = None;
        } else {
            s.count -= 1;
        }
        self.events.player_changed = true;
        true
    }

    /// Selects a hotbar slot (the behaviour's `select_slot`; vanilla's insertStack prefers it).
    pub fn select(&mut self, slot: u8) {
        if slot < 9 {
            self.m.selected = slot;
            self.m.player.touch();
        }
    }
}