ghast-client 0.5.3

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
//! 1.16.5: elytra gliding with firework rockets, the riptide spin and the rain that wets the player.

use super::*;

impl Sim16 {
    /// Whether the tick needs the slow path (entities, a non-default extension state, a use
    /// the riptide follows).
    pub(super) fn update_slow(&mut self) {
        self.slow = self.entities.is_some()
            || self.ride.is_some()
            || !self.ext.is_inert()
            || self.rt.using.is_some()
            || !self.glide.rockets.is_empty();
    }

    /// The chest slot holds a usable elytra (`ElytraItem.isUsable`: damage below 431).
    pub(super) fn elytra_equipped(inv: &ghast_inventory::Inventory) -> bool {
        inv.armor(1).is_some_and(|s| {
            u16::try_from(s.id())
                .ok()
                .and_then(ghast_data::v1_16_5::Item::from_id)
                .is_some_and(|i| i.info().name == "elytra")
                && s.damage_value(ghast_inventory::Version::V1_16_5) < 432 - 1
        })
    }

    /// The attached rockets that tick on this side of us in the client world's entity map
    /// (`FireworkRocketEntity.tick` with us as the shooter): a boost while we glide, then the
    /// rocket moves to our position. A rocket ticks only while the chunk at its position is
    /// loaded and it is filed in that chunk (`ClientWorld.tickEntity`, `checkEntityChunkPos`).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_rockets(&mut self, before: bool, yaw: f32, pitch: f32) {
        let w = &self.world;
        let loaded = |p: [f64; 3]| {
            w.is_column_loaded((p[0].floor() as i32) >> 4, (p[2].floor() as i32) >> 4)
        };
        let mut gone = false;
        for r in self.glide.rockets.iter_mut().filter(|r| r.before == before) {
            if !loaded(r.pos) {
                continue;
            }
            if r.filed {
                // Entity.baseTick: below y = -64 the rocket is removed, after this tick.
                if r.pos[1] < -64.0 {
                    r.id = i32::MIN;
                    gone = true;
                }
                ghast_physics::v1_16_5::rocket_boost(&mut self.player, &self.ext, yaw, pitch);
                r.pos = self.player.pos;
            }
            r.filed = loaded(r.pos);
        }
        if gone {
            self.glide.rockets.retain(|r| r.id != i32::MIN);
            self.update_slow();
        }
    }

    /// Which side of us each attached rocket ticks on this tick (the client world's entity map
    /// order, known with entity tracking; without it every rocket counts as after us).
    fn order_rockets(&mut self) {
        let t = self.entities.as_ref();
        for r in &mut self.glide.rockets {
            r.before = t.is_some_and(|t| t.ticks_before_self(r.id));
        }
    }

    /// A rocket spawn, removal or entity data: decoded only when it can concern us.
    #[cold]
    #[inline(never)]
    pub(super) fn rocket_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_16_5::play::clientbound as cb;
        match raw.id {
            cb::id::SPAWN_ENTITY => {
                let p: cb::SpawnEntity = raw.decode_as()?;
                // ClientWorld.addEntity: an entity with the same id leaves the world first.
                self.drop_rocket(p.entity_id);
                if p.r#type == FIREWORK_ROCKET_16 {
                    if self.glide.pending.len() >= MAX_PENDING_ROCKETS_16 {
                        self.glide.pending.remove(0);
                    }
                    self.glide.pending.push((p.entity_id, [p.x, p.y, p.z]));
                }
            }
            cb::id::ENTITY_DESTROY => {
                let p: cb::EntityDestroy = raw.decode_as()?;
                for &id in &p.entity_ids {
                    self.drop_rocket(id);
                }
            }
            _ => {}
        }
        self.update_slow();
        Ok(())
    }

    fn drop_rocket(&mut self, id: i32) {
        self.glide.pending.retain(|r| r.0 != id);
        self.glide.rockets.retain(|r| r.id != id);
    }

    /// The join / respawn packet's dimension type and seed (a new client world).
    pub(super) fn new_world(&mut self, dimension: &ghast_protocol::nbt::RawNbt, seed: i64) {
        self.ext.ultrawarm = dimension_flag(dimension, "ultrawarm").unwrap_or(false);
        self.rt.sky = dimension_flag(dimension, "has_skylight").unwrap_or(true);
        self.rt.seed = seed;
        self.update_slow();
    }

    /// `World.hasRain(pos)` without the height map: the level rains (gradient above 0.2), the
    /// dimension has sky light and the biome at the block (`VoronoiBiomeAccessType`, the
    /// dimension type the client decodes from the packet) rains there: precipitation `rain`
    /// and a base temperature of at least 0.15. A biome the world does not keep counts as
    /// raining; vanilla reads plains in a column it does not have.
    fn rains_at(&self, x: i32, y: i32, z: i32) -> bool {
        // `getRainGradient > 0.2` (false for a NaN gradient too).
        let raining = self.rt.rain_level.partial_cmp(&0.2) == Some(std::cmp::Ordering::Greater);
        if !raining || !self.rt.sky {
            return false;
        }
        let [qx, qy, qz] = voronoi_cell(self.rt.seed, x, y, z);
        let id = match self.world.column(qx >> 2, qz >> 2) {
            None => Some(1),
            Some(c) => match c.biomes() {
                ghast_world::Biomes::Cells(b) => {
                    let i = (qy.clamp(0, 63) << 4 | (qz & 3) << 2 | (qx & 3)) as usize;
                    Some(b[i])
                }
                _ => None,
            },
        };
        let Some(id) = id else {
            return true;
        };
        ghast_data::v1_16_5::biome(id)
            .is_none_or(|b| b.precipitation == "rain" && b.temperature >= 0.15)
    }

    /// `isTouchingWaterOrRain()` of the player as it is now.
    pub(super) fn wet(&self) -> bool {
        use ghast_physics::v1_16_5 as phys;
        let p = &self.player;
        if p.touching_water {
            return true;
        }
        let (bx, bz) = (p.pos[0].floor() as i32, p.pos[2].floor() as i32);
        let (feet, head) = (p.pos[1].floor() as i32, p.bb.max_y.floor() as i32);
        // The physics checks both blocks against one flag: keep only the raining ones.
        let mut q = *p;
        match (self.rains_at(bx, feet, bz), self.rains_at(bx, head, bz)) {
            (false, false) => return false,
            (true, true) => {}
            (true, false) => q.bb.max_y = q.pos[1],
            (false, true) => q.pos[1] = q.bb.max_y,
        }
        phys::in_water_or_rain(&q, &self.world, true)
    }

    /// The riptide part of the key handling, before the tick: follows the use of a riptide
    /// trident and launches on its release (`TridentItem.onStoppedUsing`).
    fn riptide_use(&mut self, input: &ghast_physics::TickInput, out: &[Outbound]) {
        let age = self.player.age;
        let hands = self
            .rt
            .held
            .hands
            .get()
            .map(|h| if h.2 == age { (h.0, h.1) } else { (0, false) });
        match (self.rt.using, input.using_item) {
            (None, true) => {
                // The hands start with the main hand, then the off hand.
                let hand = if hands[0].1 { hands[0] } else { hands[1] };
                self.rt.using = Some(hand.0);
                self.rt.use_ticks = 0;
            }
            (Some(level), false) => {
                self.rt.using = None;
                // A release (the hands sent `release_use_item`); a use cut short otherwise (a
                // slot change, ...) launches nothing.
                let released = out.iter().rev().any(|o| {
                    matches!(
                        o,
                        Outbound::Dig {
                            status: crate::common::DigStatus::ReleaseUseItem,
                            ..
                        }
                    )
                });
                if released && level > 0 && self.rt.use_ticks >= 10 && self.wet() {
                    let boxes = self.launch_boxes();
                    let around = ghast_physics::v1_16_5::Surroundings::new().with_entities(&boxes);
                    ghast_physics::v1_16_5::riptide(
                        &mut self.player,
                        &mut self.ext,
                        &around,
                        &self.world,
                        level,
                        input.yaw,
                        input.pitch,
                    );
                }
            }
            _ => {}
        }
    }

    /// The boxes of the entities the player collides with before any entity ticks (the key
    /// handling's launch move).
    fn launch_boxes(&self) -> Vec<ghast_physics::math::Aabb> {
        let Some(t) = self.entities.as_ref() else {
            return Vec::new();
        };
        let w = &self.world;
        t.iter()
            .filter(|e| entity_bits(e) & COLLIDES != 0 && t.client_alive(e.id()))
            .filter_map(|e| {
                let (pos, b) = view(t, self.parked, e.id());
                let pos = pos?;
                w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4)
                    .then(|| b.map(aabb))
                    .flatten()
            })
            .collect()
    }

    /// A pending rocket's entity data: the shooter id (index 8, `OptionalInt` as id + 1) names
    /// us: the rocket is attached.
    #[cold]
    #[inline(never)]
    pub(super) fn rocket_metadata(&mut self, raw: &RawPacket, id: i32) -> Result<(), SimError> {
        use ghast_protocol::defs::p754::types::EntityMetadataValue as V;
        use ghast_protocol::v1_16_5::play::clientbound as cb;
        let p: cb::EntityMetadata = raw.decode_as()?;
        let shooter = p.metadata.iter().find_map(|e| match (e.key, &e.value) {
            (8, V::OptVarInt(v)) => Some(*v),
            _ => None,
        });
        let Some(v) = shooter else { return Ok(()) };
        let Some(k) = self.glide.pending.iter().position(|r| r.0 == id) else {
            return Ok(());
        };
        let (rid, pos) = self.glide.pending.remove(k);
        if v != 0 && v - 1 == self.rt.own_id {
            let w = &self.world;
            let filed =
                w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4);
            self.glide.rockets.push(Rocket16 {
                id: rid,
                pos,
                filed,
                before: false,
            });
            log::debug!("firework rocket {rid} attached to us");
        }
        self.update_slow();
        Ok(())
    }

    /// The other entities of the client world the riptide spin can touch, with their boxes
    /// when the player ticks (before their own tick for the ones that tick after it).
    fn spin_contacts(&mut self, before: bool) {
        let Some(t) = self.entities.as_ref() else {
            return;
        };
        let w = &self.world;
        for e in t.iter() {
            let id = e.id();
            if t.ticks_before_self(id) != before || t.is_spectator(e) {
                continue;
            }
            let (Some(pos), Some(b)) = view(t, self.parked, id) else {
                continue;
            };
            if !w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4) {
                continue;
            }
            let living = matches!(e.entity_type(), ghast_entity::EntityType::Player)
                || e.class() == ghast_entity::EntityClass::Mob;
            self.around
                .others
                .push(ghast_physics::v1_16_5::OtherEntity::new(aabb(b), living));
        }
    }

    /// The tick with entities around and / or the extension state.
    #[inline(never)]
    pub(super) fn slow_tick(&mut self, input: &ghast_physics::TickInput, out: &[Outbound]) {
        // The key handling (before the entities tick): the riptide launch.
        if self.rt.using.is_some() || input.using_item {
            self.riptide_use(input, out);
        }
        self.around.others.clear();
        let spinning = self.ext.riptide_ticks > 0;
        if spinning {
            // The ones after the player, before the tracker ticks them.
            self.spin_contacts(false);
        }
        if self.entities.is_some() {
            self.entities_around();
        }
        if spinning {
            self.spin_contacts(true);
        }
        if !self.glide.rockets.is_empty() {
            // The rockets that tick before us (after the pushes of the entities before us).
            self.order_rockets();
            self.tick_rockets(true, input.yaw, input.pitch);
        }
        if let Some(r) = self.ride.as_deref() {
            match r {
                Ride16::Boat(_) => self.ride_tick(input),
                Ride16::Cart(_) => self.cart_tick(input),
                Ride16::Mount(_) => self.mount_tick(input),
            }
            if !self.pistons.is_empty() {
                self.tick_piston_blocks();
            }
            self.update_slow();
            return;
        }
        let around = ghast_physics::v1_16_5::Surroundings::new()
            .with_entities(&self.around.boxes)
            .with_others(&self.around.others);
        if !self.pistons.is_empty() {
            if let Some(r) = &mut self.rec {
                r.note_once("moving pistons not representable");
            }
            // The player's half: the moving blocks tick after every entity
            // ([`Sim16::tick_piston_phase`], from `tick_entities`).
            ghast_physics::v1_16_5::tick_player_among_pistons(
                &mut self.player,
                &mut self.ext,
                &around,
                input,
                &self.world,
                &self.pistons,
                &mut self.packets,
            );
        } else if self.ext.is_inert() {
            ghast_physics::v1_16_5::tick_in(
                &mut self.player,
                &around,
                input,
                &self.world,
                &mut self.packets,
            );
        } else {
            ghast_physics::v1_16_5::tick_ext(
                &mut self.player,
                &mut self.ext,
                &around,
                input,
                &self.world,
                &mut self.packets,
            );
        }
        if self.rt.using.is_some() {
            self.rt.use_ticks += 1;
        }
        self.update_slow();
    }
}