use glam::Vec2;
use std::{fmt, sync::Arc, time::Duration};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpriteError {
InvalidRegion,
EmptyName,
EmptyClip,
ZeroDuration,
DurationOverflow,
}
impl fmt::Display for SpriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidRegion => "sprite region must have nonzero dimensions and u32 endpoints",
Self::EmptyName => "animation clip must have a nonblank name",
Self::EmptyClip => "animation clip must contain at least one frame",
Self::ZeroDuration => "animation frame duration must be nonzero",
Self::DurationOverflow => "animation clip duration exceeds Duration::MAX",
})
}
}
impl std::error::Error for SpriteError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpriteRegion {
x: u32,
y: u32,
width: u32,
height: u32,
}
impl SpriteRegion {
pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, SpriteError> {
if width == 0
|| height == 0
|| x.checked_add(width).is_none()
|| y.checked_add(height).is_none()
{
return Err(SpriteError::InvalidRegion);
}
Ok(Self {
x,
y,
width,
height,
})
}
pub fn x(self) -> u32 {
self.x
}
pub fn y(self) -> u32 {
self.y
}
pub fn width(self) -> u32 {
self.width
}
pub fn height(self) -> u32 {
self.height
}
pub fn fits(self, width: u32, height: u32) -> bool {
self.x + self.width <= width && self.y + self.height <= height
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpriteTransform {
pub position: Vec2,
pub size: Vec2,
pub origin: Vec2,
pub rotation: f32,
pub flip_x: bool,
pub flip_y: bool,
}
impl Default for SpriteTransform {
fn default() -> Self {
Self {
position: Vec2::ZERO,
size: Vec2::ONE,
origin: Vec2::ZERO,
rotation: 0.0,
flip_x: false,
flip_y: false,
}
}
}
impl SpriteTransform {
pub fn is_valid(self) -> bool {
self.position.is_finite()
&& self.size.is_finite()
&& self.size.min_element() > 0.0
&& self.origin.is_finite()
&& self.rotation.is_finite()
&& self.rotation.to_degrees().is_finite()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpriteFrame {
pub region: SpriteRegion,
pub duration: Duration,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlaybackMode {
Loop,
Once,
}
#[derive(Debug)]
pub struct AnimationClip {
name: String,
frames: Vec<SpriteFrame>,
ends: Vec<Duration>,
duration: Duration,
mode: PlaybackMode,
}
impl AnimationClip {
pub fn new(
name: impl Into<String>,
frames: Vec<SpriteFrame>,
mode: PlaybackMode,
) -> Result<Self, SpriteError> {
let name = name.into();
if name.trim().is_empty() {
return Err(SpriteError::EmptyName);
}
if frames.is_empty() {
return Err(SpriteError::EmptyClip);
}
let mut duration = Duration::ZERO;
let mut ends = Vec::with_capacity(frames.len());
for frame in &frames {
if frame.duration.is_zero() {
return Err(SpriteError::ZeroDuration);
}
duration = duration
.checked_add(frame.duration)
.ok_or(SpriteError::DurationOverflow)?;
ends.push(duration);
}
Ok(Self {
name,
frames,
ends,
duration,
mode,
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn frames(&self) -> &[SpriteFrame] {
&self.frames
}
pub fn duration(&self) -> Duration {
self.duration
}
pub fn mode(&self) -> PlaybackMode {
self.mode
}
}
#[derive(Clone, Debug)]
pub struct AnimationCompleted {
pub clip: Arc<AnimationClip>,
}
#[derive(Clone, Debug)]
pub struct AnimationPlayer {
clip: Arc<AnimationClip>,
elapsed: Duration,
paused: bool,
finished: bool,
}
impl AnimationPlayer {
pub fn new(clip: impl Into<Arc<AnimationClip>>) -> Self {
Self {
clip: clip.into(),
elapsed: Duration::ZERO,
paused: false,
finished: false,
}
}
pub fn play(&mut self, clip: impl Into<Arc<AnimationClip>>) {
*self = Self::new(clip);
}
pub fn reset(&mut self) {
self.elapsed = Duration::ZERO;
self.finished = false;
}
pub fn pause(&mut self) {
self.paused = true;
}
pub fn resume(&mut self) {
self.paused = false;
}
pub fn is_paused(&self) -> bool {
self.paused
}
pub fn is_finished(&self) -> bool {
self.finished
}
pub fn clip(&self) -> &Arc<AnimationClip> {
&self.clip
}
pub fn elapsed(&self) -> Duration {
self.elapsed
}
pub fn frame_index(&self) -> usize {
self.clip
.ends
.partition_point(|end| *end <= self.elapsed)
.min(self.clip.frames.len() - 1)
}
pub fn frame(&self) -> &SpriteFrame {
&self.clip.frames[self.frame_index()]
}
pub fn advance(&mut self, dt: Duration) -> Option<AnimationCompleted> {
if self.paused || self.finished || dt.is_zero() {
return None;
}
let next = self.elapsed.as_nanos() + dt.as_nanos();
let duration = self.clip.duration.as_nanos();
let next = match self.clip.mode {
PlaybackMode::Loop => next % duration,
PlaybackMode::Once if next >= duration => {
self.elapsed = self.clip.duration;
self.finished = true;
return Some(AnimationCompleted {
clip: Arc::clone(&self.clip),
});
}
PlaybackMode::Once => next,
};
self.elapsed = Duration::new((next / 1_000_000_000) as u64, (next % 1_000_000_000) as u32);
None
}
}
#[cfg(test)]
mod tests;