use super::*;
use crate::cooldown::{
CooldownEvent, CooldownKey, MAX_EVENTS, instant_use, key_of, use_cooldown_ticks,
};
use crate::version::ItemCooldownRules;
pub(crate) const USED: u8 = 1;
pub(crate) const USED_ON: u8 = 4;
fn event(c: &mut Core, e: CooldownEvent) {
let m = c.pending.more();
if m.cooldowns.len() < MAX_EVENTS {
m.cooldowns.push(e);
}
}
pub(super) fn server_cooldown(c: &mut Core, key: CooldownKey, ticks: i32) {
if c.opts.caps.item_cooldowns == ItemCooldownRules::None {
return;
}
if ticks == 0 {
c.cooldowns.remove(&key);
event(c, CooldownEvent::Removed { key });
} else {
c.cooldowns.add(key.clone(), ticks);
event(
c,
CooldownEvent::Started {
key,
ticks,
from_server: true,
},
);
}
}
fn client_cooldown(c: &mut Core, key: CooldownKey, ticks: i32) {
c.cooldowns.add(key.clone(), ticks);
event(
c,
CooldownEvent::Started {
key,
ticks,
from_server: false,
},
);
}
fn hand(c: &Core, off_hand: bool) -> Option<&ghast_inventory::Stack> {
if off_hand {
c.inv.offhand()
} else {
c.inv.held()
}
}
#[cold]
#[inline(never)]
pub(super) fn cooling_hands(c: &Core) -> [bool; 2] {
let rules = c.opts.caps.item_cooldowns;
let v = c.inv.version();
[false, true].map(|off| {
hand(c, off)
.and_then(|s| key_of(rules, v, s))
.is_some_and(|k| c.cooldowns.is_cooling(&k))
})
}
fn ender_pearl(data: crate::version::DataSet) -> Option<i32> {
match data {
crate::version::DataSet::V1_12 => Some(368),
#[cfg(feature = "v1_16_5")]
crate::version::DataSet::V1_16_5 => {
ghast_data::v1_16_5::Item::from_name("ender_pearl").map(|i| i32::from(i.id()))
}
_ => None,
}
}
#[cold]
#[inline(never)]
pub(super) fn use_cooldowns(c: &mut Core, used: u8) {
let rules = c.opts.caps.item_cooldowns;
let v = c.inv.version();
for off in [false, true] {
let shift = u8::from(off);
let (instant, on_block) = (used & (USED << shift) != 0, used & (USED_ON << shift) != 0);
if !instant && !on_block {
continue;
}
let Some(s) = hand(c, off) else { continue };
match rules {
ItemCooldownRules::PerItem => {
if instant && ender_pearl(c.opts.caps.data) == Some(s.id()) {
client_cooldown(c, CooldownKey::Item(s.id()), 20);
}
}
ItemCooldownRules::Groups => {
let Some(ticks) = use_cooldown_ticks(v, s) else {
continue;
};
let instant = instant && instant_use(v, s);
if (instant || on_block)
&& let Some(k) = key_of(rules, v, s)
{
client_cooldown(c, k, ticks);
}
}
_ => {}
}
}
}
pub(super) fn finish_cooldown(c: &mut Core) {
let Some((off, item)) = c.hands.use_item() else {
return;
};
let v = c.inv.version();
let Some(s) = hand(c, off).filter(|s| u16::try_from(s.id()) == Ok(item)) else {
return;
};
let Some(ticks) = use_cooldown_ticks(v, s) else {
return;
};
if let Some(k) = key_of(c.opts.caps.item_cooldowns, v, s) {
client_cooldown(c, k, ticks);
}
}
pub(super) fn tick_cooldowns(c: &mut Core) {
let (cooldowns, pending) = (&mut c.cooldowns, &mut c.pending);
cooldowns.tick(|key| {
let m = pending.more();
if m.cooldowns.len() < MAX_EVENTS {
m.cooldowns.push(CooldownEvent::Ended { key: key.clone() });
}
});
}