mod support;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use ghast::ext::{Bot, Error, Event, Ext, Ride, WhenDone};
use ghast::{Controls, Interests, Vec3};
#[derive(Debug, Clone)]
struct RideOpts {
mount: String,
course: String,
leg: f64,
jump: f32,
sprint: bool,
boost: bool,
stick: Option<String>,
settle: u64,
stick_first: bool,
boat_look: bool,
}
impl RideOpts {
fn take(args: Vec<String>) -> (RideOpts, Vec<String>) {
let mut o = RideOpts {
mount: "horse".into(),
course: "square".into(),
leg: 8.0,
jump: 0.0,
sprint: false,
boost: false,
stick: None,
settle: 0,
stick_first: false,
boat_look: false,
};
let mut rest = Vec::new();
let mut it = args.into_iter();
while let Some(a) = it.next() {
let mut val = || {
it.next().unwrap_or_else(|| {
eprintln!("{a} needs a value");
std::process::exit(2)
})
};
match a.as_str() {
"--mount" => o.mount = val(),
"--course" => o.course = val(),
"--leg" => o.leg = val().parse().expect("--leg: a number"),
"--jump" => o.jump = val().parse().expect("--jump: a number"),
"--sprint" => o.sprint = true,
"--boost" => o.boost = true,
"--stick" => o.stick = Some(val()),
"--stick-first" => o.stick_first = true,
"--boat-look" => o.boat_look = true,
"--settle" => o.settle = val().parse().expect("--settle: ticks"),
_ => rest.push(a),
}
}
(o, rest)
}
}
const BOARDING: u32 = 0;
const RIDING: u32 = 1;
const OFF: u32 = 2;
#[derive(Default)]
struct Counts {
phase: AtomicU32,
setbacks: AtomicU32,
off_teleports: AtomicU32,
alerts: AtomicU32,
}
fn is_boat(name: &str) -> bool {
let n = name.to_ascii_lowercase();
n == "boat" || n.ends_with("_boat") || n.ends_with("_raft")
}
fn flat(a: Vec3, b: Vec3) -> f64 {
((a.x - b.x).powi(2) + (a.z - b.z).powi(2)).sqrt()
}
async fn ride_to(
bot: &Bot,
o: &RideOpts,
boat: bool,
goal: Vec3,
vertical: bool,
) -> Result<bool, Error> {
let sprint = o.sprint;
let keys_turn = !o.boat_look;
for _ in 0..300 {
let arrived = bot
.with(move |ctx| {
let p = ctx.pose().pos;
if flat(p, goal) < 1.2 && (!vertical || (p.y - goal.y).abs() < 1.5) {
return true;
}
let (dx, dz) = (goal.x - p.x, goal.z - p.z);
let want = (-dx).atan2(dz).to_degrees() as f32;
let mut keys = Controls {
forward: true,
sprint,
jump: ctx.controls().jump,
..Controls::NONE
};
if boat {
let yaw = ctx.vehicle().map_or(ctx.pose().yaw, |v| v.yaw);
let d = ghast::rotation::wrap_degrees(want - yaw);
keys.left = keys_turn && d < -6.0;
keys.right = keys_turn && d > 6.0;
let cur = ctx.pose().yaw;
ctx.set_aim(cur + ghast::rotation::wrap_degrees(want - cur), 0.0);
} else {
let cur = ctx.pose().yaw;
let pitch = if vertical {
let h = (dx * dx + dz * dz).sqrt().max(0.5);
(-(goal.y - p.y).atan2(h).to_degrees() as f32).clamp(-45.0, 45.0)
} else {
0.0
};
ctx.set_aim(cur + ghast::rotation::wrap_degrees(want - cur), pitch);
}
ctx.set_controls(keys);
false
})
.await?;
if arrived {
return Ok(true);
}
bot.next_tick().await;
}
Ok(false)
}
async fn course(bot: &Bot, o: &RideOpts, ride: &Ride, start: Vec3) -> Result<(u32, u32), Error> {
let boat = is_boat(ride.name);
let l = o.leg;
let (x, y, z) = (start.x, start.y, start.z);
if o.course == "idle" {
bot.set_controls(Controls {
forward: true,
..Controls::NONE
});
bot.wait_ticks((l * 10.0) as u64).await;
bot.set_controls(Controls::NONE);
return Ok((1, 1));
}
let square = |h: f64| {
vec![
Vec3::new(x, y + h, z - l),
Vec3::new(x - l, y + h, z - l),
Vec3::new(x - l, y + h, z),
Vec3::new(x, y + h, z),
]
};
let (points, vertical) = match o.course.as_str() {
"line" => (vec![Vec3::new(x, y, z - l)], false),
"fly" => {
let mut p = square(6.0);
p.push(Vec3::new(x, y, z));
(p, true)
}
_ => (square(0.0), false),
};
let n = points.len() as u32;
let mut done = 0;
for (k, goal) in points.into_iter().enumerate() {
if o.boost {
bot.look(bot.pose().yaw, 0.0).await?;
match bot.boost().await {
Ok(()) => log::info!("side {k}: boost"),
Err(e) => log::warn!("side {k}: boost: {e}"),
}
}
let jump_side = if o.course == "line" { 0 } else { 1 };
if o.jump > 0.0 && k == jump_side {
let from = bot.pose().pos;
let mid = Vec3::new((from.x + goal.x) / 2.0, goal.y, (from.z + goal.z) / 2.0);
ride_to(bot, o, boat, mid, vertical).await?;
let bar = bot.ride_jump(o.jump).await?;
log::info!(
"side {k}: jump bar released at {bar} ({:?})",
bot.pose().pos
);
}
let ok = ride_to(bot, o, boat, goal, vertical).await?;
let p = bot.pose().pos;
if ok {
done += 1;
log::info!("side {k}: at {:.2} {:.2} {:.2}", p.x, p.y, p.z);
} else {
log::warn!(
"side {k}: did not arrive (at {:.2} {:.2} {:.2})",
p.x,
p.y,
p.z
);
}
}
bot.set_controls(Controls::NONE);
Ok((done, n))
}
async fn take_stick(bot: &Bot, stick: &str) -> Result<(), Error> {
let mut held = bot.equip(stick).await;
for _ in 0..10 {
if held.is_ok() {
break;
}
bot.wait_ticks(10).await;
held = bot.equip(stick).await;
}
held?;
bot.wait_ticks(5).await;
Ok(())
}
async fn run(bot: Bot, o: RideOpts, counts: Arc<Counts>) -> Result<(), Error> {
{
let b = bot.clone();
let c = counts.clone();
let _watch = bot.spawn(async move {
let mut ev = b.events();
while let Some(e) = ev.recv().await {
match e {
Event::Chat(m) => {
let t = m.plain();
if t.contains("Grim") || t.contains("failed") {
c.alerts.fetch_add(1, Ordering::Relaxed);
log::warn!("ALERT chat: {t}");
}
}
Event::Teleport(t) => {
let p = t.after.pos;
match c.phase.load(Ordering::Relaxed) {
RIDING => {
c.setbacks.fetch_add(1, Ordering::Relaxed);
log::warn!(
"ALERT setback while riding to {:.3} {:.3} {:.3}",
p.x,
p.y,
p.z
);
}
OFF => {
c.off_teleports.fetch_add(1, Ordering::Relaxed);
log::info!(
"placed after getting off: {:.3} {:.3} {:.3}",
p.x,
p.y,
p.z
);
}
_ => log::info!(
"teleport before boarding: {:.3} {:.3} {:.3}",
p.x,
p.y,
p.z
),
}
}
_ => {}
}
}
});
}
let want = o.mount.to_ascii_lowercase();
let matches = move |name: &str| {
let n = name.to_ascii_lowercase();
n == want
|| (want == "boat" && is_boat(&n))
|| (want == "horse" && n == "entityhorse")
|| (want == "minecart" && n == "minecartrideable")
};
bot.wait_ticks(o.settle).await;
let mut target = None;
for _ in 0..60 {
let m = matches.clone();
if let Some(e) = bot
.nearest_entity(move |e| e.alive && m(e.name), 8.0)
.await?
{
target = Some(e);
break;
}
bot.wait_ticks(10).await;
}
let Some(target) = target else {
let seen: Vec<String> = bot
.find_entities(|_| true, 16.0)
.await?
.into_iter()
.map(|e| {
format!(
"{} {:?} at {:.1} {:.1} {:.1}",
e.id, e.name, e.pos.x, e.pos.y, e.pos.z
)
})
.collect();
log::error!("FAIL no {} within 8 blocks (tracked: {seen:?})", o.mount);
return Err(Error::Timeout);
};
bot.wait_ticks(20).await;
if o.stick_first
&& let Some(stick) = &o.stick
{
take_stick(&bot, stick).await?;
} else {
bot.select_slot(8);
bot.wait_ticks(2).await;
}
let mut boarded = Err(Error::EntityOutOfReach(target.id));
for _ in 0..4 {
boarded = bot.mount(target.id).await;
let Err(Error::EntityOutOfReach(_)) = boarded else {
break;
};
let Some(e) = bot.entity(target.id).await? else {
break;
};
log::info!(
"{} out of reach at {:.2} {:.2} {:.2}: walking closer",
target.name,
e.pos.x,
e.pos.y,
e.pos.z
);
let _ = bot.timeout(100, bot.walk_straight_to(e.pos, 1.0)).await;
bot.set_controls(Controls::NONE);
}
let ride = match boarded {
Ok(r) => r,
Err(e) => {
log::error!("FAIL boarding {} {}: {e}", target.name, target.id);
return Err(e);
}
};
counts.phase.store(RIDING, Ordering::Relaxed);
log::info!("boarded {ride:?}");
if let Some(stick) = &o.stick
&& !o.stick_first
{
take_stick(&bot, stick).await?;
}
bot.wait_ticks(30).await;
let start = bot.pose().pos;
let t0 = bot.tick();
let r = course(&bot, &o, &ride, start).await;
let ticks = bot.tick() - t0;
let (done, sides) = match r {
Ok(d) => d,
Err(e) => {
log::error!("FAIL course: {e}");
(0, 1)
}
};
bot.wait_ticks(10).await;
let still_on = bot
.vehicle()
.await?
.is_some_and(|v| v.entity_id == ride.entity_id);
counts.phase.store(OFF, Ordering::Relaxed);
let off = bot.dismount().await;
let p = bot.pose().pos;
match &off {
Ok(()) => log::info!("got off at {:.3} {:.3} {:.3}", p.x, p.y, p.z),
Err(e) => log::error!("FAIL getting off: {e}"),
}
bot.wait_ticks(40).await;
let setbacks = counts.setbacks.load(Ordering::Relaxed);
let alerts = counts.alerts.load(Ordering::Relaxed);
let pass = still_on && off.is_ok() && done == sides && setbacks == 0 && alerts == 0;
println!(
"RESULT {} {}: {} sides of {sides} in {ticks} ticks, {setbacks} setbacks, {} placement \
teleports after getting off, {alerts} chat alerts{} {}",
ride.name,
o.course,
done,
counts.off_teleports.load(Ordering::Relaxed),
if still_on {
""
} else {
", thrown off during the course"
},
if pass { "PASS" } else { "FAIL" }
);
if pass { Ok(()) } else { Err(Error::Stuck) }
}
fn main() {
let (ro, rest) = RideOpts::take(std::env::args().skip(1).collect());
let opts = support::Options::parse_from(rest);
support::init_logger(opts.verbose);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("tokio runtime");
let counts = Arc::new(Counts::default());
counts.phase.store(BOARDING, Ordering::Relaxed);
let c = counts.clone();
let mut ext = Ext::new(move |bot| run(bot, ro.clone(), c.clone()))
.name("ride")
.interests(Interests::CHAT | Interests::ENTITIES)
.interrupt_on_teleport(false)
.when_done(WhenDone::Disconnect);
let limit = opts.limit();
let ok = rt.block_on(async {
let client = match opts.client() {
Ok(c) => c,
Err(e) => {
log::error!("{e}");
std::process::exit(2);
}
};
let shutdown = async {
let stop = async {
#[cfg(unix)]
{
let mut term =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("SIGTERM handler");
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
let _ = tokio::signal::ctrl_c().await;
};
match limit {
Some(l) => {
tokio::select! {
() = stop => {}
() = tokio::time::sleep(l) => log::warn!("time limit reached"),
}
}
None => stop.await,
}
};
match client.run_until(&mut ext, shutdown).await {
Ok(e) => {
log::info!("session ended: {e:?}; result {:?}", ext.result());
matches!(ext.result(), Some(Ok(())))
}
Err(e) => {
log::error!("session failed: {e}");
false
}
}
});
std::process::exit(if ok { 0 } else { 1 });
}