1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#[cfg(feature = "unstable-load-from-file")]
mod parse;

#[cfg(feature = "unstable-load-from-file")]
pub(crate) mod load;

use std::{ops::RangeInclusive, time::Duration};

use bevy_reflect::TypeUuid;

#[cfg(feature = "unstable-load-from-file")]
pub use parse::AnimationParseError;

#[cfg(feature = "unstable-load-from-file")]
use serde::Deserialize;

/// Asset that define an animation of `TextureAtlasSprite`
///
/// See crate level documentation for usage
#[derive(Debug, Clone, Default, TypeUuid)]
#[cfg_attr(feature = "unstable-load-from-file", derive(Deserialize))]
#[cfg_attr(
    feature = "unstable-load-from-file",
    serde(try_from = "parse::AnimationDto")
)]
#[uuid = "6378e9c2-ecd1-4029-9cd5-801caf68517c"]
pub struct SpriteSheetAnimation {
    /// Frames
    pub(crate) frames: Vec<Frame>,
    /// Animation mode
    pub(crate) mode: Mode,
}

/// Animation mode (run once, repeat or ping-pong)
///
/// Deprecated
/// ---
/// This is not exposed in any of the public APIs of the crate so there is no reason to depend on
/// it. Use 'builder-style' methods like [`SpriteSheetAnimation::repeat`] instead.
#[deprecated]
#[doc(hidden)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum AnimationMode {
    /// Runs the animation once and then stop playing
    Once,

    /// Repeat the animation forever
    Repeat,

    /// Repeat the animation forever, going back and forth between
    /// the first and last frame.
    PingPong,
}

/// A single animation frame
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
pub struct Frame {
    /// Index in the sprite atlas
    pub(crate) index: usize,
    /// How long should the frame be displayed
    pub(crate) duration: Duration,
}

impl SpriteSheetAnimation {
    /// Create a new animation from frames
    #[must_use]
    pub fn from_frames(frames: Vec<Frame>) -> Self {
        Self {
            frames,
            mode: Mode::default(),
        }
    }

    /// Create a new animation from index-range, using the same frame duration for each frame.
    ///
    /// For more granular configuration, see [`from_frames`](SpriteSheetAnimation::from_frames)
    ///
    /// # Panics
    ///
    /// Panics if the duration is zero
    #[must_use]
    pub fn from_range(index_range: RangeInclusive<usize>, frame_duration: Duration) -> Self {
        Self::from_iter(index_range, frame_duration)
    }

    /// Create a new animation from an index iterator, using the same frame duration for each frame.
    ///
    /// # Example
    ///
    /// You may use this to create a reversed animation:
    /// ```
    /// # use benimator::SpriteSheetAnimation;
    /// # use std::time::Duration;
    /// let animation = SpriteSheetAnimation::from_iter((0..5).rev(), Duration::from_millis(100));
    /// ```
    ///
    /// For more granular configuration, see [`from_frames`](SpriteSheetAnimation::from_frames)
    ///
    /// # Panics
    ///
    /// Panics if the duration is zero
    pub fn from_iter(indices: impl IntoIterator<Item = usize>, frame_duration: Duration) -> Self {
        indices
            .into_iter()
            .map(|index| Frame::new(index, frame_duration))
            .collect()
    }

    /// Runs the animation once and then stop playing
    #[must_use]
    pub fn once(mut self) -> Self {
        self.mode = Mode::Once;
        self
    }

    /// Repeat the animation forever
    #[must_use]
    pub fn repeat(mut self) -> Self {
        self.mode = Mode::RepeatFrom(0);
        self
    }

    /// Repeat the animation forever, from a given frame index (loop back to it at the end of the
    /// animation)
    #[must_use]
    pub fn repeat_from(mut self, frame_index: usize) -> Self {
        self.mode = Mode::RepeatFrom(frame_index);
        self
    }

    /// Repeat the animation forever, going back and forth between the first and last frame.
    #[must_use]
    pub fn ping_pong(mut self) -> Self {
        self.mode = Mode::PingPong;
        self
    }

    pub(crate) fn has_frames(&self) -> bool {
        !self.frames.is_empty()
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(crate) enum Mode {
    Once,
    RepeatFrom(usize),
    PingPong,
}

impl FromIterator<Frame> for SpriteSheetAnimation {
    fn from_iter<T: IntoIterator<Item = Frame>>(iter: T) -> Self {
        Self::from_frames(iter.into_iter().collect())
    }
}

impl Default for Mode {
    #[inline]
    fn default() -> Self {
        Self::RepeatFrom(0)
    }
}

#[allow(deprecated)]
impl Default for AnimationMode {
    #[inline]
    fn default() -> Self {
        Self::Repeat
    }
}

impl Frame {
    /// Create a new animation frame
    ///
    /// The duration must be > 0
    ///
    /// # Panics
    ///
    /// Panics if the duration is zero
    #[inline]
    #[must_use]
    pub fn new(index: usize, duration: Duration) -> Self {
        assert!(
            !duration.is_zero(),
            "zero-duration is invalid for animation frame"
        );
        Self { index, duration }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn panics_for_zero_duration() {
        let _ = Frame::new(0, Duration::ZERO);
    }
}