ghast-entity 0.5.5

Entity tracking for the ghast Minecraft Java Edition client library: zero-allocation parsing of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 entity packets, vanilla-exact positions, O(1) lookup
Documentation
//! Hanging entities (paintings, item frames, leash knots): where the client puts them and their
//! box, both from the block they hang on and their facing (`AbstractDecorationEntity
//! .updateAttachmentPosition`), not from a size table.

use crate::entity::{Entity, EntityType};

/// 1.8 – 1.12 `Direction.fromHorizontal`: south, west, north, east as `(x, z)` offsets.
const HORIZONTAL: [(i32, i32); 4] = [(0, 1), (-1, 0), (0, -1), (1, 0)];

/// 1.8 / 1.12 painting motives by title: width and height in pixels (`PaintingEntity.PaintingMotive`).
const MOTIVES_1_8: [(&str, u8, u8); 26] = [
    ("Kebab", 16, 16),
    ("Aztec", 16, 16),
    ("Alban", 16, 16),
    ("Aztec2", 16, 16),
    ("Bomb", 16, 16),
    ("Plant", 16, 16),
    ("Wasteland", 16, 16),
    ("Pool", 32, 16),
    ("Courbet", 32, 16),
    ("Sea", 32, 16),
    ("Sunset", 32, 16),
    ("Creebet", 32, 16),
    ("Wanderer", 16, 32),
    ("Graham", 16, 32),
    ("Match", 32, 32),
    ("Bust", 32, 32),
    ("Stage", 32, 32),
    ("Void", 32, 32),
    ("SkullAndRoses", 32, 32),
    ("Wither", 32, 32),
    ("Fighters", 64, 32),
    ("Pointer", 64, 64),
    ("Pigscene", 64, 64),
    ("BurningSkull", 64, 64),
    ("Skeleton", 64, 48),
    ("DonkeyKong", 64, 48),
];

/// A 1.8 / 1.12 painting title's size as the painting's data keeps it above the direction byte (bits
/// 8 – 15: width / 16 in the high nibble, height / 16 in the low one). An unknown title keeps the client's default motive (Kebab).
pub(crate) fn motive_1_8(title: &[u8]) -> u8 {
    let (_, w, h) = MOTIVES_1_8
        .iter()
        .find(|(n, _, _)| n.as_bytes() == title)
        .copied()
        .unwrap_or(MOTIVES_1_8[0]);
    (w / 16) << 4 | (h / 16)
}

/// 1.16.5 painting motive size by registry id (the same 26 motives in the same order).
pub(crate) fn motive_1_16(id: i32) -> u8 {
    let (_, w, h) = MOTIVES_1_8
        .get(usize::try_from(id).unwrap_or(0))
        .copied()
        .unwrap_or(MOTIVES_1_8[0]);
    (w / 16) << 4 | (h / 16)
}

/// 1.16.5 registry ids: painting, item frame, leash knot.
const PAINTING_1_16: u16 = 55;
const ITEM_FRAME_1_16: u16 = 38;
const LEASH_KNOT_1_16: u16 = 40;

/// The kinds of hanging entity.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Painting,
    ItemFrame,
    LeashKnot,
}

/// The kind of a tracked hanging entity (by version).
fn kind(e: &Entity) -> Option<Kind> {
    use crate::entity::Era;
    let legacy = matches!(e.era, Era::V1_8 | Era::V1_12);
    match e.ty {
        EntityType::Painting if legacy => Some(Kind::Painting),
        EntityType::LegacyObject(71) if legacy => Some(Kind::ItemFrame),
        EntityType::LegacyObject(77) if legacy => Some(Kind::LeashKnot),
        EntityType::Registry(PAINTING_1_16) if e.era == Era::V1_16 => Some(Kind::Painting),
        EntityType::Registry(ITEM_FRAME_1_16) if e.era == Era::V1_16 => Some(Kind::ItemFrame),
        EntityType::Registry(LEASH_KNOT_1_16) if e.era == Era::V1_16 => Some(Kind::LeashKnot),
        _ => None,
    }
}

/// `(width, height)` in pixels of a painting or item frame (`getWidth` / `getHeight`), from
/// the type alone (at spawn the entity's era is not set yet).
fn size(e: &Entity) -> Option<(i32, i32)> {
    match e.ty {
        EntityType::Painting | EntityType::Registry(PAINTING_1_16) => {
            let m = (e.data >> 8) & 0xff;
            Some(((m >> 4) * 16, (m & 15) * 16))
        }
        EntityType::LegacyObject(71) | EntityType::Registry(ITEM_FRAME_1_16) => Some((12, 12)),
        _ => None,
    }
}

