use super::*;
pub(super) fn held_item<W: Sim + ?Sized>(
inv: &ghast_inventory::Inventory,
sim: &W,
) -> Option<hands::HeldItem> {
let s = inv.held()?;
let id = u16::try_from(s.id()).ok()?;
let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
Some(sim.item_use_facts(s, false, sim.held_item(id, count, efficiency(s))))
}
#[inline(never)]
pub(super) fn use_equips(
c: &Core,
creative: bool,
held: &mut Option<hands::HeldItem>,
off_held: &mut Option<hands::HeldItem>,
) {
let swings = c.opts.caps.use_equip_swings;
let modern = c.opts.caps.item_cooldowns == crate::version::ItemCooldownRules::Groups;
for (h, off) in [(held, false), (off_held, true)] {
if let Some(h) = h.as_mut() {
h.equips = c.inv.use_equips(off, creative);
h.equip_swings = swings;
if modern
&& let Some(s) = if off { c.inv.offhand() } else { c.inv.held() }
&& thrown_modern(c.inv.version(), s)
{
h.swing_on_use = true;
}
}
}
}
#[cold]
#[inline(never)]
pub(super) fn equip_from_hand(
inv: &mut ghast_inventory::Inventory,
off_hand: bool,
creative: bool,
) {
inv.equip_from_hand(off_hand, creative);
}
#[cold]
#[inline(never)]
pub(super) fn take_use_events(c: &mut Core) {
c.current.more().item_use.append(&mut c.hands.use_events);
}
pub(super) fn off_held_item<W: Sim + ?Sized>(
inv: &ghast_inventory::Inventory,
sim: &W,
) -> Option<hands::HeldItem> {
let s = inv.offhand()?;
let id = u16::try_from(s.id()).ok()?;
let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
Some(sim.item_use_facts(s, true, sim.held_item(id, count, 0)))
}
#[cold]
#[inline(never)]
pub(super) fn air_used(c: &mut Core, sim: &mut (impl Sim + ?Sized)) {
let used = std::mem::take(&mut c.hands.air_used);
let mut shift = 0;
for (off_hand, k, a) in used {
shift += air_used_one(c, sim, off_hand, k as usize + shift, a);
}
}
#[inline]
pub(super) fn attack_swing(caps: &crate::version::Capabilities) -> Outbound {
if caps.sends_punch {
Outbound::Punch
} else {
Outbound::Swing
}
}
fn air_used_one(
c: &mut Core,
sim: &mut (impl Sim + ?Sized),
off_hand: bool,
k: usize,
a: crate::sim::predict::AirUse,
) -> usize {
use crate::sim::predict::HandChange;
if let Some(blocks) = a.blocks.as_deref()
&& !blocks.is_empty()
{
sim.air_use_sent(blocks);
}
match a.hand {
HandChange::Keep => {}
HandChange::UseOne => {
if off_hand {
c.inv.consume_offhand(1);
} else {
c.inv.consume_held(1);
}
}
HandChange::Empty => c.inv.set_hand(off_hand, None),
HandChange::Replace(s) => c.inv.set_hand(off_hand, Some(s)),
HandChange::Exchange {
output,
creative_keeps,
} => {
let creative = c.abilities.creative_mode();
if c.inv
.exchange_hand(off_hand, output, creative, creative_keeps)
{
if !c.opts.caps.sends_swing {
return 0;
}
let at = (k + 1).min(c.out.len());
c.out.insert(at, Outbound::Swing);
return 1;
}
}
HandChange::ExchangeLegacy { output } => {
let _ = c.inv.exchange_hand(off_hand, output, false, false);
}
}
0
}
#[cold]
#[inline(never)]
pub(super) fn attack_effects(c: &mut Core, sim: &mut (impl Sim + ?Sized)) {
let knockback = attack_knockback(c);
let attacks = std::mem::take(&mut c.hands.attacks);
for &(id, ticks) in &attacks {
if !attack_hurts(sim, id) {
continue;
}
let sprint_bonus = sprint_bonus(c, ticks);
sim.attack_slow(id, c.pose.yaw, knockback, sprint_bonus);
let living = sim
.entities()
.and_then(|t| t.get(id))
.is_some_and(ghast_entity::Entity::is_player);
if living && c.game_mode != GameMode::Creative {
hit_durability(c, id);
}
}
c.hands.attacks = attacks;
c.hands.attacks.clear();
}
pub(super) fn attack_knockback(c: &Core) -> i32 {
if c.opts.caps.attack_knockback_enchantment {
c.inv.held().map_or(0, |s| i32::from(knockback(s)))
} else {
0
}
}
pub(super) fn attack_hurts(sim: &(impl Sim + ?Sized), id: i32) -> bool {
sim.entities()
.and_then(|t| t.get(id))
.is_some_and(|e| sim.attack_hurts(e))
}
pub(super) fn sprint_bonus(c: &Core, ticks: u32) -> bool {
!c.opts.caps.combat_1_9 || hands::attack_strength_at(ticks, c.attack_speed) > 0.9
}
#[cold]
#[inline(never)]
fn hit_durability(c: &mut Core, target: i32) {
use ghast_inventory::ItemKind as K;
let v = c.inv.version();
let Some(s) = c.inv.held() else {
return;
};
if !matches!(
v,
ghast_inventory::Version::V1_8 | ghast_inventory::Version::V1_12
) || enchant_level(s, 34, "minecraft:unbreaking") > 0
{
return;
}
let points = match s.kind(v) {
K::Sword => 1,
K::Axe | K::Pickaxe | K::Shovel => 2,
K::Hoe if v == ghast_inventory::Version::V1_12 => 1,
_ => return,
};
if !c.inv.damage_held(points) {
return;
}
let held = c.inv.held().cloned();
let at = c.out.iter().position(|o| {
matches!(o, Outbound::UseEntity { target: t, action: crate::common::EntityUse::Attack, .. } if *t == target)
});
if let Some(at) = at {
for o in &mut c.out[at + 1..] {
match o {
Outbound::UseItem {
held: h,
off_hand: false,
}
| Outbound::Place {
held: h,
off_hand: false,
..
}
| Outbound::PlaceInside {
held: h,
off_hand: false,
..
} => h.clone_from(&held),
_ => {}
}
}
}
}
#[cold]
#[inline(never)]
pub(super) fn finish_food(c: &mut Core) {
if let Some((false, item)) = c.hands.use_item()
&& let Some(p) = crate::sim::food_points(c.opts.caps.data, item)
{
c.health.food = (c.health.food + i32::from(p)).min(20);
}
}
pub(super) fn finish_consumes(c: &mut Core) {
let Some((off_hand, item)) = c.hands.use_item() else {
return;
};
let stack = if off_hand {
c.inv.offhand()
} else {
c.inv.held()
};
if c.game_mode == GameMode::Creative
|| !stack.is_some_and(|s| u16::try_from(s.id()) == Ok(item))
{
return;
}
if let Some(container) = finish_container(c.opts.caps.data, item) {
c.inv.finish_into(off_hand, container);
} else if crate::sim::food_points(c.opts.caps.data, item).is_some() {
if off_hand {
c.inv.consume_offhand(1);
} else {
c.inv.consume_held(1);
}
}
}
#[cold]
#[inline(never)]
pub(super) fn click_stack_effects(c: &mut Core, first: usize, entity: Option<hands::EntityHit>) {
predict_use_effects(c, first);
let Some(e) = entity else { return };
let mut clicked = [false; 2];
for o in &c.out[first..] {
if let Outbound::UseEntity {
target,
action: crate::common::EntityUse::Interact,
off_hand,
..
} = o
&& *target == e.id
{
clicked[usize::from(*off_hand)] = true;
}
}
for (k, off_hand) in [(0, false), (1, true)] {
let fx = e.interact[k].1;
if clicked[k] && fx != hands::InteractEffect::None {
interact_effect(c, off_hand, fx);
}
}
}
pub(super) fn predict_use_effects(c: &mut Core, first: usize) {
let cooled = std::mem::take(&mut c.hands.cooled);
if c.game_mode == GameMode::Creative {
return;
}
let data = c.opts.caps.data;
let inv = c.inv.version();
for k in first..c.out.len() {
let Outbound::UseItem {
held: Some(s),
off_hand,
} = &c.out[k]
else {
continue;
};
if (thrown(data, s) || thrown_modern(inv, s)) && cooled & (1 << u8::from(*off_hand)) == 0 {
let off = *off_hand;
if off {
c.inv.consume_offhand(1);
} else {
c.inv.consume_held(1);
}
}
}
if let Some((false, item, ticks)) = c.hands.released_use()
&& ticks >= 3
&& bow_damaged_on_client(data, item)
{
c.inv.damage_held(1);
}
}
#[cold]
#[inline(never)]
pub(super) fn entity_click(
c: &Core,
ents: &ghast_entity::Entities,
id: i32,
) -> [(hands::Interact, hands::InteractEffect); 2] {
let item = |s: Option<&ghast_inventory::Stack>| {
s.and_then(|s| Some((u16::try_from(s.id()).ok()?, s.damage())))
};
let inv_v = c.opts.inventory;
let named =
|s: Option<&ghast_inventory::Stack>| s.is_some_and(|s| s.custom_name(inv_v).is_some());
crate::interact::outcome(
ents,
c.opts.caps.protocol,
id,
&c.opts.name,
c.game_mode == GameMode::Spectator,
c.pose.sneaking,
c.game_mode == GameMode::Creative,
[item(c.inv.held()), item(c.inv.offhand())],
[named(c.inv.held()), named(c.inv.offhand())],
)
}
#[cold]
#[inline(never)]
pub(super) fn interact_effect(c: &mut Core, off_hand: bool, fx: hands::InteractEffect) {
use hands::InteractEffect as Fx;
match fx {
Fx::None => {}
Fx::Take if off_hand => {
c.inv.consume_offhand(1);
}
Fx::Take => {
c.inv.consume_held(1);
}
Fx::Damage if !off_hand => {
c.inv.damage_held(1);
}
Fx::Damage => {}
Fx::IntoMilk => {
if let Some(milk) = milk_bucket(c.opts.caps.data) {
c.inv.finish_into(off_hand, milk);
}
}
Fx::Into(item) => {
c.inv.finish_into(off_hand, i32::from(item));
}
}
}
pub(super) fn milk_bucket(data: crate::version::DataSet) -> Option<i32> {
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
use crate::version::DataSet;
match data {
#[cfg(feature = "v1_8")]
DataSet::V1_8 => Some(335),
#[cfg(feature = "v1_12_2")]
DataSet::V1_12 => Some(335),
#[cfg(feature = "v1_16_5")]
DataSet::V1_16_5 => {
ghast_data::v1_16_5::Item::from_name("milk_bucket").map(|i| i32::from(i.id()))
}
#[allow(unreachable_patterns)]
_ => None,
}
}
pub(super) fn thrown(data: crate::version::DataSet, s: &ghast_inventory::Stack) -> bool {
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
use crate::version::DataSet;
let Ok(id) = u16::try_from(s.id()) else {
return false;
};
match data {
#[cfg(feature = "v1_8")]
DataSet::V1_8 => {
matches!(id, 332 | 344 | 368 | 384) || (id == 373 && s.damage() & 0x4000 != 0)
}
#[cfg(feature = "v1_12_2")]
DataSet::V1_12 => matches!(id, 332 | 344 | 384 | 438 | 441),
#[cfg(feature = "v1_16_5")]
DataSet::V1_16_5 => ghast_data::v1_16_5::Item::from_id(id).is_some_and(|i| {
matches!(
i.info().name,
"snowball" | "egg" | "experience_bottle" | "splash_potion" | "lingering_potion"
)
}),
#[allow(unreachable_patterns)]
_ => {
let _ = id;
false
}
}
}
pub(super) fn thrown_modern(inv: ghast_inventory::Version, s: &ghast_inventory::Stack) -> bool {
matches!(
crate::cooldown::modern_item_name(inv, s.id()),
Some(
"snowball"
| "egg"
| "blue_egg"
| "brown_egg"
| "ender_pearl"
| "experience_bottle"
| "splash_potion"
| "lingering_potion"
| "wind_charge"
)
)
}
pub(super) fn bow_damaged_on_client(data: crate::version::DataSet, item: u16) -> bool {
#[cfg(feature = "v1_8")]
use crate::version::DataSet;
match data {
#[cfg(feature = "v1_8")]
DataSet::V1_8 => item == 261,
#[allow(unreachable_patterns)]
_ => {
let _ = item;
false
}
}
}
pub(super) fn finish_container(data: crate::version::DataSet, item: u16) -> Option<i32> {
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
use crate::version::DataSet;
match data {
#[cfg(feature = "v1_8")]
DataSet::V1_8 => match item {
373 => Some(374),
335 => Some(325),
282 => Some(281),
_ => None,
},
#[cfg(feature = "v1_12_2")]
DataSet::V1_12 => match item {
373 => Some(374),
335 => Some(325),
282 | 413 | 436 => Some(281),
_ => None,
},
#[cfg(feature = "v1_16_5")]
DataSet::V1_16_5 => {
use ghast_data::v1_16_5::Item;
let to = match Item::from_id(item)?.info().name {
"potion" | "honey_bottle" => "glass_bottle",
"milk_bucket" => "bucket",
"mushroom_stew" | "rabbit_stew" | "beetroot_soup" | "suspicious_stew" => "bowl",
_ => return None,
};
Item::from_name(to).map(|i| i32::from(i.id()))
}
#[allow(unreachable_patterns)]
_ => {
let _ = item;
None
}
}
}
#[inline]
pub(super) fn cooldown_held_check(c: &mut Core) {
let now = c.inv.held().map_or((-1, 0), |s| (s.id(), s.damage()));
if now != c.cooldown_held {
cooldown_held_changed(c, now);
}
}
#[cold]
#[inline(never)]
fn cooldown_held_changed(c: &mut Core, now: (i32, i16)) {
let old = c.cooldown_held;
c.cooldown_held = now;
let same = old.0 == now.0
&& (c.opts.caps.cooldown_reset == crate::version::CooldownReset::Item
|| old.1 == now.1
|| c.inv
.held()
.is_some_and(|s| s.is_damageable(c.inv.version())));
if !same {
c.hands.cooldown_reset_pending = true;
}
}
#[cold]
#[inline(never)]
pub(super) fn living_flags_use(c: &mut Core, flags: u8) {
let active = flags & 1 != 0;
if active && !c.hands.using_item() {
let off_hand = flags & 2 != 0;
let stack = if off_hand {
c.inv.offhand()
} else {
c.inv.held()
};
if let Some(id) = stack.and_then(|s| u16::try_from(s.id()).ok()) {
c.hands.server_start_using(off_hand, id);
}
} else if !active && c.hands.using_item() {
c.hands.stop_using();
}
}
#[inline]
pub(super) fn use_food_level(c: &Core) -> i32 {
use_food_level_of(&c.abilities, c.opts.caps.invulnerable_eating, c.health.food)
}
pub(super) fn dig_factors(c: &Core, in_water: bool) -> DigFactors {
DigFactors {
on_ground: c.pose.on_ground,
in_water,
aqua_affinity: c.aqua_affinity,
haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
}
}
#[inline]
pub(super) fn use_food_level_of(
abilities: &crate::common::Abilities,
eating: crate::version::InvulnerableEating,
food: i32,
) -> i32 {
if abilities.invulnerable() {
match eating {
crate::version::InvulnerableEating::Never => return -1,
crate::version::InvulnerableEating::Always => return 0,
crate::version::InvulnerableEating::Hunger => {}
}
}
food
}
#[inline(never)]
pub(super) fn held_use_check(c: &mut Core) {
let off_hand = c.hands.use_item().is_some_and(|(off, _)| off);
let stack = if off_hand {
c.inv.offhand()
} else {
c.inv.held()
};
let now = if c.opts.caps.use_stop == crate::version::UseStop::HeldItemChanged {
let id = stack.map_or(0, |s| u16::try_from(s.id()).unwrap_or(u16::MAX));
(c.hands.use_serial, 0, id)
} else if off_hand {
(c.hands.use_serial, 255, c.inv.offhand_writes())
} else {
(c.hands.use_serial, c.held_slot, c.inv.held_writes())
};
match c.use_mark {
Some(m) if m.0 != now.0 => c.use_mark = Some(now),
None => c.use_mark = Some(now),
Some(m) if m != now => {
c.hands.stop_using();
c.use_mark = None;
}
Some(_) => {}
}
}
pub(super) fn movement_speed(
c: &Core,
sim: &mut (impl Sim + ?Sized),
base: f64,
modifiers: &[(uuid::Uuid, f64, i8)],
) {
log::debug!(
"[{}] t{} movement speed base {base:?} modifiers {modifiers:?}",
c.opts.name,
c.tick
);
let mods: Vec<(u128, f64, u8)> = modifiers
.iter()
.map(|&(id, amount, op)| (id.as_u128(), amount, op as u8))
.collect();
sim.movement_speed(base, &mods);
}
pub(super) fn modern_attribute_value(a: &crate::common::AttributeUpdate) -> f64 {
let ops = |op: i8| a.modifiers.iter().filter(move |m| m.2 == op).map(|m| m.1);
let d = a.base + ops(0).sum::<f64>();
let mut e = d;
for v in ops(1) {
e += d * v;
}
for v in ops(2) {
e *= 1.0 + v;
}
e.clamp(0.0, 1024.0)
}
pub(super) fn knockback(s: &ghast_inventory::Stack) -> u8 {
enchant_level(s, 19, "minecraft:knockback")
}
pub(super) fn efficiency(s: &ghast_inventory::Stack) -> u8 {
enchant_level(s, 32, "minecraft:efficiency")
}
pub(super) fn enchant_level(s: &ghast_inventory::Stack, id_1_8: i32, name: &str) -> u8 {
use ghast_protocol::nbt::Tag;
let Some(root) = s.nbt().and_then(|n| n.parse().ok().flatten()) else {
return 0;
};
let Some(c) = root.tag.as_compound() else {
return 0;
};
let num = |t: Option<&Tag>| match t {
Some(Tag::Short(v)) => i32::from(*v),
Some(Tag::Int(v)) => *v,
Some(Tag::Byte(v)) => i32::from(*v),
_ => -1,
};
for key in ["ench", "Enchantments"] {
if let Some(Tag::List(l)) = c.get(key) {
for e in l.items.iter().filter_map(Tag::as_compound) {
let hit = match e.get("id") {
Some(Tag::String(n)) => n == name,
other => num(other) == id_1_8,
};
if hit {
return u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
}
}
}
}
0
}