mod support;
use std::time::{Duration, Instant};
use ghast::{Behavior, Buttons, Controls, Interests, TickContext, Vec3};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
Attack,
Victim,
Miss,
Equip,
Use,
Inventory,
Clicks,
}
fn env(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|v| !v.is_empty())
}
struct Probe {
mode: Mode,
players: bool,
sprint: bool,
retreat: f64,
hold: u64,
n: u64,
approaching: bool,
state_ticks: u64,
attacks: u32,
sprint_attacks: u32,
after_attack: Option<(u64, bool, Vec3)>,
hurts: u32,
last_hurt: Option<u64>,
presses: u32,
gap_index: usize,
held_press: Option<u64>,
next_press: u64,
equip_slot: u8,
pending_equip: Option<(u64, u8, [Option<i32>; 5])>,
corrections: u32,
equips: u32,
was_using: bool,
release_ticks: u8,
uses: u32,
opened_at: Option<u64>,
opens: u32,
clicks: u32,
refusals: u32,
cps: f64,
click_budget: f64,
sent_attacks: u32,
sent_swings: u32,
alerts: u32,
setbacks: u32,
started: Instant,
limit: Option<Duration>,
}
const GAPS: [u64; 7] = [2, 4, 6, 8, 10, 12, 15];
impl Probe {
fn new(limit: Option<Duration>) -> Probe {
let mode = match env("PROBE").as_deref() {
None | Some("attack") => Mode::Attack,
Some("victim") => Mode::Victim,
Some("miss") => Mode::Miss,
Some("equip") => Mode::Equip,
Some("use") => Mode::Use,
Some("inventory") => Mode::Inventory,
Some("clicks") => Mode::Clicks,
Some(m) => {
log::error!("unknown PROBE {m}");
std::process::exit(2);
}
};
Probe {
mode,
players: env("TARGET").as_deref() == Some("player"),
sprint: env("SPRINT").as_deref() == Some("1"),
retreat: env("RETREAT").and_then(|v| v.parse().ok()).unwrap_or(4.5),
hold: env("HOLD").and_then(|v| v.parse().ok()).unwrap_or(40),
n: 0,
approaching: true,
state_ticks: 0,
attacks: 0,
sprint_attacks: 0,
after_attack: None,
hurts: 0,
last_hurt: None,
presses: 0,
gap_index: 0,
held_press: None,
next_press: 0,
equip_slot: 0,
pending_equip: None,
corrections: 0,
equips: 0,
was_using: false,
release_ticks: 0,
uses: 0,
opened_at: None,
opens: 0,
clicks: 0,
refusals: 0,
cps: env("CPS").and_then(|v| v.parse().ok()).unwrap_or(12.0),
click_budget: 0.0,
sent_attacks: 0,
sent_swings: 0,
alerts: 0,
setbacks: 0,
started: Instant::now(),
limit,
}
}
fn summary(&self) -> String {
format!(
"summary mode {:?}: attacks {} (sprinting {}), hurts {}, presses {}, equips {}, \
corrections {}, uses {}, opens {}, clicks {}, refusals {}, sent attacks {}, \
sent swings {}, alerts {}, setbacks {}",
self.mode,
self.attacks,
self.sprint_attacks,
self.hurts,
self.presses,
self.equips,
self.corrections,
self.uses,
self.opens,
self.clicks,
self.refusals,
self.sent_attacks,
self.sent_swings,
self.alerts,
self.setbacks
)
}
fn look_at(ctx: &TickContext<'_>, b: [f64; 6]) -> (f32, f32, f64) {
let eyes = ctx.eyes(ctx.pose());
let (dx, dy, dz) = (
(b[0] + b[3]) / 2.0 - eyes.x,
(b[1] + b[4]) / 2.0 - eyes.y,
(b[2] + b[5]) / 2.0 - eyes.z,
);
let yaw = (-dx).atan2(dz).to_degrees() as f32;
let pitch = -(dy.atan2((dx * dx + dz * dz).sqrt())).to_degrees() as f32;
let cur = ctx.pose().yaw;
(
cur + ghast::rotation::wrap_degrees(yaw - cur),
pitch,
(dx * dx + dz * dz).sqrt(),
)
}
fn attack(&mut self, ctx: &mut TickContext<'_>) {
if let Some((tick, sprinted, before)) = self.after_attack.take() {
let m = ctx.pose().motion;
log::info!(
"after attack at {tick} (sprinting {sprinted}): motion x/z {:.4} {:.4} -> {:.4} {:.4}, \
sprinting {}, server sprint flag {}, next look {:.4} {:.4}",
before.x,
before.z,
m.x,
m.z,
ctx.pose().sprinting,
ctx.server_sprinting(),
ctx.sent().yaw,
ctx.sent().pitch
);
}
let me = ctx.entity_id();
let eyes = ctx.eyes(ctx.pose());
let players = self.players;
let Some(ents) = ctx.entities() else {
return;
};
let target = ents
.within([eyes.x, eyes.y, eyes.z], 16.0)
.filter(|e| {
e.id() != me
&& e.is_player() == players
&& e.is_alive()
&& !matches!(
e.class(),
ghast::entity::EntityClass::Item
| ghast::entity::EntityClass::ExperienceOrb
)
})
.filter_map(|e| Some((e.id(), e.drawn_bounding_box().or(e.bounding_box())?)))
.min_by(|a, b| {
let d = |x: &[f64; 6]| {
let (cx, cz) = ((x[0] + x[3]) / 2.0 - eyes.x, (x[2] + x[5]) / 2.0 - eyes.z);
cx * cx + cz * cz
};
d(&a.1).total_cmp(&d(&b.1))
});
let Some((id, b)) = target else {
if self.n.is_multiple_of(40) {
log::debug!(
"tick {}: no target among {} entities",
ctx.tick(),
ents.len()
);
for e in ents.iter() {
log::debug!(
" {} {:?} {:?} at {:?} alive {} player {} box {:?}",
e.id(),
e.entity_type(),
e.class(),
e.position(),
e.is_alive(),
e.is_player(),
e.bounding_box()
);
}
}
ctx.set_controls(Controls::NONE);
return;
};
let (yaw, pitch, dist) = Self::look_at(ctx, b);
ctx.set_aim(yaw, pitch);
self.state_ticks += 1;
if self.n.is_multiple_of(20) {
log::debug!(
"tick {}: target {id} at {dist:.2}, approaching {}, crosshair {:?}, pos {:?}",
ctx.tick(),
self.approaching,
ctx.target_entity().map(|e| e.id),
ctx.pose().pos
);
}
if self.approaching {
ctx.set_controls(Controls {
forward: true,
sprint: self.sprint,
..Controls::NONE
});
if let Some(hit) = ctx.target_entity().filter(|e| e.id == id) {
let before = ctx.pose().motion;
let (server, drawn) = ctx
.entities()
.and_then(|t| t.get(id))
.map_or(([0.0; 3], [0.0; 3]), |e| (e.position(), e.drawn_position()));
let eyes = ctx.eyes(ctx.sent());
log::info!(
"hit test: distance {:.5}, eyes {:.5} {:.5} {:.5}, look {:.4} {:.4}, \
target server {:.5?} drawn {:.5?}",
hit.distance,
eyes.x,
eyes.y,
eyes.z,
ctx.sent().yaw,
ctx.sent().pitch,
server,
drawn
);
let sprinting = ctx.pose().sprinting;
if ctx.attack(id) {
self.attacks += 1;
if sprinting {
self.sprint_attacks += 1;
}
log::info!(
"tick {}: attack {} on {id} at {dist:.2}, sprinting {sprinting}",
ctx.tick(),
self.attacks
);
self.after_attack = Some((ctx.tick(), sprinting, before));
self.approaching = false;
self.state_ticks = 0;
}
} else if self.state_ticks > 100 {
self.approaching = false;
self.state_ticks = 0;
}
} else {
ctx.set_controls(Controls {
back: true,
..Controls::NONE
});
if (dist > self.retreat && self.state_ticks >= 12) || self.state_ticks > 60 {
self.approaching = true;
self.state_ticks = 0;
}
}
}
fn nearest(&self, ctx: &TickContext<'_>) -> Option<(i32, [f64; 6])> {
let me = ctx.entity_id();
let eyes = ctx.eyes(ctx.pose());
let players = self.players;
ctx.entities()?
.within([eyes.x, eyes.y, eyes.z], 16.0)
.filter(|e| {
e.id() != me
&& e.is_player() == players
&& e.is_alive()
&& !matches!(
e.class(),
ghast::entity::EntityClass::Item
| ghast::entity::EntityClass::ExperienceOrb
)
})
.filter_map(|e| Some((e.id(), e.drawn_bounding_box().or(e.bounding_box())?)))
.min_by(|a, b| {
let d = |x: &[f64; 6]| {
let (cx, cz) = ((x[0] + x[3]) / 2.0 - eyes.x, (x[2] + x[5]) / 2.0 - eyes.z);
cx * cx + cz * cz
};
d(&a.1).total_cmp(&d(&b.1))
})
}
fn clicks(&mut self, ctx: &mut TickContext<'_>) {
let Some((id, b)) = self.nearest(ctx) else {
ctx.set_controls(Controls::NONE);
return;
};
let (yaw, pitch, dist) = Self::look_at(ctx, b);
let t = self.n as f64;
ctx.set_aim(
yaw + (5.0 * (t * 0.15).sin()) as f32,
pitch + (3.0 * (t * 0.11).cos()) as f32,
);
let left = (self.n / 30).is_multiple_of(2);
ctx.set_controls(Controls {
left,
right: !left,
forward: dist > 3.0,
back: dist < 2.0,
..Controls::NONE
});
self.click_budget += self.cps / 20.0;
while self.click_budget >= 1.0 {
self.click_budget -= 1.0;
if ctx.press(ghast::hands::Button::Left) {
self.presses += 1;
}
}
if self.n.is_multiple_of(100) {
log::info!(
"tick {}: target {id} at {dist:.2}, presses {}, attacks sent {}, swings sent {}",
ctx.tick(),
self.presses,
self.sent_attacks,
self.sent_swings
);
}
}
fn victim(&mut self, ctx: &mut TickContext<'_>) {
let phase = (self.n / 20) % 4;
ctx.set_controls(Controls {
forward: phase == 0,
back: phase == 1,
left: phase == 2,
right: phase == 3,
..Controls::NONE
});
let hurt = ctx.last_hurt_tick();
if hurt.is_some() && hurt != self.last_hurt {
self.hurts += 1;
let v = ctx.velocity();
log::info!(
"tick {}: hurt {} (health {:?}), velocity {:.4} {:.4} {:.4}",
ctx.tick(),
self.hurts,
ctx.health().health,
v.x,
v.y,
v.z
);
}
self.last_hurt = hurt;
}
fn miss(&mut self, ctx: &mut TickContext<'_>) {
let phase = self.n % 160;
ctx.set_controls(Controls {
forward: phase < 100 && (self.n / 160).is_multiple_of(2),
back: phase < 100 && (self.n / 160) % 2 == 1,
..Controls::NONE
});
if phase >= 100 {
let down = (103..140).contains(&phase);
ctx.set_aim(ctx.pose().yaw, if down { 89.0 } else { -89.0 });
let held = (100..140).contains(&phase);
ctx.set_buttons(Buttons {
left: held,
right: false,
});
if phase == 100 {
self.presses += 1;
self.held_press = Some(ctx.tick());
log::info!("tick {}: held press at the sky", ctx.tick());
}
if let Some(at) = self.held_press
&& ctx.mining().is_some()
{
log::info!(
"tick {}: dig started {} ticks after the held miss press",
ctx.tick(),
ctx.tick() - at
);
self.held_press = None;
}
return;
}
ctx.set_aim(ctx.pose().yaw, -89.0);
let press = self.n >= self.next_press;
ctx.set_buttons(Buttons {
left: press,
right: false,
});
if press {
self.presses += 1;
let gap = GAPS[self.gap_index % GAPS.len()];
log::info!(
"tick {}: press {} (gap {gap}), swings so far {}",
ctx.tick(),
self.presses,
ctx.swings()
);
self.gap_index += 1;
self.next_press = self.n + GAPS[self.gap_index % GAPS.len()];
}
}
fn snapshot(ctx: &TickContext<'_>, slot: u8) -> [Option<i32>; 5] {
let inv = ctx.inventory();
let id = |s: Option<&ghast::inventory::Stack>| s.map(|s| s.id());
[
id(inv.armor(0)),
id(inv.armor(1)),
id(inv.armor(2)),
id(inv.armor(3)),
id(inv.hotbar(usize::from(slot))),
]
}
fn equip(&mut self, ctx: &mut TickContext<'_>) {
ctx.set_aim(ctx.pose().yaw, -89.0);
let walk = env("WALK").as_deref() == Some("1");
ctx.set_controls(Controls {
forward: walk && (self.n / 60).is_multiple_of(2),
back: walk && (self.n / 60) % 2 == 1,
..Controls::NONE
});
let phase = self.n % 30;
if let Some((at, slot, predicted)) = self.pending_equip {
if self.n == at + 1 {
let now = Self::snapshot(ctx, slot);
log::info!("slot {slot}: predicted after the press {now:?} (before {predicted:?})");
self.pending_equip = Some((at, slot, now));
} else if self.n == at + 15 {
let now = Self::snapshot(ctx, slot);
if now == predicted {
log::info!("slot {slot}: server agrees {now:?}");
} else {
self.corrections += 1;
log::warn!("slot {slot}: correction, predicted {predicted:?}, now {now:?}");
}
self.pending_equip = None;
}
}
let right = phase == 10 && self.equip_slot < 8;
if phase == 5 && self.equip_slot < 8 {
ctx.select_slot(self.equip_slot);
} else if phase == 5 && self.pending_equip.is_none() {
ctx.select_slot(0);
}
if right {
let slot = self.equip_slot;
self.equips += 1;
log::info!(
"tick {}: right click with slot {slot} {:?}",
ctx.tick(),
Self::snapshot(ctx, slot)
);
self.pending_equip = Some((self.n, slot, Self::snapshot(ctx, slot)));
self.equip_slot += 1;
}
ctx.set_buttons(Buttons { left: false, right });
}
fn use_item(&mut self, ctx: &mut TickContext<'_>) {
ctx.set_aim(ctx.pose().yaw, -89.0);
let cycle = self.hold + 25;
let phase = self.n % cycle;
let mut right = (5..5 + self.hold).contains(&phase);
if env("RELEASE_ON_FINISH").as_deref() == Some("1") {
if ctx
.events()
.item_use()
.iter()
.any(|e| matches!(e, ghast::common::UseEvent::Finished { .. }))
{
self.release_ticks = 1;
}
if self.release_ticks > 0 {
right = false;
self.release_ticks -= 1;
}
}
ctx.set_buttons(Buttons { left: false, right });
ctx.set_controls(Controls {
forward: env("WALK").as_deref() != Some("0"),
sprint: self.sprint,
..Controls::NONE
});
for e in ctx.events().item_use() {
log::info!("tick {}: {e:?}", ctx.tick());
}
if ctx.health().food <= 6 {
ctx.set_controls(Controls::NONE);
}
let using = ctx.using_item();
if using != self.was_using {
if using {
self.uses += 1;
}
log::info!(
"tick {}: using_item {using} (held {:?}, sprinting {}, food {})",
ctx.tick(),
ctx.inventory().held().map(|s| (s.id(), s.count())),
ctx.pose().sprinting,
ctx.health().food
);
self.was_using = using;
}
}
fn inventory(&mut self, ctx: &mut TickContext<'_>) {
let forward = (self.n / 80).is_multiple_of(2);
ctx.set_controls(Controls {
forward,
back: !forward,
sprint: forward,
left: (self.n / 160) % 2 == 1,
..Controls::NONE
});
if env("REPRESS").as_deref() == Some("1")
&& self.opened_at.is_some_and(|at| self.n == at + 2)
{
ctx.set_controls(Controls::NONE);
}
if let Some(at) = self.opened_at
&& (self.n == at + 7 || self.n == at + 19)
{
log::info!(
"tick {}: open {} ticks, sprinting {}, motion {:.3} {:.3}",
ctx.tick(),
self.n - at,
ctx.pose().sprinting,
ctx.pose().motion.x,
ctx.pose().motion.z
);
}
let phase = self.n % 80;
match self.opened_at {
None if (30..40).contains(&phase) => match ctx.open_inventory() {
Ok(()) => {
self.opens += 1;
self.opened_at = Some(self.n);
log::info!(
"tick {}: opened the inventory (sprinting {}, motion {:.3} {:.3})",
ctx.tick(),
ctx.pose().sprinting,
ctx.pose().motion.x,
ctx.pose().motion.z
);
}
Err(e) => {
self.refusals += 1;
log::info!("open refused: {e}");
}
},
Some(at) if self.n == at + 6 || self.n == at + 8 => {
match ctx.click(ghast::inventory::Click::Pickup {
slot: 9,
right: false,
}) {
Ok(_) => self.clicks += 1,
Err(e) => {
self.refusals += 1;
log::info!("click refused: {e}");
}
}
}
Some(at) if self.n >= at + 20 => match ctx.close_window() {
Ok(()) => {
self.opened_at = None;
log::info!(
"tick {}: closed (sprinting {}, motion {:.3} {:.3})",
ctx.tick(),
ctx.pose().sprinting,
ctx.pose().motion.x,
ctx.pose().motion.z
);
}
Err(e) => {
self.refusals += 1;
log::info!("close refused: {e}");
}
},
_ => {}
}
}
}
impl Behavior for Probe {
fn name(&self) -> &str {
"combat-probe"
}
fn interests(&self) -> Interests {
match self.mode {
Mode::Attack | Mode::Clicks => Interests::CHAT | Interests::ENTITIES,
_ => Interests::CHAT,
}
}
fn after_tick(&mut self, view: &ghast::TickView<'_>) {
if self.mode != Mode::Clicks {
return;
}
for o in view.outbound() {
match o {
ghast::common::Outbound::UseEntity {
action: ghast::common::EntityUse::Attack,
..
} => self.sent_attacks += 1,
ghast::common::Outbound::Swing | ghast::common::Outbound::Punch => {
self.sent_swings += 1;
}
_ => {}
}
}
}
fn start(&mut self, ctx: &mut TickContext<'_>) {
ctx.select_slot(1);
ctx.select_slot(0);
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
for m in &ctx.events().chat {
let t = m.plain();
if t.contains("Grim") || t.contains("failed") {
self.alerts += 1;
log::warn!("ALERT chat: {t}");
}
}
if ctx.events().teleported && self.n > 120 {
self.setbacks += 1;
log::warn!("ALERT setback at tick {}", ctx.tick());
}
if self.limit.is_some_and(|l| self.started.elapsed() >= l) {
log::info!("{}", self.summary());
ctx.disconnect("time limit reached");
return;
}
if ctx.is_dead() {
ctx.respawn();
return;
}
self.n += 1;
if self.n < 120 {
return;
}
match self.mode {
Mode::Attack => self.attack(ctx),
Mode::Victim => self.victim(ctx),
Mode::Miss => self.miss(ctx),
Mode::Equip => self.equip(ctx),
Mode::Use => self.use_item(ctx),
Mode::Inventory => self.inventory(ctx),
Mode::Clicks => self.clicks(ctx),
}
}
}
fn main() {
let opts = support::Options::parse();
support::init_logger(opts.verbose);
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 b = Probe::new(opts.limit());
let shutdown = async {
let _ = tokio::signal::ctrl_c().await;
};
match client.run_until(&mut b, shutdown).await {
Ok(e) => log::info!("session ended: {e:?}; {}", b.summary()),
Err(e) => log::error!("session failed: {e}"),
}
});
}