Skip to main content

rayengine_core/
sprite.rs

1//! Validated sprite regions and CPU-only animation with explicit simulation time.
2
3use glam::Vec2;
4use std::{fmt, sync::Arc, time::Duration};
5
6/// Invalid sprite geometry or animation definition.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum SpriteError {
9    /// Region dimensions are zero or their endpoints overflow `u32`.
10    InvalidRegion,
11    /// Clip name is empty or contains only whitespace.
12    EmptyName,
13    /// Clip has no frames.
14    EmptyClip,
15    /// Frame duration is zero.
16    ZeroDuration,
17    /// Sum of frame durations exceeds [`Duration::MAX`].
18    DurationOverflow,
19}
20
21impl fmt::Display for SpriteError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.write_str(match self {
24            Self::InvalidRegion => "sprite region must have nonzero dimensions and u32 endpoints",
25            Self::EmptyName => "animation clip must have a nonblank name",
26            Self::EmptyClip => "animation clip must contain at least one frame",
27            Self::ZeroDuration => "animation frame duration must be nonzero",
28            Self::DurationOverflow => "animation clip duration exceeds Duration::MAX",
29        })
30    }
31}
32impl std::error::Error for SpriteError {}
33
34/// A positive, axis-aligned source rectangle in top-left texture pixel coordinates.
35/// Bounds against an actual texture are checked at drawing time.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct SpriteRegion {
38    x: u32,
39    y: u32,
40    width: u32,
41    height: u32,
42}
43
44impl SpriteRegion {
45    /// Rejects zero dimensions and overflowing endpoints. Flips belong to
46    /// [`SpriteTransform`], so source dimensions are always positive.
47    pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, SpriteError> {
48        if width == 0
49            || height == 0
50            || x.checked_add(width).is_none()
51            || y.checked_add(height).is_none()
52        {
53            return Err(SpriteError::InvalidRegion);
54        }
55        Ok(Self {
56            x,
57            y,
58            width,
59            height,
60        })
61    }
62    /// Left edge in texture pixels.
63    pub fn x(self) -> u32 {
64        self.x
65    }
66    /// Top edge in texture pixels.
67    pub fn y(self) -> u32 {
68        self.y
69    }
70    /// Width in texture pixels.
71    pub fn width(self) -> u32 {
72        self.width
73    }
74    /// Height in texture pixels.
75    pub fn height(self) -> u32 {
76        self.height
77    }
78    /// Whether the entire region is inside these texture dimensions.
79    pub fn fits(self, width: u32, height: u32) -> bool {
80        self.x + self.width <= width && self.y + self.height <= height
81    }
82}
83
84/// Sprite destination geometry in world units, with positive size and explicit pivot.
85/// Flips change texture sampling; they do not move the pivot or geometry.
86#[derive(Clone, Copy, Debug, PartialEq)]
87pub struct SpriteTransform {
88    /// World position at which the local origin is placed.
89    pub position: Vec2,
90    /// Destination width and height in world units, both strictly positive.
91    pub size: Vec2,
92    /// Pivot offset from the unrotated destination's top-left, in world units.
93    /// It may be outside the destination. Use `size * 0.5` for a centered pivot.
94    pub origin: Vec2,
95    /// Clockwise rotation in radians, matching [`crate::camera::Camera2D`].
96    pub rotation: f32,
97    /// Reverse horizontal source sampling.
98    pub flip_x: bool,
99    /// Reverse vertical source sampling.
100    pub flip_y: bool,
101}
102
103impl Default for SpriteTransform {
104    fn default() -> Self {
105        Self {
106            position: Vec2::ZERO,
107            size: Vec2::ONE,
108            origin: Vec2::ZERO,
109            rotation: 0.0,
110            flip_x: false,
111            flip_y: false,
112        }
113    }
114}
115
116impl SpriteTransform {
117    /// Rejects nonfinite coordinates, nonpositive size, and rotations whose
118    /// conversion to the backend's degrees would overflow.
119    pub fn is_valid(self) -> bool {
120        self.position.is_finite()
121            && self.size.is_finite()
122            && self.size.min_element() > 0.0
123            && self.origin.is_finite()
124            && self.rotation.is_finite()
125            && self.rotation.to_degrees().is_finite()
126    }
127}
128
129/// One selected sprite-sheet region and its simulation duration.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct SpriteFrame {
132    /// Region selected while this frame is current.
133    pub region: SpriteRegion,
134    /// Time spent on this frame; must be nonzero when constructing a clip.
135    pub duration: Duration,
136}
137
138/// Behavior at the end of a clip.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum PlaybackMode {
141    /// Wrap to the first frame; never emit a completion event.
142    Loop,
143    /// Hold the last frame and emit one completion event per play/reset.
144    Once,
145}
146
147/// Immutable named clip. Share with [`Arc`] between independent players.
148#[derive(Debug)]
149pub struct AnimationClip {
150    name: String,
151    frames: Vec<SpriteFrame>,
152    ends: Vec<Duration>,
153    duration: Duration,
154    mode: PlaybackMode,
155}
156
157impl AnimationClip {
158    /// Validates a nonblank name, at least one frame, positive durations and
159    /// a representable total duration. Texture bounds are checked when drawn.
160    pub fn new(
161        name: impl Into<String>,
162        frames: Vec<SpriteFrame>,
163        mode: PlaybackMode,
164    ) -> Result<Self, SpriteError> {
165        let name = name.into();
166        if name.trim().is_empty() {
167            return Err(SpriteError::EmptyName);
168        }
169        if frames.is_empty() {
170            return Err(SpriteError::EmptyClip);
171        }
172        let mut duration = Duration::ZERO;
173        let mut ends = Vec::with_capacity(frames.len());
174        for frame in &frames {
175            if frame.duration.is_zero() {
176                return Err(SpriteError::ZeroDuration);
177            }
178            duration = duration
179                .checked_add(frame.duration)
180                .ok_or(SpriteError::DurationOverflow)?;
181            ends.push(duration);
182        }
183        Ok(Self {
184            name,
185            frames,
186            ends,
187            duration,
188            mode,
189        })
190    }
191    /// Game-defined clip name, preserved verbatim.
192    pub fn name(&self) -> &str {
193        &self.name
194    }
195    /// Ordered frames and their individual durations.
196    pub fn frames(&self) -> &[SpriteFrame] {
197        &self.frames
198    }
199    /// Total time for one traversal.
200    pub fn duration(&self) -> Duration {
201        self.duration
202    }
203    /// Behavior at the clip's end.
204    pub fn mode(&self) -> PlaybackMode {
205        self.mode
206    }
207}
208
209/// A one-shot completion returned exactly once by [`AnimationPlayer::advance`].
210/// Can be sent to [`crate::events::Events`]; retains the completed clip even
211/// if the player immediately switches to another clip.
212#[derive(Clone, Debug)]
213pub struct AnimationCompleted {
214    /// Immutable clip that reached its end.
215    pub clip: Arc<AnimationClip>,
216}
217
218/// CPU playback cursor. Drawing/reading a frame never changes playback.
219/// Advancement uses integer nanoseconds and binary frame lookup, so large
220/// time steps do not iterate over every crossed frame or loop.
221#[derive(Clone, Debug)]
222pub struct AnimationPlayer {
223    clip: Arc<AnimationClip>,
224    elapsed: Duration,
225    paused: bool,
226    finished: bool,
227}
228
229impl AnimationPlayer {
230    /// Starts at the first frame, unpaused. Accepts an owned clip or shared `Arc`.
231    pub fn new(clip: impl Into<Arc<AnimationClip>>) -> Self {
232        Self {
233            clip: clip.into(),
234            elapsed: Duration::ZERO,
235            paused: false,
236            finished: false,
237        }
238    }
239    /// Switches/restarts a clip, clearing pause and completion state.
240    pub fn play(&mut self, clip: impl Into<Arc<AnimationClip>>) {
241        *self = Self::new(clip);
242    }
243    /// Rewinds this clip and rearms its completion event, preserving pause state.
244    pub fn reset(&mut self) {
245        self.elapsed = Duration::ZERO;
246        self.finished = false;
247    }
248    /// Stops advancement without changing the current frame.
249    pub fn pause(&mut self) {
250        self.paused = true;
251    }
252    /// Allows advancement again. A completed one-shot remains completed until reset/play.
253    pub fn resume(&mut self) {
254        self.paused = false;
255    }
256    /// Whether explicit time advancement is paused.
257    pub fn is_paused(&self) -> bool {
258        self.paused
259    }
260    /// Whether a one-shot has reached its end.
261    pub fn is_finished(&self) -> bool {
262        self.finished
263    }
264    /// Current immutable clip.
265    pub fn clip(&self) -> &Arc<AnimationClip> {
266        &self.clip
267    }
268    /// Time within this traversal, clamped to duration for a finished one-shot.
269    pub fn elapsed(&self) -> Duration {
270        self.elapsed
271    }
272    /// Current frame index. Exact boundaries select the next frame; a completed
273    /// one-shot holds the last frame for drawing.
274    pub fn frame_index(&self) -> usize {
275        self.clip
276            .ends
277            .partition_point(|end| *end <= self.elapsed)
278            .min(self.clip.frames.len() - 1)
279    }
280    /// Current frame, without advancing simulation.
281    pub fn frame(&self) -> &SpriteFrame {
282        &self.clip.frames[self.frame_index()]
283    }
284    /// Advances by explicitly supplied simulation time. Zero time, paused or
285    /// completed playback does nothing. Looping wraps including exact boundaries;
286    /// a one-shot discards excess time and returns one completion on its first end.
287    /// No allocation occurs, including at completion (the clip's `Arc` is cloned).
288    pub fn advance(&mut self, dt: Duration) -> Option<AnimationCompleted> {
289        if self.paused || self.finished || dt.is_zero() {
290            return None;
291        }
292        // Even two Duration::MAX values fit in u128 nanoseconds.
293        let next = self.elapsed.as_nanos() + dt.as_nanos();
294        let duration = self.clip.duration.as_nanos();
295        let next = match self.clip.mode {
296            PlaybackMode::Loop => next % duration,
297            PlaybackMode::Once if next >= duration => {
298                self.elapsed = self.clip.duration;
299                self.finished = true;
300                return Some(AnimationCompleted {
301                    clip: Arc::clone(&self.clip),
302                });
303            }
304            PlaybackMode::Once => next,
305        };
306        self.elapsed = Duration::new((next / 1_000_000_000) as u64, (next % 1_000_000_000) as u32);
307        None
308    }
309}
310
311#[cfg(test)]
312mod tests;