/// 1.16 `Direction.byId`: down, up, north, south, west, east as `(x, y, z)` offsets.
const BY_ID: [(i32, i32, i32); 6] = [
    (0, -1, 0),
    (0, 1, 0),
    (0, 0, -1),
    (0, 0, 1),
    (-1, 0, 0),
    (1, 0, 0),
];

/// 1.16 `ItemFrameEntity.updateAttachmentPosition`: the frame on block `b` facing `dir`
/// (`Direction.byId`, up and down too).
pub(crate) fn frame_1_16(b: [i32; 3], dir: i32) -> [f64; 3] {
    let (ox, oy, oz) = BY_ID[usize::try_from(dir).unwrap_or(0).min(5)];
    [
        f64::from(b[0]) + 0.5 - f64::from(ox) * 0.46875,
        f64::from(b[1]) + 0.5 - f64::from(oy) * 0.46875,
        f64::from(b[2]) + 0.5 - f64::from(oz) * 0.46875,
    ]
}

/// `updateAttachmentPosition` on 1.8 / 1.12: the position of a painting or item frame hanging on
/// block `b` facing `dir` (horizontal index), `None` for other entities.
pub(crate) fn attach_1_8(e: &Entity, b: [i32; 3], dir: i32) -> Option<[f64; 3]> {
    let (w, h) = size(e)?;
    let (ox, oz) = HORIZONTAL[(dir & 3) as usize];
    // rotateYCounterclockwise: south -> east, west -> south, north -> west, east -> north.
    let (cx, cz) = (oz, -ox);
    let half = |n: i32| if n % 32 == 0 { 0.5 } else { 0.0 };
    let mut d = f64::from(b[0]) + 0.5;
    let mut y = f64::from(b[1]) + 0.5;
    let mut f = f64::from(b[2]) + 0.5;
    d -= f64::from(ox) * 0.46875;
    f -= f64::from(oz) * 0.46875;
    y += half(h);
    d += half(w) * f64::from(cx);
    f += half(w) * f64::from(cz);
    Some([d, y, f])
}

/// 1.8 / 1.12 `LeashKnotEntity(world, pos)`: the knot sits at the block's centre.
pub(crate) fn knot_1_8(b: [i32; 3]) -> [f64; 3] {
    [
        f64::from(b[0]) + 0.5,
        f64::from(b[1]) + 0.5,
        f64::from(b[2]) + 0.5,
    ]
}

/// The box of a hanging entity at position `p` (`None` for other entities).
pub(crate) fn hanging_box(e: &Entity, p: [f64; 3]) -> Option<[f64; 6]> {
    let k = kind(e)?;
    let [d, y, f] = p;
    if k == Kind::ItemFrame && e.era == crate::entity::Era::V1_16 {
        // One pixel thick along the facing's axis (any of the six).
        let (ox, oy, _) = BY_ID[usize::try_from(e.data).unwrap_or(0).min(5)];
        let (mut h, mut i, mut j) = (12.0_f64, 12.0_f64, 12.0_f64);
        if ox != 0 {
            h = 1.0;
        } else if oy != 0 {
            i = 1.0;
        } else {
            j = 1.0;
        }
        let (h, i, j) = (h / 32.0, i / 32.0, j / 32.0);
        return Some([d - h, y - i, f - j, d + h, y + i, f + j]);
    }
    if k == Kind::LeashKnot {
        return Some([
            d - 0.1875,
            y - 0.25 + 0.125,
            f - 0.1875,
            d + 0.1875,
            y + 0.25 + 0.125,
            f + 0.1875,
        ]);
    }
    let (w, h) = size(e)?;
    let (ox, _) = HORIZONTAL[(e.data & 3) as usize];
    let (mut j, k, mut l) = (f64::from(w), f64::from(h), f64::from(w));
    // One pixel thick along the facing axis.
    if ox == 0 {
        l = 1.0;
    } else {
        j = 1.0;
    }
    j /= 32.0;
    let k = k / 32.0;
    l /= 32.0;
    Some([d - j, y - k, f - l, d + j, y + k, f + l])
}

/// `getTargetingMargin` of a hanging entity: 1.8 0.1 (`Entity`), item frames 0; 1.12 and
/// 1.16 0.
pub(crate) fn margin(e: &Entity) -> Option<f32> {
    let k = kind(e)?;
    Some(
        if e.era == crate::entity::Era::V1_8 && k != Kind::ItemFrame {
            0.1
        } else {
            0.0
        },
    )
}