ghast-client 0.5.6

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! Item cooldowns (1.9+): the client's `ItemCooldownManager` (1.12.2, 1.16.5; 26.x
//! `ItemCooldowns`). While an item cools down a right click with it does nothing on the client
//! after its packet (`interactItem` / `useItem` answer PASS, `interactBlock` / `useItemOn` skip
//! the item's use on the block), so holding the use key with ender pearls throws one every 20
//! ticks, not every 4.
//!
//! What starts one:
//! - the server's `set_cooldown` packet (any item on 1.12.2 / 1.16.5, any cooldown group on 26.x;
//!   a duration of 0 removes it): a shield disabled by an axe, chorus fruit, ender pearls, …;
//! - the client itself: 1.12.2 / 1.16.5 an ender pearl's use (20 ticks); 26.x an item with a
//!   `use_cooldown` component (ender pearls and chorus fruit 1 s, wind charges 0.5 s by default,
//!   any item a server gives one) after an instant use that succeeded (`ItemStack.use`), a use on
//!   a block that succeeded (`useOn`) or a finished use (`finishUsingItem`, the server's entity
//!   status 9).
//!
//! A cooldown counts in the player's tick (after the key handling) and ends when its last tick
//! is reached. A new player entity (join, respawn, dimension change) has none. 1.8.9 has no item
//! cooldowns (the manager came with 1.9): every query answers none there.
//!
//! Read them with [`crate::TickContext::item_cooldown`], [`crate::TickContext::held_cooldown`]
//! and [`crate::TickContext::item_cooldowns`]; [`crate::TickEvents::cooldowns`] lists the
//! starts and ends.

use ghast_inventory::Stack;

use crate::version::ItemCooldownRules;

/// What a cooldown is kept under.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CooldownKey {
    /// 1.12.2, 1.16.5: an item, by its raw item id (the manager keys by item: every stack of
    /// it, whatever its damage or tag).
    Item(i32),
    /// 26.x: a cooldown group, `"namespace:path"`: a stack's `use_cooldown` group, else the
    /// item's registry name (`"minecraft:ender_pearl"`).
    Group(String),
}

/// A cooldown as vanilla reads it.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ItemCooldown {
    /// Its item or group.
    pub key: CooldownKey,
    /// Player ticks until it ends (the end tick minus now).
    pub ticks_left: i32,
    /// Its whole length in ticks (end minus start).
    pub duration: i32,
    /// `getCooldownPercent(stack, 0)`: what is left of it, 1 … 0 (`ticks_left / duration`
    /// clamped, in `f32` like vanilla). An item is cooling down while this is above 0.
    pub fraction: f32,
}

/// A cooldown's start or end ([`crate::TickEvents::cooldowns`]).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CooldownEvent {
    /// A cooldown of `ticks` started (or restarted: it replaces the one before).
    Started {
        /// Its item or group.
        key: CooldownKey,
        /// Its length in ticks.
        ticks: i32,
        /// Set by the server's `set_cooldown` (else by the client's own item use).
        from_server: bool,
    },
    /// The server removed it (`set_cooldown` with 0 ticks).
    Removed {
        /// Its item or group.
        key: CooldownKey,
    },
    /// It ran out.
    Ended {
        /// Its item or group.
        key: CooldownKey,
    },
}

#[derive(Debug, Clone, PartialEq)]
struct Entry {
    key: CooldownKey,
    start: i32,
    end: i32,
}

/// The player's item cooldowns (`ItemCooldownManager` / `ItemCooldowns`): a tick counter and
/// per item or group the start and end tick.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ItemCooldowns {
    tick: i32,
    entries: Vec<Entry>,
}

