clairlune-render 0.8.0

Glyph atlas, palette-index compositor and PNG export for Clairlune ASCII-art wallpapers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Frozen scene packages (PLAN.md section 9c): how saved wallpapers are kept.
//!
//! A package holds the *output* of the generator for one scene at one size,
//! not its inputs: for each theme the scene supports, the scene graph (layout,
//! character track, props, emitters, lighting), the palette, the glyph masks
//! and the baked background; plus the activity definition, the character
//! frames the scene can show and the props' pixel art. Playback reads only the
//! package, never the generator, the activity catalog or the built-in art, so
//! a saved scene plays the same after any of them change.
//!
//! ```text
//! scene/
//! ├── package.json          format, recipe, size, art, per-theme scene data
//! ├── background-dark.png   indexed, no animated elements
//! ├── background-light.png
//! └── sprites.png           the character frames, stacked (RGBA)
//! ```
//!
//! What is *code* rather than data (particle motion, lighting bands, the
//! state machine, palette layout) is the package player for format 1; a
//! committed golden package (`tests/golden/packages`) pins its output.

use crate::art::{OwnedPixmap, Pixmap, SceneArt};
use crate::atlas::GlyphAtlas;
use crate::bake::bake_static;
use crate::clock::Clock;
use crate::frame::{hero_time_with_art, render_frame_with_art};
use crate::palette::IndexedPalette;
use crate::{IndexedImage, encode_png};
use clairlune_scene::activity::{Activity, builtin_catalog};
use clairlune_scene::{
    BuildError, BuildOptions, Rgb, SceneGraph, SceneRecipe, SpriteKind, Theme, build,
};
use clairlune_sprites::{Animation, Character, Frame, PackagedCharacter, builtin_character};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;

/// The package format this build writes. Older formats stay readable.
pub const PACKAGE_FORMAT: u32 = 1;

#[derive(Debug)]
pub enum PackageError {
    Io(std::io::Error),
    Json(serde_json::Error),
    Png(String),
    /// Written by a newer Clairlune.
    UnsupportedFormat(u32),
    Invalid(String),
}

impl fmt::Display for PackageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PackageError::Io(e) => write!(f, "{e}"),
            PackageError::Json(e) => write!(f, "package.json: {e}"),
            PackageError::Png(e) => write!(f, "image: {e}"),
            PackageError::UnsupportedFormat(v) => write!(
                f,
                "scene package format {v} is newer than this version reads ({PACKAGE_FORMAT})"
            ),
            PackageError::Invalid(e) => write!(f, "scene package: {e}"),
        }
    }
}

impl std::error::Error for PackageError {}

impl From<std::io::Error> for PackageError {
    fn from(e: std::io::Error) -> Self {
        PackageError::Io(e)
    }
}

impl From<serde_json::Error> for PackageError {
    fn from(e: serde_json::Error) -> Self {
        PackageError::Json(e)
    }
}

/// The art a package carries.
#[derive(Clone, Debug)]
pub struct PackageArt {
    activity: Option<Activity>,
    character: PackagedCharacter,
    props: Vec<(SpriteKind, OwnedPixmap)>,
}

impl SceneArt for PackageArt {
    fn activity(&self) -> Option<&Activity> {
        self.activity.as_ref()
    }
    fn character(&self) -> &dyn Character {
        &self.character
    }
    fn prop(&self, kind: SpriteKind) -> Option<&dyn Pixmap> {
        self.props
            .iter()
            .find(|(k, _)| *k == kind)
            .map(|(_, p)| p as &dyn Pixmap)
    }
}

/// One theme's frozen scene.
#[derive(Clone, Debug)]
struct ThemeScene {
    theme: Theme,
    /// Laid out with Clawd; `graph_unattended` is the same with Buddy off.
    graph: SceneGraph,
    graph_unattended: SceneGraph,
    palette: IndexedPalette,
    atlas: GlyphAtlas,
    background: IndexedImage,
    hero_ms: u64,
}

/// A frozen scene: plays without the generator.
#[derive(Clone, Debug)]
pub struct ScenePackage {
    pub recipe: SceneRecipe,
    pub width: u32,
    pub height: u32,
    /// The generator that made it (for information; playback ignores it).
    pub generator_version: u32,
    art: PackageArt,
    themes: Vec<ThemeScene>,
}

