ghast-client 0.5.5

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! The client-side physics of the non-living entities (`Interests::ENTITY_PHYSICS`) against the
//! real client: `tests/golden/<version>/nonliving_tracking.jsonl.gz` (oracle
//! `NonLivingTrackDump`). Projectiles, items, orbs, primed TNT and falling blocks are spawned,
//! moved, synced, teleported, given motion, entity data and projectile power by random packets
//! over a floor with walls, water and slippery patches; every tick the tracker's position,
//! motion, rotation and ground flag of every entity (after the tick's packets, before its
//! entity tick) must equal the real client's, bit for bit, and the set of entities too (the
//! client removes TNT whose fuse ran out, a falling block of air). Mounted once per modern
//! version.

use super::*;
use serde_json::Value;
use std::io::BufRead;

fn hex64(v: &Value) -> f64 {
    f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}

fn hex32(v: &Value) -> f32 {
    f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}

fn unhex(s: &str) -> bytes::Bytes {
    (0..s.len() / 2)
        .map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap())
        .collect::<Vec<u8>>()
        .into()
}

fn packet_id(name: &str) -> i32 {
    use proto::play::clientbound::id;
    match name {
        "add_entity" => id::SPAWN_ENTITY,
        "set_entity_data" => id::ENTITY_METADATA,
        "set_entity_motion" => id::ENTITY_VELOCITY,
        "move_entity_pos" => id::REL_ENTITY_MOVE,
        "move_entity_rot" => id::ENTITY_LOOK,
        "move_entity_pos_rot" => id::ENTITY_MOVE_LOOK,
        "entity_position_sync" => id::SYNC_ENTITY_POSITION,
        "teleport_entity" => id::ENTITY_TELEPORT,
        "remove_entities" => id::ENTITY_DESTROY,
        "projectile_power" => id::SET_PROJECTILE_POWER,
        "player_info_update" => id::PLAYER_INFO,
        n => panic!("unknown packet {n}"),
    }
}

/// The case's world: the loaded columns (stone at y 63) and the other fills as block changes.
fn world(e: &mut Engine<Box<dyn Sim>>, sc: &Value) {
    use proto::play::clientbound as cb;
    for r in sc["loaded_chunks"].as_array().unwrap() {
        let r: Vec<i32> = (0..4).map(|k| r[k].as_i64().unwrap() as i32).collect();
        for x in r[0]..=r[2] {
            for z in r[1]..=r[3] {
                load(e, x, z);
            }
        }
    }
    for fill in sc["fills"].as_array().unwrap() {
        let v: Vec<i64> = (0..7).map(|k| fill[k].as_i64().unwrap()).collect();
        let state = sc["states"][v[6].to_string()].as_str().unwrap();
        if state == "minecraft:stone" && v[1] == 63 && v[4] == 63 {
            continue;
        }
        let id = data::BlockState::parse(state.strip_prefix("minecraft:").unwrap_or(state))
            .or_else(|| data::BlockState::parse(state))
            .unwrap_or_else(|| panic!("state {state}"))
            .id();
        for x in v[0]..=v[3] {
            for y in v[1]..=v[4] {
                for z in v[2]..=v[5] {
                    let pos = ((x & 0x3FF_FFFF) << 38) | ((z & 0x3FF_FFFF) << 12) | (y & 0xFFF);
                    let mut b = pos.to_be_bytes().to_vec();
                    let mut st = u32::from(id);
                    loop {
                        let byte = (st & 0x7f) as u8;
                        st >>= 7;
                        if st == 0 {
                            b.push(byte);
                            break;
                        }
                        b.push(byte | 0x80);
                    }
                    e.sim
                        .world_packet(&RawPacket {
                            id: cb::id::BLOCK_CHANGE,
                            body: bytes::Bytes::from(b),
                        })
                        .unwrap();
                }
            }
        }
    }
}