impl ItemCooldowns {
    /// No item cools down.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    fn entry(&self, key: &CooldownKey) -> Option<&Entry> {
        self.entries.iter().find(|e| e.key == *key)
    }

    /// `getCooldownPercent` / `getCooldownProgress(item, partial)` of `key`: what is left,
    /// 1 … 0 (0 without a cooldown).
    #[must_use]
    pub fn fraction(&self, key: &CooldownKey, partial: f32) -> f32 {
        self.entry(key)
            .map_or(0.0, |e| self.fraction_of(e, partial))
    }

    fn fraction_of(&self, e: &Entry, partial: f32) -> f32 {
        // (float) (end - start), end - (tick + partial), then MathHelper.clamp (NaN stays NaN,
        // as with `f32::clamp`)
        let whole = (e.end.wrapping_sub(e.start)) as f32;
        let left = e.end as f32 - (self.tick as f32 + partial);
        (left / whole).clamp(0.0, 1.0)
    }

    /// `isCoolingDown` / `isOnCooldown`: `key` cools down now.
    #[must_use]
    pub fn is_cooling(&self, key: &CooldownKey) -> bool {
        self.fraction(key, 0.0) > 0.0
    }

    fn view(&self, e: &Entry) -> ItemCooldown {
        ItemCooldown {
            key: e.key.clone(),
            ticks_left: e.end.wrapping_sub(self.tick),
            duration: e.end.wrapping_sub(e.start),
            fraction: self.fraction_of(e, 0.0),
        }
    }

    /// The cooldown of `key`, if one is kept (it may have run out of fraction already when the
    /// server gave it no length: it is dropped at the next player tick, like vanilla).
    #[must_use]
    pub fn get(&self, key: &CooldownKey) -> Option<ItemCooldown> {
        self.entry(key).map(|e| self.view(e))
    }

    /// Every cooldown kept.
    pub fn iter(&self) -> impl Iterator<Item = ItemCooldown> + '_ {
        self.entries.iter().map(|e| self.view(e))
    }

    /// `set` / `addCooldown`: `key` cools down for `ticks` from now (replacing its cooldown).
    pub(crate) fn add(&mut self, key: CooldownKey, ticks: i32) {
        let (start, end) = (self.tick, self.tick.wrapping_add(ticks));
        if let Some(e) = self.entries.iter_mut().find(|e| e.key == key) {
            e.start = start;
            e.end = end;
        } else {
            self.entries.push(Entry { key, start, end });
        }
    }

    /// `remove` / `removeCooldown`.
    pub(crate) fn remove(&mut self, key: &CooldownKey) {
        self.entries.retain(|e| e.key != *key);
    }

    /// `update` / `tick` in the player's tick: the counter moves on and the cooldowns whose end
    /// is reached are dropped (each one an [`CooldownEvent::Ended`]). Only called with
    /// cooldowns kept (the counter is relative: an idle one need not move).
    pub(crate) fn tick(&mut self, mut ended: impl FnMut(&CooldownKey)) {
        self.tick = self.tick.wrapping_add(1);
        let now = self.tick;
        self.entries.retain(|e| {
            let keep = e.end > now;
            if !keep {
                ended(&e.key);
            }
            keep
        });
    }

    /// A new player entity: none.
    pub(crate) fn clear(&mut self) {
        self.entries.clear();
    }
}

/// Most cooldown events kept between two behaviour ticks.
pub(crate) const MAX_EVENTS: usize = 64;

/// `"path"` → `"minecraft:path"` (`Identifier` parsing); a full identifier as it is.
#[cfg_attr(not(ghast_modern), allow(dead_code))]
pub(crate) fn identifier(s: &str) -> String {
    if s.contains(':') {
        s.to_owned()
    } else {
        format!("minecraft:{s}")
    }
}

/// The key a stack cools down under (`None`: the version has no item cooldowns, or a 26.x
/// item outside the registry).
pub(crate) fn key_of(
    rules: ItemCooldownRules,
    inv: ghast_inventory::Version,
    s: &Stack,
) -> Option<CooldownKey> {
    match rules {
        ItemCooldownRules::PerItem => Some(CooldownKey::Item(s.id())),
        ItemCooldownRules::Groups => group_key(inv, s),
        _ => None,
    }
}

