ghast 0.5.6

Headless Minecraft Java Edition client / bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3) with vanilla-exact behaviour: facade crate re-exporting the ghast-* crates
Documentation
//! Piston test for the lab (`lab/pistons.sh` builds the layouts and runs the clocks): the bot
//! stands, walks, sprints or jumps (`PROBE=stand|walk|sprint|jump`, default stand) and logs its
//! position every 10 ticks, every server teleport (with the pose the server had before it) and
//! Grim alerts in chat (`ALERT`). Walking goes along the starting yaw, `TURN` ticks (default 40)
//! each way. The pistons need no option: the client runs them from the block-action packets.
//!
//! ```text
//! PROBE=walk cargo run -p ghast --release --example piston_probe -- --host 127.0.0.1 \
//!     --port 25618 --username GhastBot4 --version 1.8.9 --minutes 0.5
//! ```

mod support;

use std::time::{Duration, Instant};

use ghast::{Behavior, Controls, Interests, TickContext};

struct Probe {
    mode: String,
    turn: u64,
    n: u64,
    /// The yaw the walk keeps (the script's teleport sets it).
    yaw: Option<f32>,
    alerts: u32,
    teleports: u32,
    started: Instant,
    limit: Option<Duration>,
    /// `TRACK=1`: entity tracking on (the client view moves the other entities' copies too).
    track: bool,
    /// Ticks `piston_uncertain` was raised.
    uncertain: u32,
    /// `TRACK=1`: the number of other (non-player) entities last logged.
    others: usize,
}

impl Behavior for Probe {
    fn name(&self) -> &str {
        "piston-probe"
    }

    fn interests(&self) -> Interests {
        if self.track {
            Interests::CHAT | Interests::ENTITY_TRACKING | Interests::ENTITIES
        } else {
            Interests::CHAT
        }
    }

    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        if ctx.piston_uncertain() {
            self.uncertain += 1;
        }
        if self.track
            && let Some(es) = ctx.entities()
        {
            let others = es.iter().filter(|e| !e.is_player()).count();
            if others != self.others || (others > 0 && ctx.tick().is_multiple_of(40)) {
                self.others = others;
                let list: Vec<String> = es
                    .iter()
                    .filter(|e| !e.is_player())
                    .map(|e| {
                        let d = e.drawn_position();
                        format!("{} {:.4} {:.4} {:.4}", e.id(), d[0], d[1], d[2])
                    })
                    .collect();
                log::info!(
                    "tick {}: {} other entities: {}",
                    ctx.tick(),
                    others,
                    list.join("; ")
                );
            }
        }
        for m in &ctx.events().chat {
            let t = m.plain();
            if t.contains("Grim") {
                self.alerts += 1;
                log::warn!("ALERT chat: {t}");
            }
        }
        for t in &ctx.events().teleports {
            self.teleports += 1;
            let (s, a) = (t.sent_before.pos, t.after.pos);
            log::info!(
                "tick {}: teleport {}: server had {:.5} {:.5} {:.5}, now {:.5} {:.5} {:.5} (diff {:.5} {:.5} {:.5})",
                ctx.tick(),
                self.teleports,
                s.x,
                s.y,
                s.z,
                a.x,
                a.y,
                a.z,
                a.x - s.x,
                a.y - s.y,
                a.z - s.z
            );
            if self.n > 0 {
                // After the start: the next yaw is the new one.
                self.yaw = None;
            }
        }
        if self.limit.is_some_and(|l| self.started.elapsed() >= l) {
            let p = ctx.pose().pos;
            log::info!(
                "end position {:.5} {:.5} {:.5}; {} teleports, {} alerts, {} piston_uncertain ticks",
                p.x,
                p.y,
                p.z,
                self.teleports,
                self.alerts,
                self.uncertain
            );
            log::info!(
                "tracking {}: {:?} entities",
                self.track,
                ctx.entities().map(|e| e.len())
            );
            if self.track
                && let Some(es) = ctx.entities()
            {
                for e in es.iter().filter(|e| !e.is_player()) {
                    let d = e.drawn_position();
                    log::info!(
                        "entity {} drawn {:.5} {:.5} {:.5} server {:.5} {:.5} {:.5}",
                        e.id(),
                        d[0],
                        d[1],
                        d[2],
                        e.position()[0],
                        e.position()[1],
                        e.position()[2]
                    );
                }
            }
            ctx.disconnect("time limit reached");
            return;
        }
        self.n += 1;
        if self.n.is_multiple_of(10) {
            let p = ctx.pose();
            log::info!(
                "tick {}: pos {:.5} {:.5} {:.5} motion {:.5} {:.5} {:.5} ground {}",
                ctx.tick(),
                p.pos.x,
                p.pos.y,
                p.pos.z,
                p.motion.x,
                p.motion.y,
                p.motion.z,
                p.on_ground
            );
        }
        // Wait for the script's teleport (about tick 60) before moving.
        if self.n < 80 || self.mode == "stand" {
            ctx.set_controls(Controls::NONE);
            return;
        }
        let yaw = *self.yaw.get_or_insert(ctx.pose().yaw);
        ctx.set_aim(yaw, 0.0);
        let phase = (self.n - 80) / self.turn;
        let forward = phase.is_multiple_of(2);
        ctx.set_controls(match self.mode.as_str() {
            "walk" => Controls {
                forward,
                back: !forward,
                ..Controls::NONE
            },
            "sprint" => Controls {
                forward,
                back: !forward,
                sprint: forward,
                ..Controls::NONE
            },
            // Jumps in place (held: a jump on every landing).
            _ => Controls {
                jump: true,
                ..Controls::NONE
            },
        });
    }
}

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 {
            mode: std::env::var("PROBE").unwrap_or_else(|_| "stand".into()),
            turn: std::env::var("TURN")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(40),
            n: 0,
            yaw: None,
            alerts: 0,
            teleports: 0,
            started: Instant::now(),
            limit: opts.limit(),
            track: std::env::var("TRACK").is_ok_and(|v| !v.is_empty()),
            uncertain: 0,
            others: 0,
        };
        let shutdown = async {
            let _ = tokio::signal::ctrl_c().await;
        };
        match client.run_until(&mut b, shutdown).await {
            Ok(e) => log::info!("session ended: {e:?}; {} alerts", b.alerts),
            Err(e) => log::error!("session failed: {e}"),
        }
    });
}