ghast-client 0.5.4

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: the client's own block predictions — the server's answers to digs and the plain
//! placements known exactly.

use super::*;

impl Sim16 {
    /// `acknowledge_player_digging` (`ClientPlayerInteractionManager.processPlayerActionResponse`):
    /// the server's state of the block replaces the client's when they differ, unless the server
    /// approved a start the client recorded; the player returns to where it was when the action
    /// was sent if the block would hold it. Oldest records go from 50 on.
    #[cold]
    #[inline(never)]
    pub(super) fn action_answer(
        &mut self,
        p: &ghast_protocol::v1_16_5::play::clientbound::AcknowledgePlayerDigging,
    ) {
        use ghast_data::v1_16_5::BlockState;
        let pos = p.location;
        let at = u8::try_from(p.status)
            .ok()
            .and_then(|a| self.unacked.remove(pos, a));
        let state = u16::try_from(p.block)
            .ok()
            .and_then(BlockState::from_id)
            .unwrap_or(BlockState::AIR);
        let now = self
            .world
            .block_state(pos.x, pos.y, pos.z)
            .unwrap_or(BlockState::AIR);
        let start = p.status == crate::common::DigStatus::Start.id();
        if now != state && (at.is_none() || !p.successful || !start) {
            log::debug!(
                "dig answer {} ({}): {pos:?} {} back to the server's {}",
                p.status,
                if p.successful { "approved" } else { "refused" },
                now.block().name(),
                state.block().name()
            );
            self.world.set_block_state(pos.x, pos.y, pos.z, state);
            if let Some(at) = at
                && holds_player(state, pos, &self.player)
            {
                // Entity.updatePosition: the position and the previous position.
                self.player.set_position(at[0], at[1], at[2]);
                self.snapped = true;
            }
        }
        self.unacked.trim();
    }
}

impl Sim16 {
    /// `ClientPlayerInteractionManager.interactBlock` → `BlockItem.place` on the client, when its
    /// result is known exactly ([`crate::sim::predict::PlaceSent`]; the same rules as 26.x,
    /// with this version's blocks): the position and the state placed.
    pub(super) fn plain_placement(
        &self,
        p: &crate::sim::predict::PlaceSent<'_>,
    ) -> Option<(BlockPos, ghast_data::v1_16_5::BlockState)> {
        use crate::common::GameMode;
        use ghast_data::v1_16_5::{Block, Item};
        // ItemStack.useOnBlock: adventure needs CanPlaceOn; spectators never place.
        if !matches!(p.game_mode, GameMode::Survival | GameMode::Creative) {
            return None;
        }
        let stack = p.held?;
        // BlockStateTag / BlockEntityTag (BlockItem.placeFromTag).
        if stack.nbt().is_some() {
            return None;
        }
        let item = Item::from_id(u16::try_from(stack.id()).ok()?)?;
        let block = Block::from_name(item.info().name)?;
        let state = if block.layout().state_count == 1 {
            block.default_state()
        } else if is_pillar_16(block) {
            // PillarBlock.getPlacementState: the axis of the clicked face.
            use crate::common::Face;
            let axis = match p.face {
                Face::Down | Face::Up => "y",
                Face::North | Face::South => "z",
                Face::West | Face::East => "x",
            };
            block
                .default_state()
                .with(ghast_data::v1_16_5::Property::Axis, axis)?
        } else {
            return None;
        };
        if !state.full_cube()
            // ConcretePowderBlock.getPlacementState: concrete next to water.
            || block.info().name.ends_with("_concrete_powder")
        {
            return None;
        }
        if !crate::sim::predict::border_contains(
            &ghast_physics::BlockView::world_border(&self.world),
            p.pos,
        ) {
            return None;
        }
        let clicked = self.world.block_state(p.pos.x, p.pos.y, p.pos.z)?;
        if !clicked.full_cube() {
            return None;
        }
        // AbstractBlock.onUse of the clicked block, unless sneaking with an item.
        if !(p.sneaking && p.any_item) && activated_full_cube_16(clicked.block().info().name) {
            return None;
        }
        let at = p.face.offset(p.pos);
        if !(0..256).contains(&at.y) {
            return None;
        }
        let there = self.world.block_state(at.x, at.y, at.z)?;
        let name = there.block().info().name;
        if !(there.is_air() || name == "water" || name == "lava") {
            return None;
        }
        // World.canPlace: the player's own box (other entities: the server's updates).
        if holds_player(state, at, &self.player) {
            return None;
        }
        Some((at, state))
    }
}

/// Full-cube blocks whose `onUse` may accept a right click with a block item (from the 1.16.5
/// classes; beehives, pumpkins, TNT, redstone ore and fletching tables pass it on).
fn activated_full_cube_16(name: &str) -> bool {
    const LIST: &[&str] = &[
        "barrel",
        "beacon",
        "blast_furnace",
        "cartography_table",
        "chain_command_block",
        "command_block",
        "crafting_table",
        "dispenser",
        "dropper",
        "furnace",
        "jigsaw",
        "jukebox",
        "loom",
        "note_block",
        "repeating_command_block",
        "respawn_anchor",
        "smithing_table",
        "smoker",
        "structure_block",
    ];
    name.ends_with("shulker_box") || LIST.contains(&name)
}

/// 1.16.5 `Entity.collidesWithStateAtPos`: the state's collision shape at `pos`, for the
/// player's context (scaffolding) and with its model offset (bamboo), overlaps the player's box.
fn holds_player(
    state: ghast_data::v1_16_5::BlockState,
    pos: BlockPos,
    p: &ghast_physics::v1_16_5::PlayerState,
) -> bool {
    let b = &p.bb;
    ghast_physics::v1_16_5::state_collides(
        state,
        [pos.x, pos.y, pos.z],
        [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
        &ghast_physics::v1_16_5::CollisionContext::new(p.pos[1], p.input.sneaking),
    )
}

/// A block whose only property is `axis` (x, y, z): logs, wood, stems, hyphae, pillars, basalt,
/// hay, bone blocks (1.16.5 `PillarBlock`, placed along the clicked face's axis).
fn is_pillar_16(block: ghast_data::v1_16_5::Block) -> bool {
    let mut props = block.properties();
    props.len() == 1
        && props.next().is_some_and(|d| {
            d.property == ghast_data::v1_16_5::Property::Axis && d.values.len() == 3
        })
}