use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::common::{
Abilities, ChatMessage, ClientSettings, Controls, GameMode, Health, Inbound, MovePacket,
Outbound, Pose, Vec3,
};
use crate::hands::{self, BlockHit, Buttons, DigFactors, Hands, HandsIo};
use crate::interest::Interests;
use crate::rotation::Rotation;
use crate::sim::{Crosshair, PickQuery, Sim, WorldView};
use crate::version::{Capabilities, GameVersion};
const MAX_PENDING_CHAT: usize = 512;
pub trait Behavior {
fn name(&self) -> &str {
"behavior"
}
fn interests(&self) -> Interests {
Interests::NONE
}
fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
let _ = version;
std::borrow::Cow::Borrowed(&[])
}
fn start(&mut self, ctx: &mut TickContext<'_>) {
let _ = ctx;
}
fn tick(&mut self, ctx: &mut TickContext<'_>);
fn running(&self) -> bool {
true
}
fn after_tick(&mut self, view: &TickView<'_>) {
let _ = view;
}
fn stop(&mut self, reason: &str) {
let _ = reason;
}
fn configuration_dialog(
&mut self,
dialog: &crate::dialog::Dialog,
) -> Option<crate::dialog::DialogAnswer> {
let _ = dialog;
None
}
}
impl<B: Behavior + ?Sized> Behavior for Box<B> {
fn name(&self) -> &str {
(**self).name()
}
fn interests(&self) -> Interests {
(**self).interests()
}
fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
(**self).raw_packets(version)
}
fn start(&mut self, ctx: &mut TickContext<'_>) {
(**self).start(ctx);
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
(**self).tick(ctx);
}
fn running(&self) -> bool {
(**self).running()
}
fn after_tick(&mut self, view: &TickView<'_>) {
(**self).after_tick(view);
}
fn stop(&mut self, reason: &str) {
(**self).stop(reason);
}
fn configuration_dialog(
&mut self,
dialog: &crate::dialog::Dialog,
) -> Option<crate::dialog::DialogAnswer> {
(**self).configuration_dialog(dialog)
}
}
#[path = "engine_creative.rs"]
mod creative;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClickRefused {
Turning,
Inventory(ghast_inventory::ClickError),
Dead,
}
impl std::fmt::Display for ClickRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ClickRefused::Turning => f.write_str("the player is turning"),
ClickRefused::Inventory(e) => write!(f, "{e}"),
ClickRefused::Dead => f.write_str("the player is dead"),
}
}
}
impl std::error::Error for ClickRefused {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClickTicket {
pub window_id: i32,
pub action: i16,
}
impl ClickTicket {
#[must_use]
pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
r.window_id == self.window_id && r.action == self.action
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Idle;
impl Behavior for Idle {
fn name(&self) -> &str {
"idle"
}
fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RawInbound {
pub id: i32,
pub body: bytes::Bytes,
pub at: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TeleportEvent {
pub teleport: crate::common::Teleport,
pub sent_before: Pose,
pub pose_before: Pose,
pub after: Pose,
}
const MAX_PENDING_TELEPORTS: usize = 64;
const MAX_PENDING_RAW: usize = 4096;
const MAX_PENDING_ENTITY_EVENTS: usize = 4096;
const MAX_PENDING_DIALOGS: usize = 64;
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct TickEvents {
pub chat: Vec<ChatMessage>,
pub chat_dropped: usize,
pub teleported: bool,
pub teleports: Vec<TeleportEvent>,
pub joined: bool,
pub respawned: bool,
pub died: bool,
pub health_changed: bool,
pub game_mode_changed: bool,
pub inventory: ghast_inventory::Events,
pub block_updates: Vec<(ghast_protocol::BlockPos, u32)>,
pub block_updates_dropped: usize,
pub raw: Vec<RawInbound>,
pub raw_dropped: usize,
more: Box<MoreEvents>,
}
impl TickEvents {
fn clear(&mut self) {
self.chat.clear();
self.chat_dropped = 0;
self.teleported = false;
self.teleports.clear();
self.joined = false;
self.respawned = false;
self.died = false;
self.health_changed = false;
self.game_mode_changed = false;
if self.more.any {
*self.more = MoreEvents::default();
}
self.inventory = ghast_inventory::Events::default();
self.block_updates.clear();
self.block_updates_dropped = 0;
self.raw.clear();
self.raw_dropped = 0;
}
#[inline]
fn more(&mut self) -> &mut MoreEvents {
self.more.any = true;
&mut self.more
}
#[must_use]
pub fn effects(&self) -> &[crate::common::EffectEvent] {
&self.more.effects
}
#[must_use]
pub fn hurt(&self) -> &[crate::common::Hurt] {
&self.more.hurt
}
#[must_use]
pub fn deaths(&self) -> &[crate::common::Death] {
&self.more.deaths
}
#[must_use]
pub fn entities(&self) -> &[ghast_entity::Event] {
&self.more.entities
}
#[must_use]
pub fn entities_dropped(&self) -> usize {
self.more.entities_dropped
}
#[must_use]
pub fn item_use(&self) -> &[crate::common::UseEvent] {
&self.more.item_use
}
}
#[derive(Debug, Clone, Default, PartialEq)]
struct MoreEvents {
any: bool,
effects: Vec<crate::common::EffectEvent>,
hurt: Vec<crate::common::Hurt>,
deaths: Vec<crate::common::Death>,
entities: Vec<ghast_entity::Event>,
entities_dropped: usize,
item_use: Vec<crate::common::UseEvent>,
}
#[derive(Debug, Clone)]
pub(crate) struct CoreOptions {
pub name: Arc<str>,
pub caps: &'static Capabilities,
pub settings: ClientSettings,
pub brand: Option<String>,
pub sensitivity: f32,
pub silent_hold: Duration,
pub inventory: ghast_inventory::Version,
pub hold_turn_on_action: bool,
pub accept_required_packs: bool,
pub entity_push: bool,
pub turn_rate: (f64, f64),
pub gui_releases_keys: bool,
}
#[derive(Debug)]
pub(crate) struct Core {
opts: CoreOptions,
tick: u64,
entity_id: i32,
joined: bool,
teleported_once: bool,
ready: bool,
pose: Pose,
sent: Pose,
rotation: Rotation,
aimed: bool,
controls: Controls,
health: Health,
clocks: crate::common::Clocks,
day_clock: Option<i32>,
dead: bool,
abilities: Abilities,
game_mode: GameMode,
held_slot: u8,
sent_slot: u8,
slot_from_server: bool,
open_window: i32,
dimension: String,
respawn_screen: bool,
pending: TickEvents,
current: TickEvents,
out: Vec<Outbound>,
last_inbound: Option<Instant>,
silent: bool,
quit: Option<String>,
status: String,
hands: Hands,
buttons: Buttons,
inv: ghast_inventory::Inventory,
turned: bool,
effects: std::collections::BTreeMap<i8, i8>,
active_effects: Vec<crate::common::ActiveEffect>,
spawn_point: Option<crate::common::SpawnPoint>,
last_hurt: Option<u64>,
teams: Option<Box<crate::teams::Teams>>,
aqua_affinity: bool,
broken_now: Vec<ghast_protocol::BlockPos>,
pick: PickList,
want_flying: Option<bool>,
held_turns: u64,
swings: u64,
level_load_started: bool,
client_loaded: bool,
chat_session_due: bool,
gate_tick: bool,
#[cfg(test)]
test_gate: Option<(bool, bool)>,
load_wait: u32,
near_loaded: u8,
origin: Instant,
entity_push: bool,
entity_push_sim: bool,
dialog: Option<Arc<crate::dialog::Dialog>>,
screen_keys: Option<Controls>,
dialogs_pending: Vec<crate::dialog::DialogEvent>,
dialogs: Vec<crate::dialog::DialogEvent>,
sequence: Option<i32>,
#[cfg(test)]
forced_look: Option<(f32, f32)>,
cooldown_held: (i32, i16),
use_mark: Option<(u32, u8, u16)>,
head_yaw: Option<f32>,
attack_speed: f64,
}
#[derive(Debug, Default)]
struct BehaviorState {
started: bool,
failed: bool,
done: bool,
}
#[derive(Debug)]
pub(crate) struct Engine<S> {
pub core: Core,
pub sim: S,
state: BehaviorState,
}
impl Core {
#[inline]
fn stamp_entities(&self, sim: &mut (impl Sim + ?Sized)) {
if let Some(s) = sim.entities_mut() {
s.set_tick(self.tick + 1);
}
}
fn new(opts: CoreOptions) -> Self {
let rotation =
Rotation::new(opts.sensitivity).with_turn_rate(opts.turn_rate.0, opts.turn_rate.1);
let inv = ghast_inventory::Inventory::new(opts.inventory)
.expect("the version's feature enables its ghast-inventory feature");
let entity_push = opts.entity_push;
Core {
opts,
tick: 0,
entity_id: 0,
joined: false,
teleported_once: false,
ready: false,
pose: Pose::default(),
sent: Pose::default(),
rotation,
aimed: false,
controls: Controls::default(),
health: Health::default(),
clocks: crate::common::Clocks::default(),
day_clock: None,
dead: false,
abilities: Abilities::default(),
game_mode: GameMode::default(),
held_slot: 0,
sent_slot: 0,
slot_from_server: false,
open_window: 0,
dimension: String::new(),
respawn_screen: true,
pending: TickEvents::default(),
current: TickEvents::default(),
out: Vec::with_capacity(16),
last_inbound: None,
silent: false,
quit: None,
status: String::new(),
hands: Hands::default(),
buttons: Buttons::default(),
inv,
turned: false,
effects: std::collections::BTreeMap::new(),
active_effects: Vec::new(),
spawn_point: None,
last_hurt: None,
teams: None,
cooldown_held: (-1, 0),
use_mark: None,
head_yaw: None,
attack_speed: 4.0,
aqua_affinity: false,
broken_now: Vec::new(),
pick: PickList::default(),
want_flying: None,
held_turns: 0,
swings: 0,
level_load_started: false,
client_loaded: false,
chat_session_due: false,
gate_tick: false,
#[cfg(test)]
test_gate: None,
load_wait: 0,
near_loaded: 0,
origin: Instant::now(),
entity_push,
entity_push_sim: entity_push,
dialog: None,
screen_keys: None,
dialogs_pending: Vec::new(),
dialogs: Vec::new(),
sequence: None,
#[cfg(test)]
forced_look: None,
}
}
fn reset_player(&mut self, why: &str) {
self.teleported_once = false;
self.ready = false;
self.pose = Pose::default();
self.sent = Pose::default();
self.controls = Controls::default();
self.aimed = false;
self.open_window = 0;
self.dead = false;
self.hands.reset();
self.buttons = Buttons::default();
self.effects.clear();
if !self.active_effects.is_empty() {
self.active_effects.clear();
self.pending
.more()
.effects
.push(crate::common::EffectEvent::Cleared);
}
self.last_hurt = None;
self.level_load_started = false;
self.client_loaded = false;
self.load_wait = 0;
self.near_loaded = 0;
log::debug!(
"[{}] t{} {why}: waiting for the server position",
self.opts.name,
self.tick
);
}
fn now_nanos(&self) -> i64 {
self.last_inbound.map_or(0, |t| {
t.saturating_duration_since(self.origin).as_nanos() as i64
})
}
fn column_loaded(&self, world: &dyn WorldView) -> bool {
let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
world.is_column_loaded(cx, cz)
}
fn neighbourhood_loaded(&self, world: &dyn WorldView) -> bool {
let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
(-1..=1).all(|dx| (-1..=1).all(|dz| world.is_column_loaded(cx + dx, cz + dz)))
}
}
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)]
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;
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;
}
}
}
#[cold]
#[inline(never)]
fn equip_from_hand(inv: &mut ghast_inventory::Inventory, off_hand: bool, creative: bool) {
inv.equip_from_hand(off_hand, creative);
}
#[cold]
#[inline(never)]
fn take_use_events(c: &mut Core) {
c.current.more().item_use.append(&mut c.hands.use_events);
}
fn collidable(e: &ghast_entity::Entity) -> bool {
use ghast_entity::{EntityClass, EntityType};
match e.class() {
EntityClass::Player | EntityClass::Mob | EntityClass::Painting => true,
EntityClass::Item | EntityClass::ExperienceOrb => false,
EntityClass::Object => match e.entity_type() {
EntityType::LegacyObject(t) => {
matches!(t, 1 | 10 | 50 | 51 | 63 | 70 | 71 | 77 | 78)
}
#[cfg(feature = "v1_16_5")]
EntityType::Registry(_) => {
ghast_entity::v1_16_5::info(e.entity_type()).is_some_and(|i| {
matches!(
i.name,
"boat"
| "fireball"
| "tnt"
| "end_crystal"
| "falling_block"
| "item_frame"
| "leash_knot"
| "armor_stand"
| "shulker_bullet"
) || i.name.contains("minecart")
})
}
_ => false,
},
_ => false,
}
}
pub(crate) fn legacy_pick_margin(
ents: &ghast_entity::Entities,
e: &ghast_entity::Entity,
) -> Option<f32> {
let spectator = e.is_player()
&& ents
.player_info(&e.uuid())
.is_some_and(|p| p.game_mode == 3);
(collidable(e) && !spectator).then(|| e.targeting_margin())
}
#[derive(Debug, Default)]
struct PickList {
entities: Vec<ghast_physics::pick::PickEntity>,
ids: Vec<(i32, Vec3)>,
order: Vec<(i32, i32, i32, u32)>,
}
impl PickList {
fn fill(&mut self, w: &(impl Sim + ?Sized), caps: &Capabilities, eyes: Vec3) {
self.entities.clear();
self.ids.clear();
self.order.clear();
if let Some(ents) = w.entities() {
self.fill_from(w, ents, caps, eyes);
}
}
#[inline(never)]
fn fill_from(
&mut self,
w: &(impl Sim + ?Sized),
ents: &ghast_entity::Entities,
caps: &Capabilities,
eyes: Vec3,
) {
use ghast_entity::Entity;
let me = ents.self_id();
let root = |mut id: i32| {
for _ in 0..16 {
match ents.get(id).and_then(Entity::vehicle) {
Some(v) => id = v,
None => break,
}
}
id
};
let riding = ents.me().and_then(Entity::vehicle);
let my_root = me.map(root);
for e in ents.iter() {
let p = e.drawn_position();
let d = [p[0] - eyes.x, p[1] - eyes.y, p[2] - eyes.z];
if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 16.0 * 16.0 {
continue;
}
let Some(pick_radius) = w.pick_margin(e) else {
continue;
};
let Some(b) = e.drawn_bounding_box() else {
continue;
};
let same_root_vehicle = if caps.entity_pick_root_vehicle {
my_root.is_some_and(|r| root(e.id()) == r)
} else {
riding == Some(e.id())
};
self.entities.push(ghast_physics::pick::PickEntity {
bb: ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]),
pick_radius,
same_root_vehicle,
});
self.ids.push((e.id(), Vec3::new(p[0], p[1], p[2])));
if let Some(o) = w.search_order(e) {
self.order.push(o);
}
}
if self.entities.len() > 1 && self.order.len() == self.entities.len() {
self.sort();
}
}
#[cold]
#[inline(never)]
fn sort(&mut self) {
let mut idx: Vec<usize> = (0..self.entities.len()).collect();
idx.sort_unstable_by_key(|&i| self.order[i]);
self.entities = idx.iter().map(|&i| self.entities[i]).collect();
self.ids = idx.iter().map(|&i| self.ids[i]).collect();
}
fn split(&self, t: Crosshair, eyes: Vec3) -> (Option<BlockHit>, Option<hands::EntityHit>) {
match t {
Crosshair::Block(b) => (b, None),
Crosshair::Entity { index, hit } => {
let (id, entity_pos) = self.ids[index];
let d = [hit.x - eyes.x, hit.y - eyes.y, hit.z - eyes.z];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
(
None,
Some(hands::EntityHit {
id,
hit,
entity_pos,
distance,
interact: [(hands::Interact::NotHandled, hands::InteractEffect::None); 2],
}),
)
}
}
}
}
fn pick_box(pos: Vec3) -> ghast_physics::math::Aabb {
let h = f64::from(0.6f32 / 2.0);
ghast_physics::math::Aabb::new(
pos.x - h,
pos.y,
pos.z - h,
pos.x + h,
pos.y + f64::from(1.8f32),
pos.z + h,
)
}
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)))
}
#[inline]
fn movement_controls(c: &mut Core) -> Controls {
if c.dead {
Controls::NONE
} else if c.opts.gui_releases_keys && (c.inv.gui_open() || c.dialog.is_some()) {
screen_controls(c)
} else {
c.controls
}
}
#[cold]
#[inline(never)]
fn screen_controls(c: &mut Core) -> Controls {
if !c.opts.caps.own_inventory_passes_keys || !c.inv.inventory_open() || c.dialog.is_some() {
return Controls::NONE;
}
let keys = c.controls;
let held = c.screen_keys.get_or_insert(keys);
let still = |h: bool, k: bool| h && k;
*held = Controls {
forward: still(held.forward, keys.forward),
back: still(held.back, keys.back),
left: still(held.left, keys.left),
right: still(held.right, keys.right),
jump: still(held.jump, keys.jump),
sneak: still(held.sneak, keys.sneak),
sprint: still(held.sprint, keys.sprint),
};
Controls {
forward: keys.forward && !held.forward,
back: keys.back && !held.back,
left: keys.left && !held.left,
right: keys.right && !held.right,
jump: keys.jump && !held.jump,
sneak: keys.sneak && !held.sneak,
sprint: keys.sprint && !held.sprint,
}
}
#[cold]
#[inline(never)]
fn attack_effects(c: &mut Core, sim: &mut (impl Sim + ?Sized)) {
let caps = c.opts.caps;
let knockback = if caps.attack_knockback_enchantment {
c.inv.held().map_or(0, |s| i32::from(knockback(s)))
} else {
0
};
let attacks = std::mem::take(&mut c.hands.attacks);
for &(id, ticks) in &attacks {
let hurts = sim
.entities()
.and_then(|t| t.get(id))
.is_some_and(|e| sim.attack_hurts(e));
if !hurts {
continue;
}
let sprint_bonus =
!caps.combat_1_9 || hands::attack_strength_at(ticks, c.attack_speed) > 0.9;
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();
}
#[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)]
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);
}
}
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)]
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);
}
}
}
fn predict_use_effects(c: &mut Core, first: usize) {
if c.game_mode == GameMode::Creative {
return;
}
let data = c.opts.caps.data;
for k in first..c.out.len() {
let Outbound::UseItem {
held: Some(s),
off_hand,
} = &c.out[k]
else {
continue;
};
if thrown(data, s) {
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)]
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);
}
}
}
}
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,
}
}
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
}
}
}
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
}
}
}
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]
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)]
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]
fn use_food_level(c: &Core) -> i32 {
if c.abilities.invulnerable() {
match c.opts.caps.invulnerable_eating {
crate::version::InvulnerableEating::Never => return -1,
crate::version::InvulnerableEating::Always => return 0,
crate::version::InvulnerableEating::Hunger => {}
}
}
c.health.food
}
#[inline(never)]
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(_) => {}
}
}
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);
}
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)
}
fn knockback(s: &ghast_inventory::Stack) -> u8 {
enchant_level(s, 19, "minecraft:knockback")
}
fn efficiency(s: &ghast_inventory::Stack) -> u8 {
enchant_level(s, 32, "minecraft:efficiency")
}
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
}
impl<S: Sim> Engine<S> {
pub(crate) fn new(opts: CoreOptions, mut sim: S) -> Self {
sim.set_entity_push(opts.entity_push);
Engine {
core: Core::new(opts),
sim,
state: BehaviorState::default(),
}
}
pub(crate) fn request_chat_session(&mut self) {
self.core.chat_session_due = true;
}
pub(crate) fn joined(&self) -> bool {
self.core.joined
}
pub(crate) fn note_inbound(&mut self, now: Instant) {
self.core.last_inbound = Some(now);
}
pub(crate) fn last_inbound(&self) -> Option<Instant> {
self.core.last_inbound
}
pub(crate) fn track_teams(&mut self, on: bool) {
if on != self.core.teams.is_some() {
self.core.teams = on.then(Box::default);
}
}
pub(crate) fn note_sequence(&mut self, sequence: Option<i32>) {
self.core.sequence = sequence;
}
#[inline]
pub(crate) fn sync_snap(&mut self) {
if let Some(p) = self.sim.take_snap() {
log::debug!(
"[{}] t{} moved back to {:.3} {:.3} {:.3}: a restored block holds the player",
self.core.opts.name,
self.core.tick,
p.x,
p.y,
p.z
);
self.core.pose.pos = p;
}
}
pub(crate) fn name(&self) -> &str {
&self.core.opts.name
}
pub(crate) fn push_raw(&mut self, p: RawInbound) {
let ev = &mut self.core.pending;
if ev.raw.len() < MAX_PENDING_RAW {
ev.raw.push(p);
} else {
ev.raw_dropped += 1;
}
}
pub(crate) fn raw_packets<B: Behavior>(&self, b: &B) -> std::borrow::Cow<'static, [i32]> {
if self.state.failed || self.state.done {
std::borrow::Cow::Borrowed(&[])
} else {
b.raw_packets(self.core.opts.caps.version)
}
}
pub(crate) fn inventory_mut(&mut self) -> &mut ghast_inventory::Inventory {
&mut self.core.inv
}
pub(crate) fn mount_screen_opened(&mut self, entity_id: i32) {
if let Some(r) = self.sim.mount_rules(entity_id) {
self.core.inv.set_mount_rules(Some(r));
}
}
pub(crate) fn outbound(&mut self) -> &mut Vec<Outbound> {
&mut self.core.out
}
pub(crate) fn quit_requested(&self) -> Option<&str> {
self.core.quit.as_deref()
}
pub(crate) fn core_name(&self) -> &str {
&self.core.opts.name
}
pub(crate) fn accept_required_packs(&self) -> bool {
self.core.opts.accept_required_packs
}
pub(crate) fn tick_count(&self) -> u64 {
self.core.tick
}
pub(crate) fn handle(&mut self, p: Inbound) {
let c = &mut self.core;
let sim = &mut self.sim;
match p {
Inbound::KeepAlive(id) => c.out.push(Outbound::KeepAlive(id)),
Inbound::JoinGame(j) => {
c.entity_id = j.entity_id;
sim.set_main_arm_left(c.opts.settings.main_hand == 0);
c.game_mode = j.game_mode;
c.respawn_screen = j.respawn_screen;
c.dimension = j.dimension;
c.joined = true;
if let Some(t) = &mut c.teams {
**t = crate::teams::Teams::default();
}
c.pending.joined = true;
c.dialog = None;
c.health = Health::default();
c.abilities = Abilities::default();
c.reset_player("join game");
sim.reset_player();
sim.spectator(c.game_mode == GameMode::Spectator);
if !c.opts.caps.configuration_state {
c.out.push(Outbound::Settings(c.opts.settings.clone()));
if let Some(brand) = &c.opts.brand {
c.out.push(Outbound::Brand(brand.clone()));
}
}
log::info!(
"[{}] joined: entity {} {:?} dimension {}",
c.opts.name,
c.entity_id,
c.game_mode,
c.dimension
);
}
Inbound::Respawn {
dimension,
game_mode,
keep,
} => {
if dimension != c.dimension {
c.dimension = dimension;
}
c.game_mode = game_mode;
c.pending.respawned = true;
c.reset_player("respawn");
sim.respawn_player(keep);
sim.spectator(c.game_mode == GameMode::Spectator);
}
Inbound::Teleport(t) => {
if c.teleported_once {
log::debug!(
"[{}] t{} teleport {:?} {:?} {:?} yaw {:?} pitch {:?} flags {}; we had sent \
{:?} {:?} {:?} yaw {:?} pitch {:?} ground {}",
c.opts.name,
c.tick,
t.x,
t.y,
t.z,
t.yaw,
t.pitch,
t.flags,
c.sent.pos.x,
c.sent.pos.y,
c.sent.pos.z,
c.sent.yaw,
c.sent.pitch,
c.sent.on_ground
);
}
let (sent_before, pose_before) = (c.sent, c.pose);
sim.teleport(&mut c.pose, &t);
sim.teleport_sequence(c.sequence);
if c.pending.teleports.len() < MAX_PENDING_TELEPORTS {
c.pending.teleports.push(TeleportEvent {
teleport: t,
sent_before,
pose_before,
after: c.pose,
});
}
if let Some(id) = t.teleport_id {
c.out.push(Outbound::TeleportConfirm(id));
}
c.out.push(Outbound::Move(MovePacket::PositionLook {
horizontal_collision: false,
pos: c.pose.pos,
yaw: c.pose.yaw,
pitch: c.pose.pitch,
on_ground: false,
}));
c.sent = Pose {
on_ground: false,
..c.pose
};
if !c.teleported_once {
log::debug!(
"[{}] t{} spawn position {:.3} {:.3} {:.3}",
c.opts.name,
c.tick,
c.pose.pos.x,
c.pose.pos.y,
c.pose.pos.z
);
}
c.teleported_once = true;
c.pending.teleported = true;
}
Inbound::Chat(m) => {
if c.pending.chat.len() < MAX_PENDING_CHAT {
c.pending.chat.push(m);
} else {
c.pending.chat_dropped += 1;
}
}
Inbound::Time(t) => {
c.clocks.apply(&t);
c.day_clock = sim.day_clock();
}
Inbound::Health(h) => {
let was_dead = c.dead;
c.health = Health {
absorption: c.health.absorption,
..h
};
sim.food(h.food);
sim.player_alive(h.health > 0.0);
c.pending.health_changed = true;
if h.health <= 0.0 && !was_dead {
c.dead = true;
c.pending.died = true;
log::info!("[{}] t{} died", c.opts.name, c.tick);
}
}
Inbound::Died { entity_id } => {
if entity_id == c.entity_id && !c.respawn_screen {
c.out.push(Outbound::Respawn);
}
}
Inbound::Death(d) => {
if d.entity_id == c.entity_id && !c.respawn_screen {
c.out.push(Outbound::Respawn);
}
c.pending.more().deaths.push(d);
}
Inbound::SpawnPoint(p) => c.spawn_point = Some(p),
Inbound::Teams(p) => {
if let Some(t) = &mut c.teams
&& !t.apply(&p)
{
log::debug!("[{}] t{} team packet not applied", c.opts.name, c.tick);
}
}
Inbound::Damage(h) => {
if h.entity_id == c.entity_id {
c.last_hurt = Some(c.tick + 1);
c.pending.more().hurt.push(h);
}
}
Inbound::EffectApplied(e) => {
if e.entity_id == c.entity_id {
c.effects.insert(e.id, e.amplifier);
sim.status_effects(&c.effects);
let a = crate::common::ActiveEffect {
id: e.id,
amplifier: e.amplifier,
duration: e.duration,
flags: e.flags,
received_tick: c.tick + 1,
};
match c.active_effects.iter_mut().find(|x| x.id == e.id) {
Some(x) => *x = a,
None => c.active_effects.push(a),
}
c.pending
.more()
.effects
.push(crate::common::EffectEvent::Applied(a));
}
}
Inbound::Abilities(a) => {
c.abilities = a;
c.pose.flying = a.flying();
sim.abilities(a);
}
Inbound::HeldSlot(s) => {
if (0..9).contains(&s) {
if c.held_slot != s as u8
&& c.opts.caps.use_stop == crate::version::UseStop::AtSelect
{
c.hands.stop_using();
}
c.held_slot = s as u8;
c.slot_from_server = true;
}
}
Inbound::GameState { reason, value } => match reason {
1 | 2 | 7 => sim.weather(reason, value),
3 => {
c.game_mode = GameMode::from_wire(value as u8);
sim.spectator(c.game_mode == GameMode::Spectator);
if c.game_mode == GameMode::Spectator && c.opts.caps.spectator_switch_stops_use
{
c.hands.stop_using();
}
c.pending.game_mode_changed = true;
}
11 if c.opts.caps.immediate_respawn_rule => c.respawn_screen = value == 0.0,
13 if c.opts.caps.player_loaded_gate => {
c.level_load_started = true;
sim.level_load_start();
}
_ => {}
},
Inbound::Transaction { .. } => {}
Inbound::OpenWindow(id) => c.open_window = id,
Inbound::CloseWindow(_) => c.open_window = 0,
Inbound::Velocity { entity_id, motion } => {
if entity_id == c.entity_id {
sim.velocity(motion, false);
}
}
Inbound::ExplosionPush(motion) => sim.velocity(motion, true),
Inbound::MovementSpeed {
entity_id,
base,
modifiers,
} => {
if entity_id == c.entity_id {
movement_speed(c, sim, base, &modifiers);
}
}
Inbound::LegacyAttributes {
entity_id,
movement_speed: speed,
attack_speed,
} => {
if entity_id == c.entity_id {
if let Some((base, modifiers)) = speed {
movement_speed(c, sim, base, &modifiers);
}
if let Some((base, modifiers)) = attack_speed {
let mut m = ghast_physics::attribute::Modifiers::NONE;
for &(id, amount, op) in &modifiers {
m.insert(id.as_u128(), amount, op as u8);
}
c.attack_speed = m.value(base);
}
}
}
Inbound::Effect {
entity_id,
id,
amplifier,
} => {
if entity_id == c.entity_id {
c.effects.insert(id, amplifier);
sim.status_effects(&c.effects);
}
}
Inbound::EffectRemoved { entity_id, id } => {
if entity_id == c.entity_id {
c.effects.remove(&id);
sim.status_effects(&c.effects);
c.active_effects.retain(|x| x.id != id);
c.pending
.more()
.effects
.push(crate::common::EffectEvent::Removed(id));
}
}
Inbound::EntityStatus { entity_id, status } => {
if entity_id == c.entity_id && status == 9 {
finish_food(c);
finish_consumes(c);
c.hands.finish_using();
}
if entity_id == c.entity_id && matches!(status, 2 | 33 | 36 | 37 | 44) {
c.last_hurt = Some(c.tick + 1);
c.pending
.more()
.hurt
.push(crate::common::Hurt::from_status(entity_id, status));
}
}
Inbound::Attributes {
entity_id,
attributes,
} => {
if entity_id == c.entity_id {
if let Some(a) = attributes.iter().find(|a| a.name == "attack_speed") {
c.attack_speed = modern_attribute_value(a);
}
sim.attributes(&attributes);
}
}
Inbound::Ping(id) => c.out.push(Outbound::Pong(id)),
Inbound::ChunkBatchStart => sim.chunk_batch_start(c.now_nanos()),
Inbound::ChunkBatchFinished(size) => {
let per_tick = sim.chunk_batch_finished(size, c.now_nanos());
c.out.push(Outbound::ChunkBatchReceived(per_tick));
}
Inbound::StartConfiguration => {
c.joined = false;
c.dialog = None;
c.reset_player("reconfiguration");
sim.drop_level();
}
Inbound::ResourcePackPush { id, required } => {
if required && c.opts.accept_required_packs {
for result in [3, 4, 0] {
c.out.push(Outbound::ResourcePackStatus { id, result });
}
} else {
c.out.push(Outbound::ResourcePackStatus { id, result: 1 });
}
}
Inbound::CookieRequest(key) => {
c.out.push(Outbound::CookieResponse { key, value: None });
}
Inbound::StoreCookie { .. } => {}
Inbound::Transfer { .. } => {}
Inbound::Rotate {
yaw,
pitch,
relative_yaw,
relative_pitch,
} => {
let yaw = if relative_yaw { c.pose.yaw + yaw } else { yaw };
let pitch = if relative_pitch {
c.pose.pitch + pitch
} else {
pitch
};
c.pose.yaw = yaw;
c.pose.pitch = pitch.clamp(-90.0, 90.0);
c.rotation.reset(c.pose.yaw, c.pose.pitch);
c.out.push(Outbound::LookAnswer {
yaw: c.pose.yaw,
pitch: c.pose.pitch,
});
c.sent.yaw = c.pose.yaw;
c.sent.pitch = c.pose.pitch;
}
Inbound::ShowDialog(d) => {
log::debug!("[{}] t{} dialog \"{}\"", c.opts.name, c.tick, d.title);
c.dialog = Some(d.clone());
if c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
c.dialogs_pending.push(crate::dialog::DialogEvent::Shown(d));
}
}
Inbound::ClearDialog => {
if c.dialog.take().is_some() && c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
c.dialogs_pending.push(crate::dialog::DialogEvent::Cleared);
}
}
Inbound::Disconnect(_) | Inbound::SetCompression(_) => {}
}
}
pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
if self.state.failed {
Interests::NONE
} else {
b.interests()
}
}
pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
if self.state.started && !self.state.failed {
self.state.failed = true;
let name = self.core.opts.name.clone();
if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
log::error!("[{name}] behaviour {} panicked in stop", b.name());
}
}
}
#[cfg(test)]
#[allow(dead_code, reason = "the engine tests need every version feature")]
pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
self.tick_with(b, now, &|_| crate::dialog::CommandCheck::ParseErrors);
}
pub(crate) fn tick_with<B: Behavior>(
&mut self,
b: &mut B,
now: Instant,
commands: &dyn Fn(&str) -> crate::dialog::CommandCheck,
) {
let c = &mut self.core;
c.tick += 1;
c.clocks.tick();
c.inv.tick();
let was_ready = c.ready;
c.ready = c.teleported_once
&& ((c.opts.caps.player_loaded_gate && c.client_loaded) || c.column_loaded(&self.sim));
if c.ready != was_ready {
if c.ready {
log::info!(
"[{}] t{} in the world at {:.3} {:.3} {:.3}",
c.opts.name,
c.tick,
c.pose.pos.x,
c.pose.pos.y,
c.pose.pos.z
);
} else {
log::debug!(
"[{}] t{} player column not loaded: not ticking",
c.opts.name,
c.tick
);
}
}
if c.chat_session_due && c.joined {
c.chat_session_due = false;
c.out.push(Outbound::ChatSessionUpdate);
}
if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
c.load_wait += 1;
let near = c.neighbourhood_loaded(&self.sim);
c.near_loaded = if near {
c.near_loaded.saturating_add(1)
} else {
0
};
let (compiled, timed_out) = (c.ready && c.near_loaded >= 2, c.load_wait >= 600);
#[cfg(test)]
let (compiled, timed_out) = c.test_gate.unwrap_or((compiled, timed_out));
if self.sim.load_gate_tick(compiled, timed_out) {
c.client_loaded = true;
c.gate_tick = true;
c.out.push(Outbound::PlayerLoaded);
log::debug!("[{}] t{} player loaded", c.opts.name, c.tick);
}
}
if !c.ready || (c.opts.caps.player_loaded_gate && !c.client_loaded) {
if c.opts.caps.sends_tick_end && c.joined {
c.out.push(Outbound::TickEnd);
}
if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
self.sim.tick_unloaded();
}
self.sim.tick_entities(&mut c.pose);
c.stamp_entities(&mut self.sim);
return;
}
let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
if silent != c.silent {
c.silent = silent;
if silent {
log::warn!(
"[{}] t{} server silent for {} ms: behaviour on hold",
c.opts.name,
c.tick,
silent_for.unwrap_or_default().as_millis()
);
} else {
log::info!(
"[{}] t{} server answering again: behaviour resumes",
c.opts.name,
c.tick
);
}
}
if silent {
c.controls = Controls::default();
c.aimed = false;
} else if !self.state.failed && !self.state.done {
std::mem::swap(&mut c.pending, &mut c.current);
c.pending.clear();
if let Some(a) = self.sim.take_absorption() {
c.current.health_changed |= a.to_bits() != c.health.absorption.to_bits();
c.health.absorption = a;
}
if let Some(f) = self.sim.take_living_flags()
&& c.opts.caps.living_flags_drive_use
{
living_flags_use(c, f);
}
if !c.dialogs.is_empty() || !c.dialogs_pending.is_empty() {
c.dialogs.clear();
std::mem::swap(&mut c.dialogs, &mut c.dialogs_pending);
}
c.current.inventory = c.inv.drain_events();
if !c.hands.use_events.is_empty() {
take_use_events(c);
}
if let Some(s) = self.sim.entities_mut() {
let ev = s.drain_events();
let n = ev.len();
if n > 0 {
let skip = n.saturating_sub(MAX_PENDING_ENTITY_EVENTS);
let m = c.current.more();
m.entities.extend(ev.skip(skip));
m.entities_dropped = skip;
}
}
c.current.block_updates_dropped =
self.sim.drain_block_updates(&mut c.current.block_updates);
if c.current.inventory.player_changed {
let ench = |a: usize, id: i32, name: &str| {
c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
};
let depth = ench(3, 8, "minecraft:depth_strider");
let soul = ench(3, -1, "minecraft:soul_speed");
c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
self.sim.boots(depth, soul);
self.sim.feet_item(c.inv.armor(3).map(|s| s.id()));
}
for o in c.inv.take_screen_packets() {
c.out.push(Outbound::Inventory(o));
}
let started = self.state.started;
self.state.started = true;
if !started {
c.rotation.reset(c.pose.yaw, c.pose.pitch);
}
let name = c.opts.name.clone();
let result = catch_unwind(AssertUnwindSafe(|| {
let held = held_item(&c.inv, &self.sim);
let mut ctx = TickContext {
core: c,
world: &self.sim,
held,
crosshair: std::cell::OnceCell::new(),
commands,
};
if !started {
b.start(&mut ctx);
}
b.tick(&mut ctx);
b.running()
}));
match result {
Ok(true) => {}
Ok(false) => {
self.state.done = true;
log::info!("[{name}] behaviour {} finished", b.name());
}
Err(_) => {
log::error!("[{name}] behaviour {} panicked: stopped", b.name());
self.stop(b, "panic");
}
}
}
let c = &mut self.core;
c.turned = false;
#[cfg(test)]
if let Some((yaw, pitch)) = c.forced_look.take() {
c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
c.pose.yaw = yaw;
c.pose.pitch = pitch;
c.aimed = false;
}
if c.entity_push != c.entity_push_sim {
c.entity_push_sim = c.entity_push;
self.sim.set_entity_push(c.entity_push);
}
if c.held_slot != c.sent_slot {
c.sent_slot = c.held_slot;
c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
}
c.slot_from_server = false;
{
let gui = c.inv.gui_open();
if self.sim.modern_inputs() && ((c.buttons.right && !gui) || c.hands.using_item()) {
self.sim.held_use_inputs(&mut c.inv);
}
let eye = pick_eye_height(&self.sim, c.opts.caps, c.pose.sneaking);
let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
let sim = &self.sim;
let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
sim.place_suppressed(p, f, id)
};
let pick_rot = pick_rotation(c);
let look = hands::look_vector(pick_rot.0, pick_rot.1);
let held_id = c.inv.held().and_then(|s| u16::try_from(s.id()).ok());
let (left, right) = (
c.buttons.left && !gui && !c.dead,
c.buttons.right && !gui && !c.dead,
);
let (target, entity) = if left || right {
c.pick.fill(sim, c.opts.caps, eyes);
let crosshair = sim.crosshair_target(&PickQuery {
eyes,
rotation: pick_rot,
look,
held: held_id,
now: true,
creative: c.game_mode == GameMode::Creative,
player_bb: pick_box(c.pose.pos),
entities: &c.pick.entities,
});
let (b, mut e) = c.pick.split(crosshair, eyes);
if right
&& let Some(h) = &mut e
&& let Some(ents) = sim.entities()
{
let id = |s: Option<&ghast_inventory::Stack>| {
s.and_then(|s| Some((u16::try_from(s.id()).ok()?, s.damage())))
};
h.interact = crate::interact::outcome(
ents,
c.opts.caps.protocol,
h.id,
c.game_mode == GameMode::Spectator,
c.pose.sneaking,
c.game_mode == GameMode::Creative,
[id(c.inv.held()), id(c.inv.offhand())],
);
}
(b, e)
} else {
(None, None)
};
let in_water = blocks(
eyes.x.floor() as i32,
eyes.y.floor() as i32,
eyes.z.floor() as i32,
)
.is_some_and(|b| b.water);
let mut held = held_item(&c.inv, sim);
let mut off_held = off_held_item(&c.inv, sim);
let creative = c.game_mode == GameMode::Creative;
if right {
use_equips(c, creative, &mut held, &mut off_held);
}
let mut placed = false;
let first = c.out.len();
let rules_fn;
let rules: &PlaceRulesFn<'_> = if right {
rules_fn = |p: ghast_protocol::BlockPos,
f: crate::common::Face,
cursor: [f32; 3],
off: bool| {
sim.place_rules(&crate::sim::predict::PlaceQuery {
pos: p,
face: f,
cursor,
held: if off { c.inv.offhand() } else { c.inv.held() },
sneaking: c.pose.sneaking,
any_item: c.inv.held().is_some() || c.inv.offhand().is_some(),
game_mode: c.game_mode,
yaw: c.pose.yaw,
})
};
&rules_fn
} else {
&no_place_rules
};
let mut io = HandsIo {
blocks: &blocks,
target,
held,
held_stack: c.inv.held().cloned(),
food: use_food_level(c),
modern: c.opts.caps.combat_1_9,
off_held,
off_stack: c.inv.offhand().cloned(),
entity,
factors: 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)),
},
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
creative,
creative_dig: creative && c.opts.caps.creative_instant_dig,
place_blocked: &blocked,
place_rules: rules,
};
c.hands.tick(left, right, &mut io);
let _ = placed;
if right && let Some(off_hand) = c.hands.equipped.take() {
equip_from_hand(&mut c.inv, off_hand, creative);
}
predict_planting(c, sim, first);
if c.out.len() != first {
click_stack_effects(c, first, entity);
}
}
if !c.hands.attacks.is_empty() {
attack_effects(c, &mut self.sim);
}
if c.hands.using_item() && c.opts.caps.use_stop != crate::version::UseStop::AtSelect {
held_use_check(c);
} else {
c.use_mark = None;
}
if c.opts.caps.cooldown_reset != crate::version::CooldownReset::AtSelect {
cooldown_held_check(c);
}
if c.hands.dug || !c.hands.placing.is_empty() {
if !c.broken_now.is_empty() || !c.hands.placing.is_empty() || self.sim.records_digs() {
sent_predictions(c, &mut self.sim);
}
c.hands.dug = false;
c.hands.placing.clear();
}
if let Some(f) = c.want_flying.take() {
let first = c.out.len();
self.sim.set_flying(f, &mut c.out);
if c.out.len() > first {
c.pose.flying = f;
} else if f && !c.pose.flying {
log::debug!(
"[{}] t{} set_flying(true) refused: flight not allowed",
c.opts.name,
c.tick
);
}
}
let gate_tick = std::mem::take(&mut c.gate_tick);
if c.aimed && !gate_tick {
let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
if c.opts.hold_turn_on_action && !post_look_ok(c, &self.sim, yaw, pitch) {
c.held_turns += 1;
} else {
c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
c.pose.yaw = yaw;
c.pose.pitch = pitch;
}
c.aimed = false;
}
let first = c.out.len();
let controls = movement_controls(c);
if self.sim.modern_inputs()
&& (c.hands.using_item()
|| c.hands.released_use().is_some()
|| controls.jump
|| self.sim.pre_tick_wanted())
{
let pre = crate::sim::PreTick {
using: c.hands.use_item(),
released: c.hands.released_use(),
controls,
look: (c.pose.yaw, c.pose.pitch),
};
if !self.sim.pre_tick(&c.inv, &pre) {
c.hands.stop_using();
}
}
let using = c.hands.using_item();
self.sim
.step(&mut c.pose, controls, using, c.entity_id, &mut c.out);
if c.opts.caps.pick_head_yaw {
c.head_yaw = Some(c.pose.yaw);
}
self.sim.tick_entities(&mut c.pose);
c.stamp_entities(&mut self.sim);
c.hands.count_use_tick();
for o in &c.out[first..] {
let Outbound::Move(m) = o else { continue };
match *m {
MovePacket::Position { pos, .. } => c.sent.pos = pos,
MovePacket::Look { yaw, pitch, .. } => {
c.sent.yaw = yaw;
c.sent.pitch = pitch;
}
MovePacket::PositionLook {
pos, yaw, pitch, ..
} => {
c.sent.pos = pos;
c.sent.yaw = yaw;
c.sent.pitch = pitch;
}
MovePacket::Flying { .. } => {}
}
if matches!(
m,
MovePacket::Position { .. } | MovePacket::PositionLook { .. }
) {
c.sent.motion = c.pose.motion;
}
}
c.sent.on_ground = c.pose.on_ground;
c.sent.sneaking = c.pose.sneaking;
c.sent.sprinting = c.pose.sprinting;
c.sent.flying = c.pose.flying;
c.swings += count_swings(&c.out);
if c.dead && c.joined && !c.respawn_screen && !c.inv.gui_open() {
c.out.push(Outbound::Respawn);
}
if c.opts.caps.sends_tick_end {
c.out.push(Outbound::TickEnd);
}
if self.state.started && !self.state.failed {
let name = c.opts.name.clone();
let view = TickView {
core: &self.core,
world: &self.sim,
};
if catch_unwind(AssertUnwindSafe(|| b.after_tick(&view))).is_err() {
log::error!(
"[{name}] behaviour {} panicked in after_tick: stopped",
b.name()
);
self.stop(b, "panic");
}
}
}
}
fn count_swings(out: &[Outbound]) -> u64 {
out.iter()
.filter(|o| matches!(o, Outbound::Swing | Outbound::SwingOffHand))
.count() as u64
}
pub struct TickView<'a> {
core: &'a Core,
world: &'a dyn WorldView,
}
impl std::fmt::Debug for TickView<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TickView")
.field("tick", &self.core.tick)
.field("sent", &self.core.sent)
.finish_non_exhaustive()
}
}
impl TickView<'_> {
#[must_use]
pub fn tick(&self) -> u64 {
self.core.tick
}
#[must_use]
pub fn version(&self) -> GameVersion {
self.core.opts.caps.version
}
#[must_use]
pub fn pose(&self) -> &Pose {
&self.core.pose
}
#[must_use]
pub fn sent(&self) -> &Pose {
&self.core.sent
}
#[must_use]
pub fn horizontal_collision(&self) -> bool {
self.world.collisions().0
}
#[must_use]
pub fn vertical_collision(&self) -> bool {
self.world.collisions().1
}
#[must_use]
pub fn piston_uncertain(&self) -> bool {
self.world.piston_uncertain()
}
#[must_use]
pub fn world(&self) -> &dyn WorldView {
self.world
}
#[must_use]
pub fn entities(&self) -> Option<&ghast_entity::Entities> {
self.world.entities()
}
#[must_use]
pub fn inventory(&self) -> &ghast_inventory::Inventory {
&self.core.inv
}
#[must_use]
pub fn events(&self) -> &TickEvents {
&self.core.current
}
#[must_use]
pub fn entity_id(&self) -> i32 {
self.core.entity_id
}
#[must_use]
pub fn health(&self) -> Health {
self.core.health
}
#[must_use]
pub fn effects(&self) -> &[crate::common::ActiveEffect] {
&self.core.active_effects
}
#[must_use]
pub fn spawn_position(&self) -> Option<&crate::common::SpawnPoint> {
self.core.spawn_point.as_ref()
}
#[must_use]
pub fn teams(&self) -> Option<&crate::teams::Teams> {
self.core.teams.as_deref()
}
#[must_use]
pub fn last_hurt_tick(&self) -> Option<u64> {
self.core.last_hurt
}
#[must_use]
pub fn world_time(&self) -> Option<crate::common::WorldTime> {
self.core.clocks.world_time(self.core.day_clock)
}
#[must_use]
pub fn game_mode(&self) -> GameMode {
self.core.game_mode
}
#[must_use]
pub fn held_slot(&self) -> u8 {
self.core.held_slot
}
#[must_use]
pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
self.core.hands.mining()
}
#[must_use]
pub fn swings(&self) -> u64 {
self.core.swings
}
#[must_use]
pub fn broken(&self) -> u64 {
self.core.hands.broken
}
#[must_use]
pub fn dimension(&self) -> &str {
&self.core.dimension
}
#[must_use]
pub fn using_item(&self) -> bool {
self.core.hands.using_item()
}
#[must_use]
pub fn outbound(&self) -> &[Outbound] {
&self.core.out
}
#[must_use]
pub fn prediction_sequence(&self) -> Option<i32> {
self.core.sequence
}
}
#[cfg(all(test, feature = "v1_8"))]
impl Core {
pub(crate) fn test_set_slot(&mut self, slot: u8) {
self.held_slot = slot;
self.sent_slot = slot;
self.inv.select(slot);
}
pub(crate) fn test_poses(&mut self) -> (&mut Pose, &mut Pose) {
(&mut self.pose, &mut self.sent)
}
pub(crate) fn test_held_turns(&self) -> u64 {
self.held_turns
}
}
#[cfg(all(test, feature = "v1_8"))]
impl TickContext<'_> {
pub(crate) fn test_force_look(&mut self, yaw: f32, pitch: f32) {
self.core.forced_look = Some((yaw, pitch));
}
pub(crate) fn test_rotation(&self) -> Rotation {
self.core.rotation
}
}
#[cold]
#[inline(never)]
fn sent_predictions<S: Sim>(c: &mut Core, sim: &mut S) {
use crate::common::DigStatus;
let player = c.pose.pos;
let mut sequence = c.sequence.unwrap_or(0);
let mut broken = 0;
let mut placing = c.hands.placing.iter().copied().peekable();
let any_item = c.inv.held().is_some() || c.inv.offhand().is_some();
let mut used = [0u8; 2];
for (i, o) in c.out.iter().enumerate() {
match *o {
Outbound::Dig { status, pos, .. } => {
let predicting = matches!(status, DigStatus::Start | DigStatus::Finish);
if predicting {
sequence = sequence.wrapping_add(1);
} else if status != DigStatus::Abort {
continue;
}
let b = predicting && c.broken_now.get(broken) == Some(&pos);
if b {
broken += 1;
}
sim.dig_sent(pos, status, b, sequence, player);
}
Outbound::Place {
pos,
face,
cursor,
ref held,
off_hand,
}
| Outbound::PlaceInside {
pos,
face,
cursor,
ref held,
off_hand,
} => {
sequence = sequence.wrapping_add(1);
while placing.next_if(|&p| (p as usize) < i).is_some() {}
if placing.next_if_eq(&(i as u32)).is_some()
&& sim.place_sent(&crate::sim::predict::PlaceSent {
pos,
face,
held: held.as_ref(),
sneaking: c.pose.sneaking,
any_item,
game_mode: c.game_mode,
sequence,
player,
cursor: [cursor.x as f32, cursor.y as f32, cursor.z as f32],
yaw: c.pose.yaw,
})
&& crate::sim::predict::placing_uses_item(c.game_mode)
{
used[usize::from(off_hand)] = used[usize::from(off_hand)].saturating_add(1);
}
}
Outbound::UseItem { .. } => {
sequence = sequence.wrapping_add(1);
}
_ => {}
}
}
debug_assert_eq!(
broken,
c.broken_now.len(),
"a broken block without its dig packet"
);
for p in &c.broken_now[broken..] {
sim.predict_air(p.x, p.y, p.z);
}
c.broken_now.clear();
if used[0] > 0 {
c.inv.consume_held(used[0]);
}
if used[1] > 0 {
c.inv.consume_offhand(used[1]);
}
}
type PlaceRulesFn<'a> = dyn Fn(
ghast_protocol::BlockPos,
crate::common::Face,
[f32; 3],
bool,
) -> crate::sim::predict::PlaceRules
+ 'a;
fn no_place_rules(
_: ghast_protocol::BlockPos,
_: crate::common::Face,
_: [f32; 3],
_: bool,
) -> crate::sim::predict::PlaceRules {
crate::sim::predict::PlaceRules::default()
}
fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
if !c.opts.caps.seed_planting_prediction || c.game_mode == GameMode::Creative {
return;
}
let mut uses = 0u8;
for o in &c.out[first..] {
let Outbound::Place {
pos,
face: crate::common::Face::Up,
held: Some(held),
off_hand: false,
..
} = o
else {
continue;
};
let soil = match held.id() {
295 | 361 | 362 | 391 | 392 => 60,
372 => 88,
_ => continue,
};
let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
if held.count() > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
uses += 1;
}
}
if uses > 0 {
c.inv.consume_held(uses);
}
}
fn post_look_ok(c: &Core, world: &(impl Sim + ?Sized), yaw: f32, pitch: f32) -> bool {
let (mut action, mut use_item) = (false, false);
for o in &c.out {
match o {
Outbound::UseEntity { .. } => return (yaw, pitch) == (c.pose.yaw, c.pose.pitch),
Outbound::Dig {
status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
..
}
| Outbound::Place { .. }
| Outbound::PlaceInside { .. } => action = true,
Outbound::UseItem { .. } => use_item = true,
_ => {}
}
}
if !action && !use_item {
return true;
}
let looks = [
hands::look_vector(c.pose.yaw, pitch),
hands::look_vector(yaw, pitch),
];
let heights = [c.opts.caps.eye_height, c.opts.caps.sneak_eye_height];
if use_item && (yaw, pitch) != (c.pose.yaw, c.pose.pitch) {
let rotations = [(c.pose.yaw, pitch), (yaw, pitch)];
let picks = [c.sent.pos, c.pose.pos].iter().any(|o| {
heights.iter().any(|h| {
let eyes = Vec3::new(o.x, o.y + *h, o.z);
rotations.iter().zip(&looks).any(|(r, l)| {
let t = world.crosshair_target(&PickQuery {
eyes,
rotation: *r,
look: *l,
held: None,
now: false,
creative: c.game_mode == GameMode::Creative,
player_bb: pick_box(*o),
entities: &[],
});
matches!(t, Crosshair::Block(Some(_)))
})
})
});
if picks {
return false;
}
}
c.out
.iter()
.filter_map(|o| match o {
Outbound::Dig {
status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
pos,
..
}
| Outbound::Place { pos, .. }
| Outbound::PlaceInside { pos, .. } => Some(*pos),
_ => None,
})
.all(|t| {
[c.sent.pos, c.pose.pos].iter().all(|o| {
heights.iter().any(|h| {
let eyes = Vec3::new(o.x, o.y + *h, o.z);
looks
.iter()
.any(|l| hands::ray_hits_cube(eyes, *l, t, ACTION_LOOK_REACH))
})
})
})
}
#[inline]
fn pick_rotation(c: &Core) -> (f32, f32) {
match c.head_yaw {
Some(y) if c.opts.caps.pick_head_yaw => (y, c.pose.pitch),
_ => (c.pose.yaw, c.pose.pitch),
}
}
#[inline]
fn pick_eye_height(sim: &(impl Sim + ?Sized), caps: &Capabilities, sneaking: bool) -> f64 {
sim.eye_height().unwrap_or(if sneaking {
caps.sneak_eye_height
} else {
caps.eye_height
})
}
const ACTION_LOOK_REACH: f64 = 6.0;
pub struct TickContext<'a> {
core: &'a mut Core,
world: &'a dyn Sim,
held: Option<hands::HeldItem>,
crosshair: std::cell::OnceCell<(Option<BlockHit>, Option<hands::EntityHit>)>,
commands: &'a dyn Fn(&str) -> crate::dialog::CommandCheck,
}
impl std::fmt::Debug for TickContext<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TickContext")
.field("tick", &self.core.tick)
.field("pose", &self.core.pose)
.finish_non_exhaustive()
}
}
impl TickContext<'_> {
#[must_use]
pub fn tick(&self) -> u64 {
self.core.tick
}
#[must_use]
pub fn version(&self) -> GameVersion {
self.core.opts.caps.version
}
#[must_use]
pub fn pose(&self) -> &Pose {
&self.core.pose
}
#[must_use]
pub fn sent(&self) -> &Pose {
&self.core.sent
}
#[must_use]
pub fn velocity(&self) -> Vec3 {
self.world.velocity_now()
}
#[must_use]
pub fn horizontal_collision(&self) -> bool {
self.world.collisions().0
}
#[must_use]
pub fn vertical_collision(&self) -> bool {
self.world.collisions().1
}
#[must_use]
pub fn piston_uncertain(&self) -> bool {
self.world.piston_uncertain()
}
#[must_use]
pub fn server_flags(&self) -> Option<u8> {
self.world.server_flags()
}
#[must_use]
pub fn server_sprinting(&self) -> bool {
self.server_flags().is_some_and(|f| f & 0x08 != 0)
}
#[must_use]
pub fn eyes(&self, pose: &Pose) -> Vec3 {
let v = self.core.opts.caps;
pose.eyes(if pose.sneaking {
v.sneak_eye_height
} else {
v.eye_height
})
}
#[must_use]
pub fn world(&self) -> &dyn WorldView {
self.world
}
#[cfg(ghast_modern)]
#[must_use]
pub fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
self.world.modern_player()
}
#[must_use]
pub fn events(&self) -> &TickEvents {
&self.core.current
}
#[must_use]
pub fn entity_id(&self) -> i32 {
self.core.entity_id
}
#[must_use]
pub fn swings(&self) -> u64 {
self.core.swings + count_swings(&self.core.out)
}
#[must_use]
pub fn health(&self) -> Health {
self.core.health
}
#[must_use]
pub fn effects(&self) -> &[crate::common::ActiveEffect] {
&self.core.active_effects
}
#[must_use]
pub fn spawn_position(&self) -> Option<&crate::common::SpawnPoint> {
self.core.spawn_point.as_ref()
}
#[must_use]
pub fn teams(&self) -> Option<&crate::teams::Teams> {
self.core.teams.as_deref()
}
#[must_use]
pub fn last_hurt_tick(&self) -> Option<u64> {
self.core.last_hurt
}
#[must_use]
pub fn world_time(&self) -> Option<crate::common::WorldTime> {
self.core.clocks.world_time(self.core.day_clock)
}
#[must_use]
pub fn is_dead(&self) -> bool {
self.core.dead
}
#[must_use]
pub fn game_mode(&self) -> GameMode {
self.core.game_mode
}
#[must_use]
pub fn abilities(&self) -> Abilities {
self.core.abilities
}
#[must_use]
pub fn can_fly(&self) -> bool {
self.core.abilities.may_fly()
}
#[must_use]
pub fn held_slot(&self) -> u8 {
self.core.held_slot
}
#[must_use]
pub fn open_window(&self) -> Option<i32> {
(self.core.open_window != 0).then_some(self.core.open_window)
}
#[must_use]
pub fn dimension(&self) -> &str {
&self.core.dimension
}
#[must_use]
pub fn controls(&self) -> Controls {
self.core.controls
}
#[must_use]
pub fn aim(&self) -> (f32, f32) {
self.core.rotation.target()
}
pub fn chat(&mut self, text: impl Into<String>) {
self.core.out.push(Outbound::Chat(text.into()));
}
pub fn respawn(&mut self) -> bool {
if self.core.dead {
self.core.out.push(Outbound::Respawn);
true
} else {
false
}
}
pub fn select_slot(&mut self, slot: u8) {
if slot < 9 {
if self.core.slot_from_server && self.core.held_slot != slot {
self.core.slot_from_server = false;
if self.core.sent_slot != self.core.held_slot {
self.core.sent_slot = self.core.held_slot;
self.core
.out
.push(Outbound::HeldSlot(i16::from(self.core.held_slot)));
}
}
if self.core.held_slot != slot {
if self.core.opts.caps.use_stop == crate::version::UseStop::AtSelect {
self.core.hands.stop_using();
}
if self.core.opts.caps.cooldown_reset == crate::version::CooldownReset::AtSelect {
self.core.hands.ticks_since_swing = 0;
}
}
self.core.held_slot = slot;
self.core.inv.select(slot);
if self.core.sent_slot != slot {
self.core.sent_slot = slot;
self.core.out.push(Outbound::HeldSlot(i16::from(slot)));
}
}
}
#[must_use]
pub fn mob_state_known(&self) -> bool {
self.world.entities().is_some_and(|e| e.config().metadata)
}
pub fn swing(&mut self) {
self.core.out.push(Outbound::Swing);
}
pub fn drop_held(&mut self, whole_stack: bool) -> bool {
if !self.keys_reach_player() {
return false;
}
let c = &mut *self.core;
c.out.push(Outbound::Dig {
status: if whole_stack {
crate::common::DigStatus::DropStack
} else {
crate::common::DigStatus::DropItem
},
pos: ghast_protocol::BlockPos::new(0, 0, 0),
face: crate::common::Face::Down,
});
if c.opts.caps.drop_prediction && c.inv.drop_held(whole_stack) {
if c.inv.held().is_none() && c.hands.use_item().is_some_and(|(off, _)| !off) {
c.hands.stop_using();
}
c.out.push(Outbound::Swing);
self.held = held_item(&self.core.inv, self.world);
}
true
}
pub fn swap_hands(&mut self) -> bool {
if !self.core.opts.caps.combat_1_9 || !self.keys_reach_player() {
return false;
}
self.core.out.push(Outbound::Dig {
status: crate::common::DigStatus::SwapHands,
pos: ghast_protocol::BlockPos::new(0, 0, 0),
face: crate::common::Face::Down,
});
true
}
fn keys_reach_player(&self) -> bool {
let c = &*self.core;
!c.inv.gui_open() && c.dialog.is_none() && !c.dead && c.game_mode != GameMode::Spectator
}
pub fn send_raw(&mut self, id: i32, body: impl Into<bytes::Bytes>) {
self.core
.out
.push(Outbound::Raw(ghast_protocol::RawPacket::new(
id,
body.into(),
)));
}
pub fn send_packet<P: ghast_protocol::Packet>(
&mut self,
packet: &P,
) -> Result<(), ghast_protocol::EncodeError> {
if P::STATE != ghast_protocol::State::Play
|| P::DIRECTION != ghast_protocol::Direction::Serverbound
{
return Err(ghast_protocol::EncodeError::Invalid(
"not a serverbound play packet",
));
}
let mut body = bytes::BytesMut::new();
packet.encode(&mut body)?;
self.send_raw(P::ID, body.freeze());
Ok(())
}
pub fn disconnect(&mut self, reason: impl Into<String>) {
self.core.quit = Some(reason.into());
}
pub fn set_aim(&mut self, yaw: f32, pitch: f32) {
self.core.rotation.set_target(yaw, pitch);
self.core.aimed = true;
}
pub fn set_controls(&mut self, controls: Controls) {
self.core.controls = controls;
}
#[must_use]
pub fn inventory(&self) -> &ghast_inventory::Inventory {
&self.core.inv
}
pub fn click(&mut self, click: ghast_inventory::Click) -> Result<ClickTicket, ClickRefused> {
self.still()?;
let o = self
.core
.inv
.click(click)
.map_err(ClickRefused::Inventory)?;
for s in self.core.inv.take_screen_packets() {
self.core.out.push(Outbound::Inventory(s));
}
let ticket = match &o {
ghast_inventory::Outgoing::Click(p) => ClickTicket {
window_id: i32::from(p.window_id),
action: p.action,
},
ghast_inventory::Outgoing::ContainerClick(p) => ClickTicket {
window_id: p.window_id,
action: p.action,
},
_ => ClickTicket {
window_id: -1,
action: -1,
},
};
self.core.out.push(Outbound::Inventory(o));
Ok(ticket)
}
pub fn can_click(&self) -> Result<(), ClickRefused> {
self.still()?;
self.core.inv.can_click().map_err(ClickRefused::Inventory)
}
fn still(&self) -> Result<(), ClickRefused> {
if self.core.dead {
return Err(ClickRefused::Dead);
}
if self.core.turned || self.core.aimed {
return Err(ClickRefused::Turning);
}
Ok(())
}
pub fn anvil_rename(&mut self, name: &str) -> Result<(), ClickRefused> {
if let Some(o) = self
.core
.inv
.anvil_rename(name)
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
Ok(())
}
pub fn select_loom_pattern(&mut self, index: i32) -> Result<(), ClickRefused> {
#[cfg(ghast_modern)]
if let Some(o) = self
.core
.inv
.select_loom_pattern_modern(index)
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
#[cfg(not(ghast_modern))]
let _ = index;
Ok(())
}
pub fn set_mount_rules(&mut self, rules: Option<ghast_inventory::MountRules>) {
self.core.inv.set_mount_rules(rules);
}
pub fn click_button(&mut self, index: i32) -> Result<(), ClickRefused> {
if let Some(o) = self
.core
.inv
.click_button(index)
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
Ok(())
}
pub fn select_trade(&mut self, index: i32) -> Result<(), ClickRefused> {
let o = self
.core
.inv
.select_trade(index)
.map_err(ClickRefused::Inventory)?;
self.core.out.push(Outbound::Inventory(o));
Ok(())
}
pub fn open_inventory(&mut self) -> Result<(), ClickRefused> {
self.still()?;
self.core.screen_keys = None;
if let Some(o) = self
.core
.inv
.open_inventory()
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
let echo = self.core.inv.take_creative_echo_legacy();
if !echo.is_empty() {
self.core
.out
.push(Outbound::Inventory(ghast_inventory::Outgoing::Creative(
echo,
)));
}
Ok(())
}
pub fn close_window(&mut self) -> Result<(), ClickRefused> {
let o = self.core.inv.close().map_err(ClickRefused::Inventory)?;
self.core.out.push(Outbound::Inventory(o));
self.core.open_window = 0;
Ok(())
}
pub fn set_buttons(&mut self, buttons: Buttons) {
self.core.buttons = buttons;
}
pub fn set_entity_push(&mut self, on: bool) {
self.core.entity_push = on;
}
#[must_use]
pub fn entity_push(&self) -> bool {
self.core.entity_push
}
#[must_use]
pub fn dialog(&self) -> Option<&crate::dialog::Dialog> {
self.core.dialog.as_deref()
}
#[must_use]
pub fn dialog_events(&self) -> &[crate::dialog::DialogEvent] {
&self.core.dialogs
}
pub fn answer_dialog(
&mut self,
answer: &crate::dialog::DialogAnswer,
) -> Result<crate::dialog::DialogOutcome, crate::dialog::DialogRefused> {
use crate::dialog::{CommandCheck, DialogOutcome, DialogRefused, DialogSent, Effect, Next};
let d = self.core.dialog.clone().ok_or(DialogRefused::NoDialog)?;
let (effect, mut next) = crate::dialog::resolve(&d, answer)?;
let sent = match effect {
Effect::Nothing => DialogSent::Nothing,
Effect::Custom { id, payload } => {
self.core.out.push(Outbound::CustomClickAction {
id: id.clone(),
payload: crate::dialog::payload_nbt(payload.as_ref()),
});
DialogSent::Custom(id)
}
Effect::Command(command) => match ((self.commands)(&command), answer.confirms()) {
(CommandCheck::NoIssues, _)
| (CommandCheck::ParseErrors | CommandCheck::PermissionsRequired, true) => {
self.core.out.push(Outbound::DialogCommand(command.clone()));
DialogSent::Command(command)
}
(CommandCheck::SignatureRequired, true) => {
self.core.out.push(Outbound::Chat(format!("/{command}")));
DialogSent::Command(command)
}
(check, _) => {
next = Next::Stay;
DialogSent::CommandHeld { command, check }
}
},
};
let (open, waiting) = match next {
Next::Stay => (Some(d.clone()), false),
Next::Closed => (None, false),
Next::Waiting => (None, true),
Next::Open(n) => (Some(n), false),
};
if let Some(n) = &open
&& !Arc::ptr_eq(n, &d)
{
self.core
.dialogs_pending
.push(crate::dialog::DialogEvent::Shown(n.clone()));
}
self.core.dialog = open.clone();
Ok(DialogOutcome {
sent,
open,
waiting,
})
}
#[must_use]
pub fn buttons(&self) -> Buttons {
self.core.buttons
}
fn sent_crosshair(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
*self.crosshair.get_or_init(|| self.pick_sent())
}
fn pick_sent(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
let s = &self.core.sent;
let v = self.core.opts.caps;
let eye = pick_eye_height(self.world, v, s.sneaking);
let eyes = Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z);
let mut list = PickList::default();
list.fill(self.world, v, eyes);
let t = self.world.crosshair_target(&PickQuery {
eyes,
rotation: (s.yaw, s.pitch),
look: hands::look_vector(s.yaw, s.pitch),
held: None,
now: false,
creative: self.core.game_mode == GameMode::Creative,
player_bb: pick_box(s.pos),
entities: &list.entities,
});
list.split(t, eyes)
}
#[must_use]
pub fn target(&self) -> Option<BlockHit> {
self.sent_crosshair().0
}
#[must_use]
pub fn entities(&self) -> Option<&ghast_entity::Entities> {
self.world.entities()
}
#[must_use]
pub fn target_entity(&self) -> Option<hands::EntityHit> {
self.sent_crosshair().1
}
#[must_use]
pub fn press_preview(&self, button: hands::Button) -> hands::PressOutcome {
use hands::PressOutcome;
let c = &*self.core;
let caps = c.opts.caps;
let eye = pick_eye_height(self.world, caps, c.pose.sneaking);
let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
let mut list = PickList::default();
list.fill(self.world, caps, eyes);
let (mut yaw, pitch) = self.planned_look();
if c.opts.caps.pick_head_yaw
&& let Some(y) = c.head_yaw
{
yaw = y;
}
let t = self.world.crosshair_target(&PickQuery {
eyes,
rotation: (yaw, pitch),
look: hands::look_vector(yaw, pitch),
held: c.inv.held().and_then(|s| u16::try_from(s.id()).ok()),
now: true,
creative: c.game_mode == GameMode::Creative,
player_bb: pick_box(c.pose.pos),
entities: &list.entities,
});
match list.split(t, eyes) {
(_, Some(e)) => return PressOutcome::Entity(e),
(Some(hit), None)
if !c.broken_now.contains(&hit.pos)
&& self
.world
.block_query(hit.pos.x, hit.pos.y, hit.pos.z)
.is_some_and(|b| !b.air) =>
{
return PressOutcome::Block(hit);
}
_ => {}
}
let has_item = c.inv.held().is_some() || (caps.combat_1_9 && c.inv.offhand().is_some());
match button {
hands::Button::Right if has_item && c.game_mode != GameMode::Spectator => {
PressOutcome::Item
}
_ => PressOutcome::Nothing,
}
}
pub fn attack(&mut self, entity: i32) -> bool {
if self.core.dead || self.target_entity().is_none_or(|e| e.id != entity) {
return false;
}
let world = self.world;
let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
world.place_suppressed(p, f, id)
};
let c = &mut *self.core;
let modern = c.opts.caps.combat_1_9;
let mut placed = false;
let rules =
|p: ghast_protocol::BlockPos, f: crate::common::Face, cursor: [f32; 3], off: bool| {
world.place_rules(&crate::sim::predict::PlaceQuery {
pos: p,
face: f,
cursor,
held: if off { c.inv.offhand() } else { c.inv.held() },
sneaking: c.pose.sneaking,
any_item: c.inv.held().is_some() || c.inv.offhand().is_some(),
game_mode: c.game_mode,
yaw: c.pose.yaw,
})
};
let mut io = HandsIo {
blocks: &blocks,
target: None,
held: self.held,
held_stack: None,
food: use_food_level(c),
modern,
off_held: None,
off_stack: None,
entity: None,
factors: DigFactors::default(),
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
creative: c.game_mode == GameMode::Creative,
creative_dig: c.game_mode == GameMode::Creative && c.opts.caps.creative_instant_dig,
place_blocked: &blocked,
place_rules: &rules,
};
if !modern {
io.out.push(Outbound::Swing);
}
c.hands.attack(entity, &mut io);
if modern {
c.out.push(Outbound::Swing);
}
true
}
#[must_use]
pub fn attack_strength(&self, attack_speed: f64) -> f32 {
if self.core.opts.caps.combat_1_9 {
self.core.hands.attack_strength(attack_speed)
} else {
1.0
}
}
#[must_use]
pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
self.core.hands.mining()
}
#[must_use]
pub fn broken(&self) -> u64 {
self.core.hands.broken
}
#[must_use]
pub fn using_item(&self) -> bool {
self.core.hands.using_item()
}
#[must_use]
pub fn prediction_sequence(&self) -> Option<i32> {
self.core.sequence
}
#[must_use]
pub fn vehicle(&self) -> Option<crate::common::Vehicle> {
self.world.vehicle()
}
#[must_use]
pub fn is_riding(&self) -> bool {
self.world.vehicle().is_some()
}
#[must_use]
pub fn is_gliding(&self) -> bool {
self.world.gliding()
}
pub fn start_gliding(&mut self) {
self.core.controls.jump = true;
}
#[must_use]
pub fn item_facts(&self, stack: &ghast_inventory::Stack) -> Option<hands::HeldItem> {
let id = u16::try_from(stack.id()).ok()?;
let count = u8::try_from(stack.count().clamp(0, 255)).unwrap_or(0);
Some(crate::sim::held_item_facts(
self.core.opts.caps.data,
id,
count,
efficiency(stack),
))
}
#[must_use]
pub fn dig_speed(
&self,
pos: ghast_protocol::BlockPos,
stack: Option<&ghast_inventory::Stack>,
) -> Option<f32> {
let b = self.world.block_query(pos.x, pos.y, pos.z)?;
if b.air {
return Some(0.0);
}
let c = &*self.core;
let eyes = self.eyes(&c.pose);
let in_water = self
.world
.block_query(
eyes.x.floor() as i32,
eyes.y.floor() as i32,
eyes.z.floor() as i32,
)
.is_some_and(|b| b.water);
let held = stack.and_then(|s| self.item_facts(s));
let factors = 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)),
};
Some(hands::relative_hardness(&b, held.as_ref(), factors))
}
pub fn dig(&mut self, pos: ghast_protocol::BlockPos, face: crate::common::Face) -> bool {
if self.core.dead
|| !self
.target()
.is_some_and(|t| t.pos == pos && t.face == face)
{
return false;
}
let world = self.world;
let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
world.place_suppressed(p, f, id)
};
let c = &mut *self.core;
let mut placed = false;
let rules =
|p: ghast_protocol::BlockPos, f: crate::common::Face, cursor: [f32; 3], off: bool| {
world.place_rules(&crate::sim::predict::PlaceQuery {
pos: p,
face: f,
cursor,
held: if off { c.inv.offhand() } else { c.inv.held() },
sneaking: c.pose.sneaking,
any_item: c.inv.held().is_some() || c.inv.offhand().is_some(),
game_mode: c.game_mode,
yaw: c.pose.yaw,
})
};
let mut io = HandsIo {
blocks: &blocks,
target: None,
held: self.held,
held_stack: c.inv.held().cloned(),
food: use_food_level(c),
modern: c.opts.caps.combat_1_9,
off_held: None,
off_stack: None,
entity: None,
factors: DigFactors {
on_ground: c.pose.on_ground,
in_water: false,
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)),
},
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
creative: c.game_mode == GameMode::Creative,
creative_dig: c.game_mode == GameMode::Creative && c.opts.caps.creative_instant_dig,
place_blocked: &blocked,
place_rules: &rules,
};
c.hands.click_block(pos, face, &mut io);
c.out.push(Outbound::Swing);
true
}
pub fn place(
&mut self,
support: ghast_protocol::BlockPos,
face: crate::common::Face,
hit: Vec3,
) -> bool {
if self.core.dead {
return false;
}
let Some(t) = self.target().filter(|t| t.pos == support && t.face == face) else {
return false;
};
let world = self.world;
let Some(b) = world.block_query(support.x, support.y, support.z) else {
return false;
};
let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
world.place_suppressed(p, f, id)
};
let c = &mut *self.core;
let mut placed = false;
let first = c.out.len();
let rules =
|p: ghast_protocol::BlockPos, f: crate::common::Face, cursor: [f32; 3], off: bool| {
world.place_rules(&crate::sim::predict::PlaceQuery {
pos: p,
face: f,
cursor,
held: if off { c.inv.offhand() } else { c.inv.held() },
sneaking: c.pose.sneaking,
any_item: c.inv.held().is_some() || c.inv.offhand().is_some(),
game_mode: c.game_mode,
yaw: c.pose.yaw,
})
};
let mut io = HandsIo {
blocks: &blocks,
target: None,
held: self.held,
held_stack: c.inv.held().cloned(),
food: use_food_level(c),
modern: c.opts.caps.combat_1_9,
off_held: None,
off_stack: None,
entity: None,
factors: DigFactors::default(),
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
creative: c.game_mode == GameMode::Creative,
creative_dig: c.game_mode == GameMode::Creative && c.opts.caps.creative_instant_dig,
place_blocked: &blocked,
place_rules: &rules,
};
c.hands
.right_click_block(BlockHit { hit, ..t }, &b, &mut io);
let _ = placed;
if c.out.len() == first {
return false;
}
predict_planting(c, world, first);
c.out.push(Outbound::Swing);
true
}
#[must_use]
pub fn last_inbound(&self) -> Option<Instant> {
self.core.last_inbound
}
#[must_use]
pub fn planned_look(&self) -> (f32, f32) {
let c = &*self.core;
let now = (c.pose.yaw, c.pose.pitch);
#[cfg(test)]
if let Some(l) = c.forced_look {
return l;
}
if !c.aimed {
return now;
}
let mut r = c.rotation;
let (yaw, pitch) = r.step(c.pose.yaw, c.pose.pitch);
if c.opts.hold_turn_on_action && !post_look_ok(c, self.world, yaw, pitch) {
now
} else {
(yaw, pitch)
}
}
pub fn set_flying(&mut self, flying: bool) {
self.core.want_flying = Some(flying);
}
#[must_use]
pub fn held_turns(&self) -> u64 {
self.core.held_turns
}
pub fn status(&mut self, text: &str) {
if self.core.status != text {
text.clone_into(&mut self.core.status);
log::info!(
"[{}] t{} status: {text}",
self.core.opts.name,
self.core.tick
);
}
}
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_26_1.rs"]
mod tests_26_1;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2"
))]
#[path = "engine_tests_26_2.rs"]
mod tests_26_2;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_actions.rs"]
mod tests_actions;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2"
))]
#[path = "engine_tests_combat.rs"]
mod tests_combat;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2"
))]
#[path = "engine_tests_entities.rs"]
mod tests_entities;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2"
))]
#[path = "engine_tests_self.rs"]
mod tests_self;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2"
))]
#[path = "engine_tests_hands.rs"]
mod tests_hands;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_combat_legacy.rs"]
mod tests_combat_legacy;
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_creative.rs"]
mod tests_creative;
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_pistons_1_8.rs"]
mod tests_pistons_1_8;
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_mounts.rs"]
mod tests_mounts;
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_time.rs"]
mod tests_time;
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_menus.rs"]
mod tests_menus;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_record.rs"]
mod tests_record;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_1_12.rs"]
mod tests_1_12;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_1_8.rs"]
mod tests_1_8;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_1_16_5.rs"]
mod tests_1_16_5;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_predict.rs"]
mod tests_predict;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
mod tests {
use super::*;
use crate::common::Teleport;
use crate::common::{ChatPosition, EntityAction, JoinGame};
use ghast_protocol::RawPacket;
pub(super) fn opts(version: GameVersion) -> CoreOptions {
CoreOptions {
name: "test".into(),
caps: version.caps(),
settings: ClientSettings::default(),
brand: Some("vanilla".into()),
sensitivity: 0.5,
silent_hold: Duration::from_millis(1500),
hold_turn_on_action: true,
accept_required_packs: true,
entity_push: true,
turn_rate: (
crate::rotation::Rotation::MAX_YAW_PER_TICK,
crate::rotation::Rotation::MAX_PITCH_PER_TICK,
),
gui_releases_keys: true,
inventory: match version.instance() {
GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
GameVersion::V1_12_2 => ghast_inventory::Version::V1_12,
GameVersion::V26_1 => ghast_inventory::Version::V26_1,
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => ghast_inventory::Version::V26_2,
_ => ghast_inventory::Version::V1_16_5,
},
}
}
pub(super) fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
let sim: Box<dyn Sim> = match version.instance() {
GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
GameVersion::V1_12_2 => Box::new(crate::sim::Sim12::new()),
GameVersion::V26_1 => Box::new(crate::sim::Sim26::test_overworld()),
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => Box::new(crate::sim::Sim262::test_overworld()),
_ => Box::new(crate::sim::Sim16::new()),
};
Engine::new(opts(version), sim)
}
pub(super) fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
let raw = match e.core.opts.caps.version.instance() {
GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
GameVersion::V1_12_2 => crate::sim::test_chunks::v1_12_2(x, z),
GameVersion::V26_1 => crate::sim::test_chunks::v26_1(x, z),
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => crate::sim::test_chunks::v26_2(x, z),
_ => crate::sim::test_chunks::v1_16_5(x, z),
};
e.sim.world_packet(&raw).unwrap();
}
pub(super) fn join(e: &mut Engine<Box<dyn Sim>>) {
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 7,
game_mode: GameMode::Survival,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
for x in -1..=1 {
for z in -1..=1 {
load(e, x, z);
}
}
e.handle(Inbound::Teleport(Teleport {
x: 8.5,
y: 64.0,
z: 8.5,
yaw: 90.0,
pitch: 0.0,
flags: 0,
teleport_id: None,
..Default::default()
}));
e.handle(Inbound::GameState {
reason: 13,
value: 0.0,
});
e.core.near_loaded = 1;
e.outbound().clear();
}
pub(super) fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
let v = out
.iter()
.map(|o| match o {
Outbound::Move(m) => m.trace_id(),
Outbound::Chat(_) => "chat",
Outbound::HeldSlot(_) => "held_slot",
Outbound::Swing => "swing",
Outbound::EntityAction { .. } => "entity_action",
Outbound::KeepAlive(_) => "keep_alive",
Outbound::Transaction { .. } => "transaction",
Outbound::TeleportConfirm(_) => "teleport_confirm",
Outbound::Respawn => "respawn",
Outbound::Settings(_) => "settings",
Outbound::Brand(_) => "brand",
Outbound::Abilities { .. } => "abilities",
Outbound::Dig { .. } => "block_dig",
Outbound::Place { .. }
| Outbound::PlaceInside { .. }
| Outbound::UseItem { .. } => "block_place",
Outbound::SwingOffHand => "swing_off",
Outbound::UseEntity { .. } => "use_entity",
Outbound::Inventory(_) => "inventory",
Outbound::PlayerInput(_) => "player_input",
Outbound::TickEnd => "tick_end",
Outbound::PlayerLoaded => "player_loaded",
Outbound::ChatSessionUpdate => "chat_session_update",
Outbound::ChunkBatchReceived(_) => "chunk_batch_received",
Outbound::Pong(_) => "pong",
Outbound::ResourcePackStatus { .. } => "resource_pack",
Outbound::CookieResponse { .. } => "cookie_response",
Outbound::LookAnswer { .. } => "C05",
Outbound::VehicleMove { .. } => "vehicle_move",
Outbound::SteerBoat { .. } => "steer_boat",
Outbound::SteerVehicle { .. } => "steer_vehicle",
Outbound::CustomClickAction { .. } => "custom_click_action",
Outbound::DialogCommand(_) => "chat_command",
Outbound::Raw(_) => "raw",
})
.collect();
out.clear();
v
}
pub(super) struct Script<F: FnMut(&mut TickContext<'_>)>(pub(super) F);
impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
(self.0)(ctx);
}
}
#[test]
fn join_sends_settings_then_brand() {
let mut e = engine(GameVersion::V1_8_9);
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 1,
game_mode: GameMode::Creative,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
assert_eq!(names(e.outbound()), ["settings", "brand"]);
}
#[test]
fn nothing_before_the_first_teleport() {
let mut e = engine(GameVersion::V1_8_9);
let mut b = Idle;
let t0 = Instant::now();
load(&mut e, 0, 0);
e.outbound().clear();
for i in 0..5 {
e.tick(&mut b, t0 + Duration::from_millis(50 * i));
}
assert!(e.outbound().is_empty());
}
#[test]
fn teleport_reply_per_version() {
let mut e = engine(GameVersion::V1_16_5);
e.handle(Inbound::Teleport(Teleport {
x: 1.0,
y: 2.0,
z: 3.0,
yaw: 450.0,
pitch: 100.0,
flags: 0,
teleport_id: Some(5),
..Default::default()
}));
let out = std::mem::take(e.outbound());
assert_eq!(out[0], Outbound::TeleportConfirm(5));
match out[1] {
Outbound::Move(MovePacket::PositionLook {
yaw,
pitch,
on_ground,
..
}) => {
assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
}
ref o => panic!("unexpected {o:?}"),
}
let mut e = engine(GameVersion::V1_8_9);
e.handle(Inbound::Teleport(Teleport {
x: 1.0,
y: 2.0,
z: 3.0,
yaw: 450.0,
pitch: 100.0,
flags: 0,
teleport_id: None,
..Default::default()
}));
let out = std::mem::take(e.outbound());
assert_eq!(out.len(), 1);
assert!(matches!(
out[0],
Outbound::Move(MovePacket::PositionLook {
yaw: 90.0,
pitch: 100.0,
..
})
));
}
#[test]
fn entity_pick_uses_the_tracker_and_the_proven_pick() {
use ghast_protocol::v1_8::play::clientbound::id;
use std::cell::Cell;
let raw = |id: i32, b: Vec<u8>| RawPacket {
id,
body: bytes::Bytes::from(b),
};
let zombie = |eid: u8, x: f64| {
let mut b = vec![eid, 54];
for v in [x, 64.0, 8.5] {
b.extend(((v * 32.0) as i32).to_be_bytes());
}
b.extend([0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f]);
raw(id::SPAWN_ENTITY_LIVING, b)
};
let mut e = engine(GameVersion::V1_8_9);
let mut login = 7i32.to_be_bytes().to_vec();
login.extend([0, 0, 2, 20, 7]);
login.extend(b"default");
login.push(0);
e.sim.world_packet(&raw(id::LOGIN, login)).unwrap();
e.sim.set_entities(Some(ghast_entity::Config::default()));
join(&mut e);
let pos: i64 = (4 << 38) | (65 << 26) | 8;
let mut b = pos.to_be_bytes().to_vec();
b.push(1 << 4);
e.sim.world_packet(&raw(id::BLOCK_CHANGE, b)).unwrap();
let t0 = Instant::now();
e.note_inbound(t0);
let seen = Cell::new((None, None));
let look = |e: &mut Engine<Box<dyn Sim>>| {
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.set((
ctx.target_entity().map(|h| (h.id, h.distance)),
ctx.target().map(|t| (t.pos, t.face)),
));
});
e.tick(&mut b, t0);
seen.get()
};
assert_eq!(
look(&mut e),
(
None,
Some((ghast_protocol::BlockPos::new(4, 65, 8), crate::Face::East))
)
);
e.sim.world_packet(&zombie(50, 6.5)).unwrap();
let (ent, block) = look(&mut e);
let (eid, d) = ent.unwrap();
assert_eq!(eid, 50);
assert!((d - 1.6).abs() < 1e-6, "{d}");
assert_eq!(block, None);
e.sim
.world_packet(&raw(id::ENTITY_DESTROY, vec![1, 50]))
.unwrap();
e.sim.world_packet(&zombie(51, 5.0)).unwrap();
assert_eq!(look(&mut e), (None, None));
}
#[test]
fn actions_precede_the_single_movement_packet() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 2 {
ctx.select_slot(3);
ctx.chat("hello");
ctx.swing();
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
}
});
e.tick(&mut b, t0);
assert_eq!(names(e.outbound()), ["C06"]);
e.tick(&mut b, t0);
assert_eq!(
names(e.outbound()),
["held_slot", "chat", "swing", "entity_action", "C03"]
);
for _ in 0..100 {
e.tick(&mut b, t0);
let n = names(e.outbound());
assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
}
}
#[test]
fn raw_packets_keep_the_call_order() {
use crate::version::ClientVersion;
for v in [GameVersion::V1_8_9, GameVersion::V26_1] {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut refused = None;
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 3 {
ctx.swing();
ctx.send_raw(0x7f, vec![1, 2, 3]);
ctx.send_packet(&ghast_protocol::v26_1::play::serverbound::ArmAnimation {
hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
})
.unwrap();
refused = Some(ctx.send_packet(
&ghast_protocol::v26_1::play::clientbound::KeepAlive { keep_alive_id: 1 },
));
ctx.chat("after");
}
});
for _ in 0..2 {
e.tick(&mut b, t0);
}
e.outbound().clear();
e.tick(&mut b, t0);
let out = e.outbound().clone();
let n = names(e.outbound());
assert_eq!(n[..4], ["swing", "raw", "raw", "chat"], "{v:?} {n:?}");
let movement = n.iter().position(|x| {
x.starts_with('C') || x.contains("position") || *x == "flying" || *x == "look"
});
assert!(movement.is_none_or(|m| m > 3), "{v:?} {n:?}");
assert!(refused.unwrap().is_err());
let typed = ghast_protocol::v26_1::play::serverbound::ArmAnimation {
hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
};
let mut want = ghast_protocol::FrameEncoder::new();
want.write_packet(&typed).unwrap();
let mut got = ghast_protocol::FrameEncoder::new();
let mut wire = crate::version::Wire26_1::default();
crate::version::V26_1::write_play(&mut got, &out[2], &mut wire).unwrap();
assert_eq!(got.take(), want.take());
}
}
#[test]
fn standing_bot_packets() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let mut b = Idle;
let t0 = Instant::now();
e.note_inbound(t0);
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert!(matches!(
out[..],
[Outbound::Move(MovePacket::PositionLook {
on_ground: false,
..
})]
));
let mut kinds = Vec::new();
for _ in 0..42 {
e.tick(&mut b, t0);
kinds.extend(names(e.outbound()));
}
assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
assert!(e.core.sent.on_ground);
}
#[test]
fn silent_server_freezes_behaviour() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut ticks = 0;
let mut b = Script(|ctx: &mut TickContext<'_>| {
ticks += 1;
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
});
e.tick(&mut b, t0 + Duration::from_millis(100));
e.tick(&mut b, t0 + Duration::from_millis(1600));
let n = names(e.outbound());
assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
e.note_inbound(t0 + Duration::from_millis(1700));
e.tick(&mut b, t0 + Duration::from_millis(1700));
let _ = b;
assert_eq!(ticks, 2);
}
#[test]
fn keepalive_answered_transactions_left_to_the_inventory() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
e.handle(Inbound::KeepAlive(42));
e.handle(Inbound::Transaction {
window_id: 0,
action: -5,
accepted: false,
});
assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
}
#[test]
fn panicking_behaviour_does_not_stop_the_tick() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 2 {
panic!("boom");
}
});
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
for _ in 0..5 {
e.tick(&mut b, t0);
}
std::panic::set_hook(hook);
assert!(e.state.failed);
assert_eq!(names(e.outbound()).len(), 5);
}
#[test]
fn chat_events_reach_the_behaviour_once() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
e.handle(Inbound::Chat(ChatMessage {
rendered: None,
json: r#"{"text":"hi"}"#.into(),
position: ChatPosition::System,
sender: None,
}));
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
});
let t0 = Instant::now();
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
assert_eq!(seen, ["hi"]);
}
#[test]
fn joining_dead_respawns_like_vanilla() {
let mut versions = vec![
(GameVersion::V1_8_9, false),
(GameVersion::V1_12_2, false),
(GameVersion::V1_16_5, true),
(GameVersion::V26_1, true),
];
#[cfg(feature = "v26_2")]
versions.push((GameVersion::V26_2, true));
for (v, rule) in versions {
for immediate in [false, true] {
let mut e = engine(v);
join(&mut e);
if rule {
e.handle(Inbound::GameState {
reason: 11,
value: if immediate { 1.0 } else { 0.0 },
});
}
e.handle(Inbound::Health(crate::common::Health {
health: 0.0,
food: 20,
saturation: 5.0,
..crate::common::Health::default()
}));
let t0 = Instant::now();
e.note_inbound(t0);
let mut died = false;
let mut b = Script(|ctx: &mut TickContext<'_>| died |= ctx.events().died);
let mut respawns = 0;
for _ in 0..3 {
e.tick(&mut b, t0);
respawns += e
.outbound()
.iter()
.filter(|o| matches!(o, Outbound::Respawn))
.count();
e.outbound().clear();
}
let _ = b;
assert!(died, "{v:?}");
let want = if rule && immediate { 3 } else { 0 };
assert_eq!(respawns, want, "{v:?} immediate {immediate}");
}
}
}
#[test]
fn immediate_respawn_1_16() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
e.handle(Inbound::GameState {
reason: 11,
value: 1.0,
});
e.handle(Inbound::Died { entity_id: 7 });
assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
}
#[test]
fn dig_with_the_left_button() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
let down = ctx.target().is_some_and(|t| {
t.pos == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
});
ctx.set_buttons(Buttons {
left: down,
right: false,
});
});
let mut ticks = Vec::new();
for _ in 0..200 {
e.tick(&mut b, t0);
let n = names(e.outbound());
assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
ticks.push(n);
}
let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
assert_eq!(
flat.iter().filter(|x| **x == "block_dig").count(),
2,
"start + finish"
);
assert!(e.core.hands.broken == 1);
let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
let finish = ticks
.iter()
.rposition(|t| t.contains(&"block_dig"))
.unwrap();
assert_eq!(finish - start, 150);
assert!(e.sim.block_query(8, 63, 8).unwrap().air);
assert!(
e.core.pose.pos.y < 64.0,
"falls into the hole: {:?}",
e.core.pose.pos
);
}
#[test]
fn outbound_visible_to_the_behaviour() {
use crate::version::ClientVersion;
struct Watch {
seen: Vec<Vec<Outbound>>,
seq: Vec<Option<i32>>,
}
impl Behavior for Watch {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
self.seq.push(ctx.prediction_sequence());
ctx.set_aim(90.0, 89.5);
let down = ctx.target().is_some_and(|t| t.face == crate::Face::Up);
ctx.set_buttons(Buttons {
left: down,
right: false,
});
}
fn after_tick(&mut self, view: &TickView<'_>) {
self.seen.push(view.outbound().to_vec());
assert_eq!(view.prediction_sequence(), *self.seq.last().unwrap());
}
}
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Watch {
seen: Vec::new(),
seq: Vec::new(),
};
for t in 0..20 {
e.note_sequence(Some(t));
e.tick(&mut b, t0);
assert_eq!(*e.outbound(), *b.seen.last().unwrap());
e.outbound().clear();
}
assert_eq!(b.seq.last(), Some(&Some(19)));
let dig = b
.seen
.iter()
.find(|o| o.iter().any(|p| matches!(p, Outbound::Dig { .. })))
.expect("a dig start");
assert!(matches!(
dig.iter()
.find(|p| matches!(p, Outbound::Dig { .. }))
.unwrap(),
Outbound::Dig {
status: crate::common::DigStatus::Start,
face: crate::Face::Up,
..
}
));
assert!(matches!(dig.last(), Some(Outbound::Move(_))));
let mut wire = crate::version::Wire26_1::default();
let mut enc = ghast_protocol::FrameEncoder::new();
let dig = |status| Outbound::Dig {
status,
pos: ghast_protocol::BlockPos::new(1, 2, 3),
face: crate::Face::Up,
};
use crate::common::DigStatus;
assert_eq!(crate::version::V26_1::prediction_sequence(&wire), Some(0));
for (s, want) in [
(DigStatus::Start, 1),
(DigStatus::Abort, 1),
(DigStatus::Start, 2),
(DigStatus::Finish, 3),
] {
crate::version::V26_1::write_play(&mut enc, &dig(s), &mut wire).unwrap();
assert_eq!(
crate::version::V26_1::prediction_sequence(&wire),
Some(want)
);
}
assert_eq!(crate::version::V1_8::prediction_sequence(&()), None);
}
#[test]
fn dig_speed_and_item_facts() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
let id = |n: &str| i32::from(ghast_data::v1_16_5::Item::from_name(n).unwrap().id());
let bread = ctx.item_facts(&ghast_inventory::Stack::new(id("bread"), 3, 0));
assert!(bread.is_some_and(|f| f.food && f.usable && !f.places_block && f.count == 3));
let dirt = ctx.item_facts(&ghast_inventory::Stack::new(id("dirt"), 1, 0));
assert!(dirt.is_some_and(|f| f.places_block && !f.food));
});
e.tick(&mut b, t0);
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
e.note_inbound(t0);
let got = std::cell::Cell::new(None);
let mut b = Script(|ctx: &mut TickContext<'_>| {
let stone = ghast_protocol::BlockPos::new(8, 63, 8);
let pick = ghast_inventory::Stack::new(278, 1, 0);
let facts = ctx.item_facts(&pick).unwrap();
assert!(!facts.places_block && !facts.food);
got.set(Some((
ctx.dig_speed(stone, None),
ctx.dig_speed(stone, Some(&pick)),
ctx.dig_speed(ghast_protocol::BlockPos::new(8, 64, 8), None),
ctx.dig_speed(ghast_protocol::BlockPos::new(500, 63, 8), None),
)));
});
for _ in 0..40 {
e.tick(&mut b, t0);
}
assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
let (hand, pick, air, unloaded) = got.get().expect("ticked");
assert_eq!(hand, Some(1.0 / 1.5 / 100.0));
assert_eq!(pick, Some(8.0 / 1.5 / 30.0));
assert_eq!(air, Some(0.0));
assert_eq!(unloaded, None);
}
#[test]
fn place_needs_the_sent_look() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut results = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
});
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let mut placed_tick = None;
for i in 0..20 {
e.tick(&mut b, t0);
let n = names(e.outbound());
if n.contains(&"block_place") {
assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
placed_tick.get_or_insert(i);
}
}
let _ = b;
let first = results.iter().position(|r| *r).unwrap();
assert!(first > 3, "refused while still turning");
assert_eq!(placed_tick, Some(first));
assert_eq!(e.core.inv.held().map(|s| s.id()), Some(50));
}
#[test]
fn sneak_action_order() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
});
e.tick(&mut b, Instant::now());
let out = std::mem::take(e.outbound());
assert_eq!(
out[0],
Outbound::EntityAction {
entity_id: 7,
action: EntityAction::StartSneaking
}
);
assert!(matches!(out[1], Outbound::Move(_)));
}
#[test]
fn block_updates_per_version() {
use ghast_protocol::BlockPos;
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
e.sim.collect_block_updates(true);
let t0 = Instant::now();
e.note_inbound(t0);
let raws = match v.instance() {
GameVersion::V1_8_9 => {
use ghast_protocol::v1_8::play::clientbound as cb;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 59 << 4 | 7,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_x: 0,
chunk_z: 0,
records: vec![cb::MultiBlockChangeRecords {
horizontal_pos: 5 << 4 | 6,
y: 62,
block_id: 60 << 4 | 7,
}],
})
.unwrap(),
]
}
GameVersion::V1_12_2 => {
use ghast_protocol::v1_12_2::play::clientbound as cb;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 59 << 4 | 7,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_x: 0,
chunk_z: 0,
records: vec![cb::MultiBlockChangeRecords {
horizontal_pos: 5 << 4 | 6,
y: 62,
block_id: 60 << 4 | 7,
}],
})
.unwrap(),
]
}
GameVersion::V26_1 => {
use ghast_protocol::v26_1::play::clientbound as cb;
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: -1,
},
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => {
use ghast_protocol::v26_2::play::clientbound as cb;
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: -1,
},
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
_ => {
use ghast_protocol::v1_16_5::play::clientbound as cb;
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: 0xF_FFFF,
},
not_trust_edges: false,
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
};
for raw in &raws {
e.sim.world_packet(raw).unwrap();
}
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.push(ctx.events().block_updates.clone());
});
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
let want = match v.instance() {
GameVersion::V1_8_9 | GameVersion::V1_12_2 => vec![
(BlockPos::new(3, 63, 4), 59 << 4 | 7),
(BlockPos::new(5, 62, 6), 60 << 4 | 7),
],
_ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
};
assert_eq!(seen, [want, Vec::new()], "{v:?}");
e.sim.collect_block_updates(false);
e.sim.world_packet(&raws[0]).unwrap();
let mut n = usize::MAX;
let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
e.tick(&mut b, t0);
let _ = b;
assert_eq!(n, 0);
}
}
#[test]
fn set_flying_needs_may_fly() {
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.handle(Inbound::Teleport(Teleport {
x: 8.5,
y: 70.0,
z: 8.5,
yaw: 90.0,
pitch: 0.0,
flags: 0,
teleport_id: Some(2),
..Default::default()
}));
e.outbound().clear();
let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
e.tick(&mut b, t0);
assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
assert!(!e.core.pose.flying);
e.handle(Inbound::Abilities(Abilities {
flags: 4,
..Abilities::default()
}));
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert_eq!(
out[0],
Outbound::Abilities {
flags: 6,
flying_speed: 0.05,
walking_speed: 0.1
},
"{v:?}"
);
assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
assert!(e.core.pose.flying && e.core.sent.flying);
e.tick(&mut b, t0);
assert!(!names(e.outbound()).contains(&"abilities"));
let _ = b;
}
}
#[test]
fn v1_12_2_walks_with_physics() {
let mut e = engine(GameVersion::V1_12_2);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut idle = Script(|_: &mut TickContext<'_>| {});
e.tick(&mut idle, t0);
assert!(
!names(e.outbound())
.iter()
.any(|n| matches!(*n, "C04" | "C06"))
);
for _ in 0..5 {
e.tick(&mut idle, t0);
}
e.outbound().clear();
let start = e.core.pose.pos;
assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
let mut walk = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(crate::common::Controls {
forward: true,
..Default::default()
});
});
for _ in 0..10 {
e.tick(&mut walk, t0);
}
let _ = walk;
let moved = names(e.outbound());
assert!(
moved.iter().any(|n| matches!(*n, "C04" | "C06")),
"{moved:?}"
);
assert!(e.core.pose.pos.x < start.x - 0.5, "{:?}", e.core.pose.pos);
assert_eq!(e.core.pose.pos.y, 64.0);
let mut stop = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(crate::common::Controls::default());
});
for _ in 0..30 {
e.tick(&mut stop, t0);
}
e.outbound().clear();
for _ in 0..5 {
e.tick(&mut stop, t0);
}
let _ = (idle, stop);
let still = names(e.outbound());
assert!(still.len() <= 1 && !still.contains(&"C03"), "{still:?}");
}
#[test]
fn finished_behaviour_is_not_ticked() {
struct Three(std::rc::Rc<std::cell::Cell<u32>>);
impl Behavior for Three {
fn tick(&mut self, _ctx: &mut TickContext<'_>) {
self.0.set(self.0.get() + 1);
}
fn running(&self) -> bool {
self.0.get() < 3
}
}
let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
for _ in 0..10 {
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert!(
out.iter().any(|o| matches!(o, Outbound::Move(_))),
"{out:?}"
);
}
assert_eq!(
ticks.get(),
3,
"not ticked after running() == false (through the Box)"
);
}
#[test]
fn turn_held_on_a_place_tick() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut tick = 0;
let mut placed_at = None;
let mut pitches = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
tick += 1;
if placed_at.is_none() {
ctx.set_aim(90.0, 89.5);
if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
placed_at = Some(tick);
ctx.set_aim(90.0, -60.0);
}
} else {
ctx.set_aim(90.0, -60.0);
}
pitches.push(ctx.pose().pitch);
});
for _ in 0..30 {
e.tick(&mut b, t0);
e.outbound().clear();
}
let _ = b;
let p = placed_at.expect("placed");
assert_eq!(e.core.held_turns, 1);
assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
}
#[test]
fn click_ticket_matches_the_confirm() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let mut ticket = None;
let mut n = 0;
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
if n == 1 {
ctx.open_inventory().unwrap();
} else if ticket.is_none() {
ticket = ctx
.click(ghast_inventory::Click::Pickup {
slot: 36,
right: false,
})
.ok();
}
});
for _ in 0..3 {
e.tick(&mut b, t0);
}
let _ = b;
let t = ticket.expect("click sent");
assert_eq!(t.window_id, 0);
assert!(t.matches(&ghast_inventory::ClickResult::new(
0,
t.action,
ghast_inventory::ClickOutcome::Accepted,
)));
}
#[test]
fn planting_uses_the_seed_at_once() {
use ghast_protocol::v1_8::play::clientbound as cb;
for (soil, item, used) in [
(60 << 4 | 7, 295, true),
(1 << 4, 295, false),
(1 << 4, 50, true),
] {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let raw = RawPacket::from_packet(&cb::BlockChange {
location: floor,
r#type: soil,
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
let mut done = false;
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
if !done {
done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
}
});
let mut sent = None;
for _ in 0..20 {
e.tick(&mut b, t0);
for o in e.outbound().drain(..) {
if let Outbound::Place { held, .. } = o {
sent = held.map(|h| h.count());
}
}
}
let _ = b;
assert_eq!(sent, Some(64), "the packet carries the stack before use");
let left = e.core.inv.held().map(|s| s.count());
assert_eq!(
left,
Some(if used { 63 } else { 64 }),
"soil {soil} item {item}"
);
}
}
#[test]
fn planned_look_is_the_next_look() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut n = 0;
let mut placed = false;
let mut plans: Vec<(f32, f32)> = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
if n % 5 == 0 {
} else if !placed {
ctx.set_aim(90.0, 89.5);
if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
placed = true;
ctx.set_aim(90.0, -60.0);
}
} else {
ctx.set_aim(150.0, -60.0);
}
let p = ctx.planned_look();
assert_eq!(p, ctx.planned_look());
plans.push(p);
});
let mut looks = Vec::new();
for _ in 0..40 {
e.tick(&mut b, t0);
e.outbound().clear();
looks.push((e.core.pose.yaw, e.core.pose.pitch));
}
let _ = b;
assert!(placed);
assert_eq!(e.core.test_held_turns(), 1);
assert_eq!(plans, looks);
}
#[test]
fn teleport_event_has_the_sent_pose_before() {
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.extend(ctx.events().teleports.iter().copied());
});
e.tick(&mut b, t0);
let sent = e.core.sent;
let tp = Teleport {
x: 10.5,
y: 64.0,
z: 8.5,
yaw: 30.0,
pitch: 0.0,
flags: crate::common::teleport_flags::YAW,
teleport_id: Some(9),
relative: crate::common::teleport_flags::YAW as u32,
..Default::default()
};
e.handle(Inbound::Teleport(tp));
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
assert_eq!(seen.len(), 2, "{v:?}");
let ev = seen[1];
assert_eq!(ev.teleport, tp);
assert_eq!(ev.sent_before, sent);
assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
}
}
#[test]
fn closed_window_frees_the_buttons() {
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
if v.instance() == GameVersion::V1_16_5 {
use ghast_protocol::v1_16_5::play::clientbound as cb;
let raw = RawPacket::from_packet(&cb::BlockChange {
location: ghast_protocol::BlockPos::new(8, 63, 8),
r#type: 1,
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
}
e.core.inv.on_open_window(
5,
Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
"Vault".into(),
);
e.handle(Inbound::OpenWindow(5));
e.core
.inv
.on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
let mut n = 0;
let mut closed_at = None;
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
ctx.set_aim(90.0, 89.5);
ctx.set_buttons(Buttons {
left: true,
right: false,
});
if n == 15 {
assert!(ctx.inventory().cursor().is_some());
ctx.close_window().unwrap();
assert_eq!(ctx.open_window(), None);
let inv = ctx.inventory();
assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
closed_at = Some(n);
}
});
let mut first_dig = None;
for i in 1..=30 {
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
if first_dig.is_none()
&& out.iter().any(|o| {
matches!(
o,
Outbound::Dig {
status: crate::common::DigStatus::Start,
..
}
)
})
{
first_dig = Some(i);
}
}
let _ = b;
assert_eq!(closed_at, Some(15));
let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
}
}
#[test]
fn swings_count_every_arm_swing() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut n = 0;
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
ctx.set_aim(90.0, 89.5);
if n == 1 {
ctx.swing();
ctx.swing();
}
if n == 20 {
ctx.set_buttons(Buttons {
left: true,
right: false,
});
}
seen.push(ctx.swings());
});
let mut sent = 0u64;
for _ in 0..30 {
e.tick(&mut b, t0);
sent += count_swings(&std::mem::take(e.outbound()));
}
let _ = b;
assert_eq!(seen[0], 2, "this tick's own swings count at once");
assert!(sent > 10, "the held button swings: {sent}");
assert_eq!(*seen.last().unwrap() + 1, sent);
assert_eq!(e.core.swings, sent);
}
#[test]
fn column_view_and_world_config() {
for config in [
None,
Some(
ghast_world::WorldConfig::default()
.with_biomes(true)
.with_light(true),
),
] {
let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
world: config,
..crate::sim::SimOptions::default()
});
let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
join(&mut e);
let w: &dyn WorldView = &e.sim;
let col = w.column(0, 0).expect("loaded");
assert_eq!(u32::from(col.raw(8, 63, 8)), w.raw_block(8, 63, 8).unwrap());
assert_eq!(col.raw(8, 63, 8), 1 << 4);
assert!(w.column(5, 5).is_none());
let light = col.sky_light(8, 63, 8);
assert_eq!(light.is_some(), config.is_some(), "{config:?}");
let biomes = !matches!(col.biomes(), ghast_world::Biomes::None);
assert_eq!(biomes, config.is_some(), "{config:?}");
}
}
#[test]
fn after_tick_sees_the_sent_pose() {
struct Obs {
n: u32,
views: Vec<(u64, Pose, u64)>,
}
impl Behavior for Obs {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
self.n += 1;
ctx.set_aim(150.0, 10.0);
ctx.set_controls(Controls {
forward: true,
..Controls::default()
});
}
fn running(&self) -> bool {
self.n < 5
}
fn after_tick(&mut self, view: &TickView<'_>) {
self.views.push((view.tick(), *view.sent(), view.swings()));
assert!(view.world().is_column_loaded(0, 0));
assert_eq!(view.version(), GameVersion::V1_8_9);
}
}
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Obs {
n: 0,
views: Vec::new(),
};
let mut sent = Vec::new();
for _ in 0..10 {
e.tick(&mut b, t0);
e.outbound().clear();
sent.push(e.core.sent);
}
assert_eq!(b.n, 5);
assert_eq!(b.views.len(), 10, "also after the behaviour finished");
for (i, (_, p, _)) in b.views.iter().enumerate() {
assert_eq!(*p, sent[i]);
}
assert_ne!(
b.views[0].1.yaw, b.views[4].1.yaw,
"the view follows the turn"
);
}
#[test]
fn block_entities_follow_the_world_config() {
use ghast_protocol::v1_8::play::clientbound as cb;
for on in [false, true] {
let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
world: on.then(|| ghast_world::WorldConfig::default().with_block_entities(true)),
..crate::sim::SimOptions::default()
});
assert_eq!(sim.world_packet_ids().contains(&cb::id::UPDATE_SIGN), on);
let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
join(&mut e);
let raw = RawPacket::from_packet(&cb::UpdateSign {
location: ghast_protocol::BlockPos::new(3, 64, 4),
text1: "\"Hello\"".into(),
text2: "\"\"".into(),
text3: "\"\"".into(),
text4: "\"\"".into(),
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
let w: &dyn WorldView = &e.sim;
let be = w.column(0, 0).unwrap().block_entity(3, 64, 4);
assert_eq!(be.is_some(), on, "{be:?}");
}
}
}