anitty 0.1.0

Anime character animation rendering for terminals
Documentation
//! Spine 3.8 binary validation, native ownership, posing and mesh adaptation.

use std::{
    ffi::{CStr, c_char, c_int, c_void},
    ptr::NonNull,
    sync::Mutex,
    time::Duration,
};

use super::raster::{BlendMode, Mesh};
use crate::Error;

// Only this module knows about C pointers. No runtime pointers escape the source.
pub(super) struct Runtime(NonNull<c_void>);

// Spine 3.8 assigns attachment IDs through a process-global counter on load.
static LOAD_LOCK: Mutex<()> = Mutex::new(());

#[repr(C)]
struct RawMesh {
    vertices: *const f32,
    uvs: *const f32,
    indices: *const u16,
    vertices_len: c_int,
    indices_len: c_int,
    page: c_int,
    blend: c_int,
    light: [f32; 4],
    dark: [f32; 3],
}

unsafe extern "C" {
    fn anitty_spine38_create(
        atlas: *const c_char,
        atlas_len: c_int,
        bytes: *const u8,
        len: c_int,
        error: *mut c_char,
        error_len: c_int,
    ) -> *mut c_void;
    fn anitty_spine38_dispose(runtime: *mut c_void);
    fn anitty_spine38_page(runtime: *mut c_void, index: c_int) -> *const c_char;
    fn anitty_spine38_animation_count(runtime: *mut c_void) -> c_int;
    fn anitty_spine38_animation(
        runtime: *mut c_void,
        index: c_int,
        duration: *mut f32,
    ) -> *const c_char;
    fn anitty_spine38_pose(runtime: *mut c_void, animation: c_int, time: f32);
    fn anitty_spine38_next_mesh(runtime: *mut c_void, mesh: *mut RawMesh) -> c_int;
}

impl Runtime {
    pub fn load(atlas: &[u8], skeleton: &[u8]) -> Result<Self, Error> {
        let version = binary_version(skeleton)?;
        if !version.starts_with("3.8.") || version == "3.8.75" {
            return Err(Error::Spine(format!(
                "unsupported Spine version {version}; expected 3.8 (except 3.8.75)"
            )));
        }
        let atlas_len =
            c_int::try_from(atlas.len()).map_err(|_| Error::Spine("atlas is too large".into()))?;
        let skeleton_len = c_int::try_from(skeleton.len())
            .map_err(|_| Error::Spine("skeleton is too large".into()))?;
        let mut error = [0 as c_char; 512];
        let _guard = LOAD_LOCK.lock().unwrap();
        // The C loader copies its inputs and writes a terminated error on failure.
        let pointer = unsafe {
            anitty_spine38_create(
                atlas.as_ptr().cast(),
                atlas_len,
                skeleton.as_ptr(),
                skeleton_len,
                error.as_mut_ptr(),
                error.len() as c_int,
            )
        };
        NonNull::new(pointer).map(Self).ok_or_else(|| {
            Error::Spine(
                unsafe { CStr::from_ptr(error.as_ptr()) }
                    .to_string_lossy()
                    .into_owned(),
            )
        })
    }

    pub fn pages(&self) -> Vec<String> {
        let mut pages = Vec::new();
        for index in 0.. {
            // The returned name belongs to the atlas, which outlives this borrow.
            let name = unsafe { anitty_spine38_page(self.0.as_ptr(), index) };
            if name.is_null() {
                break;
            }
            pages.push(
                unsafe { CStr::from_ptr(name) }
                    .to_string_lossy()
                    .into_owned(),
            );
        }
        pages
    }

    pub fn animations(&self) -> Result<Vec<(String, Duration)>, Error> {
        let count = unsafe { anitty_spine38_animation_count(self.0.as_ptr()) };
        (0..count)
            .map(|index| {
                let mut seconds = 0.0;
                // Index is within the runtime's animation array; names are owned by it.
                let name = unsafe {
                    CStr::from_ptr(anitty_spine38_animation(
                        self.0.as_ptr(),
                        index,
                        &mut seconds,
                    ))
                };
                let duration = Duration::try_from_secs_f32(seconds)
                    .map_err(|_| Error::Spine("invalid animation duration".into()))?;
                Ok((name.to_string_lossy().into_owned(), duration))
            })
            .collect()
    }

    pub fn pose(&mut self, animation: usize, time: f32) {
        // Callers select indices from animations(), and pass finite local time.
        unsafe { anitty_spine38_pose(self.0.as_ptr(), animation as c_int, time) }
    }

    pub fn meshes(&mut self, mut visit: impl FnMut(Mesh<'_>)) {
        let mut raw = std::mem::MaybeUninit::<RawMesh>::uninit();
        while unsafe { anitty_spine38_next_mesh(self.0.as_ptr(), raw.as_mut_ptr()) } != 0 {
            // The bridge initializes every field and returns nonempty arrays. The
            // callback's slices cannot outlive this call or the next runtime mutation.
            let raw = unsafe { raw.assume_init_ref() };
            visit(Mesh {
                vertices: unsafe {
                    std::slice::from_raw_parts(raw.vertices, raw.vertices_len as usize)
                },
                uvs: unsafe { std::slice::from_raw_parts(raw.uvs, raw.vertices_len as usize) },
                indices: unsafe {
                    std::slice::from_raw_parts(raw.indices, raw.indices_len as usize)
                },
                page: raw.page as usize,
                blend: match raw.blend {
                    0 => BlendMode::Normal,
                    1 => BlendMode::Additive,
                    2 => BlendMode::Multiply,
                    3 => BlendMode::Screen,
                    _ => unreachable!("Spine 3.8 blend mode"),
                },
                light: raw.light,
                dark: raw.dark,
            });
        }
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        // This object uniquely owns the runtime, including partially loaded data.
        unsafe { anitty_spine38_dispose(self.0.as_ptr()) }
    }
}

// Read only the version header before invoking the version-specific C parser.
fn binary_version(mut data: &[u8]) -> Result<&str, Error> {
    fn string<'a>(data: &mut &'a [u8]) -> Option<&'a [u8]> {
        let mut length = 0usize;
        for shift in (0..35).step_by(7) {
            let (&byte, rest) = data.split_first()?;
            *data = rest;
            length |= ((byte & 127) as usize).checked_shl(shift)?;
            if byte & 128 == 0 {
                let size = length.checked_sub(1)?;
                let value = data.get(..size)?;
                *data = &data[size..];
                return Some(value);
            }
        }
        None
    }
    let invalid = || Error::Spine("invalid Spine binary header".into());
    string(&mut data).ok_or_else(invalid)?;
    let version = string(&mut data).ok_or_else(invalid)?;
    // Four floats and the nonessential flag follow the version.
    if data.len() < 17 {
        return Err(invalid());
    }
    std::str::from_utf8(version).map_err(|_| invalid())
}