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                    let len = (p.width as usize).checked_mul(p.height as usize);
422                    if len != Some(p.pixels.len()) || p.width == 0 || p.height == 0 {
423                        return Err(PackageError::Invalid(format!("prop {:?} size", p.kind)));
424                    }
425                    Ok((
426                        p.kind,
427                        OwnedPixmap {
428                            width: p.width,
429                            height: p.height,
430                            pixels: p.pixels,
431                        },
432                    ))
433                })
434                .collect::<Result<_, _>>()?,
435        };
436        if art.activity.as_ref().is_some_and(|a| !a.playable()) {
437            return Err(PackageError::Invalid(
438                "activity has a state with no way on".into(),
439            ));
440        }
441        let mut themes = Vec::new();
442        for t in file.themes {
443            let (background, colors) =
444                decode_indexed(&std::fs::read(dir.join(background_name(t.theme)))?)?;
445            let palette = IndexedPalette::from_colors(t.palette);
446            if colors != palette.rgb_bytes()
447                || (background.width, background.height) != (file.width, file.height)
448            {
449                return Err(PackageError::Invalid(format!(
450                    "{} background does not match its palette or size",
451                    t.theme.as_str()
452                )));
453            }
454            check_graph(&t.graph, &t.atlas, file.width, file.height)?;
455            check_colors(&art, &palette)?;
456            let mut graph = t.graph;
457            if let Some(j) = &mut graph.journey {
458                let rows = graph.grid.rows;
459                for (i, layer) in j.layers.iter_mut().enumerate() {
460                    let bytes = std::fs::read(dir.join(layer_name(t.theme, i)))?;
461                    layer.cells = decode_layer(&bytes, layer.cols, rows)?;
462                }
463                let width = j.layers.last().map_or(0, |l| l.cols * graph.grid.cell_w);
464                if j.ground.len() != width as usize || j.loop_ms == 0 {
465                    return Err(PackageError::Invalid("journey ground or loop".into()));
466                }
467            }
468            let mut graph_unattended = graph.clone();
469            graph_unattended.buddy = false;
470            themes.push(ThemeScene {
471                theme: t.theme,
472                graph,
473                graph_unattended,
474                palette,
475                atlas: t.atlas,
476                background,
477                hero_ms: t.hero_ms,
478                journey: OnceLock::new(),
479            });
480        }
481        if themes.is_empty() {
482            return Err(PackageError::Invalid("no themes".into()));
483        }
484        Ok(ScenePackage {
485            recipe: file.recipe,
486            width: file.width,
487            height: file.height,
488            generator_version: file.generator_version,
489            art,
490            themes,
491        })
492    }
493}
494
495/// A loaded theme's graph and atlas agree with each other and the image,
496/// so playback can index without checks (a damaged file is an error, not a
497/// crash).
498fn check_graph(
499    graph: &SceneGraph,
500    atlas: &GlyphAtlas,
501    width: u32,
502    height: u32,
503) -> Result<(), PackageError> {
504    let bad = |what: &str| {
505        Err(PackageError::Invalid(format!(
506            "{} {what}",
507            graph.theme.as_str()
508        )))
509    };
510    if (graph.width, graph.height) != (width, height) {
511        return bad("scene size differs from the package's");
512    }
513    let g = &graph.grid;
514    let fits = |origin: u32, n: u32, cell: u32, room: u32| {
515        cell > 0 && u64::from(origin) + u64::from(n) * u64::from(cell) <= u64::from(room)
516    };
517    if !fits(g.origin_x, g.cols, g.cell_w, width) || !fits(g.origin_y, g.rows, g.cell_h, height) {
518        return bad("grid doesn't fit the image");
519    }
520    if !atlas.fits(g.cell_w, g.cell_h) {
521        return bad("glyph atlas doesn't fit the grid");
522    }
523    if !graph.emitters.iter().all(|e| e.is_sound()) {
524        return bad("particles");
525    }
526    Ok(())
527}
528
529/// Every colour of the packaged art is in a theme's palette.
530fn check_colors(art: &PackageArt, palette: &IndexedPalette) -> Result<(), PackageError> {
531    let known = |rgb: &Rgb| palette.sprite_index(*rgb).is_some();
532    let props = art
533        .props
534        .iter()
535        .flat_map(|(_, p)| p.pixels.iter().flatten());
536    let character = art
537        .character
538        .iter()
539        .flat_map(|(_, a)| a.frames.iter().flat_map(|f| f.pixels.iter().flatten()));
540    if props.chain(character).all(known) {
541        Ok(())
542    } else {
543        Err(PackageError::Invalid(
544            "art colour missing from the palette".into(),
545        ))
546    }
547}
548
549fn background_name(theme: Theme) -> String {
550    format!("background-{}.png", theme.as_str())
551}
552
553fn layer_name(theme: Theme, i: usize) -> String {
554    format!("journey-{}-{i}.png", theme.as_str())
555}
556
557/// A journey layer's cells as a grey-and-alpha PNG: one pixel per cell,
558/// the glyph as grey and the shade as alpha.
559fn encode_layer(
560    cols: u32,
561    rows: u32,
562    cells: &[clairlune_scene::Cell],
563) -> Result<Vec<u8>, PackageError> {
564    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
565    let mut out = Vec::new();
566    let mut enc = png::Encoder::new(&mut out, cols, rows);
567    enc.set_color(png::ColorType::GrayscaleAlpha);
568    enc.set_depth(png::BitDepth::Eight);
569    let mut w = enc.write_header().map_err(|e| png_err(&e))?;
570    let data: Vec<u8> = cells.iter().flat_map(|c| [c.glyph, c.shade]).collect();
571    w.write_image_data(&data).map_err(|e| png_err(&e))?;
572    w.finish().map_err(|e| png_err(&e))?;
573    Ok(out)
574}
575
576fn decode_layer(
577    bytes: &[u8],
578    cols: u32,
579    rows: u32,
580) -> Result<Vec<clairlune_scene::Cell>, PackageError> {
581    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
582    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
583    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
584    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
585    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
586    if info.color_type != png::ColorType::GrayscaleAlpha
587        || info.bit_depth != png::BitDepth::Eight
588        || (info.width, info.height) != (cols, rows)
589    {
590        return Err(PackageError::Png(
591            "journey layer: wrong kind or size".into(),
592        ));
593    }
594    let glyphs = clairlune_scene::glyphs::GLYPHS.len() as u8;
595    buf[..info.buffer_size()]
596        .as_chunks::<2>()
597        .0
598        .iter()
599        .map(|&[glyph, shade]| {
600            if glyph < glyphs {
601                Ok(clairlune_scene::Cell { glyph, shade })
602            } else {
603                Err(PackageError::Invalid("journey layer: unknown glyph".into()))
604            }
605        })
606        .collect()
607}
608
609/// Every `(activity, state)` the scene can show: all states of its activity
610/// (the state machine may reach any), or the idle fallback.
611fn capture_character(from: &dyn Character, activity: Option<&Activity>) -> PackagedCharacter {
612    match activity {
613        Some(a) => PackagedCharacter::capture(
614            from,
615            a.animation
616                .states
617                .keys()
618                .map(|s| (a.id.as_str(), s.as_str())),
619        ),
620        None => PackagedCharacter::capture(from, [("", "idle")]),
621    }
622}
623
624/// Every colour the captured frames use, in a stable order.
625fn character_colors(c: &PackagedCharacter) -> Vec<Rgb> {
626    let mut out: Vec<Rgb> = Vec::new();
627    for (_, anim) in c.iter() {
628        for f in &anim.frames {
629            for rgb in f.pixels.iter().flatten() {
630                if !out.contains(rgb) {
631                    out.push(*rgb);
632                }
633            }
634        }
635    }
636    out
637}
638
639/// The pixel art of every prop the scene places, in either Buddy state.
640fn capture_props(graphs: &[SceneGraph]) -> Vec<(SpriteKind, OwnedPixmap)> {
641    let mut out: Vec<(SpriteKind, OwnedPixmap)> = Vec::new();
642    for g in graphs {
643        for s in g.props.iter().chain(&g.unattended) {
644            if s.kind != SpriteKind::Character && !out.iter().any(|(k, _)| *k == s.kind) {
645                out.push((s.kind, OwnedPixmap::copy_of(s.kind.map())));
646            }
647        }
648    }
649    out
650}
651
652// ---- On-disk format (1, and 2 with a journey's layer images) -----------
653
654#[derive(Deserialize)]
655struct FormatProbe {
656    format: u32,
657}
658
659#[derive(Serialize, Deserialize)]
660struct PackageFile {
661    format: u32,
662    generator_version: u32,
663    recipe: SceneRecipe,
664    width: u32,
665    height: u32,
666    activity: Option<Activity>,
667    character: Vec<AnimationFile>,
668    props: Vec<PropFile>,
669    themes: Vec<ThemeFile>,
670}
671
672#[derive(Serialize, Deserialize)]
673struct AnimationFile {
674    activity: String,
675    state: String,
676    name: String,
677    frames: Vec<FrameFile>,
678}
679
680/// A frame's place in `sprites.png` and its timing and anchors.
681#[derive(Serialize, Deserialize)]
682struct FrameFile {
683    y: u32,
684    width: u32,
685    height: u32,
686    duration_ms: u32,
687    anchors: BTreeMap<String, (i32, i32)>,
688}
689
690#[derive(Serialize, Deserialize)]
691struct PropFile {
692    kind: SpriteKind,
693    width: u32,
694    height: u32,
695    pixels: Vec<Option<Rgb>>,
696}
697
698#[derive(Serialize, Deserialize)]
699struct ThemeFile {
700    theme: Theme,
701    graph: SceneGraph,
702    palette: Vec<Rgb>,
703    atlas: GlyphAtlas,
704    hero_ms: u64,
705}
706
707/// Stacks frames top to bottom in one RGBA image; identical frames share
708/// their pixels.
709#[derive(Default)]
710struct SpriteSheetWriter {
711    width: u32,
712    rows: Vec<(u32, u32, Vec<Option<Rgb>>)>,
713    height: u32,
714}
715
716impl SpriteSheetWriter {
717    fn add(&mut self, f: &Frame) -> FrameFile {
718        let y = match self
719            .rows
720            .iter()
721            .find(|(_, w, px)| *w == f.width && *px == f.pixels)
722        {
723            Some((y, _, _)) => *y,
724            None => {
725                let y = self.height;
726                self.rows.push((y, f.width, f.pixels.clone()));
727                self.height += f.height;
728                self.width = self.width.max(f.width);
729                y
730            }
731        };
732        FrameFile {
733            y,
734            width: f.width,
735            height: f.height,
736            duration_ms: f.duration_ms,
737            anchors: f.anchors.clone(),
738        }
739    }
740
741    fn png(&self) -> Result<Vec<u8>, PackageError> {
742        let (w, h) = (self.width.max(1), self.height.max(1));
743        let mut rgba = vec![0u8; (w * h * 4) as usize];
744        for (y0, fw, px) in &self.rows {
745            for (i, p) in px.iter().enumerate() {
746                let Some(c) = p else { continue };
747                let (x, y) = (i as u32 % fw, y0 + i as u32 / fw);
748                let o = ((y * w + x) * 4) as usize;
749                rgba[o..o + 4].copy_from_slice(&[c.r, c.g, c.b, 255]);
750            }
751        }
752        let mut out = Vec::new();
753        let mut enc = png::Encoder::new(&mut out, w, h);
754        enc.set_color(png::ColorType::Rgba);
755        enc.set_depth(png::BitDepth::Eight);
756        let mut writer = enc
757            .write_header()
758            .map_err(|e| PackageError::Png(e.to_string()))?;
759        writer
760            .write_image_data(&rgba)
761            .map_err(|e| PackageError::Png(e.to_string()))?;
762        writer
763            .finish()
764            .map_err(|e| PackageError::Png(e.to_string()))?;
765        Ok(out)
766    }
767}
768
769struct SpriteSheetReader {
770    width: u32,
771    height: u32,
772    rgba: Vec<u8>,
773}
774
775impl SpriteSheetReader {
776    fn open(bytes: &[u8]) -> Result<Self, PackageError> {
777        let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
778        dec.set_transformations(png::Transformations::EXPAND);
779        let mut reader = dec
780            .read_info()
781            .map_err(|e| PackageError::Png(e.to_string()))?;
782        let mut buf = vec![0; reader.output_buffer_size().unwrap_or(0)];
783        let info = reader
784            .next_frame(&mut buf)
785            .map_err(|e| PackageError::Png(e.to_string()))?;
786        if info.color_type != png::ColorType::Rgba {
787            return Err(PackageError::Png("sprites.png must be RGBA".into()));
788        }
789        buf.truncate(info.buffer_size());
790        Ok(SpriteSheetReader {
791            width: info.width,
792            height: info.height,
793            rgba: buf,
794        })
795    }
796
797    fn frame(&self, f: &FrameFile) -> Result<Frame, PackageError> {
798        if f.width > self.width
799            || f.y
800                .checked_add(f.height)
801                .is_none_or(|end| end > self.height)
802        {
803            return Err(PackageError::Invalid(
804                "a frame lies outside sprites.png".into(),
805            ));
806        }
807        let mut pixels = Vec::with_capacity((f.width * f.height) as usize);
808        for y in f.y..f.y + f.height {
809            for x in 0..f.width {
810                let o = ((y * self.width + x) * 4) as usize;
811                let p = &self.rgba[o..o + 4];
812                pixels.push((p[3] != 0).then_some(Rgb {
813                    r: p[0],
814                    g: p[1],
815                    b: p[2],
816                }));
817            }
818        }
819        Ok(Frame {
820            width: f.width,
821            height: f.height,
822            pixels,
823            duration_ms: f.duration_ms,
824            anchors: f.anchors.clone(),
825        })
826    }
827}
828
829/// Decodes an 8-bit indexed PNG to its indices and palette bytes.
830fn decode_indexed(bytes: &[u8]) -> Result<(IndexedImage, Vec<u8>), PackageError> {
831    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
832    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
833    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
834    let palette = reader
835        .info()
836        .palette
837        .as_ref()
838        .ok_or_else(|| PackageError::Png("background must be indexed".into()))?
839        .to_vec();
840    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
841    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
842    if info.color_type != png::ColorType::Indexed || info.bit_depth != png::BitDepth::Eight {
843        return Err(PackageError::Png("background must be 8-bit indexed".into()));
844    }
845    buf.truncate(info.buffer_size());
846    Ok((
847        IndexedImage {
848            width: info.width,
849            height: info.height,
850            pixels: buf,
851        },
852        palette,
853    ))
854}