/// Compares the tracker with one tick line; returns the number of entities compared.
fn compare(e: &Engine<Box<dyn Sim>>, rec: &Value, at: &str) -> usize {
    let t = e.sim.entities().unwrap();
    // The other players (orb cases): where the tracker holds them is what the orbs read.
    for w in rec["players"].as_array().into_iter().flatten() {
        let id = w["id"].as_i64().unwrap() as i32;
        let p = t
            .get(id)
            .unwrap_or_else(|| panic!("{at}: player {id} missing"));
        let pos: Vec<u64> = (0..3).map(|k| hex64(&w["pos"][k]).to_bits()).collect();
        let got: Vec<u64> = p.position().iter().map(|v| v.to_bits()).collect();
        assert_eq!(got, pos, "{at}: player {id} pos {:?}", p.position());
        let eye = p.dimensions().map_or(1.62, |d| d.eye_height);
        assert_eq!(
            eye.to_bits(),
            hex32(&w["eye"]).to_bits(),
            "{at}: player {id} eye"
        );
    }
    let want = rec["entities"].as_array().unwrap();
    let mut got: Vec<i32> = t
        .iter()
        .filter(|e| !e.is_player())
        .map(ghast_entity::Entity::id)
        .collect();
    got.sort_unstable();
    let ids: Vec<i32> = want
        .iter()
        .map(|w| w["id"].as_i64().unwrap() as i32)
        .collect();
    assert_eq!(got, ids, "{at}: entity ids");
    for w in want {
        let id = w["id"].as_i64().unwrap() as i32;
        let x = t.get(id).unwrap();
        let ty = w["type"].as_str().unwrap();
        let pos: Vec<f64> = (0..3).map(|k| hex64(&w["pos"][k])).collect();
        let vel: Vec<f64> = (0..3).map(|k| hex64(&w["vel"][k])).collect();
        let bits = |a: &[f64]| a.iter().map(|v| v.to_bits()).collect::<Vec<_>>();
        assert_eq!(
            bits(&x.position()),
            bits(&pos),
            "{at}: {ty} {id} pos {:?} want {pos:?}",
            x.position()
        );
        assert_eq!(
            bits(&x.velocity()),
            bits(&vel),
            "{at}: {ty} {id} vel {:?} want {vel:?}",
            x.velocity()
        );
        let rot = [hex32(&w["rot"][0]), hex32(&w["rot"][1])];
        assert_eq!(
            [x.yaw().to_bits(), x.pitch().to_bits()],
            [rot[0].to_bits(), rot[1].to_bits()],
            "{at}: {ty} {id} rot {:?} want {rot:?}",
            [x.yaw(), x.pitch()]
        );
        assert_eq!(
            x.on_ground(),
            w["ground"].as_bool().unwrap(),
            "{at}: {ty} {id} ground"
        );
    }
    want.len()
}

/// What one replayed file held.
#[derive(Default)]
struct Totals {
    cases: usize,
    orb_cases: usize,
    ticks: usize,
    compared: usize,
    kinds: std::collections::BTreeSet<String>,
}

