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