anitty 0.1.0

Anime character animation rendering for terminals
Documentation
use crate::{Error, RgbaFrame};

/// A source-space rectangle. Both sources use X right, Y down; Sprite units are
/// pixels, Spine units are skeleton units with the runtime's Y axis inverted.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Bounds {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

impl Bounds {
    fn validate(self) -> Result<(), Error> {
        if ![
            self.x,
            self.y,
            self.width,
            self.height,
            self.x + self.width,
            self.y + self.height,
        ]
        .into_iter()
        .all(f64::is_finite)
            || self.width <= 0.0
            || self.height <= 0.0
        {
            return Err(Error::InvalidRender(
                "view must be finite with positive dimensions",
            ));
        }
        Ok(())
    }
}

/// An overall transform in output pixels, applied after fitting the source.
/// Scale (negative values mirror), then rotate clockwise in radians about
/// `pivot`, then translate. `None` pivots around the canvas center.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Transform {
    pub translation: [f64; 2],
    pub scale: [f64; 2],
    pub rotation: f64,
    pub pivot: Option<[f64; 2]>,
}

impl Default for Transform {
    fn default() -> Self {
        Self {
            translation: [0.0; 2],
            scale: [1.0; 2],
            rotation: 0.0,
            pivot: None,
        }
    }
}

impl Transform {
    pub(crate) fn is_identity(self) -> bool {
        self.translation == [0.0; 2] && self.scale == [1.0; 2] && self.rotation == 0.0
    }

    // A canvas-centered mirror commutes with canvas clipping and needs no
    // resampling. Preserve the exact rasterized pixels, including triangle seams.
    pub(crate) fn canvas_mirror(self, width: u32, height: u32) -> Option<[bool; 2]> {
        (self.translation == [0.0; 2]
            && self.rotation == 0.0
            && self.scale.map(f64::abs) == [1.0; 2]
            && self
                .pivot
                .is_none_or(|p| p == [width as f64 * 0.5, height as f64 * 0.5]))
        .then_some(self.scale.map(|s| s < 0.0))
    }
}

pub(crate) fn mirror_frame(frame: &mut RgbaFrame, axes: [bool; 2]) {
    let (width, height) = (frame.width() as usize, frame.height() as usize);
    let pixels = frame.pixels_mut();
    if axes[0] {
        for row in pixels.chunks_exact_mut(width * 4) {
            for x in 0..width / 2 {
                for c in 0..4 {
                    row.swap(x * 4 + c, (width - 1 - x) * 4 + c);
                }
            }
        }
    }
    if axes[1] {
        let (top, bottom) = pixels.split_at_mut((height - height / 2) * width * 4);
        for (a, b) in top
            .chunks_exact_mut(width * 4)
            .zip(bottom.chunks_exact_mut(width * 4).rev())
        {
            a.swap_with_slice(b);
        }
    }
}

/// Per-call visual controls shared by Sprite and Spine. Defaults use automatic
/// fit and full opacity. Options never change playback mode or time.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RenderOptions {
    /// Fit this fixed source rectangle proportionally and centrally, without
    /// automatic padding. It defines the mapping, not an additional clip mask;
    /// only the output canvas clips the transformed content.
    pub view: Option<Bounds>,
    pub transform: Transform,
    /// Overall opacity in [0, 1], applied after the source's internal blending.
    pub opacity: f64,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            view: None,
            transform: Transform::default(),
            opacity: 1.0,
        }
    }
}

impl RenderOptions {
    pub(crate) fn validate(&self) -> Result<(), Error> {
        let t = self.transform;
        if !t
            .translation
            .into_iter()
            .chain(t.scale)
            .chain([t.rotation])
            .chain(t.pivot.into_iter().flatten())
            .all(f64::is_finite)
            || t.scale.contains(&0.0)
        {
            return Err(Error::InvalidRender(
                "transform must be finite with nonzero scales",
            ));
        }
        if !self.opacity.is_finite() || !(0.0..=1.0).contains(&self.opacity) {
            return Err(Error::InvalidRender("opacity must be finite and in [0, 1]"));
        }
        if let Some(view) = self.view {
            view.validate()?;
        }
        Ok(())
    }
}

/// The complete source-to-canvas mapping, including fit and overall transform.
/// Coordinates refer to pixel edges; pixel centers are at (x + 0.5, y + 0.5).
#[derive(Clone, Copy, Debug)]
pub struct RenderMapping {
    matrix: [[f64; 3]; 2],
    inverse: [[f64; 3]; 2],
}

impl RenderMapping {
    pub(crate) fn fit(
        bounds: Bounds,
        width: u32,
        height: u32,
        options: &RenderOptions,
    ) -> Result<Self, Error> {
        let bounds = options.view.unwrap_or(bounds);
        bounds.validate()?;
        let scale = (width as f64 / bounds.width).min(height as f64 / bounds.height);
        Self::new(
            [scale; 2],
            [
                width as f64 * 0.5 - (bounds.x + bounds.width * 0.5) * scale,
                height as f64 * 0.5 - (bounds.y + bounds.height * 0.5) * scale,
            ],
            width,
            height,
            options,
        )
    }

    pub(crate) fn new(
        scale: [f64; 2],
        offset: [f64; 2],
        width: u32,
        height: u32,
        options: &RenderOptions,
    ) -> Result<Self, Error> {
        RgbaFrame::byte_len(width, height)?;
        options.validate()?;
        let t = options.transform;
        let pivot = t.pivot.unwrap_or([width as f64 * 0.5, height as f64 * 0.5]);
        let (sin, cos) = t.rotation.sin_cos();
        let a = cos * t.scale[0];
        let b = -sin * t.scale[1];
        let c = sin * t.scale[0];
        let d = cos * t.scale[1];
        let matrix = [
            [
                a * scale[0],
                b * scale[1],
                a * offset[0] + b * offset[1] + (1.0 - a) * pivot[0] - b * pivot[1]
                    + t.translation[0],
            ],
            [
                c * scale[0],
                d * scale[1],
                c * offset[0] + d * offset[1] - c * pivot[0]
                    + (1.0 - d) * pivot[1]
                    + t.translation[1],
            ],
        ];
        let [[a, b, x], [c, d, y]] = matrix;
        let determinant = a * d - b * c;
        let inverse = [
            [
                d / determinant,
                -b / determinant,
                (b * y - d * x) / determinant,
            ],
            [
                -c / determinant,
                a / determinant,
                (c * x - a * y) / determinant,
            ],
        ];
        if !matrix
            .into_iter()
            .flatten()
            .chain(inverse.into_iter().flatten())
            .all(f64::is_finite)
        {
            return Err(Error::InvalidRender(
                "mapping exceeds finite invertible coordinates",
            ));
        }
        Ok(Self { matrix, inverse })
    }

    pub fn map_point(&self, point: [f64; 2]) -> [f64; 2] {
        self.matrix
            .map(|row| row[0] * point[0] + row[1] * point[1] + row[2])
    }

    pub fn unmap_point(&self, point: [f64; 2]) -> [f64; 2] {
        self.inverse
            .map(|row| row[0] * point[0] + row[1] * point[1] + row[2])
    }
}

pub(crate) fn apply_opacity(frame: &mut RgbaFrame, opacity: f64) {
    if opacity == 1.0 {
        return;
    }
    for pixel in frame.pixels_mut().chunks_exact_mut(4) {
        pixel[3] = (pixel[3] as f64 * opacity).round() as u8;
        if pixel[3] == 0 {
            pixel.fill(0);
        }
    }
}