Skip to main content

clairlune_render/
package.rs

1//! Frozen scene packages: 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_for};
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    graph: SceneGraph,
116    palette: IndexedPalette,
117    atlas: GlyphAtlas,
118    background: IndexedImage,
119    hero_ms: u64,
120    /// A journey's moving layers, baked on first use (they are large, and
121    /// a live wallpaper only ever plays one theme).
122    journey: OnceLock<Option<JourneyBake>>,
123}
124
125impl ThemeScene {
126    fn journey(&self) -> Option<&JourneyBake> {
127        self.journey
128            .get_or_init(|| JourneyBake::new(&self.graph, &self.atlas))
129            .as_ref()
130    }
131}
132
133/// A frozen scene: plays without the generator.
134#[derive(Clone, Debug)]
135pub struct ScenePackage {
136    pub recipe: SceneRecipe,
137    pub width: u32,
138    pub height: u32,
139    /// The generator that made it (for information; playback ignores it).
140    pub generator_version: u32,
141    art: PackageArt,
142    themes: Vec<ThemeScene>,
143}
144
145impl ScenePackage {
146    /// Builds the scene in every theme it supports and freezes the result.
147    pub fn capture(recipe: &SceneRecipe, width: u32, height: u32) -> Result<Self, BuildError> {
148        Self::capture_with(
149            recipe,
150            width,
151            height,
152            builtin_catalog(),
153            builtin_character(),
154        )
155    }
156
157    /// [`capture`](Self::capture) with another activity catalog and character
158    /// (the developer preview loads both from disk).
159    pub fn capture_with(
160        recipe: &SceneRecipe,
161        width: u32,
162        height: u32,
163        catalog: &Catalog,
164        character: &dyn Character,
165    ) -> Result<Self, BuildError> {
166        let mut themes = Vec::new();
167        let mut graphs = Vec::new();
168        for theme in [Theme::Dark, Theme::Light] {
169            let opts = BuildOptions {
170                width,
171                height,
172                theme,
173                buddy: true,
174            };
175            match build_with(catalog, recipe, &opts) {
176                Ok(g) => graphs.push(g),
177                Err(BuildError::ThemeLocked(_)) => {}
178                Err(e) => return Err(e),
179            }
180        }
181        let first = graphs.first().ok_or(BuildError::ThemeLocked(Theme::Dark))?;
182        let activity = first
183            .activity
184            .as_deref()
185            .and_then(|id| catalog.get(id))
186            .cloned();
187        let art = PackageArt {
188            character: capture_character(character, activity.as_ref()),
189            props: capture_props(&graphs),
190            activity,
191        };
192        for mut graph in graphs {
193            let atlas = GlyphAtlas::for_graph(&graph);
194            let palette = IndexedPalette::for_graph(&graph)
195                .with_sprite_colors(character_colors(&art.character));
196            let background = bake_static(&graph, &atlas);
197            // The background replaces the cells; a loaded package has none.
198            graph.cells = Vec::new();
199            let hero_ms = hero_time_with_art(&graph, &art);
200            themes.push(ThemeScene {
201                theme: graph.theme,
202                graph,
203                palette,
204                atlas,
205                background,
206                hero_ms,
207                journey: OnceLock::new(),
208            });
209        }
210        Ok(ScenePackage {
211            recipe: recipe.clone(),
212            width,
213            height,
214            generator_version: recipe.generator_version,
215            art,
216            themes,
217        })
218    }
219
220    /// Themes this scene has, dark first.
221    pub fn themes(&self) -> Vec<Theme> {
222        self.themes.iter().map(|t| t.theme).collect()
223    }
224
225    /// Bytes a journey's baked layers take in a theme (baking them now), 0
226    /// for a scene that stays put.
227    pub fn journey_bytes(&self, theme: Theme) -> usize {
228        self.theme(theme)
229            .and_then(ThemeScene::journey)
230            .map_or(0, JourneyBake::bytes)
231    }
232
233    /// Keeps only `theme` (when the scene has it): a wallpaper on screen
234    /// plays one, and each theme carries a full-size background and its
235    /// own layout. Saved after this, the package has only that theme.
236    pub fn keep_only(&mut self, theme: Theme) {
237        if self.theme(theme).is_some() {
238            self.themes.retain(|t| t.theme == theme);
239            self.themes.shrink_to_fit();
240        }
241    }
242
243    /// First pixel row a journey's scrolling band covers in `theme`, or `None`
244    /// for a scene that stays put.
245    pub fn journey_band_top(&self, theme: Theme) -> Option<u32> {
246        self.theme(theme)?.journey().map(JourneyBake::band_top)
247    }
248
249    fn theme(&self, theme: Theme) -> Option<&ThemeScene> {
250        self.themes.iter().find(|t| t.theme == theme)
251    }
252
253    /// The still-frame time in a theme.
254    pub fn hero_ms(&self, theme: Theme) -> Option<u64> {
255        self.theme(theme).map(|t| t.hero_ms)
256    }
257
258    /// One frame, or `None` if the scene has no such theme.
259    pub fn frame(
260        &self,
261        theme: Theme,
262        buddy: bool,
263        t_ms: u64,
264        clock: Clock,
265    ) -> Option<(IndexedImage, &IndexedPalette)> {
266        let t = self.theme(theme)?;
267        let moved = t
268            .journey()
269            .map(|j| j.background_at(&t.graph, &t.background, t_ms));
270        let img = render_frame_for(
271            moved.as_ref().unwrap_or(&t.background),
272            &t.graph,
273            buddy,
274            &t.atlas,
275            &t.palette,
276            t_ms,
277            clock,
278            &self.art,
279        );
280        Some((img, &t.palette))
281    }
282
283    /// A frame to play the scene live, starting from the bare background;
284    /// move it with [`ScenePackage::advance`].
285    pub fn incremental(&self, theme: Theme) -> Option<IncrementalFrame> {
286        self.theme(theme)
287            .map(|t| IncrementalFrame::new(&t.background))
288    }
289
290    /// Moves a live frame to `t_ms` and returns the rectangles that changed;
291    /// the frame then equals [`ScenePackage::frame`] at that time.
292    pub fn advance(
293        &self,
294        frame: &mut IncrementalFrame,
295        theme: Theme,
296        buddy: bool,
297        t_ms: u64,
298        clock: Clock,
299    ) -> Option<Vec<PixelRect>> {
300        let t = self.theme(theme)?;
301        if let Some(j) = t.journey() {
302            return Some(frame.advance_journey_for(
303                j,
304                &t.background,
305                &t.graph,
306                buddy,
307                &t.atlas,
308                &t.palette,
309                t_ms,
310                clock,
311                &self.art,
312            ));
313        }
314        Some(frame.advance_for(
315            &t.background,
316            &t.graph,
317            buddy,
318            &t.atlas,
319            &t.palette,
320            t_ms,
321            clock,
322            &self.art,
323        ))
324    }
325
326    /// The still (hero) frame in a theme.
327    pub fn still(&self, theme: Theme, buddy: bool) -> Option<(IndexedImage, &IndexedPalette)> {
328        let t = self.hero_ms(theme)?;
329        self.frame(theme, buddy, t, Clock::Live)
330    }
331
332    /// The palette in a theme.
333    pub fn palette(&self, theme: Theme) -> Option<&IndexedPalette> {
334        self.theme(theme).map(|t| &t.palette)
335    }
336
337    /// The scene graph in a theme (layout, emitters, loop length).
338    pub fn graph(&self, theme: Theme) -> Option<&SceneGraph> {
339        self.theme(theme).map(|t| &t.graph)
340    }
341
342    /// Writes the package into `dir` (created if needed).
343    pub fn save(&self, dir: &Path) -> Result<(), PackageError> {
344        std::fs::create_dir_all(dir)?;
345        let mut sheet = SpriteSheetWriter::default();
346        let character = self
347            .art
348            .character
349            .iter()
350            .map(|((activity, state), anim)| AnimationFile {
351                activity: activity.clone(),
352                state: state.clone(),
353                name: anim.name.clone(),
354                frames: anim.frames.iter().map(|f| sheet.add(f)).collect(),
355            })
356            .collect();
357        let journeys = self.themes.iter().any(|t| t.graph.journey.is_some());
358        let file = PackageFile {
359            format: if journeys { 2 } else { 1 },
360            generator_version: self.generator_version,
361            recipe: self.recipe.clone(),
362            width: self.width,
363            height: self.height,
364            activity: self.art.activity.clone(),
365            character,
366            props: self
367                .art
368                .props
369                .iter()
370                .map(|(k, p)| PropFile {
371                    kind: *k,
372                    width: p.width,
373                    height: p.height,
374                    pixels: p.pixels.clone(),
375                })
376                .collect(),
377            themes: self
378                .themes
379                .iter()
380                .map(|t| ThemeFile {
381                    theme: t.theme,
382                    graph: t.graph.clone(),
383                    palette: t.palette.colors().to_vec(),
384                    atlas: t.atlas.clone(),
385                    hero_ms: t.hero_ms,
386                })
387                .collect(),
388        };
389        for t in &self.themes {
390            let mut png = Vec::new();
391            encode_png(&t.background, &t.palette, &mut png)
392                .map_err(|e| PackageError::Png(e.to_string()))?;
393            std::fs::write(dir.join(background_name(t.theme)), png)?;
394            if let Some(j) = &t.graph.journey {
395                for (i, layer) in j.layers.iter().enumerate() {
396                    let png = encode_layer(layer.cols, t.graph.grid.rows, &layer.cells)?;
397                    std::fs::write(dir.join(layer_name(t.theme, i)), png)?;
398                }
399            }
400        }
401        std::fs::write(dir.join("sprites.png"), sheet.png()?)?;
402        let json = serde_json::to_string(&file)?;
403        let tmp = dir.join("package.json.part");
404        std::fs::write(&tmp, json)?;
405        std::fs::rename(tmp, dir.join("package.json"))?;
406        Ok(())
407    }
408
409    /// Reads a package written by this or an older version.
410    pub fn load(dir: &Path) -> Result<Self, PackageError> {
411        let text = std::fs::read_to_string(dir.join("package.json"))?;
412        let probe: FormatProbe = serde_json::from_str(&text)?;
413        if probe.format > PACKAGE_FORMAT || probe.format == 0 {
414            return Err(PackageError::UnsupportedFormat(probe.format));
415        }
416        let file: PackageFile = serde_json::from_str(&text)?;
417        let sheet = SpriteSheetReader::open(&std::fs::read(dir.join("sprites.png"))?)?;
418        let mut character = PackagedCharacter::default();
419        for a in &file.character {
420            let frames = a
421                .frames
422                .iter()
423                .map(|f| sheet.frame(f))
424                .collect::<Result<Vec<_>, _>>()?;
425            character.insert(
426                &a.activity,
427                &a.state,
428                Animation {
429                    name: a.name.clone(),
430                    frames,
431                },
432            );
433        }
434        let art = PackageArt {
435            activity: file.activity,
436            character,
437            props: file
438                .props
439                .into_iter()
440                .map(|p| {
441                    let len = (p.width as usize).checked_mul(p.height as usize);
442                    if len != Some(p.pixels.len()) || p.width == 0 || p.height == 0 {
443                        return Err(PackageError::Invalid(format!("prop {:?} size", p.kind)));
444                    }
445                    Ok((
446                        p.kind,
447                        OwnedPixmap {
448                            width: p.width,
449                            height: p.height,
450                            pixels: p.pixels,
451                        },
452                    ))
453                })
454                .collect::<Result<_, _>>()?,
455        };
456        if art.activity.as_ref().is_some_and(|a| !a.playable()) {
457            return Err(PackageError::Invalid(
458                "activity has a state with no way on".into(),
459            ));
460        }
461        let mut themes = Vec::new();
462        for t in file.themes {
463            let (background, colors) =
464                decode_indexed(&std::fs::read(dir.join(background_name(t.theme)))?)?;
465            let palette = IndexedPalette::from_colors(t.palette);
466            if colors != palette.rgb_bytes()
467                || (background.width, background.height) != (file.width, file.height)
468            {
469                return Err(PackageError::Invalid(format!(
470                    "{} background does not match its palette or size",
471                    t.theme.as_str()
472                )));
473            }
474            check_graph(&t.graph, &t.atlas, file.width, file.height)?;
475            check_colors(&art, &palette)?;
476            let mut graph = t.graph;
477            if let Some(j) = &mut graph.journey {
478                let rows = graph.grid.rows;
479                for (i, layer) in j.layers.iter_mut().enumerate() {
480                    let bytes = std::fs::read(dir.join(layer_name(t.theme, i)))?;
481                    layer.cells = decode_layer(&bytes, layer.cols, rows)?;
482                }
483                let width = j.layers.last().map_or(0, |l| l.cols * graph.grid.cell_w);
484                if j.ground.len() != width as usize || j.loop_ms == 0 {
485                    return Err(PackageError::Invalid("journey ground or loop".into()));
486                }
487            }
488            themes.push(ThemeScene {
489                theme: t.theme,
490                graph,
491                palette,
492                atlas: t.atlas,
493                background,
494                hero_ms: t.hero_ms,
495                journey: OnceLock::new(),
496            });
497        }
498        if themes.is_empty() {
499            return Err(PackageError::Invalid("no themes".into()));
500        }
501        Ok(ScenePackage {
502            recipe: file.recipe,
503            width: file.width,
504            height: file.height,
505            generator_version: file.generator_version,
506            art,
507            themes,
508        })
509    }
510}
511
512/// A loaded theme's graph and atlas agree with each other and the image,
513/// so playback can index without checks (a damaged file is an error, not a
514/// crash).
515fn check_graph(
516    graph: &SceneGraph,
517    atlas: &GlyphAtlas,
518    width: u32,
519    height: u32,
520) -> Result<(), PackageError> {
521    let bad = |what: &str| {
522        Err(PackageError::Invalid(format!(
523            "{} {what}",
524            graph.theme.as_str()
525        )))
526    };
527    if (graph.width, graph.height) != (width, height) {
528        return bad("scene size differs from the package's");
529    }
530    let g = &graph.grid;
531    let fits = |origin: u32, n: u32, cell: u32, room: u32| {
532        cell > 0 && u64::from(origin) + u64::from(n) * u64::from(cell) <= u64::from(room)
533    };
534    if !fits(g.origin_x, g.cols, g.cell_w, width) || !fits(g.origin_y, g.rows, g.cell_h, height) {
535        return bad("grid doesn't fit the image");
536    }
537    if !atlas.fits(g.cell_w, g.cell_h) {
538        return bad("glyph atlas doesn't fit the grid");
539    }
540    if !graph.emitters.iter().all(|e| e.is_sound()) {
541        return bad("particles");
542    }
543    Ok(())
544}
545
546/// Every colour of the packaged art is in a theme's palette.
547fn check_colors(art: &PackageArt, palette: &IndexedPalette) -> Result<(), PackageError> {
548    let known = |rgb: &Rgb| palette.sprite_index(*rgb).is_some();
549    let props = art
550        .props
551        .iter()
552        .flat_map(|(_, p)| p.pixels.iter().flatten());
553    let character = art
554        .character
555        .iter()
556        .flat_map(|(_, a)| a.frames.iter().flat_map(|f| f.pixels.iter().flatten()));
557    if props.chain(character).all(known) {
558        Ok(())
559    } else {
560        Err(PackageError::Invalid(
561            "art colour missing from the palette".into(),
562        ))
563    }
564}
565
566fn background_name(theme: Theme) -> String {
567    format!("background-{}.png", theme.as_str())
568}
569
570fn layer_name(theme: Theme, i: usize) -> String {
571    format!("journey-{}-{i}.png", theme.as_str())
572}
573
574/// A journey layer's cells as a grey-and-alpha PNG: one pixel per cell,
575/// the glyph as grey and the shade as alpha.
576fn encode_layer(
577    cols: u32,
578    rows: u32,
579    cells: &[clairlune_scene::Cell],
580) -> Result<Vec<u8>, PackageError> {
581    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
582    let mut out = Vec::new();
583    let mut enc = png::Encoder::new(&mut out, cols, rows);
584    enc.set_color(png::ColorType::GrayscaleAlpha);
585    enc.set_depth(png::BitDepth::Eight);
586    let mut w = enc.write_header().map_err(|e| png_err(&e))?;
587    let data: Vec<u8> = cells.iter().flat_map(|c| [c.glyph, c.shade]).collect();
588    w.write_image_data(&data).map_err(|e| png_err(&e))?;
589    w.finish().map_err(|e| png_err(&e))?;
590    Ok(out)
591}
592
593fn decode_layer(
594    bytes: &[u8],
595    cols: u32,
596    rows: u32,
597) -> Result<Vec<clairlune_scene::Cell>, PackageError> {
598    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
599    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
600    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
601    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
602    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
603    if info.color_type != png::ColorType::GrayscaleAlpha
604        || info.bit_depth != png::BitDepth::Eight
605        || (info.width, info.height) != (cols, rows)
606    {
607        return Err(PackageError::Png(
608            "journey layer: wrong kind or size".into(),
609        ));
610    }
611    let glyphs = clairlune_scene::glyphs::GLYPHS.len() as u8;
612    buf[..info.buffer_size()]
613        .as_chunks::<2>()
614        .0
615        .iter()
616        .map(|&[glyph, shade]| {
617            if glyph < glyphs {
618                Ok(clairlune_scene::Cell { glyph, shade })
619            } else {
620                Err(PackageError::Invalid("journey layer: unknown glyph".into()))
621            }
622        })
623        .collect()
624}
625
626/// Every `(activity, state)` the scene can show: all states of its activity
627/// (the state machine may reach any), or the idle fallback.
628fn capture_character(from: &dyn Character, activity: Option<&Activity>) -> PackagedCharacter {
629    match activity {
630        Some(a) => PackagedCharacter::capture(
631            from,
632            a.animation
633                .states
634                .keys()
635                .map(|s| (a.id.as_str(), s.as_str())),
636        ),
637        None => PackagedCharacter::capture(from, [("", "idle")]),
638    }
639}
640
641/// Every colour the captured frames use, in a stable order.
642fn character_colors(c: &PackagedCharacter) -> Vec<Rgb> {
643    let mut out: Vec<Rgb> = Vec::new();
644    for (_, anim) in c.iter() {
645        for f in &anim.frames {
646            for rgb in f.pixels.iter().flatten() {
647                if !out.contains(rgb) {
648                    out.push(*rgb);
649                }
650            }
651        }
652    }
653    out
654}
655
656/// The pixel art of every prop the scene places, in either Buddy state.
657fn capture_props(graphs: &[SceneGraph]) -> Vec<(SpriteKind, OwnedPixmap)> {
658    let mut out: Vec<(SpriteKind, OwnedPixmap)> = Vec::new();
659    for g in graphs {
660        for s in g.props.iter().chain(&g.unattended) {
661            if s.kind != SpriteKind::Character && !out.iter().any(|(k, _)| *k == s.kind) {
662                out.push((s.kind, OwnedPixmap::copy_of(s.kind.map())));
663            }
664        }
665    }
666    out
667}
668
669// ---- On-disk format (1, and 2 with a journey's layer images) -----------
670
671#[derive(Deserialize)]
672struct FormatProbe {
673    format: u32,
674}
675
676#[derive(Serialize, Deserialize)]
677struct PackageFile {
678    format: u32,
679    generator_version: u32,
680    recipe: SceneRecipe,
681    width: u32,
682    height: u32,
683    activity: Option<Activity>,
684    character: Vec<AnimationFile>,
685    props: Vec<PropFile>,
686    themes: Vec<ThemeFile>,
687}
688
689#[derive(Serialize, Deserialize)]
690struct AnimationFile {
691    activity: String,
692    state: String,
693    name: String,
694    frames: Vec<FrameFile>,
695}
696
697/// A frame's place in `sprites.png` and its timing and anchors.
698#[derive(Serialize, Deserialize)]
699struct FrameFile {
700    y: u32,
701    width: u32,
702    height: u32,
703    duration_ms: u32,
704    anchors: BTreeMap<String, (i32, i32)>,
705}
706
707#[derive(Serialize, Deserialize)]
708struct PropFile {
709    kind: SpriteKind,
710    width: u32,
711    height: u32,
712    pixels: Vec<Option<Rgb>>,
713}
714
715#[derive(Serialize, Deserialize)]
716struct ThemeFile {
717    theme: Theme,
718    graph: SceneGraph,
719    palette: Vec<Rgb>,
720    atlas: GlyphAtlas,
721    hero_ms: u64,
722}
723
724/// Stacks frames top to bottom in one RGBA image; identical frames share
725/// their pixels.
726#[derive(Default)]
727struct SpriteSheetWriter {
728    width: u32,
729    rows: Vec<(u32, u32, Vec<Option<Rgb>>)>,
730    height: u32,
731}
732
733impl SpriteSheetWriter {
734    fn add(&mut self, f: &Frame) -> FrameFile {
735        let y = match self
736            .rows
737            .iter()
738            .find(|(_, w, px)| *w == f.width && *px == f.pixels)
739        {
740            Some((y, _, _)) => *y,
741            None => {
742                let y = self.height;
743                self.rows.push((y, f.width, f.pixels.clone()));
744                self.height += f.height;
745                self.width = self.width.max(f.width);
746                y
747            }
748        };
749        FrameFile {
750            y,
751            width: f.width,
752            height: f.height,
753            duration_ms: f.duration_ms,
754            anchors: f.anchors.clone(),
755        }
756    }
757
758    fn png(&self) -> Result<Vec<u8>, PackageError> {
759        let (w, h) = (self.width.max(1), self.height.max(1));
760        let mut rgba = vec![0u8; (w * h * 4) as usize];
761        for (y0, fw, px) in &self.rows {
762            for (i, p) in px.iter().enumerate() {
763                let Some(c) = p else { continue };
764                let (x, y) = (i as u32 % fw, y0 + i as u32 / fw);
765                let o = ((y * w + x) * 4) as usize;
766                rgba[o..o + 4].copy_from_slice(&[c.r, c.g, c.b, 255]);
767            }
768        }
769        let mut out = Vec::new();
770        let mut enc = png::Encoder::new(&mut out, w, h);
771        enc.set_color(png::ColorType::Rgba);
772        enc.set_depth(png::BitDepth::Eight);
773        let mut writer = enc
774            .write_header()
775            .map_err(|e| PackageError::Png(e.to_string()))?;
776        writer
777            .write_image_data(&rgba)
778            .map_err(|e| PackageError::Png(e.to_string()))?;
779        writer
780            .finish()
781            .map_err(|e| PackageError::Png(e.to_string()))?;
782        Ok(out)
783    }
784}
785
786struct SpriteSheetReader {
787    width: u32,
788    height: u32,
789    rgba: Vec<u8>,
790}
791
792impl SpriteSheetReader {
793    fn open(bytes: &[u8]) -> Result<Self, PackageError> {
794        let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
795        dec.set_transformations(png::Transformations::EXPAND);
796        let mut reader = dec
797            .read_info()
798            .map_err(|e| PackageError::Png(e.to_string()))?;
799        let mut buf = vec![0; reader.output_buffer_size().unwrap_or(0)];
800        let info = reader
801            .next_frame(&mut buf)
802            .map_err(|e| PackageError::Png(e.to_string()))?;
803        if info.color_type != png::ColorType::Rgba {
804            return Err(PackageError::Png("sprites.png must be RGBA".into()));
805        }
806        buf.truncate(info.buffer_size());
807        Ok(SpriteSheetReader {
808            width: info.width,
809            height: info.height,
810            rgba: buf,
811        })
812    }
813
814    fn frame(&self, f: &FrameFile) -> Result<Frame, PackageError> {
815        if f.width > self.width
816            || f.y
817                .checked_add(f.height)
818                .is_none_or(|end| end > self.height)
819        {
820            return Err(PackageError::Invalid(
821                "a frame lies outside sprites.png".into(),
822            ));
823        }
824        let mut pixels = Vec::with_capacity((f.width * f.height) as usize);
825        for y in f.y..f.y + f.height {
826            for x in 0..f.width {
827                let o = ((y * self.width + x) * 4) as usize;
828                let p = &self.rgba[o..o + 4];
829                pixels.push((p[3] != 0).then_some(Rgb {
830                    r: p[0],
831                    g: p[1],
832                    b: p[2],
833                }));
834            }
835        }
836        Ok(Frame {
837            width: f.width,
838            height: f.height,
839            pixels,
840            duration_ms: f.duration_ms,
841            anchors: f.anchors.clone(),
842        })
843    }
844}
845
846/// Decodes an 8-bit indexed PNG to its indices and palette bytes.
847fn decode_indexed(bytes: &[u8]) -> Result<(IndexedImage, Vec<u8>), PackageError> {
848    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
849    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
850    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
851    let palette = reader
852        .info()
853        .palette
854        .as_ref()
855        .ok_or_else(|| PackageError::Png("background must be indexed".into()))?
856        .to_vec();
857    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
858    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
859    if info.color_type != png::ColorType::Indexed || info.bit_depth != png::BitDepth::Eight {
860        return Err(PackageError::Png("background must be 8-bit indexed".into()));
861    }
862    buf.truncate(info.buffer_size());
863    Ok((
864        IndexedImage {
865            width: info.width,
866            height: info.height,
867            pixels: buf,
868        },
869        palette,
870    ))
871}