mod support;
use std::time::{Duration, Instant};
use ghast::inventory::{Click, ClickError, ClickOutcome};
use ghast::{Behavior, Buttons, ClickRefused, Controls, Interests, TickContext, Vec3};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Walk,
Horse,
Villager,
Boat,
Cart,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
Settle,
Aim,
Use,
WaitWindow,
Trade,
Clicks,
Close,
Done,
}
struct Probe {
mode: Mode,
entities: bool,
step: Step,
wait: u32,
target: Option<i32>,
opened: bool,
awaiting: bool,
clicks: Vec<Click>,
sent: u32,
accepted: u32,
failures: Vec<String>,
started: Instant,
limit: Duration,
reported: bool,
ride_ticks: Option<u32>,
rode: bool,
off_ticks: u32,
cart_yaw: Option<f32>,
yaw: f32,
}
impl Probe {
fn finish(&mut self, ctx: &mut TickContext<'_>) {
if self.reported {
return;
}
self.reported = true;
let p = ctx.pose().pos;
println!("end position {:.4} {:.4} {:.4}", p.x, p.y, p.z);
if self.mode != Mode::Walk {
println!(
"screen opened {}, clicks sent {}, accepted {}, failures {}",
self.opened,
self.sent,
self.accepted,
self.failures.len()
);
for f in &self.failures {
println!(" FAIL {f}");
}
if self.ok() {
println!("PASS");
}
}
ctx.disconnect("probe done");
}
fn ok(&self) -> bool {
if matches!(self.mode, Mode::Boat | Mode::Cart) {
return self.rode && self.failures.is_empty();
}
self.mode == Mode::Walk
|| (self.opened
&& self.failures.is_empty()
&& self.sent > 0
&& self.sent == self.accepted)
}
fn find(ctx: &TickContext<'_>, name: &str) -> Option<(i32, [f64; 6])> {
let ents = ctx.entities()?;
let eyes = ctx.eyes(ctx.pose());
ents.iter()
.filter(|e| type_name(ctx, e) == Some(name))
.filter_map(|e| Some((e.id(), e.bounding_box()?)))
.min_by(|a, b| {
let d = |b: &[f64; 6]| {
let c = [
(b[0] + b[3]) / 2.0,
(b[1] + b[4]) / 2.0,
(b[2] + b[5]) / 2.0,
];
(c[0] - eyes.x).powi(2) + (c[1] - eyes.y).powi(2) + (c[2] - eyes.z).powi(2)
};
d(&a.1).total_cmp(&d(&b.1))
})
}
}
impl Probe {
fn boat(&mut self, ctx: &mut TickContext<'_>) {
let riding = ctx.is_riding();
if riding && self.ride_ticks.is_none() {
self.ride_ticks = Some(0);
self.rode = true;
println!("boarded: {:?}", ctx.vehicle());
}
let Some(t) = self.ride_ticks else {
if self.wait < 40 {
self.wait += 1;
return;
}
if let Some((id, b)) = Self::find_boat(ctx, self.mode == Mode::Cart) {
let eyes = ctx.eyes(ctx.pose());
let near = |lo: f64, hi: f64, v: f64| v.clamp(lo + 0.1, hi - 0.1);
let c = Vec3::new(
near(b[0], b[3], eyes.x),
near(b[1], b[4], eyes.y),
near(b[2], b[5], eyes.z),
);
let (dx, dy, dz) = (c.x - eyes.x, c.y - eyes.y, c.z - eyes.z);
let yaw = (-dx).atan2(dz).to_degrees() as f32;
let mut pitch = -(dy.atan2((dx * dx + dz * dz).sqrt())).to_degrees() as f32;
let (sent, pose) = (*ctx.sent(), ctx.pose());
if sent.yaw != pose.yaw || sent.pitch != pose.pitch {
pitch += 0.5;
}
let cur = pose.yaw;
ctx.set_aim(cur + ghast::rotation::wrap_degrees(yaw - cur), pitch);
let on = ctx.target_entity().is_some_and(|e| e.id == id);
ctx.set_buttons(Buttons {
left: false,
right: on && ctx.tick().is_multiple_of(10),
});
}
return;
};
ctx.set_buttons(Buttons::default());
if !riding {
if self.off_ticks == 0 {
println!("dismounted after {t} ticks at {:?}", ctx.pose().pos);
}
self.off_ticks += 1;
ctx.set_controls(Controls::NONE);
if self.off_ticks > 20 {
self.finish(ctx);
}
return;
}
self.ride_ticks = Some(t + 1);
if self.mode == Mode::Cart {
self.cart(ctx, t);
return;
}
let (forward, left, right, sneak) = match t {
0..20 => (false, false, false, false),
20..80 => (true, false, false, false),
80..110 => (true, true, false, false),
110..150 => (true, false, true, false),
150..230 => (true, false, false, false),
230..260 => (false, false, false, false),
_ => (false, false, false, true),
};
ctx.set_controls(Controls {
forward,
left,
right,
sneak,
..Controls::NONE
});
if t % 20 == 0
&& let Some(v) = ctx.vehicle()
{
let tracked = ctx
.entities()
.and_then(|es| es.get(v.entity_id))
.map(ghast::entity::Entity::position);
log::info!(
"vehicle at {:.3} {:.3} {:.3} yaw {:.1} ground {} tracked {:?}",
v.pos.x,
v.pos.y,
v.pos.z,
v.yaw,
v.on_ground,
tracked
);
}
if t > 400 {
self.failures
.push("not dismounted after 140 sneaking ticks".into());
self.finish(ctx);
}
}
fn cart(&mut self, ctx: &mut TickContext<'_>, t: u32) {
let base = *self.cart_yaw.get_or_insert(-90.0);
let look = (60..1200).contains(&t);
if t < 60 {
ctx.set_aim(base, 10.0);
} else if look {
let f = t as f32;
ctx.set_aim(
base + 70.0 * (f / 40.0).sin(),
15.0 + 25.0 * (f / 27.0).sin(),
);
}
ctx.set_controls(Controls {
forward: (20..60).contains(&t),
jump: look && t % 100 < 4,
sprint: (300..340).contains(&t),
sneak: t >= 1200,
..Controls::NONE
});
if t.is_multiple_of(20)
&& let Some(v) = ctx.vehicle()
{
let tracked = ctx
.entities()
.and_then(|es| es.get(v.entity_id))
.map(ghast::entity::Entity::position);
log::info!(
"cart at {:.3} {:.3} {:.3} yaw {:.1}; seat sent {:.3} {:.3} {:.3}; tracked {:?}",
v.pos.x,
v.pos.y,
v.pos.z,
v.yaw,
ctx.sent().pos.x,
ctx.sent().pos.y,
ctx.sent().pos.z,
tracked
);
}
if t > 1400 {
self.failures
.push("not dismounted after 200 sneaking ticks".into());
self.finish(ctx);
}
}
fn find_boat(ctx: &TickContext<'_>, cart: bool) -> Option<(i32, [f64; 6])> {
let ents = ctx.entities()?;
ents.iter()
.filter(|e| {
type_name(ctx, e).is_some_and(|t| {
if cart {
t == "minecart"
} else {
t == "boat" || t.ends_with("_boat") || t.ends_with("_raft")
}
})
})
.filter_map(|e| Some((e.id(), e.bounding_box()?)))
.next()
}
}
impl Behavior for Probe {
fn name(&self) -> &str {
"entity-probe"
}
fn interests(&self) -> Interests {
if self.entities || matches!(self.mode, Mode::Horse | Mode::Villager) {
Interests::ENTITIES | Interests::PLAYER_LIST | Interests::CHAT
} else {
Interests::CHAT
}
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
for m in &ctx.events().chat {
let line = m.plain();
if line.contains("Grim") || line.contains("failed") {
log::warn!("ALERT {line}");
}
}
if ctx.is_dead() {
ctx.respawn();
return;
}
if self.started.elapsed() >= self.limit {
if self.mode != Mode::Walk {
self.failures.push(format!("timed out at {:?}", self.step));
}
self.finish(ctx);
return;
}
let ev = ctx.events().inventory.clone();
for c in &ev.clicks {
self.awaiting = false;
match c.outcome {
ClickOutcome::Accepted => self.accepted += 1,
o => self.failures.push(format!(
"action {} in window {}: {o:?}",
c.action, c.window_id
)),
}
}
if ev.opened.is_some() {
self.opened = true;
}
if matches!(self.mode, Mode::Boat | Mode::Cart) {
self.boat(ctx);
return;
}
if self.mode == Mode::Walk {
if self.wait < 40 {
self.wait += 1;
return;
}
ctx.set_aim(self.yaw, 0.0);
ctx.set_controls(Controls {
forward: true,
..Controls::NONE
});
if ctx.tick().is_multiple_of(20) {
let p = ctx.pose().pos;
log::info!("at {:.3} {:.3} {:.3}", p.x, p.y, p.z);
}
return;
}
if self.wait > 0 {
self.wait -= 1;
return;
}
match self.step {
Step::Settle => {
self.wait = 40;
self.step = Step::Aim;
}
Step::Aim => {
let name = if self.mode == Mode::Horse {
"horse"
} else {
"villager"
};
let Some((id, b)) = Self::find(ctx, name) else {
return;
};
self.target = Some(id);
let eyes = ctx.eyes(ctx.pose());
let c = Vec3::new(
(b[0] + b[3]) / 2.0,
(b[1] + b[4]) / 2.0,
(b[2] + b[5]) / 2.0,
);
let (dx, dy, dz) = (c.x - eyes.x, c.y - eyes.y, c.z - eyes.z);
let yaw = (-dx).atan2(dz).to_degrees() as f32;
let mut pitch = -(dy.atan2((dx * dx + dz * dz).sqrt())).to_degrees() as f32;
let (sent, pose) = (*ctx.sent(), ctx.pose());
if sent.yaw != pose.yaw || sent.pitch != pose.pitch {
pitch += 0.5;
}
let cur = pose.yaw;
ctx.set_aim(cur + ghast::rotation::wrap_degrees(yaw - cur), pitch);
ctx.set_controls(Controls {
sneak: self.mode == Mode::Horse,
..Controls::NONE
});
if ctx.target_entity().is_some_and(|e| e.id == id) {
self.wait = 3;
self.step = Step::Use;
}
}
Step::Use => {
if ctx
.target_entity()
.is_none_or(|e| Some(e.id) != self.target)
{
self.step = Step::Aim;
return;
}
ctx.set_buttons(Buttons {
left: false,
right: true,
});
self.step = Step::WaitWindow;
}
Step::WaitWindow => {
ctx.set_buttons(Buttons::default());
ctx.set_controls(Controls::NONE);
if self.opened && !ctx.inventory().resyncing() {
let n = ctx.inventory().container_len();
println!(
"screen open: window {:?}, {n} container slots",
ctx.open_window()
);
self.wait = 10;
self.step = if self.mode == Mode::Villager {
Step::Trade
} else {
self.clicks = vec![Click::QuickMove {
slot: 0,
right: false,
}];
Step::Clicks
};
}
}
Step::Trade => match ctx.select_trade(0) {
Ok(()) => {
println!("trade 0 selected");
self.wait = 10;
self.clicks = vec![Click::QuickMove {
slot: 2,
right: false,
}];
self.step = Step::Clicks;
}
Err(ClickRefused::Turning) => {}
Err(e) => {
self.failures.push(format!("select_trade refused: {e}"));
self.step = Step::Close;
}
},
Step::Clicks => {
if self.awaiting {
return;
}
if self.clicks.is_empty() {
if self.mode == Mode::Horse && self.sent == 1 {
let inv = ctx.inventory();
let n = inv.container_len();
let id = ghast::inventory::modern::item_id(inv.version(), "saddle");
let saddle = (n..inv.slot_count())
.find(|&i| inv.slot(i).is_some_and(|s| Some(s.id()) == id));
match saddle {
Some(i) => self.clicks.push(Click::QuickMove {
slot: i as i16,
right: false,
}),
None => self.failures.push("saddle not in the inventory".into()),
}
if !self.clicks.is_empty() {
return;
}
}
self.wait = 10;
self.step = Step::Close;
return;
}
let c = self.clicks[0];
match ctx.click(c) {
Ok(_) => {
println!(" click {c:?}");
self.clicks.remove(0);
self.sent += 1;
self.awaiting = true;
}
Err(
ClickRefused::Turning
| ClickRefused::Inventory(
ClickError::Pending | ClickError::SameTick | ClickError::Resyncing,
),
) => {}
Err(e) => {
self.failures.push(format!("{c:?} refused: {e}"));
self.clicks.clear();
}
}
}
Step::Close => {
if ctx.close_window().is_ok() {
self.wait = 20;
self.step = Step::Done;
}
}
Step::Done => self.finish(ctx),
}
}
}
fn main() {
let opts = support::Options::parse();
support::init_logger(opts.verbose);
let mode = match std::env::var("GHAST_PROBE").as_deref() {
Ok("horse") => Mode::Horse,
Ok("villager") => Mode::Villager,
Ok("boat") => Mode::Boat,
Ok("cart") => Mode::Cart,
Ok("walk") | Err(_) => Mode::Walk,
Ok(other) => {
eprintln!("GHAST_PROBE: walk | horse | villager | boat | cart, not {other}");
std::process::exit(2);
}
};
let limit = Duration::from_secs_f64(opts.minutes.unwrap_or(1.0) * 60.0);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("tokio runtime");
rt.block_on(async {
let client = match opts.client() {
Ok(c) => c,
Err(e) => {
log::error!("{e}");
std::process::exit(2);
}
};
let mut probe = Probe {
mode,
entities: opts.entities,
step: Step::Settle,
wait: 0,
target: None,
opened: false,
awaiting: false,
clicks: Vec::new(),
sent: 0,
accepted: 0,
failures: Vec::new(),
started: Instant::now(),
limit,
reported: false,
ride_ticks: None,
rode: false,
off_ticks: 0,
cart_yaw: None,
yaw: std::env::var("GHAST_YAW")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.0),
};
let end = client.run(&mut probe).await;
log::info!("session ended: {end:?}");
std::process::exit(if probe.ok() { 0 } else { 1 });
});
}
fn type_name(ctx: &TickContext<'_>, e: &ghast::entity::Entity) -> Option<&'static str> {
match ctx.version() {
#[cfg(feature = "v26_2")]
ghast::GameVersion::V26_2 => ghast::entity::v26_2::entity_type(e).map(|t| t.name),
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
ghast::GameVersion::V1_8_9 | ghast::GameVersion::V1_12_2 => match e.entity_type() {
ghast::entity::EntityType::LegacyObject(1) => Some("boat"),
ghast::entity::EntityType::LegacyObject(10) => Some("minecart"),
_ => None,
},
#[cfg(feature = "v1_16_5")]
ghast::GameVersion::V1_16_5 => match e.entity_type() {
ghast::entity::EntityType::Registry(id) => {
ghast::data::v1_16_5::entity(ghast::data::EntityKind::Mob, id).map(|t| t.name)
}
_ => None,
},
_ => ghast::entity::v26_1::entity_type(e).map(|t| t.name),
}
}