impl ScenePackage {
    /// Builds the scene in every theme it supports and freezes the result.
    pub fn capture(recipe: &SceneRecipe, width: u32, height: u32) -> Result<Self, BuildError> {
        let mut themes = Vec::new();
        let mut graphs = Vec::new();
        for theme in [Theme::Dark, Theme::Light] {
            let opts = BuildOptions {
                width,
                height,
                theme,
                buddy: true,
            };
            match build(recipe, &opts) {
                Ok(g) => graphs.push(g),
                Err(BuildError::ThemeLocked(_)) => {}
                Err(e) => return Err(e),
            }
        }
        let first = graphs.first().ok_or(BuildError::ThemeLocked(Theme::Dark))?;
        let activity = first
            .activity
            .as_deref()
            .and_then(|id| builtin_catalog().get(id))
            .cloned();
        let art = PackageArt {
            character: capture_character(activity.as_ref()),
            props: capture_props(&graphs),
            activity,
        };
        for mut graph in graphs {
            let atlas = GlyphAtlas::for_grid(&graph.grid);
            let palette = IndexedPalette::new(&graph.family);
            let background = bake_static(&graph, &atlas);
            // The background replaces the cells; a loaded package has none.
            graph.cells = Vec::new();
            let hero_ms = hero_time_with_art(&graph, &art);
            let mut graph_unattended = graph.clone();
            graph_unattended.buddy = false;
            themes.push(ThemeScene {
                theme: graph.theme,
                graph,
                graph_unattended,
                palette,
                atlas,
                background,
                hero_ms,
            });
        }
        Ok(ScenePackage {
            recipe: recipe.clone(),
            width,
            height,
            generator_version: recipe.generator_version,
            art,
            themes,
        })
    }

    /// Themes this scene has, dark first.
    pub fn themes(&self) -> Vec<Theme> {
        self.themes.iter().map(|t| t.theme).collect()
    }

    fn theme(&self, theme: Theme) -> Option<&ThemeScene> {
        self.themes.iter().find(|t| t.theme == theme)
    }

    /// The still-frame time in a theme.
    pub fn hero_ms(&self, theme: Theme) -> Option<u64> {
        self.theme(theme).map(|t| t.hero_ms)
    }

    /// One frame, or `None` if the scene has no such theme.
    pub fn frame(
        &self,
        theme: Theme,
        buddy: bool,
        t_ms: u64,
        clock: Clock,
    ) -> Option<(IndexedImage, &IndexedPalette)> {
        let t = self.theme(theme)?;
        let graph = if buddy { &t.graph } else { &t.graph_unattended };
        let img = render_frame_with_art(
            &t.background,
            graph,
            &t.atlas,
            &t.palette,
            t_ms,
            clock,
            &self.art,
        );
        Some((img, &t.palette))
    }

    /// The still (hero) frame in a theme.
    pub fn still(&self, theme: Theme, buddy: bool) -> Option<(IndexedImage, &IndexedPalette)> {
        let t = self.hero_ms(theme)?;
        self.frame(theme, buddy, t, Clock::Live)
    }

    /// The palette in a theme.
    pub fn palette(&self, theme: Theme) -> Option<&IndexedPalette> {
        self.theme(theme).map(|t| &t.palette)
    }

    /// The scene graph in a theme (layout, emitters, loop length).
    pub fn graph(&self, theme: Theme) -> Option<&SceneGraph> {
        self.theme(theme).map(|t| &t.graph)
    }

    /// Writes the package into `dir` (created if needed).
    pub fn save(&self, dir: &Path) -> Result<(), PackageError> {
        std::fs::create_dir_all(dir)?;
        let mut sheet = SpriteSheetWriter::default();
        let character = self
            .art
            .character
            .iter()
            .map(|((activity, state), anim)| AnimationFile {
                activity: activity.clone(),
                state: state.clone(),
                name: anim.name.clone(),
                frames: anim.frames.iter().map(|f| sheet.add(f)).collect(),
            })
            .collect();
        let file = PackageFile {
            format: PACKAGE_FORMAT,
            generator_version: self.generator_version,
            recipe: self.recipe.clone(),
            width: self.width,
            height: self.height,
            activity: self.art.activity.clone(),
            character,
            props: self
                .art
                .props
                .iter()
                .map(|(k, p)| PropFile {
                    kind: *k,
                    width: p.width,
                    height: p.height,
                    pixels: p.pixels.clone(),
                })
                .collect(),
            themes: self
                .themes
                .iter()
                .map(|t| ThemeFile {
                    theme: t.theme,
                    graph: t.graph.clone(),
                    palette: t.palette.colors().to_vec(),
                    atlas: t.atlas.clone(),
                    hero_ms: t.hero_ms,
                })
                .collect(),
        };
        for t in &self.themes {
            let mut png = Vec::new();
            encode_png(&t.background, &t.palette, &mut png)
                .map_err(|e| PackageError::Png(e.to_string()))?;
            std::fs::write(dir.join(background_name(t.theme)), png)?;
        }
        std::fs::write(dir.join("sprites.png"), sheet.png()?)?;
        let json = serde_json::to_string(&file)?;
        let tmp = dir.join("package.json.part");
        std::fs::write(&tmp, json)?;
        std::fs::rename(tmp, dir.join("package.json"))?;
        Ok(())
    }

