ghast-client 0.5.6

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
//! Unit tests of the modern world and movement (pushes, team rules, forced step position,
//! teleports).

use super::*;

/// `spawn_entity` of type `ty` at `pos` (no rotation, no velocity).
fn spawn_raw(eid: i32, uuid: u128, ty: &str, pos: [f64; 3]) -> RawPacket {
    use super::super::proto::play::clientbound as cb;
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    let ty = super::super::data::entity_by_name(ty).unwrap().id;
    let mut b = bytes::BytesMut::new();
    b.put_varint(eid);
    b.put_u128(uuid);
    b.put_varint(i32::from(ty));
    for v in pos {
        b.put_f64(v);
    }
    b.put_u8(0);
    b.put_i8(0);
    b.put_i8(0);
    b.put_i8(0);
    b.put_varint(0);
    RawPacket::new(cb::id::SPAWN_ENTITY, b.freeze())
}

/// `isAlive` decides whether a shulker collides: a health that is not above 0 (NaN
/// included) makes it dead.
#[test]
fn dead_shulkers_do_not_collide() {
    use super::super::proto::play::clientbound as cb;
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    for (health, collides) in [
        (None, true),
        (Some(10.0f32), true),
        (Some(0.0), false),
        (Some(f32::NAN), false),
    ] {
        let mut s = ModernSim::test_overworld();
        s.set_entities(Some(ghast_entity::Config::default()));
        s.world_packet(&spawn_raw(7, 0x77, "shulker", [1.5, 0.0, 0.5]))
            .unwrap();
        if let Some(h) = health {
            // entity_metadata: LivingEntity health (index 9, float serializer 3).
            let mut b = bytes::BytesMut::new();
            b.put_varint(7);
            b.put_u8(super::super::entity::meta::HEALTH);
            b.put_varint(3);
            b.put_f32(h);
            b.put_u8(0xFF);
            s.world_packet(&RawPacket::new(cb::id::ENTITY_METADATA, b.freeze()))
                .unwrap();
        }
        let (mut boxes, mut boat) = (Vec::new(), Vec::new());
        let player = modern::PlayerState::new([0.5, 0.0, 0.5], 0.0, 0.0);
        collect_colliders(
            s.entities.as_ref(),
            None,
            &player,
            None,
            &mut boxes,
            &mut boat,
            &s.own.mounts,
        );
        assert_eq!(boxes.len(), usize::from(collides), "health {health:?}");
    }
}

/// `Entity.push`: a spectator player (noPhysics) pushes nothing, a survival one does, and a
/// dying mob still does (its aiStep runs until it is removed).
#[test]
fn spectators_do_not_push_dying_mobs_do() {
    use super::super::proto::play::clientbound as cb;
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    let pushed = |ty: &str, game_mode: Option<i32>, health: Option<f32>| {
        let mut s = ModernSim::test_overworld();
        s.set_entities(crate::client::entity_config(
            crate::Interests::ENTITIES,
            super::super::GAME.caps(),
        ));
        let uuid = 0x55u128;
        if let Some(gm) = game_mode {
            // player_info: add_player + update_game_mode.
            let mut b = bytes::BytesMut::new();
            b.put_u8(0b101);
            b.put_varint(1);
            b.put_u128(uuid);
            b.put_string("Alex").unwrap();
            b.put_varint(0);
            b.put_varint(gm);
            s.world_packet(&RawPacket::new(cb::id::PLAYER_INFO, b.freeze()))
                .unwrap();
        }
        s.world_packet(&spawn_raw(9, uuid, ty, [0.8, 64.0, 0.5]))
            .unwrap();
        if let Some(h) = health {
            let mut b = bytes::BytesMut::new();
            b.put_varint(9);
            b.put_u8(super::super::entity::meta::HEALTH);
            b.put_varint(3);
            b.put_f32(h);
            b.put_u8(0xFF);
            s.world_packet(&RawPacket::new(cb::id::ENTITY_METADATA, b.freeze()))
                .unwrap();
        }
        let t = s.entities.as_mut().unwrap();
        assert!(t.get(9).is_some(), "{ty} spawned");
        t.mark_column_loaded(0, 0);
        s.player = modern::PlayerState::new([0.5, 64.0, 0.5], 0.0, 0.0);
        let mut pose = Pose::default();
        s.push_player(&mut pose, false);
        s.player.vel[0] != 0.0
    };
    assert!(pushed("player", Some(0), None));
    assert!(!pushed("player", Some(3), None));
    assert!(pushed("zombie", None, None));
    assert!(pushed("zombie", None, Some(0.0)));
}

