Skip to main content

clairlune_render/
package.rs

1//! Frozen scene packages (PLAN.md section 9c): how saved wallpapers are kept.
2//!
3//! A package holds the *output* of the generator for one scene at one size,
4//! not its inputs: for each theme the scene supports, the scene graph (layout,
5//! character track, props, emitters, lighting), the palette, the glyph masks
6//! and the baked background; plus the activity definition, the character
7//! frames the scene can show and the props' pixel art. Playback reads only the
8//! package, never the generator, the activity catalog or the built-in art, so
9//! a saved scene plays the same after any of them change.
10//!
11//! ```text
12//! scene/
13//! ├── package.json          format, recipe, size, art, per-theme scene data
14//! ├── background-dark.png   indexed, no animated elements
15//! ├── background-light.png
16//! ├── sprites.png           the character frames, stacked (RGBA)
17//! └── journey-dark-0.png    a journey's moving layers (format 2), one per
18//!                           theme and layer: glyph as grey, shade as alpha
19//! ```
20//!
21//! What is *code* rather than data (particle motion, lighting bands, the
22//! state machine, palette layout) is the package player for formats 1 and 2; a
23//! committed golden package (`tests/golden/packages`) pins its output.
24
25use crate::art::{OwnedPixmap, Pixmap, SceneArt};
26use crate::atlas::GlyphAtlas;
27use crate::bake::bake_static;
28use crate::clock::Clock;
29use crate::frame::{IncrementalFrame, PixelRect, hero_time_with_art, render_frame_with_art};
30use crate::journey::JourneyBake;
31use crate::palette::IndexedPalette;
32use crate::{IndexedImage, encode_png};
33use clairlune_scene::activity::{Activity, Catalog, builtin_catalog};
34use clairlune_scene::{
35    BuildError, BuildOptions, Rgb, SceneGraph, SceneRecipe, SpriteKind, Theme, build_with,
36};
37use clairlune_sprites::{Animation, Character, Frame, PackagedCharacter, builtin_character};
38use serde::{Deserialize, Serialize};
39use std::collections::BTreeMap;
40use std::fmt;
41use std::path::Path;
42use std::sync::OnceLock;
43
44/// The newest package format this build writes and reads. Older formats
45/// stay readable. Format 2 adds a journey's moving layers; a package without
46/// one is still written as format 1, so older versions can play it.
47pub const PACKAGE_FORMAT: u32 = 2;
48
49#[derive(Debug)]
50pub enum PackageError {
51    Io(std::io::Error),
52    Json(serde_json::Error),
53    Png(String),
54    /// Written by a newer Clairlune.
55    UnsupportedFormat(u32),
56    Invalid(String),
57}
58
59impl fmt::Display for PackageError {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            PackageError::Io(e) => write!(f, "{e}"),
63            PackageError::Json(e) => write!(f, "package.json: {e}"),
64            PackageError::Png(e) => write!(f, "image: {e}"),
65            PackageError::UnsupportedFormat(v) => write!(
66                f,
67                "scene package format {v} is newer than this version reads ({PACKAGE_FORMAT})"
68            ),
69            PackageError::Invalid(e) => write!(f, "scene package: {e}"),
70        }
71    }
72}
73
74impl std::error::Error for PackageError {}
75
76impl From<std::io::Error> for PackageError {
77    fn from(e: std::io::Error) -> Self {
78        PackageError::Io(e)
79    }
80}
81
82impl From<serde_json::Error> for PackageError {
83    fn from(e: serde_json::Error) -> Self {
84        PackageError::Json(e)
85    }
86}
87
88/// The art a package carries.
89#[derive(Clone, Debug)]
90pub struct PackageArt {
91    activity: Option<Activity>,
92    character: PackagedCharacter,
93    props: Vec<(SpriteKind, OwnedPixmap)>,
94}
95
96impl SceneArt for PackageArt {
97    fn activity(&self) -> Option<&Activity> {
98        self.activity.as_ref()
99    }
100    fn character(&self) -> &dyn Character {
101        &self.character
102    }
103    fn prop(&self, kind: SpriteKind) -> Option<&dyn Pixmap> {
104        self.props
105            .iter()
106            .find(|(k, _)| *k == kind)
107            .map(|(_, p)| p as &dyn Pixmap)
108    }
109}
110
111/// One theme's frozen scene.
112#[derive(Clone, Debug)]
113struct ThemeScene {
114    theme: Theme,
115    /// Laid out with Clawd; `graph_unattended` is the same with Buddy off.
116    graph: SceneGraph,
117    graph_unattended: SceneGraph,
118    palette: IndexedPalette,
119    atlas: GlyphAtlas,
120    background: IndexedImage,
121    hero_ms: u64,
122    /// A journey's moving layers, baked on first use (they are large, and
123    /// a live wallpaper only ever plays one theme).
124    journey: OnceLock<Option<JourneyBake>>,
125}
126
127impl ThemeScene {
128    fn journey(&self) -> Option<&JourneyBake> {
129        self.journey
130            .get_or_init(|| JourneyBake::new(&self.graph, &self.atlas))
131            .as_ref()
132    }
133}
134
135/// A frozen scene: plays without the generator.
136#[derive(Clone, Debug)]
137pub struct ScenePackage {
138    pub recipe: SceneRecipe,
139    pub width: u32,
140    pub height: u32,
141    /// The generator that made it (for information; playback ignores it).
142    pub generator_version: u32,
143    art: PackageArt,
144    themes: Vec<ThemeScene>,
145}
146
147impl ScenePackage {
148    /// Builds the scene in every theme it supports and freezes the result.
149    pub fn capture(recipe: &SceneRecipe, width: u32, height: u32) -> Result<Self, BuildError> {
150        Self::capture_with(
151            recipe,
152            width,
153            height,
154            builtin_catalog(),
155            builtin_character(),
156        )
157    }
158
159    /// [`capture`](Self::capture) with another activity catalog and character
160    /// (the developer preview loads both from disk).
161    pub fn capture_with(
162        recipe: &SceneRecipe,
163        width: u32,
164        height: u32,
165        catalog: &Catalog,
166        character: &dyn Character,
167    ) -> Result<Self, BuildError> {
168        let mut themes = Vec::new();
169        let mut graphs = Vec::new();
170        for theme in [Theme::Dark, Theme::Light] {
171            let opts = BuildOptions {
172                width,
173                height,
174                theme,
175                buddy: true,
176            };
177            match build_with(catalog, recipe, &opts) {
178                Ok(g) => graphs.push(g),
179                Err(BuildError::ThemeLocked(_)) => {}
180                Err(e) => return Err(e),
181            }
182        }
183        let first = graphs.first().ok_or(BuildError::ThemeLocked(Theme::Dark))?;
184        let activity = first
185            .activity
186            .as_deref()
187            .and_then(|id| catalog.get(id))
188            .cloned();
189        let art = PackageArt {
190            character: capture_character(character, activity.as_ref()),
191            props: capture_props(&graphs),
192            activity,
193        };
194        for mut graph in graphs {
195            let atlas = GlyphAtlas::for_grid(&graph.grid);
196            let palette = IndexedPalette::for_graph(&graph)
197                .with_sprite_colors(character_colors(&art.character));
198            let background = bake_static(&graph, &atlas);
199            // The background replaces the cells; a loaded package has none.
200            graph.cells = Vec::new();
201            let hero_ms = hero_time_with_art(&graph, &art);
202            let mut graph_unattended = graph.clone();
203            graph_unattended.buddy = false;
204            themes.push(ThemeScene {
205                theme: graph.theme,
206                graph,
207                graph_unattended,
208                palette,
209                atlas,
210                background,
211                hero_ms,
212                journey: OnceLock::new(),
213            });
214        }
215        Ok(ScenePackage {
216            recipe: recipe.clone(),
217            width,
218            height,
219            generator_version: recipe.generator_version,
220            art,
221            themes,
222        })
223    }
224
225    /// Themes this scene has, dark first.
226    pub fn themes(&self) -> Vec<Theme> {
227        self.themes.iter().map(|t| t.theme).collect()
228    }
229
230    fn theme(&self, theme: Theme) -> Option<&ThemeScene> {
231        self.themes.iter().find(|t| t.theme == theme)
232    }
233
234    /// The still-frame time in a theme.
235    pub fn hero_ms(&self, theme: Theme) -> Option<u64> {
236        self.theme(theme).map(|t| t.hero_ms)
237    }
238
239    /// One frame, or `None` if the scene has no such theme.
240    pub fn frame(
241        &self,
242        theme: Theme,
243        buddy: bool,
244        t_ms: u64,
245        clock: Clock,
246    ) -> Option<(IndexedImage, &IndexedPalette)> {
247        let t = self.theme(theme)?;
248        let graph = if buddy { &t.graph } else { &t.graph_unattended };
249        let moved = t
250            .journey()
251            .map(|j| j.background_at(graph, &t.background, t_ms));
252        let img = render_frame_with_art(
253            moved.as_ref().unwrap_or(&t.background),
254            graph,
255            &t.atlas,
256            &t.palette,
257            t_ms,
258            clock,
259            &self.art,
260        );
261        Some((img, &t.palette))
262    }
263
264    /// A frame to play the scene live, starting from the bare background;
265    /// move it with [`ScenePackage::advance`].
266    pub fn incremental(&self, theme: Theme) -> Option<IncrementalFrame> {
267        self.theme(theme)
268            .map(|t| IncrementalFrame::new(&t.background))
269    }
270
271    /// Moves a live frame to `t_ms` and returns the rectangles that changed;
272    /// the frame then equals [`ScenePackage::frame`] at that time.
273    pub fn advance(
274        &self,
275        frame: &mut IncrementalFrame,
276        theme: Theme,
277        buddy: bool,
278        t_ms: u64,
279        clock: Clock,
280    ) -> Option<Vec<PixelRect>> {
281        let t = self.theme(theme)?;
282        let graph = if buddy { &t.graph } else { &t.graph_unattended };
283        if let Some(j) = t.journey() {
284            return Some(frame.advance_journey(
285                j,
286                &t.background,
287                graph,
288                &t.atlas,
289                &t.palette,
290                t_ms,
291                clock,
292                &self.art,
293            ));
294        }
295        Some(frame.advance(
296            &t.background,
297            graph,
298            &t.atlas,
299            &t.palette,
300            t_ms,
301            clock,
302            &self.art,
303        ))
304    }
305
306    /// The still (hero) frame in a theme.
307    pub fn still(&self, theme: Theme, buddy: bool) -> Option<(IndexedImage, &IndexedPalette)> {
308        let t = self.hero_ms(theme)?;
309        self.frame(theme, buddy, t, Clock::Live)
310    }
311
312    /// The palette in a theme.
313    pub fn palette(&self, theme: Theme) -> Option<&IndexedPalette> {
314        self.theme(theme).map(|t| &t.palette)
315    }
316
317    /// The scene graph in a theme (layout, emitters, loop length).
318    pub fn graph(&self, theme: Theme) -> Option<&SceneGraph> {
319        self.theme(theme).map(|t| &t.graph)
320    }
321
322    /// Writes the package into `dir` (created if needed).
323    pub fn save(&self, dir: &Path) -> Result<(), PackageError> {
324        std::fs::create_dir_all(dir)?;
325        let mut sheet = SpriteSheetWriter::default();
326        let character = self
327            .art
328            .character
329            .iter()
330            .map(|((activity, state), anim)| AnimationFile {
331                activity: activity.clone(),
332                state: state.clone(),
333                name: anim.name.clone(),
334                frames: anim.frames.iter().map(|f| sheet.add(f)).collect(),
335            })
336            .collect();
337        let journeys = self.themes.iter().any(|t| t.graph.journey.is_some());
338        let file = PackageFile {
339            format: if journeys { 2 } else { 1 },
340            generator_version: self.generator_version,
341            recipe: self.recipe.clone(),
342            width: self.width,
343            height: self.height,
344            activity: self.art.activity.clone(),
345            character,
346            props: self
347                .art
348                .props
349                .iter()
350                .map(|(k, p)| PropFile {
351                    kind: *k,
352                    width: p.width,
353                    height: p.height,
354                    pixels: p.pixels.clone(),
355                })
356                .collect(),
357            themes: self
358                .themes
359                .iter()
360                .map(|t| ThemeFile {
361                    theme: t.theme,
362                    graph: t.graph.clone(),
363                    palette: t.palette.colors().to_vec(),
364                    atlas: t.atlas.clone(),
365                    hero_ms: t.hero_ms,
366                })
367                .collect(),
368        };
369        for t in &self.themes {
370            let mut png = Vec::new();
371            encode_png(&t.background, &t.palette, &mut png)
372                .map_err(|e| PackageError::Png(e.to_string()))?;
373            std::fs::write(dir.join(background_name(t.theme)), png)?;
374            if let Some(j) = &t.graph.journey {
375                for (i, layer) in j.layers.iter().enumerate() {
376                    let png = encode_layer(layer.cols, t.graph.grid.rows, &layer.cells)?;
377                    std::fs::write(dir.join(layer_name(t.theme, i)), png)?;
378                }
379            }
380        }
381        std::fs::write(dir.join("sprites.png"), sheet.png()?)?;
382        let json = serde_json::to_string(&file)?;
383        let tmp = dir.join("package.json.part");
384        std::fs::write(&tmp, json)?;
385        std::fs::rename(tmp, dir.join("package.json"))?;
386        Ok(())
387    }
388
389    /// Reads a package written by this or an older version.
390    pub fn load(dir: &Path) -> Result<Self, PackageError> {
391        let text = std::fs::read_to_string(dir.join("package.json"))?;
392        let probe: FormatProbe = serde_json::from_str(&text)?;
393        if probe.format > PACKAGE_FORMAT || probe.format == 0 {
394            return Err(PackageError::UnsupportedFormat(probe.format));
395        }
396        let file: PackageFile = serde_json::from_str(&text)?;
397        let sheet = SpriteSheetReader::open(&std::fs::read(dir.join("sprites.png"))?)?;
398        let mut character = PackagedCharacter::default();
399        for a in &file.character {
400            let frames = a
401                .frames
402                .iter()
403                .map(|f| sheet.frame(f))
404                .collect::<Result<Vec<_>, _>>()?;
405            character.insert(
406                &a.activity,
407                &a.state,
408                Animation {
409                    name: a.name.clone(),
410                    frames,
411                },
412            );
413        }
414        let art = PackageArt {
415            activity: file.activity,
416            character,
417            props: file
418                .props
419                .into_iter()
420                .map(|p| {
421                    if p.pixels.len() != (p.width * p.height) as usize {
422                        return Err(PackageError::Invalid(format!("prop {:?} size", p.kind)));
423                    }
424                    Ok((
425                        p.kind,
426                        OwnedPixmap {
427                            width: p.width,
428                            height: p.height,
429                            pixels: p.pixels,
430                        },
431                    ))
432                })
433                .collect::<Result<_, _>>()?,
434        };
435        let mut themes = Vec::new();
436        for t in file.themes {
437            let (background, colors) =
438                decode_indexed(&std::fs::read(dir.join(background_name(t.theme)))?)?;
439            let palette = IndexedPalette::from_colors(t.palette);
440            if colors != palette.rgb_bytes()
441                || (background.width, background.height) != (file.width, file.height)
442            {
443                return Err(PackageError::Invalid(format!(
444                    "{} background does not match its palette or size",
445                    t.theme.as_str()
446                )));
447            }
448            let mut graph = t.graph;
449            if let Some(j) = &mut graph.journey {
450                let rows = graph.grid.rows;
451                for (i, layer) in j.layers.iter_mut().enumerate() {
452                    let bytes = std::fs::read(dir.join(layer_name(t.theme, i)))?;
453                    layer.cells = decode_layer(&bytes, layer.cols, rows)?;
454                }
455                let width = j.layers.last().map_or(0, |l| l.cols * graph.grid.cell_w);
456                if j.ground.len() != width as usize || j.loop_ms == 0 {
457                    return Err(PackageError::Invalid("journey ground or loop".into()));
458                }
459            }
460            let mut graph_unattended = graph.clone();
461            graph_unattended.buddy = false;
462            themes.push(ThemeScene {
463                theme: t.theme,
464                graph,
465                graph_unattended,
466                palette,
467                atlas: t.atlas,
468                background,
469                hero_ms: t.hero_ms,
470                journey: OnceLock::new(),
471            });
472        }
473        if themes.is_empty() {
474            return Err(PackageError::Invalid("no themes".into()));
475        }
476        Ok(ScenePackage {
477            recipe: file.recipe,
478            width: file.width,
479            height: file.height,
480            generator_version: file.generator_version,
481            art,
482            themes,
483        })
484    }
485}
486
487fn background_name(theme: Theme) -> String {
488    format!("background-{}.png", theme.as_str())
489}
490
491fn layer_name(theme: Theme, i: usize) -> String {
492    format!("journey-{}-{i}.png", theme.as_str())
493}
494
495/// A journey layer's cells as a grey-and-alpha PNG: one pixel per cell,
496/// the glyph as grey and the shade as alpha.
497fn encode_layer(
498    cols: u32,
499    rows: u32,
500    cells: &[clairlune_scene::Cell],
501) -> Result<Vec<u8>, PackageError> {
502    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
503    let mut out = Vec::new();
504    let mut enc = png::Encoder::new(&mut out, cols, rows);
505    enc.set_color(png::ColorType::GrayscaleAlpha);
506    enc.set_depth(png::BitDepth::Eight);
507    let mut w = enc.write_header().map_err(|e| png_err(&e))?;
508    let data: Vec<u8> = cells.iter().flat_map(|c| [c.glyph, c.shade]).collect();
509    w.write_image_data(&data).map_err(|e| png_err(&e))?;
510    w.finish().map_err(|e| png_err(&e))?;
511    Ok(out)
512}
513
514fn decode_layer(
515    bytes: &[u8],
516    cols: u32,
517    rows: u32,
518) -> Result<Vec<clairlune_scene::Cell>, PackageError> {
519    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
520    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
521    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
522    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
523    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
524    if info.color_type != png::ColorType::GrayscaleAlpha
525        || info.bit_depth != png::BitDepth::Eight
526        || (info.width, info.height) != (cols, rows)
527    {
528        return Err(PackageError::Png(
529            "journey layer: wrong kind or size".into(),
530        ));
531    }
532    let glyphs = clairlune_scene::glyphs::GLYPHS.len() as u8;
533    buf[..info.buffer_size()]
534        .as_chunks::<2>()
535        .0
536        .iter()
537        .map(|&[glyph, shade]| {
538            if glyph < glyphs {
539                Ok(clairlune_scene::Cell { glyph, shade })
540            } else {
541                Err(PackageError::Invalid("journey layer: unknown glyph".into()))
542            }
543        })
544        .collect()
545}
546
547/// Every `(activity, state)` the scene can show: all states of its activity
548/// (the state machine may reach any), or the idle fallback.
549fn capture_character(from: &dyn Character, activity: Option<&Activity>) -> PackagedCharacter {
550    match activity {
551        Some(a) => PackagedCharacter::capture(
552            from,
553            a.animation
554                .states
555                .keys()
556                .map(|s| (a.id.as_str(), s.as_str())),
557        ),
558        None => PackagedCharacter::capture(from, [("", "idle")]),
559    }
560}
561
562/// Every colour the captured frames use, in a stable order.
563fn character_colors(c: &PackagedCharacter) -> Vec<Rgb> {
564    let mut out: Vec<Rgb> = Vec::new();
565    for (_, anim) in c.iter() {
566        for f in &anim.frames {
567            for rgb in f.pixels.iter().flatten() {
568                if !out.contains(rgb) {
569                    out.push(*rgb);
570                }
571            }
572        }
573    }
574    out
575}
576
577/// The pixel art of every prop the scene places, in either Buddy state.
578fn capture_props(graphs: &[SceneGraph]) -> Vec<(SpriteKind, OwnedPixmap)> {
579    let mut out: Vec<(SpriteKind, OwnedPixmap)> = Vec::new();
580    for g in graphs {
581        for s in g.props.iter().chain(&g.unattended) {
582            if s.kind != SpriteKind::Character && !out.iter().any(|(k, _)| *k == s.kind) {
583                out.push((s.kind, OwnedPixmap::copy_of(s.kind.map())));
584            }
585        }
586    }
587    out
588}
589
590// ---- On-disk format (1, and 2 with a journey's layer images) -----------
591
592#[derive(Deserialize)]
593struct FormatProbe {
594    format: u32,
595}
596
597#[derive(Serialize, Deserialize)]
598struct PackageFile {
599    format: u32,
600    generator_version: u32,
601    recipe: SceneRecipe,
602    width: u32,
603    height: u32,
604    activity: Option<Activity>,
605    character: Vec<AnimationFile>,
606    props: Vec<PropFile>,
607    themes: Vec<ThemeFile>,
608}
609
610#[derive(Serialize, Deserialize)]
611struct AnimationFile {
612    activity: String,
613    state: String,
614    name: String,
615    frames: Vec<FrameFile>,
616}
617
618/// A frame's place in `sprites.png` and its timing and anchors.
619#[derive(Serialize, Deserialize)]
620struct FrameFile {
621    y: u32,
622    width: u32,
623    height: u32,
624    duration_ms: u32,
625    anchors: BTreeMap<String, (i32, i32)>,
626}
627
628#[derive(Serialize, Deserialize)]
629struct PropFile {
630    kind: SpriteKind,
631    width: u32,
632    height: u32,
633    pixels: Vec<Option<Rgb>>,
634}
635
636#[derive(Serialize, Deserialize)]
637struct ThemeFile {
638    theme: Theme,
639    graph: SceneGraph,
640    palette: Vec<Rgb>,
641    atlas: GlyphAtlas,
642    hero_ms: u64,
643}
644
645/// Stacks frames top to bottom in one RGBA image; identical frames share
646/// their pixels.
647#[derive(Default)]
648struct SpriteSheetWriter {
649    width: u32,
650    rows: Vec<(u32, u32, Vec<Option<Rgb>>)>,
651    height: u32,
652}
653
654impl SpriteSheetWriter {
655    fn add(&mut self, f: &Frame) -> FrameFile {
656        let y = match self
657            .rows
658            .iter()
659            .find(|(_, w, px)| *w == f.width && *px == f.pixels)
660        {
661            Some((y, _, _)) => *y,
662            None => {
663                let y = self.height;
664                self.rows.push((y, f.width, f.pixels.clone()));
665                self.height += f.height;
666                self.width = self.width.max(f.width);
667                y
668            }
669        };
670        FrameFile {
671            y,
672            width: f.width,
673            height: f.height,
674            duration_ms: f.duration_ms,
675            anchors: f.anchors.clone(),
676        }
677    }
678
679    fn png(&self) -> Result<Vec<u8>, PackageError> {
680        let (w, h) = (self.width.max(1), self.height.max(1));
681        let mut rgba = vec![0u8; (w * h * 4) as usize];
682        for (y0, fw, px) in &self.rows {
683            for (i, p) in px.iter().enumerate() {
684                let Some(c) = p else { continue };
685                let (x, y) = (i as u32 % fw, y0 + i as u32 / fw);
686                let o = ((y * w + x) * 4) as usize;
687                rgba[o..o + 4].copy_from_slice(&[c.r, c.g, c.b, 255]);
688            }
689        }
690        let mut out = Vec::new();
691        let mut enc = png::Encoder::new(&mut out, w, h);
692        enc.set_color(png::ColorType::Rgba);
693        enc.set_depth(png::BitDepth::Eight);
694        let mut writer = enc
695            .write_header()
696            .map_err(|e| PackageError::Png(e.to_string()))?;
697        writer
698            .write_image_data(&rgba)
699            .map_err(|e| PackageError::Png(e.to_string()))?;
700        writer
701            .finish()
702            .map_err(|e| PackageError::Png(e.to_string()))?;
703        Ok(out)
704    }
705}
706
707struct SpriteSheetReader {
708    width: u32,
709    height: u32,
710    rgba: Vec<u8>,
711}
712
713impl SpriteSheetReader {
714    fn open(bytes: &[u8]) -> Result<Self, PackageError> {
715        let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
716        dec.set_transformations(png::Transformations::EXPAND);
717        let mut reader = dec
718            .read_info()
719            .map_err(|e| PackageError::Png(e.to_string()))?;
720        let mut buf = vec![0; reader.output_buffer_size().unwrap_or(0)];
721        let info = reader
722            .next_frame(&mut buf)
723            .map_err(|e| PackageError::Png(e.to_string()))?;
724        if info.color_type != png::ColorType::Rgba {
725            return Err(PackageError::Png("sprites.png must be RGBA".into()));
726        }
727        buf.truncate(info.buffer_size());
728        Ok(SpriteSheetReader {
729            width: info.width,
730            height: info.height,
731            rgba: buf,
732        })
733    }
734
735    fn frame(&self, f: &FrameFile) -> Result<Frame, PackageError> {
736        if f.width > self.width || f.y + f.height > self.height {
737            return Err(PackageError::Invalid(
738                "a frame lies outside sprites.png".into(),
739            ));
740        }
741        let mut pixels = Vec::with_capacity((f.width * f.height) as usize);
742        for y in f.y..f.y + f.height {
743            for x in 0..f.width {
744                let o = ((y * self.width + x) * 4) as usize;
745                let p = &self.rgba[o..o + 4];
746                pixels.push((p[3] != 0).then_some(Rgb {
747                    r: p[0],
748                    g: p[1],
749                    b: p[2],
750                }));
751            }
752        }
753        Ok(Frame {
754            width: f.width,
755            height: f.height,
756            pixels,
757            duration_ms: f.duration_ms,
758            anchors: f.anchors.clone(),
759        })
760    }
761}
762
763/// Decodes an 8-bit indexed PNG to its indices and palette bytes.
764fn decode_indexed(bytes: &[u8]) -> Result<(IndexedImage, Vec<u8>), PackageError> {
765    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
766    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
767    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
768    let palette = reader
769        .info()
770        .palette
771        .as_ref()
772        .ok_or_else(|| PackageError::Png("background must be indexed".into()))?
773        .to_vec();
774    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
775    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
776    if info.color_type != png::ColorType::Indexed || info.bit_depth != png::BitDepth::Eight {
777        return Err(PackageError::Png("background must be 8-bit indexed".into()));
778    }
779    buf.truncate(info.buffer_size());
780    Ok((
781        IndexedImage {
782            width: info.width,
783            height: info.height,
784            pixels: buf,
785        },
786        palette,
787    ))
788}