    /// Reads a package written by this or an older version.
    pub fn load(dir: &Path) -> Result<Self, PackageError> {
        let text = std::fs::read_to_string(dir.join("package.json"))?;
        let probe: FormatProbe = serde_json::from_str(&text)?;
        if probe.format > PACKAGE_FORMAT || probe.format == 0 {
            return Err(PackageError::UnsupportedFormat(probe.format));
        }
        let file: PackageFile = serde_json::from_str(&text)?;
        let sheet = SpriteSheetReader::open(&std::fs::read(dir.join("sprites.png"))?)?;
        let mut character = PackagedCharacter::default();
        for a in &file.character {
            let frames = a
                .frames
                .iter()
                .map(|f| sheet.frame(f))
                .collect::<Result<Vec<_>, _>>()?;
            character.insert(
                &a.activity,
                &a.state,
                Animation {
                    name: a.name.clone(),
                    frames,
                },
            );
        }
        let art = PackageArt {
            activity: file.activity,
            character,
            props: file
                .props
                .into_iter()
                .map(|p| {
                    if p.pixels.len() != (p.width * p.height) as usize {
                        return Err(PackageError::Invalid(format!("prop {:?} size", p.kind)));
                    }
                    Ok((
                        p.kind,
                        OwnedPixmap {
                            width: p.width,
                            height: p.height,
                            pixels: p.pixels,
                        },
                    ))
                })
                .collect::<Result<_, _>>()?,
        };
        let mut themes = Vec::new();
        for t in file.themes {
            let (background, colors) =
                decode_indexed(&std::fs::read(dir.join(background_name(t.theme)))?)?;
            let palette = IndexedPalette::from_colors(t.palette);
            if colors != palette.rgb_bytes()
                || (background.width, background.height) != (file.width, file.height)
            {
                return Err(PackageError::Invalid(format!(
                    "{} background does not match its palette or size",
                    t.theme.as_str()
                )));
            }
            let mut graph_unattended = t.graph.clone();
            graph_unattended.buddy = false;
            themes.push(ThemeScene {
                theme: t.theme,
                graph: t.graph,
                graph_unattended,
                palette,
                atlas: t.atlas,
                background,
                hero_ms: t.hero_ms,
            });
        }
        if themes.is_empty() {
            return Err(PackageError::Invalid("no themes".into()));
        }
        Ok(ScenePackage {
            recipe: file.recipe,
            width: file.width,
            height: file.height,
            generator_version: file.generator_version,
            art,
            themes,
        })
    }
}

fn background_name(theme: Theme) -> String {
    format!("background-{}.png", theme.as_str())
}

/// Every `(activity, state)` the scene can show: all states of its activity
/// (the state machine may reach any), or the idle fallback.
fn capture_character(activity: Option<&Activity>) -> PackagedCharacter {
    let from = builtin_character();
    match activity {
        Some(a) => PackagedCharacter::capture(
            from,
            a.animation
                .states
                .keys()
                .map(|s| (a.id.as_str(), s.as_str())),
        ),
        None => PackagedCharacter::capture(from, [("", "idle")]),
    }
}

/// The pixel art of every prop the scene places, in either Buddy state.
fn capture_props(graphs: &[SceneGraph]) -> Vec<(SpriteKind, OwnedPixmap)> {
    let mut out: Vec<(SpriteKind, OwnedPixmap)> = Vec::new();
    for g in graphs {
        for s in g.props.iter().chain(&g.unattended) {
            if s.kind != SpriteKind::Character && !out.iter().any(|(k, _)| *k == s.kind) {
                out.push((s.kind, OwnedPixmap::copy_of(s.kind.map())));
            }
        }
    }
    out
}

// ---- On-disk format 1 ---------------------------------------------------

#[derive(Deserialize)]
struct FormatProbe {
    format: u32,
}

#[derive(Serialize, Deserialize)]
struct PackageFile {
    format: u32,
    generator_version: u32,
    recipe: SceneRecipe,
    width: u32,
    height: u32,
    activity: Option<Activity>,
    character: Vec<AnimationFile>,
    props: Vec<PropFile>,
    themes: Vec<ThemeFile>,
}

#[derive(Serialize, Deserialize)]
struct AnimationFile {
    activity: String,
    state: String,
    name: String,
    frames: Vec<FrameFile>,
}

/// A frame's place in `sprites.png` and its timing and anchors.
#[derive(Serialize, Deserialize)]
struct FrameFile {
    y: u32,
    width: u32,
    height: u32,
    duration_ms: u32,
    anchors: BTreeMap<String, (i32, i32)>,
}

#[derive(Serialize, Deserialize)]
struct PropFile {
    kind: SpriteKind,
    width: u32,
    height: u32,
    pixels: Vec<Option<Rgb>>,
}