/// A player that pushes the local player is judged by its team under its profile name,
/// which comes from the tab list: with entity tracking as the client sets it up for
/// `Interests::ENTITIES` alone the name must still be known.
#[test]
fn pushing_players_are_judged_by_their_profile_name() {
    use super::super::proto::play::clientbound as cb;
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    let mut s = ModernSim::test_overworld();
    s.set_entities(crate::client::entity_config(
        crate::Interests::ENTITIES,
        super::super::GAME.caps(),
    ));
    let uuid = 0x1234_5678_9abc_def0_1122_3344_5566_7788u128;
    // player_info: add_player (action bit 0) for one profile, no properties.
    let mut b = bytes::BytesMut::new();
    b.put_u8(1);
    b.put_varint(1);
    b.put_u128(uuid);
    b.put_string("Steve").unwrap();
    b.put_varint(0);
    let info = RawPacket::new(cb::id::PLAYER_INFO, b.freeze());
    // spawn_entity: a player next to the local one.
    let player = super::super::data::entity_by_name("player").unwrap().id;
    let mut b = bytes::BytesMut::new();
    b.put_varint(42);
    b.put_u128(uuid);
    b.put_varint(i32::from(player));
    b.put_f64(0.5);
    b.put_f64(64.0);
    b.put_f64(0.5);
    b.put_u8(0);
    b.put_i8(0);
    b.put_i8(0);
    b.put_i8(0);
    b.put_varint(0);
    let spawn = RawPacket::new(cb::id::SPAWN_ENTITY, b.freeze());
    // What the client lets through to the sim.
    let wanted = s.entity_packet_ids();
    for raw in [&info, &spawn] {
        if wanted.contains(&raw.id) {
            s.world_packet(raw).unwrap();
        }
    }
    let t = s.entities.as_ref().unwrap();
    let e = t.get(42).expect("the player spawned");
    let mut buf = [0u8; 36];
    assert_eq!(scoreboard_name(t, e, &mut buf), "Steve");
    // The names-only list is not the tab list the behaviour sees (it did not ask for it).
    assert_eq!(t.players().count(), 0);
    // Vanilla skips a player spawn whose profile is not in the tab list.
    s.world_packet(&spawn_raw(43, 0x99, "player", [0.5, 64.0, 0.5]))
        .unwrap();
    assert!(s.entities.as_ref().unwrap().get(43).is_none());
}

/// Grim compatibility: a status-only move whose feet height differs from the sent one gets
/// the position (and the sent bookkeeping follows); off, or with the same height, nothing
/// changes.
#[test]
fn forced_step_position() {
    use ghast_physics::Packet as P;
    let status = P::Move {
        pos: None,
        look: None,
        on_ground: true,
        horizontal_collision: false,
    };
    let mut p = modern::PlayerState::new([0.5, 4.0, 0.5], 0.0, 0.0);
    p.sent.pos = [0.5, 4.000_061_962_301_82, 0.5];
    let mut packets = ghast_physics::Packets::new();
    packets.push(status);
    force_modern_position(&mut packets, &mut p, ForceStepPosition::Always);
    assert_eq!(
        packets.as_slice(),
        [P::Move {
            pos: Some([0.5, 4.0, 0.5]),
            look: None,
            on_ground: true,
            horizontal_collision: false,
        }]
    );
    assert_eq!(p.sent.pos, [0.5, 4.0, 0.5]);
    let mut packets = ghast_physics::Packets::new();
    packets.push(status);
    force_modern_position(&mut packets, &mut p, ForceStepPosition::Always);
    assert_eq!(packets.as_slice(), [status]);
}

/// The engine's teleport path (`ModernSim::teleport`, fed from the decoded `Teleport`) lands
/// exactly where `modern::PlayerState::apply_teleport` does — the function the oracle's
/// teleport goldens (`tests/golden/26.1/teleports.jsonl.gz`) prove — for random
/// relative bits, deltas, rotations and prior motion.
#[test]
fn teleport_matches_the_proven_physics_call() {
    let mut seed = 0x9E37_79B9_7F4A_7C15u64;
    let mut rnd = move || {
        seed ^= seed << 13;
        seed ^= seed >> 7;
        seed ^= seed << 17;
        (seed >> 11) as f64 / (1u64 << 53) as f64
    };
    for _ in 0..2000 {
        let mut sim = ModernSim::new();
        let start = [rnd() * 64.0 - 32.0, rnd() * 100.0, rnd() * 64.0 - 32.0];
        sim.player.set_pos(start[0], start[1], start[2]);
        sim.player.vel = [rnd() - 0.5, rnd() - 0.5, rnd() - 0.5];
        sim.player.yaw = (rnd() * 720.0 - 360.0) as f32;
        sim.player.pitch = (rnd() * 180.0 - 90.0) as f32;
        let mut pose = Pose::default();
        sync_pose_26(&mut pose, &sim.player);
        let mut direct = sim.player;
        let relative = (rnd() * 512.0) as u32 & 0x1ff;
        let t = Teleport {
            x: rnd() * 40.0 - 20.0,
            y: rnd() * 40.0 - 20.0,
            z: rnd() * 40.0 - 20.0,
            yaw: (rnd() * 720.0 - 360.0) as f32,
            pitch: (rnd() * 200.0 - 100.0) as f32,
            flags: (relative & 0x1f) as i8,
            teleport_id: Some(1),
            relative,
            delta: Vec3::new(
                rnd() * 40.0 - 20.0,
                rnd() * 40.0 - 20.0,
                rnd() * 40.0 - 20.0,
            ),
        };
        sim.teleport(&mut pose, &t);
        let _ = direct.apply_teleport(
            [t.x, t.y, t.z],
            [t.delta.x, t.delta.y, t.delta.z],
            t.yaw,
            t.pitch,
            relative,
        );
        assert_eq!(sim.player, direct, "{t:?}");
        assert_eq!(
            pose.pos,
            Vec3::new(direct.pos[0], direct.pos[1], direct.pos[2])
        );
        assert_eq!((pose.yaw, pose.pitch), (direct.yaw, direct.pitch));
    }
}