Skip to main content

clairlune_render/
frame.rs

1//! Frame compositing: the baked background plus animated elements at time `t`.
2//! Particles snap to the cell grid (exact palette, small GIF diffs); sprites use
3//! integer nearest-neighbour scaling.
4
5use crate::IndexedImage;
6use crate::atlas::GlyphAtlas;
7use crate::palette::{IndexedPalette, LEVELS, ink_level};
8use clairlune_scene::activity::builtin_catalog;
9use clairlune_scene::anim::state_at;
10use clairlune_scene::graph::CHARACTER_BOX;
11use clairlune_scene::{SceneGraph, SpriteInstance, SpriteKind};
12use clairlune_sprites::{Character, builtin_character};
13
14/// Composites one frame at `t_ms` over a baked background.
15pub fn render_frame(
16    background: &IndexedImage,
17    graph: &SceneGraph,
18    atlas: &GlyphAtlas,
19    palette: &IndexedPalette,
20    t_ms: u64,
21) -> IndexedImage {
22    let mut img = background.clone();
23    for (col, row, p) in graph.particles_at(t_ms) {
24        draw_particle(&mut img, graph, atlas, col, row, p.glyph, p.level);
25    }
26    for sprite in graph.sprites_at(t_ms) {
27        if sprite.kind == SpriteKind::Character {
28            draw_character(&mut img, graph, &sprite, palette, t_ms);
29            continue;
30        }
31        draw_sprite(&mut img, &sprite, palette);
32    }
33    img
34}
35
36/// A particle replaces its whole cell: background band, then the glyph in ember colour.
37fn draw_particle(
38    img: &mut IndexedImage,
39    graph: &SceneGraph,
40    atlas: &GlyphAtlas,
41    col: u32,
42    row: u32,
43    glyph: u8,
44    level: u8,
45) {
46    let g = &graph.grid;
47    let shade =
48        ((u32::from(level.min(LEVELS)) * 255 + u32::from(LEVELS) / 2) / u32::from(LEVELS)) as u8;
49    let mask = atlas.mask(glyph);
50    let (x0, y0) = (g.origin_x + col * g.cell_w, g.origin_y + row * g.cell_h);
51    let w = img.width as usize;
52    for my in 0..g.cell_h {
53        let y = y0 + my;
54        let rt = graph.lighting.row_terms(y);
55        for mx in 0..g.cell_w {
56            let x = x0 + mx;
57            let band = graph.lighting.band_in_row(&rt, x);
58            let lvl = ink_level(mask[(my * g.cell_w + mx) as usize], shade);
59            img.pixels[y as usize * w + x as usize] = if lvl > 0 {
60                IndexedPalette::ember(band, lvl)
61            } else {
62                band
63            };
64        }
65    }
66}
67
68/// The still-frame time used for stills, thumbnails and the static wallpaper:
69/// the first moment at or after the scene's ember-based hero time (50 ms steps,
70/// up to 10 s) when the character shows the first frame of its activity's start
71/// state, so a still never catches a blink or a mid-gesture. Independent of the
72/// Buddy toggle, so toggling it keeps the same moment.
73pub fn hero_time(graph: &SceneGraph) -> u64 {
74    let base = graph.t_hero_ms;
75    let activity = graph
76        .activity
77        .as_deref()
78        .and_then(|id| builtin_catalog().get(id));
79    let (Some(a), Some(_)) = (activity, graph.character) else {
80        return base;
81    };
82    let character = builtin_character();
83    for k in 0..200u64 {
84        let t = base + k * 50;
85        let st = state_at(a, graph.seed, t, &|s| character.one_shot_ms(&a.id, s));
86        if st.state != a.animation.start {
87            continue;
88        }
89        let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
90        if let Some(anim) = character.animation(&a.id, &st.state)
91            && anim.frame_index_at(t - st.since_ms, looping) == 0
92        {
93            return t;
94        }
95    }
96    base
97}
98
99/// Draws the character's animation frame for the activity state at `t`,
100/// aligned on the art's origin (feet row, body centre) inside its layout box,
101/// mirrored when it faces left. All character art comes through `Character`.
102fn draw_character(
103    img: &mut IndexedImage,
104    graph: &SceneGraph,
105    s: &SpriteInstance,
106    palette: &IndexedPalette,
107    t_ms: u64,
108) {
109    let character = builtin_character();
110    let activity = graph
111        .activity
112        .as_deref()
113        .and_then(|id| builtin_catalog().get(id));
114    let (anim, elapsed, looping) = match activity {
115        Some(a) => {
116            let st = state_at(a, graph.seed, t_ms, &|state| {
117                character.one_shot_ms(&a.id, state)
118            });
119            let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
120            (
121                character.animation(&a.id, &st.state),
122                t_ms - st.since_ms,
123                looping,
124            )
125        }
126        None => (character.animation("", "idle"), t_ms, true),
127    };
128    let Some(anim) = anim else { return };
129    let f = anim.frame_at(elapsed, looping);
130    let (ox, oy) = f.origin();
131    let sc = s.scale as i32;
132    // Origin pixel's top-left on screen: box centre column, box bottom row.
133    let x0 = s.x + (CHARACTER_BOX.0 as i32 / 2) * sc;
134    let y0 = s.y + (CHARACTER_BOX.1 as i32 - 1) * sc;
135    let (w, h) = (img.width as i32, img.height as i32);
136    for row in 0..f.height {
137        for col in 0..f.width {
138            let Some(rgb) = f.pixel(col, row) else {
139                continue;
140            };
141            let idx = palette
142                .sprite_index(rgb)
143                .expect("character colour in palette");
144            let dx = (col as i32 - ox) * if s.mirror { -1 } else { 1 };
145            let px = x0 + dx * sc;
146            let py = y0 + (row as i32 - oy) * sc;
147            for y in py.max(0)..(py + sc).min(h) {
148                let line = (y * w) as usize;
149                for x in px.max(0)..(px + sc).min(w) {
150                    img.pixels[line + x as usize] = idx;
151                }
152            }
153        }
154    }
155}
156
157fn draw_sprite(img: &mut IndexedImage, s: &SpriteInstance, palette: &IndexedPalette) {
158    let map = s.kind.map();
159    let (w, h) = (img.width as i32, img.height as i32);
160    let scale = s.scale as i32;
161    for my in 0..map.height {
162        for mx in 0..map.width {
163            let sx = if s.mirror { map.width - 1 - mx } else { mx };
164            let Some(rgb) = map.pixel(sx, my) else {
165                continue;
166            };
167            let idx = palette.sprite_index(rgb).expect("sprite colour in palette");
168            let px = s.x + mx as i32 * scale;
169            let py = s.y + my as i32 * scale;
170            for y in py.max(0)..(py + scale).min(h) {
171                let line = (y * w) as usize;
172                for x in px.max(0)..(px + scale).min(w) {
173                    img.pixels[line + x as usize] = idx;
174                }
175            }
176        }
177    }
178}