#[test]
fn nonliving_physics_matches_the_oracle() {
    // A larger run of the same dump (`oracle/run.sh nonliving-tracking --seed N --cases N
    // --out FILE`) in place of the golden: `GHAST_NONLIVING_<version, dots as underscores>`.
    let var = format!("GHAST_NONLIVING_{}", GOLDEN.replace('.', "_"));
    let path = std::env::var(&var).unwrap_or_else(|_| {
        format!(
            "{}/../../tests/golden/{GOLDEN}/nonliving_tracking.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        )
    });
    let t = replay(&path);
    eprintln!(
        "{GOLDEN} non-living physics: {} cases ({} with orbs around players), {} ticks, {} entity states identical, kinds {:?}",
        t.cases, t.orb_cases, t.ticks, t.compared, t.kinds
    );
    assert!(
        t.cases >= 10 && t.orb_cases >= 3 && t.ticks >= 400 && t.compared >= 2000,
        "{} {} {} {}",
        t.cases,
        t.orb_cases,
        t.ticks,
        t.compared
    );
    assert!(t.kinds.len() >= 15, "{:?}", t.kinds);
}

/// The cached large runs (`oracle/cache/<version>/fuzz-nonliving/*.jsonl.gz`, git-ignored; made
/// by `MC=<version> oracle/run.sh nonliving-tracking --seed N --cases N --ticks N --out FILE`),
/// one line in memory at a time.
#[test]
#[ignore = "needs the cached oracle runs"]
fn nonliving_cache_matches_the_oracle() {
    let dir = format!(
        "{}/../../oracle/cache/{GOLDEN}/fuzz-nonliving",
        env!("CARGO_MANIFEST_DIR")
    );
    let mut files: Vec<_> = std::fs::read_dir(&dir)
        .unwrap_or_else(|e| panic!("{dir}: {e}"))
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
        .collect();
    files.sort();
    assert!(!files.is_empty(), "{dir}: no runs");
    let mut all = Totals::default();
    for f in files {
        let t = replay(f.to_str().unwrap());
        all.cases += t.cases;
        all.orb_cases += t.orb_cases;
        all.ticks += t.ticks;
        all.compared += t.compared;
        all.kinds.extend(t.kinds);
    }
    eprintln!(
        "{GOLDEN} non-living cache: {} cases ({} with orbs around players), {} ticks, {} entity states identical",
        all.cases, all.orb_cases, all.ticks, all.compared
    );
}

/// Replays one dump file through the client's sim; panics at the first difference.
fn replay(path: &str) -> Totals {
    let f = std::fs::File::open(path).unwrap_or_else(|e| panic!("{path}: {e}"));
    let mut lines = std::io::BufReader::new(flate2::read::GzDecoder::new(f))
        .lines()
        .map(|l| serde_json::from_str::<Value>(&l.unwrap()).unwrap())
        .peekable();
    let mut t = Totals::default();
    let (cases, ticks, compared, kinds) =
        (&mut t.cases, &mut t.ticks, &mut t.compared, &mut t.kinds);
    while let Some(sc) = lines.next() {
        assert_eq!(sc["type"], "scenario");
        *cases += 1;
        let name = sc["name"].as_str().unwrap().to_owned();
        let me = sc["tracking"]["player_id"].as_i64().unwrap() as i32;
        let mut e = engine(GAME);
        e.sim.set_entities(crate::client::entity_config(
            crate::Interests::ENTITY_TRACKING | crate::Interests::ENTITY_PHYSICS,
            GAME.caps(),
        ));
        e.sim.set_entity_physics(true);
        e.sim.test_set_own_id(me);
        if sc["tracking"]["orbs"].as_bool() == Some(true) {
            // Our player stands still where it spawned (survival): the orbs read it there.
            t.orb_cases += 1;
            let s = &sc["tracking"];
            let at = |k: &str| hex64(&s[k][1]);
            e.sim
                .set_player_pos(Vec3::new(at("own_x"), at("own_y"), at("own_z")));
        }
        world(&mut e, &sc);
        let mut pose = e.core.pose;
        while let Some(rec) = lines.next_if(|l| l["type"] == "tick") {
            let k = rec["tick"].as_i64().unwrap();
            for p in rec["packets"].as_array().unwrap() {
                let raw = RawPacket {
                    id: packet_id(p[0].as_str().unwrap()),
                    body: unhex(p[1].as_str().unwrap()),
                };
                e.sim.world_packet(&raw).unwrap();
            }
            for w in rec["entities"].as_array().unwrap() {
                kinds.insert(w["type"].as_str().unwrap().to_owned());
            }
            // Orb cases: the real client's player stood still (the replay keeps ours there).
            if let Some(own) = rec["own"].as_array() {
                let s = &sc["tracking"];
                for (i, c) in ["own_x", "own_y", "own_z"].iter().enumerate() {
                    assert_eq!(
                        hex64(&own[i]),
                        hex64(&s[c][1]),
                        "{name} tick {k}: player moved"
                    );
                }
            }
            *compared += compare(&e, &rec, &format!("{name} tick {k}"));
            e.sim.tick_entities(&mut pose);
            *ticks += 1;
        }
    }
    t
}

/// Without `Interests::ENTITY_PHYSICS` nothing is simulated: a snowball keeps the position of
/// its spawn packet; with it, the same packets make it fall.
#[test]
fn nonliving_physics_only_with_the_interest() {
    use bytes::BufMut;
    let snowball = data::entities::entity_types()
        .iter()
        .find(|t| t.name.ends_with("snowball"))
        .unwrap()
        .id;
    let run = |physics: bool| {
        let mut e = engine(GAME);
        e.sim.set_entities(crate::client::entity_config(
            crate::Interests::ENTITY_TRACKING,
            GAME.caps(),
        ));
        e.sim.set_entity_physics(physics);
        load(&mut e, 0, 0);
        let mut b = bytes::BytesMut::new();
        b.put_u8(50); // id
        b.put_u128(9); // uuid
        assert!(snowball < 128);
        b.put_u8(snowball as u8);
        for v in [4.5f64, 66.0, 4.5] {
            b.put_f64(v);
        }
        b.put_u8(0); // zero motion (LpVec3)
        b.put_bytes(0, 3); // rotations
        b.put_u8(0); // data
        e.sim
            .world_packet(&RawPacket {
                id: proto::play::clientbound::id::SPAWN_ENTITY,
                body: b.freeze(),
            })
            .unwrap();
        let mut pose = e.core.pose;
        for _ in 0..5 {
            e.sim.tick_entities(&mut pose);
        }
        e.sim.entities().unwrap().get(50).unwrap().position()
    };
    assert_eq!(run(false), [4.5, 66.0, 4.5]);
    let p = run(true);
    assert!(p[1] < 66.0 && p[0] == 4.5 && p[2] == 4.5, "{p:?}");
}