#[derive(Serialize, Deserialize)]
struct ThemeFile {
    theme: Theme,
    graph: SceneGraph,
    palette: Vec<Rgb>,
    atlas: GlyphAtlas,
    hero_ms: u64,
}

/// Stacks frames top to bottom in one RGBA image; identical frames share
/// their pixels.
#[derive(Default)]
struct SpriteSheetWriter {
    width: u32,
    rows: Vec<(u32, u32, Vec<Option<Rgb>>)>,
    height: u32,
}

impl SpriteSheetWriter {
    fn add(&mut self, f: &Frame) -> FrameFile {
        let y = match self
            .rows
            .iter()
            .find(|(_, w, px)| *w == f.width && *px == f.pixels)
        {
            Some((y, _, _)) => *y,
            None => {
                let y = self.height;
                self.rows.push((y, f.width, f.pixels.clone()));
                self.height += f.height;
                self.width = self.width.max(f.width);
                y
            }
        };
        FrameFile {
            y,
            width: f.width,
            height: f.height,
            duration_ms: f.duration_ms,
            anchors: f.anchors.clone(),
        }
    }

    fn png(&self) -> Result<Vec<u8>, PackageError> {
        let (w, h) = (self.width.max(1), self.height.max(1));
        let mut rgba = vec![0u8; (w * h * 4) as usize];
        for (y0, fw, px) in &self.rows {
            for (i, p) in px.iter().enumerate() {
                let Some(c) = p else { continue };
                let (x, y) = (i as u32 % fw, y0 + i as u32 / fw);
                let o = ((y * w + x) * 4) as usize;
                rgba[o..o + 4].copy_from_slice(&[c.r, c.g, c.b, 255]);
            }
        }
        let mut out = Vec::new();
        let mut enc = png::Encoder::new(&mut out, w, h);
        enc.set_color(png::ColorType::Rgba);
        enc.set_depth(png::BitDepth::Eight);
        let mut writer = enc
            .write_header()
            .map_err(|e| PackageError::Png(e.to_string()))?;
        writer
            .write_image_data(&rgba)
            .map_err(|e| PackageError::Png(e.to_string()))?;
        writer
            .finish()
            .map_err(|e| PackageError::Png(e.to_string()))?;
        Ok(out)
    }
}

struct SpriteSheetReader {
    width: u32,
    height: u32,
    rgba: Vec<u8>,
}

impl SpriteSheetReader {
    fn open(bytes: &[u8]) -> Result<Self, PackageError> {
        let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
        dec.set_transformations(png::Transformations::EXPAND);
        let mut reader = dec
            .read_info()
            .map_err(|e| PackageError::Png(e.to_string()))?;
        let mut buf = vec![0; reader.output_buffer_size().unwrap_or(0)];
        let info = reader
            .next_frame(&mut buf)
            .map_err(|e| PackageError::Png(e.to_string()))?;
        if info.color_type != png::ColorType::Rgba {
            return Err(PackageError::Png("sprites.png must be RGBA".into()));
        }
        buf.truncate(info.buffer_size());
        Ok(SpriteSheetReader {
            width: info.width,
            height: info.height,
            rgba: buf,
        })
    }

    fn frame(&self, f: &FrameFile) -> Result<Frame, PackageError> {
        if f.width > self.width || f.y + f.height > self.height {
            return Err(PackageError::Invalid(
                "a frame lies outside sprites.png".into(),
            ));
        }
        let mut pixels = Vec::with_capacity((f.width * f.height) as usize);
        for y in f.y..f.y + f.height {
            for x in 0..f.width {
                let o = ((y * self.width + x) * 4) as usize;
                let p = &self.rgba[o..o + 4];
                pixels.push((p[3] != 0).then_some(Rgb {
                    r: p[0],
                    g: p[1],
                    b: p[2],
                }));
            }
        }
        Ok(Frame {
            width: f.width,
            height: f.height,
            pixels,
            duration_ms: f.duration_ms,
            anchors: f.anchors.clone(),
        })
    }
}

/// Decodes an 8-bit indexed PNG to its indices and palette bytes.
fn decode_indexed(bytes: &[u8]) -> Result<(IndexedImage, Vec<u8>), PackageError> {
    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
    let palette = reader
        .info()
        .palette
        .as_ref()
        .ok_or_else(|| PackageError::Png("background must be indexed".into()))?
        .to_vec();
    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
    if info.color_type != png::ColorType::Indexed || info.bit_depth != png::BitDepth::Eight {
        return Err(PackageError::Png("background must be 8-bit indexed".into()));
    }
    buf.truncate(info.buffer_size());
    Ok((
        IndexedImage {
            width: info.width,
            height: info.height,
            pixels: buf,
        },
        palette,
    ))
}