Skip to main content

crcbl_sprite/
lib.rs

1//! Sprite sheets: what is in one, how it animates, and how it stretches.
2//!
3//! # What this crate is, and is not
4//!
5//! It is the **description** of a sheet — where each frame sits in an image,
6//! which frames make up a named animation, how long each is held, and which
7//! parts of a frame may stretch when it is drawn at a size it was not drawn at.
8//! It is deliberately none of the rest: no GPU types, no file I/O, no image
9//! codec. Turning a description into pixels belongs to `crcbl-render`, and
10//! reading a PNG belongs to whoever owns the bytes.
11//!
12//! That division is what lets a `build.rs` depend on this crate to convert
13//! source art without dragging a renderer into the build, and it is what makes
14//! every rule here testable with no device and no files.
15//!
16//! # Two formats, and only one of them reaches the engine
17//!
18//! ```text
19//! .crpix (text, in git) ──bake──▶ PNG + Aseprite-schema JSON ─┐
20//! Aseprite ──────────export────▶ PNG + Aseprite-schema JSON ──┴──▶ [`Sheet`]
21//! ```
22//!
23//! **Aseprite is the interchange format**, because it is the one the world
24//! already uses and because its JSON export already carries everything a sprite
25//! system needs: `frames[]` with per-frame `duration`, `meta.frameTags` for
26//! named clips with a direction, and `meta.slices[].keys[].center` — which *is*
27//! nine-slice. Reading that schema means art drawn in Aseprite drops in with no
28//! engine change.
29//!
30//! [`crpix`] is the other half: a text format for art authored **in this
31//! repository**, baked to a PNG and that same Aseprite schema at build time. It
32//! takes XPM's design — a declared header that acts as a checksum, `c None`,
33//! multi-character palette keys — and adds the frames XPM has no concept of.
34//! `docs/specs/crcbl/pix.md` is its specification; nothing downstream of the
35//! converter knows it exists.
36//!
37//! # Pixels are the unit
38//!
39//! Every rectangle here is in **texels of the sheet image**, as unsigned
40//! integers. Not normalised UVs, and not floats: a sprite sheet is a grid of
41//! whole pixels, half a texel is always a bug, and the conversion to UVs needs
42//! the image's size, which a description of a sheet does not have to know.
43
44pub mod colours;
45pub mod crpix;
46pub mod trace;
47
48#[cfg(feature = "bake")]
49pub mod bake;
50
51#[cfg(feature = "load")]
52pub mod load;
53
54use core::fmt;
55
56/// A rectangle in sheet texels.
57///
58/// `x`/`y` are the top-left corner, matching image order and Aseprite's own
59/// `frame` rects, so a value read out of a JSON export needs no flipping.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub struct Rect {
62    pub x: u32,
63    pub y: u32,
64    pub w: u32,
65    pub h: u32,
66}
67
68impl Rect {
69    #[must_use]
70    pub const fn new(x: u32, y: u32, w: u32, h: u32) -> Self {
71        Self { x, y, w, h }
72    }
73
74    /// Whether the rectangle has any area at all.
75    #[must_use]
76    pub const fn is_empty(&self) -> bool {
77        self.w == 0 || self.h == 0
78    }
79
80    /// Whether `self` lies entirely within a `width` × `height` image.
81    #[must_use]
82    pub const fn fits_in(&self, width: u32, height: u32) -> bool {
83        // Addition rather than subtraction, and checked: a frame at
84        // `x = u32::MAX - 1` with `w = 4` must not wrap into "fits".
85        match (self.x.checked_add(self.w), self.y.checked_add(self.h)) {
86            (Some(right), Some(bottom)) => right <= width && bottom <= height,
87            _ => false,
88        }
89    }
90}
91
92/// One frame of a sheet: where it is, and how long it is held.
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub struct Frame {
95    /// The frame's name. Aseprite writes one per frame; `.pix` requires one,
96    /// because a clip refers to frames by name and an index is a thing that
97    /// silently means something else after an edit.
98    pub name: String,
99    /// Where the frame sits in the sheet image.
100    pub rect: Rect,
101    /// How long the frame is held, in **simulation ticks**.
102    ///
103    /// Ticks, not milliseconds. A sample's animation has to advance the same
104    /// way at 20 fps and 240 fps for the same reason its physics does, and the
105    /// only clock that is true of is the fixed tick. Aseprite records
106    /// milliseconds, so the importer converts once, at the tick rate it is
107    /// told.
108    pub hold: u32,
109}
110
111/// Which way a clip runs through its frames.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub enum Direction {
114    /// First frame to last, then back to the first.
115    #[default]
116    Forward,
117    /// Last frame to first.
118    Reverse,
119    /// Forward, then back, without repeating either end.
120    ///
121    /// The end frames are held once, not twice: a four-frame ping-pong is
122    /// `0 1 2 3 2 1` and then `0` again, which is what Aseprite does and what
123    /// looks right. Holding them twice reads as a stutter at each extreme.
124    PingPong,
125}
126
127/// A named animation: an ordered run of frames, and how to walk it.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct Clip {
130    pub name: String,
131    /// Indices into [`Sheet::frames`], in playback order.
132    pub frames: Vec<usize>,
133    pub direction: Direction,
134    /// Whether the clip returns to the start after the last frame.
135    ///
136    /// A clip that does not loop holds its final frame forever, which is what a
137    /// one-shot — a death, a button press — should do.
138    pub looping: bool,
139}
140
141impl Clip {
142    /// How many frame *showings* one pass of the clip contains.
143    ///
144    /// Not the same as `frames.len()`: a ping-pong shows the middle frames
145    /// twice. This is the number [`Clip::step`] indexes, and the clip's period
146    /// in showings when it loops.
147    ///
148    /// | direction   | looping  | showings |
149    /// | ----------- | -------- | -------- |
150    /// | `Forward`   | either   | `n`      |
151    /// | `Reverse`   | either   | `n`      |
152    /// | `PingPong`  | looping  | `2n - 2` |
153    /// | `PingPong`  | one-shot | `2n - 1` |
154    ///
155    /// **A looping ping-pong's period is `2n - 2`, not `2n`,** because neither
156    /// end is repeated: four frames run `0 1 2 3 2 1` and then `0` again. A
157    /// one-shot has the extra showing precisely because that trailing `0` is no
158    /// longer the next cycle's first — an out-and-back that stopped on frame 1
159    /// would look truncated, so it plays the return home and parks there.
160    ///
161    /// Degenerate cases: no frames is zero showings, and a single frame is one
162    /// showing in every direction (`2n - 2` would be `0`).
163    #[must_use]
164    pub fn steps(&self) -> usize {
165        let n = self.frames.len();
166        match self.direction {
167            _ if n <= 1 => n,
168            Direction::Forward | Direction::Reverse => n,
169            Direction::PingPong if self.looping => 2 * n - 2,
170            Direction::PingPong => 2 * n - 1,
171        }
172    }
173
174    /// The frame shown at showing `step`: an index into [`Sheet::frames`].
175    ///
176    /// `None` past the end of one pass, so `0..clip.steps()` walks it exactly.
177    /// [`Direction::Reverse`] reverses the *frames*, and each frame keeps its
178    /// own `hold` — a hold belongs to the frame it holds, not to the position
179    /// in the list — so a reversed clip's tick pattern is the forward one read
180    /// backwards.
181    #[must_use]
182    pub fn step(&self, step: usize) -> Option<usize> {
183        let n = self.frames.len();
184        if step >= self.steps() {
185            return None;
186        }
187        let position = match self.direction {
188            _ if n <= 1 => step,
189            Direction::Forward => step,
190            Direction::Reverse => n - 1 - step,
191            // The descending leg mirrors the ascending one about `n - 1`, and
192            // a one-shot's extra showing lands back on `0`.
193            Direction::PingPong if step < n => step,
194            Direction::PingPong => 2 * n - 2 - step,
195        };
196        self.frames.get(position).copied()
197    }
198}
199
200/// Where a clip has got to, counted in whole simulation ticks.
201///
202/// **Ticks, not seconds.** The engine is fixed-tick — `crcbl-server`'s
203/// accumulator calls the world a whole number of times per frame — and an
204/// animation that advanced on a float clock would land on a different frame at
205/// 20 fps than at 240 fps for the same reason a float physics step would.
206/// There is no `dt` anywhere in here.
207///
208/// A `Playback` is a bare cursor: it holds neither the sheet nor the clip, so
209/// it is `Copy`, costs eight bytes, and can sit in a component next to whatever
210/// names the clip. The sheet and clip are passed to the queries, which means
211/// one entity can be pointed at a different clip without rebuilding anything.
212///
213/// ```
214/// # use crcbl_sprite::{Clip, Direction, Frame, Playback, Rect, Sheet};
215/// # let frame = |name: &str, x, hold| Frame { name: name.into(), rect: Rect::new(x, 0, 8, 8), hold };
216/// let sheet = Sheet {
217///     width: 16,
218///     height: 8,
219///     frames: vec![frame("a", 0, 2), frame("b", 8, 3)],
220///     clips: vec![Clip {
221///         name: "idle".into(),
222///         frames: vec![0, 1],
223///         direction: Direction::Forward,
224///         looping: true,
225///     }],
226///     ..Sheet::default()
227/// };
228/// let clip = sheet.clip("idle").expect("the sheet declares it");
229///
230/// let mut play = Playback::new();
231/// assert_eq!(play.frame_index(&sheet, clip), Some(0));
232/// play.advance(2);
233/// assert_eq!(play.frame_index(&sheet, clip), Some(1), "`a` is held for 2 ticks");
234/// play.advance(3);
235/// assert_eq!(play.frame_index(&sheet, clip), Some(0), "and it wraps after 5");
236/// ```
237#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
238pub struct Playback {
239    elapsed: u64,
240}
241
242impl Playback {
243    /// A clip about to show its first frame.
244    #[must_use]
245    pub const fn new() -> Self {
246        Self { elapsed: 0 }
247    }
248
249    /// Ticks since the clip started.
250    ///
251    /// Keeps counting past the end of a looping clip rather than wrapping, so
252    /// two playbacks started at the same tick stay comparable however long they
253    /// run. At 60 Hz a `u64` of ticks is longer than the age of the universe;
254    /// it saturates rather than wrapping regardless.
255    #[must_use]
256    pub const fn elapsed(&self) -> u64 {
257        self.elapsed
258    }
259
260    /// Moves the clip on by whole ticks.
261    ///
262    /// Advancing by `n` in one call is exactly advancing by one `n` times —
263    /// every query is a pure function of [`Playback::elapsed`], so a client
264    /// catching up after a stall lands where a client that never stalled would.
265    pub const fn advance(&mut self, ticks: u64) {
266        self.elapsed = self.elapsed.saturating_add(ticks);
267    }
268
269    /// Back to the first frame, as if the clip had just started.
270    pub const fn restart(&mut self) {
271        self.elapsed = 0;
272    }
273
274    /// Jumps to `tick` ticks after the clip started.
275    pub const fn seek(&mut self, tick: u64) {
276        self.elapsed = tick;
277    }
278
279    /// The frame to draw: an index into [`Sheet::frames`].
280    ///
281    /// `None` only when there is nothing to draw — a clip with no frames, or
282    /// one naming a frame the sheet does not have, both of which
283    /// [`Sheet::validate`] refuses.
284    ///
285    /// A looping clip wraps; a one-shot holds its last showing forever, and
286    /// says so through [`Playback::finished`].
287    #[must_use]
288    pub fn frame_index(&self, sheet: &Sheet, clip: &Clip) -> Option<usize> {
289        let steps = clip.steps();
290        let total = sheet.clip_duration(clip)?;
291        if total == 0 {
292            return None;
293        }
294        // The whole of playback is this one line: a looping clip is its
295        // position modulo the pass, a one-shot is clamped to the last tick of
296        // the pass. Everything below is finding which showing owns that tick.
297        let tick = if clip.looping {
298            self.elapsed % total
299        } else {
300            self.elapsed.min(total - 1)
301        };
302        let mut end = 0;
303        for step in 0..steps {
304            let frame = clip.step(step)?;
305            end += u64::from(sheet.frames.get(frame)?.hold);
306            if tick < end {
307                return Some(frame);
308            }
309        }
310        // `tick < total` and the holds sum to `total`, so the loop always
311        // returns. Answering with the last showing rather than panicking keeps
312        // a malformed sheet from taking the frame down.
313        clip.step(steps - 1)
314    }
315
316    /// Whether a one-shot has played out.
317    ///
318    /// **Distinct from being on the last frame.** A one-shot reaches its final
319    /// frame and then holds it for that frame's `hold` before this turns true,
320    /// so an explosion's last puff is on screen for as long as it was drawn
321    /// for. [`Playback::frame_index`] keeps answering with that frame
322    /// afterwards, so a caller that ignores this still draws something.
323    ///
324    /// Always `false` for a looping clip: it never ends. A one-shot that cannot
325    /// be drawn at all — no frames, or a frame the sheet does not have — is
326    /// finished immediately, because there is nothing left for it to show.
327    #[must_use]
328    pub fn finished(&self, sheet: &Sheet, clip: &Clip) -> bool {
329        !clip.looping
330            && sheet
331                .clip_duration(clip)
332                .is_none_or(|total| self.elapsed >= total)
333    }
334}
335
336/// The four insets that make a frame stretchable.
337///
338/// A nine-slice splits a frame into a 3×3 grid: the four corners never scale,
339/// the top and bottom edges stretch horizontally only, the left and right edges
340/// stretch vertically only, and the centre stretches both ways. That is what
341/// keeps a button's rounded corner square at any size, and what lets one pipe
342/// image serve a gap of any height.
343///
344/// Stored as insets rather than as Aseprite's centre rectangle because insets
345/// are what the geometry needs and what a human can write; the two are the same
346/// information and [`NineSlice::from_center`] converts.
347#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
348pub struct NineSlice {
349    pub left: u32,
350    pub right: u32,
351    pub top: u32,
352    pub bottom: u32,
353}
354
355impl NineSlice {
356    #[must_use]
357    pub const fn new(left: u32, right: u32, top: u32, bottom: u32) -> Self {
358        Self {
359            left,
360            right,
361            top,
362            bottom,
363        }
364    }
365
366    /// The insets implied by Aseprite's `center` rect inside a `frame` rect.
367    ///
368    /// Aseprite stores the *middle* of the nine, positioned relative to the
369    /// slice's own bounds. Returns `None` when the centre is not actually inside
370    /// the frame, which is a malformed export rather than a slice with odd
371    /// insets.
372    #[must_use]
373    pub fn from_center(frame: Rect, center: Rect) -> Option<Self> {
374        let right_edge = center.x.checked_add(center.w)?;
375        let bottom_edge = center.y.checked_add(center.h)?;
376        if right_edge > frame.w || bottom_edge > frame.h {
377            return None;
378        }
379        Some(Self {
380            left: center.x,
381            right: frame.w - right_edge,
382            top: center.y,
383            bottom: frame.h - bottom_edge,
384        })
385    }
386
387    /// Whether these insets leave a non-negative centre inside `frame`.
388    ///
389    /// Insets that overlap would give the centre a negative size, and the
390    /// geometry builder would produce inside-out quads that render as nothing —
391    /// a sprite that silently disappears at one size and not another.
392    #[must_use]
393    pub fn fits_in(&self, frame: Rect) -> bool {
394        self.left.saturating_add(self.right) <= frame.w
395            && self.top.saturating_add(self.bottom) <= frame.h
396    }
397
398    /// The smallest size this slice can be drawn at without the fixed parts
399    /// overlapping, in pixels.
400    #[must_use]
401    pub const fn minimum_size(&self) -> (u32, u32) {
402        (self.left + self.right, self.top + self.bottom)
403    }
404}
405
406/// How a sprite is sampled when the screen does not agree with the art.
407#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
408pub enum SampleMode {
409    /// Preserve the art's pixels as exactly as the output allows.
410    ///
411    /// Not simply nearest-neighbour. At a non-integer scale — a 320-wide field
412    /// stretched across a 1366-wide canvas — nearest makes some art pixels four
413    /// screen pixels across and their neighbours five, and the unevenness
414    /// crawls as the sprite moves. This mode samples linearly but bends the UV
415    /// so the blend happens only within a one-fragment band at each texel
416    /// boundary, which is identical to nearest at whole scales and even-looking
417    /// at every other one.
418    #[default]
419    Pixel,
420    /// Ordinary filtered sampling, for art that is not pixel art and for the
421    /// normal 2D and 3D path.
422    Smooth,
423}
424
425/// A sheet: one image, the frames cut out of it, and the clips over those.
426#[derive(Clone, Debug, Default, PartialEq)]
427pub struct Sheet {
428    /// The sheet image's size in texels. Every frame must fit inside it.
429    pub width: u32,
430    pub height: u32,
431    pub frames: Vec<Frame>,
432    pub clips: Vec<Clip>,
433    /// The nine-slice insets, when this sheet's frames are stretchable.
434    pub nine: Option<NineSlice>,
435    pub sample: SampleMode,
436}
437
438impl Sheet {
439    /// The frame with this name.
440    #[must_use]
441    pub fn frame(&self, name: &str) -> Option<&Frame> {
442        self.frames.iter().find(|frame| frame.name == name)
443    }
444
445    /// The index of the frame with this name.
446    #[must_use]
447    pub fn frame_index(&self, name: &str) -> Option<usize> {
448        self.frames.iter().position(|frame| frame.name == name)
449    }
450
451    /// The clip with this name.
452    #[must_use]
453    pub fn clip(&self, name: &str) -> Option<&Clip> {
454        self.clips.iter().find(|clip| clip.name == name)
455    }
456
457    /// Frame `index` as normalised UVs: `[u0, v0, u1, v1]`, top-left first.
458    ///
459    /// The one conversion out of texels this crate does, and it lives here
460    /// because the divisor is the sheet's own size — the thing a `Rect` on its
461    /// own does not know. `crcbl_render::Sprite::uv` wants exactly this layout,
462    /// and every caller that spelled it out by hand was a place the halves
463    /// could be swapped.
464    ///
465    /// `None` for an index the sheet does not have, or a sheet with no size at
466    /// all, which would otherwise divide by zero and hand a `NaN` to a vertex
467    /// buffer.
468    #[must_use]
469    pub fn uv(&self, index: usize) -> Option<[f32; 4]> {
470        if self.width == 0 || self.height == 0 {
471            return None;
472        }
473        let rect = self.frames.get(index)?.rect;
474        let width = self.width as f32;
475        let height = self.height as f32;
476        // 64-bit for the far edges: a rect that overflows `u32` here is one
477        // `validate` refuses, and wrapping to a small UV would sample the
478        // wrong sprite rather than fail.
479        let right = u64::from(rect.x) + u64::from(rect.w);
480        let bottom = u64::from(rect.y) + u64::from(rect.h);
481        Some([
482            rect.x as f32 / width,
483            rect.y as f32 / height,
484            right as f32 / width,
485            bottom as f32 / height,
486        ])
487    }
488
489    /// How many ticks one pass of `clip` lasts.
490    ///
491    /// The sum of the `hold` of every showing in [`Clip::steps`] order, so a
492    /// ping-pong counts its middle frames twice and a reversed clip counts the
493    /// same holds as its forward twin. For a one-shot this is when
494    /// [`Playback::finished`] turns true; for a looping clip it is the period.
495    ///
496    /// `None` when the clip has no frames, or names one this sheet does not
497    /// have — both refused by [`Sheet::validate`]. Skipping the missing frame
498    /// and returning a shorter total would be worse than admitting it: the
499    /// clip would then play forever without that frame's tick ever arriving,
500    /// which looks like a renderer bug.
501    #[must_use]
502    pub fn clip_duration(&self, clip: &Clip) -> Option<u64> {
503        let steps = clip.steps();
504        if steps == 0 {
505            return None;
506        }
507        let mut total = 0u64;
508        for step in 0..steps {
509            let frame = self.frames.get(clip.step(step)?)?;
510            total = total.saturating_add(u64::from(frame.hold));
511        }
512        Some(total)
513    }
514
515    /// Checks every rule a consumer is entitled to assume.
516    ///
517    /// Called by every constructor in this crate, and worth calling on a sheet
518    /// built by hand. The alternative to failing here is a frame rect that
519    /// samples whatever is next to it in the atlas, which renders as a sliver of
520    /// the neighbouring sprite along one edge — the kind of bug that is looked
521    /// at for an hour and blamed on the sampler.
522    ///
523    /// # Errors
524    ///
525    /// [`SheetError`] naming the first rule broken.
526    pub fn validate(&self) -> Result<(), SheetError> {
527        if self.frames.is_empty() {
528            return Err(SheetError::NoFrames);
529        }
530        for frame in &self.frames {
531            if frame.rect.is_empty() {
532                return Err(SheetError::EmptyFrame {
533                    frame: frame.name.clone(),
534                });
535            }
536            if !frame.rect.fits_in(self.width, self.height) {
537                return Err(SheetError::FrameOutsideSheet {
538                    frame: frame.name.clone(),
539                    rect: frame.rect,
540                    width: self.width,
541                    height: self.height,
542                });
543            }
544            if frame.hold == 0 {
545                return Err(SheetError::ZeroHold {
546                    frame: frame.name.clone(),
547                });
548            }
549        }
550        for (index, frame) in self.frames.iter().enumerate() {
551            if self.frames[..index]
552                .iter()
553                .any(|other| other.name == frame.name)
554            {
555                return Err(SheetError::DuplicateFrame {
556                    frame: frame.name.clone(),
557                });
558            }
559        }
560        for clip in &self.clips {
561            if clip.frames.is_empty() {
562                return Err(SheetError::EmptyClip {
563                    clip: clip.name.clone(),
564                });
565            }
566            if let Some(&bad) = clip.frames.iter().find(|&&i| i >= self.frames.len()) {
567                return Err(SheetError::ClipFrameOutOfRange {
568                    clip: clip.name.clone(),
569                    index: bad,
570                    frames: self.frames.len(),
571                });
572            }
573        }
574        if let Some(nine) = self.nine {
575            // Against the *first* frame: every frame in a sheet is the same size
576            // (an animation of differently sized frames is not a thing), and
577            // `.pix` enforces that, so one check covers them all.
578            let frame = &self.frames[0];
579            if !nine.fits_in(frame.rect) {
580                return Err(SheetError::NineTooBig {
581                    nine,
582                    frame: frame.rect,
583                });
584            }
585        }
586        Ok(())
587    }
588}
589
590/// Why a sheet is not usable.
591#[derive(Clone, Debug, PartialEq, Eq)]
592pub enum SheetError {
593    NoFrames,
594    EmptyFrame {
595        frame: String,
596    },
597    FrameOutsideSheet {
598        frame: String,
599        rect: Rect,
600        width: u32,
601        height: u32,
602    },
603    ZeroHold {
604        frame: String,
605    },
606    DuplicateFrame {
607        frame: String,
608    },
609    EmptyClip {
610        clip: String,
611    },
612    ClipFrameOutOfRange {
613        clip: String,
614        index: usize,
615        frames: usize,
616    },
617    NineTooBig {
618        nine: NineSlice,
619        frame: Rect,
620    },
621}
622
623impl fmt::Display for SheetError {
624    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625        match self {
626            Self::NoFrames => write!(f, "a sheet with no frames draws nothing"),
627            Self::EmptyFrame { frame } => {
628                write!(f, "frame `{frame}` has no area")
629            }
630            Self::FrameOutsideSheet {
631                frame,
632                rect,
633                width,
634                height,
635            } => write!(
636                f,
637                "frame `{frame}` at {}x{}+{}+{} runs outside a {width}x{height} sheet; \
638                 it would sample whatever is next to it",
639                rect.w, rect.h, rect.x, rect.y
640            ),
641            Self::ZeroHold { frame } => write!(
642                f,
643                "frame `{frame}` is held for zero ticks, so a clip containing it \
644                 would advance forever without drawing"
645            ),
646            Self::DuplicateFrame { frame } => {
647                write!(f, "two frames are both called `{frame}`")
648            }
649            Self::EmptyClip { clip } => write!(f, "clip `{clip}` names no frames"),
650            Self::ClipFrameOutOfRange {
651                clip,
652                index,
653                frames,
654            } => write!(
655                f,
656                "clip `{clip}` names frame {index}, but the sheet has {frames}"
657            ),
658            Self::NineTooBig { nine, frame } => write!(
659                f,
660                "nine-slice insets {}+{} wide and {}+{} tall do not fit a {}x{} frame",
661                nine.left, nine.right, nine.top, nine.bottom, frame.w, frame.h
662            ),
663        }
664    }
665}
666
667impl core::error::Error for SheetError {}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672
673    fn sheet() -> Sheet {
674        Sheet {
675            width: 32,
676            height: 16,
677            frames: vec![
678                Frame {
679                    name: "a".into(),
680                    rect: Rect::new(0, 0, 16, 16),
681                    hold: 4,
682                },
683                Frame {
684                    name: "b".into(),
685                    rect: Rect::new(16, 0, 16, 16),
686                    hold: 4,
687                },
688            ],
689            clips: vec![Clip {
690                name: "walk".into(),
691                frames: vec![0, 1],
692                direction: Direction::Forward,
693                looping: true,
694            }],
695            nine: None,
696            sample: SampleMode::Pixel,
697        }
698    }
699
700    #[test]
701    fn a_well_formed_sheet_validates_and_can_be_looked_up_by_name() {
702        let sheet = sheet();
703        sheet.validate().expect("this sheet is well formed");
704        assert_eq!(
705            sheet.frame("b").map(|f| f.rect),
706            Some(Rect::new(16, 0, 16, 16))
707        );
708        assert_eq!(sheet.frame_index("b"), Some(1));
709        assert_eq!(sheet.frame("nope"), None);
710        assert_eq!(sheet.clip("walk").map(|c| c.frames.len()), Some(2));
711    }
712
713    /// **The rule this crate exists to enforce.** A frame that runs past the
714    /// edge of its image samples whatever is next to it, which renders as a
715    /// sliver of the neighbouring sprite along one edge.
716    #[test]
717    fn a_frame_that_runs_off_the_sheet_is_refused() {
718        let mut sheet = sheet();
719        sheet.frames[1].rect = Rect::new(20, 0, 16, 16);
720        let error = sheet.validate().expect_err("this frame runs off the right");
721        assert!(matches!(error, SheetError::FrameOutsideSheet { .. }));
722        assert!(error.to_string().contains("outside"), "{error}");
723    }
724
725    /// And it must not be possible to arrive at "fits" by wrapping.
726    #[test]
727    fn a_frame_rect_cannot_wrap_its_way_inside_the_sheet() {
728        assert!(!Rect::new(u32::MAX - 1, 0, 4, 4).fits_in(64, 64));
729        assert!(!Rect::new(0, u32::MAX, 4, 4).fits_in(64, 64));
730        // The case the obvious `x <= width - w` formulation gets wrong: a frame
731        // wider than the whole sheet underflows the subtraction, which panics in
732        // debug and answers "fits" in release.
733        assert!(!Rect::new(0, 0, 128, 4).fits_in(64, 64));
734        assert!(!Rect::new(0, 0, 4, 128).fits_in(64, 64));
735        assert!(
736            Rect::new(60, 60, 4, 4).fits_in(64, 64),
737            "flush to the edge fits"
738        );
739    }
740
741    #[test]
742    fn the_other_rules_each_have_a_message() {
743        let mut empty = sheet();
744        empty.frames.clear();
745        assert_eq!(empty.validate(), Err(SheetError::NoFrames));
746
747        let mut zero = sheet();
748        zero.frames[0].hold = 0;
749        assert!(matches!(zero.validate(), Err(SheetError::ZeroHold { .. })));
750
751        let mut duplicate = sheet();
752        duplicate.frames[1].name = "a".into();
753        assert!(matches!(
754            duplicate.validate(),
755            Err(SheetError::DuplicateFrame { .. })
756        ));
757
758        let mut dangling = sheet();
759        dangling.clips[0].frames = vec![0, 7];
760        assert!(matches!(
761            dangling.validate(),
762            Err(SheetError::ClipFrameOutOfRange { .. })
763        ));
764
765        let mut hollow = sheet();
766        hollow.clips[0].frames.clear();
767        assert!(matches!(
768            hollow.validate(),
769            Err(SheetError::EmptyClip { .. })
770        ));
771
772        let mut flat = sheet();
773        flat.frames[0].rect = Rect::new(0, 0, 0, 16);
774        assert!(matches!(
775            flat.validate(),
776            Err(SheetError::EmptyFrame { .. })
777        ));
778    }
779
780    /// Overlapping insets would give the centre a negative size, and the
781    /// geometry builder would emit inside-out quads that draw nothing — a
782    /// sprite that vanishes at one size and not another.
783    #[test]
784    fn nine_slice_insets_that_overlap_are_refused() {
785        let frame = Rect::new(0, 0, 16, 16);
786        assert!(
787            NineSlice::new(8, 8, 8, 8).fits_in(frame),
788            "exactly touching is fine"
789        );
790        assert!(!NineSlice::new(9, 8, 0, 0).fits_in(frame));
791        assert!(!NineSlice::new(0, 0, 12, 12).fits_in(frame));
792        assert!(
793            !NineSlice::new(u32::MAX, 1, 0, 0).fits_in(frame),
794            "and must not wrap"
795        );
796
797        let mut sheet = sheet();
798        sheet.nine = Some(NineSlice::new(9, 9, 0, 0));
799        assert!(matches!(
800            sheet.validate(),
801            Err(SheetError::NineTooBig { .. })
802        ));
803    }
804
805    /// Aseprite stores the middle of the nine; we store the four insets. The
806    /// conversion is the one place that could silently transpose them.
807    #[test]
808    fn asepite_centre_rects_convert_to_the_insets_they_describe() {
809        let frame = Rect::new(0, 0, 32, 16);
810        // A centre 4 in from the left, 6 from the top, 20 wide and 4 tall
811        // leaves 8 on the right and 6 on the bottom.
812        let nine = NineSlice::from_center(frame, Rect::new(4, 6, 20, 4))
813            .expect("the centre is inside the frame");
814        assert_eq!(nine, NineSlice::new(4, 8, 6, 6));
815        assert_eq!(nine.minimum_size(), (12, 12));
816
817        // A centre that runs outside the frame is a malformed export.
818        assert_eq!(NineSlice::from_center(frame, Rect::new(30, 0, 8, 4)), None);
819        assert_eq!(NineSlice::from_center(frame, Rect::new(0, 14, 4, 8)), None);
820    }
821
822    // -----------------------------------------------------------------------
823    // Clip playback
824    // -----------------------------------------------------------------------
825
826    /// A four-frame strip. The holds are **unequal on purpose**: with every
827    /// hold the same, "showing 3" and "tick 3" are the same number and every
828    /// confusion between them passes.
829    fn strip(holds: [u32; 4]) -> Sheet {
830        let frame = |name: &str, x: u32, hold: u32| Frame {
831            name: name.into(),
832            rect: Rect::new(x, 0, 16, 16),
833            hold,
834        };
835        Sheet {
836            width: 64,
837            height: 16,
838            frames: vec![
839                frame("a", 0, holds[0]),
840                frame("b", 16, holds[1]),
841                frame("c", 32, holds[2]),
842                frame("d", 48, holds[3]),
843            ],
844            ..Sheet::default()
845        }
846    }
847
848    fn clip(frames: Vec<usize>, direction: Direction, looping: bool) -> Clip {
849        Clip {
850            name: "clip".into(),
851            frames,
852            direction,
853            looping,
854        }
855    }
856
857    /// The frame drawn on each of the first `ticks` ticks, in order.
858    fn drawn(sheet: &Sheet, clip: &Clip, ticks: u64) -> Vec<usize> {
859        let mut play = Playback::new();
860        (0..ticks)
861            .map(|_| {
862                let frame = play.frame_index(sheet, clip).expect("the clip draws");
863                play.advance(1);
864                frame
865            })
866            .collect()
867    }
868
869    /// The showings of one pass, ignoring how long each is held.
870    fn showings(clip: &Clip) -> Vec<usize> {
871        (0..clip.steps())
872            .map(|step| clip.step(step).expect("inside the pass"))
873            .collect()
874    }
875
876    /// An independent model of the same rule: a cursor and a countdown, walked
877    /// one tick at a time with no modular arithmetic anywhere. This is what
878    /// [`Playback::frame_index`]'s closed form is checked against — the two
879    /// agreeing is the thing that catches an off-by-one in either.
880    fn naive(sheet: &Sheet, clip: &Clip, ticks: u64) -> usize {
881        let steps = clip.steps();
882        let mut step = 0;
883        let mut held = 0;
884        for _ in 0..ticks {
885            let frame = clip.step(step).expect("inside the pass");
886            let hold = sheet.frames[frame].hold;
887            held += 1;
888            if held < hold {
889                continue;
890            }
891            held = 0;
892            if step + 1 < steps {
893                step += 1;
894            } else if clip.looping {
895                step = 0;
896            } else {
897                held = hold; // parked on the last showing, forever
898            }
899        }
900        clip.step(step).expect("inside the pass")
901    }
902
903    /// Every shape of clip worth running a property over.
904    fn cases() -> Vec<(Sheet, Clip)> {
905        let uneven = strip([2, 1, 3, 1]);
906        let flat = strip([1, 1, 1, 1]);
907        let mut out = Vec::new();
908        for direction in [Direction::Forward, Direction::Reverse, Direction::PingPong] {
909            for looping in [true, false] {
910                for sheet in [uneven.clone(), flat.clone()] {
911                    out.push((sheet.clone(), clip(vec![0, 1, 2, 3], direction, looping)));
912                    out.push((sheet.clone(), clip(vec![2], direction, looping)));
913                    out.push((sheet.clone(), clip(vec![1, 3], direction, looping)));
914                    // A clip may name a frame more than once.
915                    out.push((sheet, clip(vec![0, 2, 0, 3], direction, looping)));
916                }
917            }
918        }
919        out
920    }
921
922    /// Forward is the plain case, and it is still worth writing the whole
923    /// sequence out: an implementation that never advances satisfies every
924    /// invariant an "is it in range" assertion can express.
925    #[test]
926    fn forward_holds_each_frame_for_its_own_ticks_and_wraps() {
927        let sheet = strip([2, 1, 3, 1]);
928        let walk = clip(vec![0, 1, 2, 3], Direction::Forward, true);
929        assert_eq!(showings(&walk), vec![0, 1, 2, 3]);
930        assert_eq!(sheet.clip_duration(&walk), Some(7), "2 + 1 + 3 + 1");
931        assert_eq!(
932            drawn(&sheet, &walk, 16),
933            vec![0, 0, 1, 2, 2, 2, 3, 0, 0, 1, 2, 2, 2, 3, 0, 0],
934            "two whole cycles and a bit"
935        );
936
937        // Equal holds are the case that hides index/tick confusion, so pin it
938        // separately rather than trusting the one above to cover it.
939        let flat = strip([1, 1, 1, 1]);
940        assert_eq!(flat.clip_duration(&walk), Some(4));
941        assert_eq!(drawn(&flat, &walk, 9), vec![0, 1, 2, 3, 0, 1, 2, 3, 0]);
942    }
943
944    /// **Holds belong to frames, not to positions.** Reversing the clip
945    /// reverses the tick sequence exactly — which is only visible at all when
946    /// the holds differ.
947    #[test]
948    fn reverse_runs_the_frames_backwards_and_takes_their_holds_with_them() {
949        let sheet = strip([2, 1, 3, 1]);
950        let back = clip(vec![0, 1, 2, 3], Direction::Reverse, true);
951        assert_eq!(showings(&back), vec![3, 2, 1, 0]);
952        assert_eq!(
953            sheet.clip_duration(&back),
954            Some(7),
955            "the same holds, so the same total"
956        );
957        assert_eq!(
958            drawn(&sheet, &back, 14),
959            vec![3, 2, 2, 2, 1, 0, 0, 3, 2, 2, 2, 1, 0, 0],
960            "`d` is held 1 tick and `c` 3, exactly as forward holds them"
961        );
962
963        // The same claim said the other way: one reversed cycle is one forward
964        // cycle read backwards. It would fail if holds stayed with positions.
965        let forward = clip(vec![0, 1, 2, 3], Direction::Forward, true);
966        let mut mirrored = drawn(&sheet, &forward, 7);
967        mirrored.reverse();
968        assert_eq!(drawn(&sheet, &back, 7), mirrored);
969    }
970
971    /// **The choice: each end is shown once, not twice.** A wing does not pause
972    /// at the top of its stroke. Four frames run `0 1 2 3 2 1` — six showings,
973    /// `2n - 2`, not the eight a repeated-ends implementation would give.
974    #[test]
975    fn ping_pong_shows_each_end_once_so_its_period_is_two_n_minus_two() {
976        let sheet = strip([2, 1, 3, 1]);
977        let flap = clip(vec![0, 1, 2, 3], Direction::PingPong, true);
978
979        assert_eq!(flap.steps(), 6, "2n - 2 for n = 4, not 2n");
980        assert_eq!(showings(&flap), vec![0, 1, 2, 3, 2, 1]);
981        assert_eq!(
982            sheet.clip_duration(&flap),
983            Some(11),
984            "2 + 1 + 3 + 1 + 3 + 1; repeating the ends would be 14"
985        );
986
987        let cycle = vec![0, 0, 1, 2, 2, 2, 3, 2, 2, 2, 1];
988        let mut twice = cycle.clone();
989        twice.extend_from_slice(&cycle);
990        assert_eq!(drawn(&sheet, &flap, 22), twice);
991
992        // And the period really is the period, out where drift would show.
993        let mut here = Playback::new();
994        let mut later = Playback::new();
995        later.advance(11 * 9);
996        for _ in 0..40 {
997            assert_eq!(
998                here.frame_index(&sheet, &flap),
999                later.frame_index(&sheet, &flap),
1000                "at tick {}",
1001                here.elapsed()
1002            );
1003            here.advance(1);
1004            later.advance(1);
1005        }
1006
1007        // Anti-vacuity: the sequence has to actually move.
1008        assert!(
1009            cycle.windows(2).any(|pair| pair[0] != pair[1]),
1010            "a playback that never advances would satisfy a weaker assertion"
1011        );
1012    }
1013
1014    /// A one-shot ping-pong plays the return home. The trailing `0` is the next
1015    /// cycle's first showing when the clip loops, so it is not counted twice —
1016    /// but a clip that stops has to show it, or it ends on frame 1.
1017    #[test]
1018    fn a_one_shot_ping_pong_returns_to_its_first_frame_and_parks() {
1019        let sheet = strip([2, 1, 3, 1]);
1020        let once = clip(vec![0, 1, 2, 3], Direction::PingPong, false);
1021        assert_eq!(once.steps(), 7, "2n - 1: the walk home is not a repeat");
1022        assert_eq!(showings(&once), vec![0, 1, 2, 3, 2, 1, 0]);
1023        assert_eq!(sheet.clip_duration(&once), Some(13), "11 + `a`'s two ticks");
1024        assert_eq!(
1025            drawn(&sheet, &once, 17),
1026            vec![0, 0, 1, 2, 2, 2, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0]
1027        );
1028    }
1029
1030    /// A one-shot has to say it is **over**, distinguishably from being on its
1031    /// last frame — a game acts when the explosion ends, not when it starts its
1032    /// final puff.
1033    #[test]
1034    fn a_one_shot_holds_its_last_frame_and_reports_finished_after_it() {
1035        let sheet = strip([2, 1, 3, 1]);
1036        let once = clip(vec![0, 1, 2, 3], Direction::Forward, false);
1037        assert_eq!(sheet.clip_duration(&once), Some(7));
1038        assert_eq!(
1039            drawn(&sheet, &once, 12),
1040            vec![0, 0, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3],
1041            "and then `d` forever"
1042        );
1043
1044        let mut play = Playback::new();
1045        play.advance(6);
1046        assert_eq!(
1047            play.frame_index(&sheet, &once),
1048            Some(3),
1049            "the last frame, on the first tick it is drawn"
1050        );
1051        assert!(
1052            !play.finished(&sheet, &once),
1053            "on the last frame is not the same as done with it"
1054        );
1055        play.advance(1);
1056        assert_eq!(play.frame_index(&sheet, &once), Some(3));
1057        assert!(play.finished(&sheet, &once), "after its hold, it is over");
1058        play.advance(1_000);
1059        assert!(play.finished(&sheet, &once));
1060        assert_eq!(
1061            play.frame_index(&sheet, &once),
1062            Some(3),
1063            "a caller ignoring `finished` still draws something"
1064        );
1065
1066        // A looping clip never ends, however far it runs.
1067        let forever = clip(vec![0, 1, 2, 3], Direction::Forward, true);
1068        assert!(!play.finished(&sheet, &forever));
1069    }
1070
1071    /// One frame is where `2n - 2` is zero. It must be a period of one, not a
1072    /// clip that draws nothing or divides by zero.
1073    #[test]
1074    fn a_single_frame_clip_is_one_showing_in_every_direction() {
1075        let sheet = strip([2, 1, 3, 1]);
1076        for direction in [Direction::Forward, Direction::Reverse, Direction::PingPong] {
1077            for looping in [true, false] {
1078                let lone = clip(vec![2], direction, looping);
1079                assert_eq!(lone.steps(), 1, "{direction:?} looping={looping}");
1080                assert_eq!(showings(&lone), vec![2]);
1081                assert_eq!(lone.step(1), None);
1082                assert_eq!(
1083                    sheet.clip_duration(&lone),
1084                    Some(3),
1085                    "`c`'s hold, counted once: {direction:?}"
1086                );
1087                assert_eq!(
1088                    drawn(&sheet, &lone, 8),
1089                    vec![2; 8],
1090                    "{direction:?} looping={looping}"
1091                );
1092                let mut play = Playback::new();
1093                play.advance(3);
1094                assert_eq!(play.finished(&sheet, &lone), !looping);
1095            }
1096        }
1097    }
1098
1099    /// **The property that catches every off-by-one in the modular
1100    /// arithmetic.** A closed form over `elapsed` and a cursor walked one tick
1101    /// at a time have to agree at every tick, for every shape of clip.
1102    #[test]
1103    fn the_closed_form_agrees_with_a_tick_by_tick_walk() {
1104        for (sheet, clip) in cases() {
1105            for ticks in 0..200 {
1106                let mut play = Playback::new();
1107                play.advance(ticks);
1108                assert_eq!(
1109                    play.frame_index(&sheet, &clip),
1110                    Some(naive(&sheet, &clip, ticks)),
1111                    "{:?} looping={} frames={:?} at tick {ticks}",
1112                    clip.direction,
1113                    clip.looping,
1114                    clip.frames,
1115                );
1116            }
1117        }
1118    }
1119
1120    /// Catching up after a stall must land where never stalling would.
1121    #[test]
1122    fn advancing_many_ticks_at_once_lands_where_one_at_a_time_does() {
1123        for (sheet, clip) in cases() {
1124            let mut stepped = Playback::new();
1125            for ticks in 0..300u64 {
1126                let mut jumped = Playback::new();
1127                jumped.advance(ticks);
1128                assert_eq!(
1129                    jumped.frame_index(&sheet, &clip),
1130                    stepped.frame_index(&sheet, &clip),
1131                    "{:?} looping={} frames={:?} at tick {ticks}",
1132                    clip.direction,
1133                    clip.looping,
1134                    clip.frames,
1135                );
1136                assert_eq!(jumped.elapsed(), stepped.elapsed());
1137                // And in two hops, which is where a wrap-then-wrap would show.
1138                let mut split = Playback::new();
1139                split.advance(ticks / 3);
1140                split.advance(ticks - ticks / 3);
1141                assert_eq!(
1142                    split.frame_index(&sheet, &clip),
1143                    stepped.frame_index(&sheet, &clip)
1144                );
1145                stepped.advance(1);
1146            }
1147        }
1148    }
1149
1150    #[test]
1151    fn restarting_and_seeking_put_playback_where_asked() {
1152        let sheet = strip([2, 1, 3, 1]);
1153        let walk = clip(vec![0, 1, 2, 3], Direction::Forward, false);
1154        let mut play = Playback::new();
1155        play.advance(5);
1156        assert_eq!(play.elapsed(), 5);
1157        assert_eq!(play.frame_index(&sheet, &walk), Some(2));
1158        play.restart();
1159        assert_eq!(play.elapsed(), 0);
1160        assert_eq!(play.frame_index(&sheet, &walk), Some(0));
1161        play.seek(6);
1162        assert_eq!(play.frame_index(&sheet, &walk), Some(3));
1163        assert!(!play.finished(&sheet, &walk));
1164        play.seek(u64::MAX);
1165        play.advance(9);
1166        assert_eq!(play.elapsed(), u64::MAX, "saturates rather than wrapping");
1167        assert!(play.finished(&sheet, &walk));
1168    }
1169
1170    /// A clip with nothing in it, or one naming a frame that is not there,
1171    /// draws nothing rather than panicking. `validate` refuses both.
1172    #[test]
1173    fn a_clip_that_cannot_draw_answers_none() {
1174        let sheet = strip([2, 1, 3, 1]);
1175        let empty = clip(vec![], Direction::PingPong, true);
1176        assert_eq!(empty.steps(), 0);
1177        assert_eq!(empty.step(0), None);
1178        assert_eq!(sheet.clip_duration(&empty), None);
1179        assert_eq!(Playback::new().frame_index(&sheet, &empty), None);
1180
1181        let dangling = clip(vec![0, 9], Direction::Forward, true);
1182        assert_eq!(Playback::new().frame_index(&sheet, &dangling), None);
1183    }
1184
1185    /// The renderer wants `[u0, v0, u1, v1]` with the top-left corner first,
1186    /// and every caller was computing it by hand from a rect and the sheet
1187    /// size. Halves swapped here would mirror every sprite in the game.
1188    #[test]
1189    fn frame_uvs_are_normalised_with_the_top_left_corner_first() {
1190        let sheet = Sheet {
1191            width: 64,
1192            height: 32,
1193            frames: vec![
1194                Frame {
1195                    name: "left".into(),
1196                    rect: Rect::new(0, 0, 16, 8),
1197                    hold: 1,
1198                },
1199                Frame {
1200                    name: "far".into(),
1201                    rect: Rect::new(48, 24, 16, 8),
1202                    hold: 1,
1203                },
1204            ],
1205            ..Sheet::default()
1206        };
1207        sheet.validate().expect("well formed");
1208        assert_eq!(sheet.uv(0), Some([0.0, 0.0, 0.25, 0.25]));
1209        assert_eq!(sheet.uv(1), Some([0.75, 0.75, 1.0, 1.0]));
1210        assert_eq!(sheet.uv(2), None, "no such frame");
1211
1212        // A sheet with no size would divide by zero and hand a NaN to a vertex
1213        // buffer, which draws nothing and blames the shader.
1214        let sizeless = Sheet {
1215            width: 0,
1216            ..sheet.clone()
1217        };
1218        assert_eq!(sizeless.uv(0), None);
1219    }
1220}