use ghast_inventory::Stack;
use crate::version::ItemCooldownRules;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CooldownKey {
Item(i32),
Group(String),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ItemCooldown {
pub key: CooldownKey,
pub ticks_left: i32,
pub duration: i32,
pub fraction: f32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CooldownEvent {
Started {
key: CooldownKey,
ticks: i32,
from_server: bool,
},
Removed {
key: CooldownKey,
},
Ended {
key: CooldownKey,
},
}
#[derive(Debug, Clone, PartialEq)]
struct Entry {
key: CooldownKey,
start: i32,
end: i32,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ItemCooldowns {
tick: i32,
entries: Vec<Entry>,
}
impl ItemCooldowns {
#[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)
}
#[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 {
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)
}
#[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),
}
}
#[must_use]
pub fn get(&self, key: &CooldownKey) -> Option<ItemCooldown> {
self.entry(key).map(|e| self.view(e))
}
pub fn iter(&self) -> impl Iterator<Item = ItemCooldown> + '_ {
self.entries.iter().map(|e| self.view(e))
}
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 });
}
}
pub(crate) fn remove(&mut self, key: &CooldownKey) {
self.entries.retain(|e| e.key != *key);
}
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
});
}
pub(crate) fn clear(&mut self) {
self.entries.clear();
}
}
pub(crate) const MAX_EVENTS: usize = 64;
#[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}")
}
}
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,
}
}
#[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}"))),
}
}
#[cfg(not(ghast_modern))]
fn group_key(_: ghast_inventory::Version, _: &Stack) -> Option<CooldownKey> {
None
}
#[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
}
#[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
}
#[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);
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());
c.add(k.clone(), 3);
tick(&mut c);
assert_eq!(c.fraction(&k, 0.0), 2.0f32 / 3.0);
c.add(CooldownKey::Item(1), 0);
assert!(!c.is_cooling(&CooldownKey::Item(1)));
assert!(c.get(&CooldownKey::Item(1)).is_some());
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");
}
}