/// 26.x `getCooldownGroup`: the component's group, else the item's registry name.
#[cfg(ghast_modern)]
fn group_key(inv: ghast_inventory::Version, s: &Stack) -> Option<CooldownKey> {
    match ghast_inventory::modern::use_cooldown(inv, s).and_then(|c| c.group) {
        Some(g) => Some(CooldownKey::Group(identifier(&g))),
        None => ghast_inventory::modern::item_name(inv, s.id())
            .map(|n| CooldownKey::Group(format!("minecraft:{n}"))),
    }
}

/// No modern version in this build: no groups.
#[cfg(not(ghast_modern))]
fn group_key(_: ghast_inventory::Version, _: &Stack) -> Option<CooldownKey> {
    None
}

/// 26.x: the ticks of the stack's `use_cooldown` (`None` without one, or without a modern
/// version in this build).
#[cfg(ghast_modern)]
pub(crate) fn use_cooldown_ticks(inv: ghast_inventory::Version, s: &Stack) -> Option<i32> {
    ghast_inventory::modern::use_cooldown(inv, s).map(|c| c.ticks())
}

#[cfg(not(ghast_modern))]
pub(crate) fn use_cooldown_ticks(_: ghast_inventory::Version, _: &Stack) -> Option<i32> {
    None
}

/// 26.x `getUseDuration <= 0`: the stack's use is instant (its `use_cooldown` applies after a
/// successful `use`).
#[cfg(ghast_modern)]
pub(crate) fn instant_use(inv: ghast_inventory::Version, s: &Stack) -> bool {
    ghast_inventory::modern::item_use(inv, s).is_some_and(|u| u.duration == Some(0))
}

#[cfg(not(ghast_modern))]
pub(crate) fn instant_use(_: ghast_inventory::Version, _: &Stack) -> bool {
    false
}

/// 26.x registry name of item `id` (`None` on the legacy versions or without a modern version
/// in this build).
#[cfg(ghast_modern)]
pub(crate) fn modern_item_name(inv: ghast_inventory::Version, id: i32) -> Option<&'static str> {
    ghast_inventory::modern::item_name(inv, id)
}

#[cfg(not(ghast_modern))]
pub(crate) fn modern_item_name(_: ghast_inventory::Version, _: i32) -> Option<&'static str> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn counts_like_vanilla() {
        let mut c = ItemCooldowns::default();
        let k = CooldownKey::Item(368);
        let mut ev = Vec::new();
        let mut tick = |c: &mut ItemCooldowns| c.tick(|k| ev.push(k.clone()));
        c.add(k.clone(), 20);
        // set in the key handling of tick N: cooling at N+1 … N+19, free at N+20
        for n in 1..20 {
            tick(&mut c);
            assert!(c.is_cooling(&k), "{n}");
            assert_eq!(c.get(&k).unwrap().ticks_left, 20 - n);
        }
        tick(&mut c);
        assert!(!c.is_cooling(&k));
        assert!(c.is_empty());
        // a fraction in f32 like getCooldownPercent(stack, 0)
        c.add(k.clone(), 3);
        tick(&mut c);
        assert_eq!(c.fraction(&k, 0.0), 2.0f32 / 3.0);
        // no length: kept until the next tick, not cooling (0 / 0)
        c.add(CooldownKey::Item(1), 0);
        assert!(!c.is_cooling(&CooldownKey::Item(1)));
        assert!(c.get(&CooldownKey::Item(1)).is_some());
        // a negative length cools until the next tick (-n / -n = 1)
        c.add(CooldownKey::Item(2), -5);
        assert!(c.is_cooling(&CooldownKey::Item(2)));
        tick(&mut c);
        assert!(c.get(&CooldownKey::Item(1)).is_none());
        assert!(c.get(&CooldownKey::Item(2)).is_none());
        c.remove(&k);
        assert!(c.is_empty());
        assert_eq!(ev, vec![k, CooldownKey::Item(1), CooldownKey::Item(2)]);
    }

    #[test]
    fn identifiers() {
        assert_eq!(identifier("ender_pearl"), "minecraft:ender_pearl");
        assert_eq!(identifier("test:throw"), "test:throw");
    }
}