anitty 0.1.0

Anime character animation rendering for terminals
Documentation
//! Animation sources that render into a common RGBA frame.

mod render;
mod sprite;

#[cfg(feature = "spine-38")]
mod spine;

pub use render::{Bounds, RenderMapping, RenderOptions, Transform};
#[cfg(feature = "spine-38")]
pub use spine::{SpineAnimation, SpineOptions};
pub use sprite::{SpriteAnimation, SpriteClip};

use crate::{Error, RgbaFrame};
use std::time::Duration;

/// Time sampling only; neither mode owns a clock or emits events.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlaybackMode {
    #[default]
    Loop,
    /// Play once and hold the final pose (or final Sprite frame).
    Once,
}

impl PlaybackMode {
    /// Use the source's `clip_duration`, which may be zero for a static pose.
    /// Loop never finishes; Once finishes at `elapsed >= clip_duration`.
    pub fn is_finished(self, elapsed: Duration, clip_duration: Duration) -> bool {
        self == Self::Once && elapsed >= clip_duration
    }

    #[cfg(feature = "spine-38")]
    pub(crate) fn sample_time(self, elapsed: Duration, duration: Duration) -> Duration {
        if duration.is_zero() {
            return Duration::ZERO;
        }
        match self {
            Self::Once => elapsed.min(duration),
            Self::Loop => {
                let nanos = elapsed.as_nanos() % duration.as_nanos();
                Duration::new(
                    (nanos / 1_000_000_000) as u64,
                    (nanos % 1_000_000_000) as u32,
                )
            }
        }
    }
}

/// An animation source independent of terminal output.
pub trait Animation {
    /// Clip names and actual durations, in source/definition order. The list is
    /// nonempty, has unique names, and includes [`Self::animation_name`]. A static
    /// Spine clip may have zero duration. Names are borrowed from this source.
    /// Querying allocates an iterator; rendering and selection do not use it.
    fn animations(&self) -> Box<dyn Iterator<Item = (&str, Duration)> + '_>;

    /// Name of the selected clip.
    fn animation_name(&self) -> &str;

    /// Hard-switch to a named clip. Does not own or reset a clock: subsequent
    /// render times are local to the selected clip; pass zero to start at its
    /// beginning. Selecting the current name is a no-op. On error the previous
    /// selection remains usable. Playback mode is retained; view/transform options
    /// are unaffected.
    fn set_animation(&mut self, name: &str) -> Result<(), Error>;

    /// This instance's time sampling mode, initially [`PlaybackMode::Loop`].
    fn playback_mode(&self) -> PlaybackMode;

    /// Set the sampling mode for subsequent renders. Retained across clip changes;
    /// does not reset or advance time. Both render methods honor this setting.
    fn set_playback_mode(&mut self, mode: PlaybackMode);

    /// Whether the selected clip has finished at this local time. Loop never
    /// finishes; Once finishes at the actual clip length, including zero.
    fn is_finished(&self, elapsed: Duration) -> bool {
        self.playback_mode()
            .is_finished(elapsed, self.clip_duration())
    }

    /// The nonzero duration of one complete cycle.
    fn duration(&self) -> Duration;

    /// Actual clip length, possibly zero for a static Spine pose. Use this for
    /// [`Self::is_finished`]; `duration` retains its nonzero-cycle contract.
    fn clip_duration(&self) -> Duration {
        self.duration()
    }

    /// Source extent in X-right/Y-down coordinates. Spine bounds are estimated
    /// across the selected animation; Sprite bounds are the original frame edges.
    fn bounds(&self) -> Bounds;

    /// Query the mapping without rendering or advancing animation time.
    fn mapping(
        &self,
        width: u32,
        height: u32,
        options: &RenderOptions,
    ) -> Result<RenderMapping, Error> {
        RenderMapping::fit(self.bounds(), width, height, options)
    }

    /// Render into a transparent RGBA canvas of exactly `width` by `height` pixels,
    /// at an absolute elapsed time within the selected clip, using [`Self::playback_mode`].
    /// Content is fitted proportionally and centered; unused space is transparent.
    ///
    /// Backward seeks are supported. The returned frame is borrowed until the
    /// next mutable access, allowing sources to reuse their render buffer.
    /// Zero or unaddressable dimensions return an error. Sources reuse output
    /// buffers across calls; callers do not need to send a separate resize event.
    fn render(&mut self, elapsed: Duration, width: u32, height: u32) -> Result<&RgbaFrame, Error> {
        self.render_with_options(elapsed, width, height, &RenderOptions::default())
    }

    /// Render using the instance's playback mode and explicit view, transform and
    /// opacity. Options apply only to this call; they never change playback mode or time.
    fn render_with_options(
        &mut self,
        elapsed: Duration,
        width: u32,
        height: u32,
        options: &RenderOptions,
    ) -> Result<&RgbaFrame, Error>;
}