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//!
5//! The activity, character and prop art come through [`SceneArt`], so the same
6//! code plays live scenes (built-in art) and saved ones (their own copy).
7
8use crate::IndexedImage;
9use crate::art::{BuiltinArt, SceneArt};
10use crate::atlas::GlyphAtlas;
11use crate::clock::{Clock, LoopScript, loop_track};
12use crate::palette::{IndexedPalette, LEVELS, ink_level};
13use clairlune_scene::anim::state_at;
14use clairlune_scene::graph::CHARACTER_BOX;
15use clairlune_scene::particles::{Preset, preset_particles};
16use clairlune_scene::{SceneGraph, SpriteInstance, SpriteKind};
17use clairlune_sprites::Frame;
18
19/// Composites one frame at `t_ms` over a baked background (live clock).
20pub fn render_frame(
21    background: &IndexedImage,
22    graph: &SceneGraph,
23    atlas: &GlyphAtlas,
24    palette: &IndexedPalette,
25    t_ms: u64,
26) -> IndexedImage {
27    render_frame_clocked(background, graph, atlas, palette, t_ms, Clock::Live)
28}
29
30/// Like [`render_frame`], with an explicit character clock: `Clock::Loop` makes
31/// the character follow the activity's loop script for a seamless GIF.
32pub fn render_frame_clocked(
33    background: &IndexedImage,
34    graph: &SceneGraph,
35    atlas: &GlyphAtlas,
36    palette: &IndexedPalette,
37    t_ms: u64,
38    clock: Clock,
39) -> IndexedImage {
40    let art = BuiltinArt::for_graph(graph);
41    render_frame_with_art(background, graph, atlas, palette, t_ms, clock, &art)
42}
43
44/// Composites one frame with the given art (built-in, or a saved scene's).
45pub fn render_frame_with_art(
46    background: &IndexedImage,
47    graph: &SceneGraph,
48    atlas: &GlyphAtlas,
49    palette: &IndexedPalette,
50    t_ms: u64,
51    clock: Clock,
52    art: &dyn SceneArt,
53) -> IndexedImage {
54    let mut img = background.clone();
55    for (col, row, p) in graph.particles_at(t_ms) {
56        draw_particle(
57            &mut img, graph, atlas, col, row, p.glyph, p.level, p.ink, false,
58        );
59    }
60    for sprite in graph.sprites_at(t_ms) {
61        if sprite.kind == SpriteKind::Character {
62            let sprite = match (clock, graph.character) {
63                (Clock::Loop(loop_ms), Some(track)) => loop_track(track, loop_ms).at(t_ms),
64                _ => sprite,
65            };
66            if let Some(pose) = character_pose(graph, art, &sprite, t_ms, clock) {
67                // Effects go on top as an overlay (only the glyph's own pixels),
68                // so steam over a mug or sparkles over the hat stay visible.
69                draw_pose(&mut img, &pose, palette);
70                draw_effects(&mut img, graph, art, atlas, &pose, t_ms);
71            }
72            continue;
73        }
74        draw_sprite(&mut img, &sprite, art, palette);
75    }
76    img
77}
78
79/// Draws a particle glyph in ember colour, or ink colour when `ink` (faint
80/// wisps such as steam). Normally it replaces its whole cell (background band,
81/// then the glyph); with `overlay` only the glyph's pixels are written.
82#[allow(clippy::too_many_arguments)]
83fn draw_particle(
84    img: &mut IndexedImage,
85    graph: &SceneGraph,
86    atlas: &GlyphAtlas,
87    col: u32,
88    row: u32,
89    glyph: u8,
90    level: u8,
91    ink: bool,
92    overlay: bool,
93) {
94    let g = &graph.grid;
95    let shade =
96        ((u32::from(level.min(LEVELS)) * 255 + u32::from(LEVELS) / 2) / u32::from(LEVELS)) as u8;
97    let mask = atlas.mask(glyph);
98    let (x0, y0) = (g.origin_x + col * g.cell_w, g.origin_y + row * g.cell_h);
99    let w = img.width as usize;
100    for my in 0..g.cell_h {
101        let y = y0 + my;
102        let rt = graph.lighting.row_terms(y);
103        for mx in 0..g.cell_w {
104            let x = x0 + mx;
105            let band = graph.lighting.band_in_row(&rt, x);
106            let lvl = ink_level(mask[(my * g.cell_w + mx) as usize], shade);
107            if overlay && lvl == 0 {
108                continue; // overlay: leave whatever is under the glyph
109            }
110            img.pixels[y as usize * w + x as usize] = match (lvl > 0, ink) {
111                (false, _) => band,
112                (true, false) => IndexedPalette::ember(band, lvl),
113                (true, true) => IndexedPalette::ink(band, lvl),
114            };
115        }
116    }
117}
118
119/// The still-frame time used for stills, thumbnails and the static wallpaper:
120/// the first moment at or after the scene's ember-based hero time (50 ms steps,
121/// up to 10 s) when the character shows the first frame of its activity's start
122/// state, so a still never catches a blink or a mid-gesture. Independent of the
123/// Buddy toggle, so toggling it keeps the same moment.
124pub fn hero_time(graph: &SceneGraph) -> u64 {
125    hero_time_with_art(graph, &BuiltinArt::for_graph(graph))
126}
127
128/// [`hero_time`] with the given art.
129pub fn hero_time_with_art(graph: &SceneGraph, art: &dyn SceneArt) -> u64 {
130    let base = graph.t_hero_ms;
131    let (Some(a), Some(_)) = (art.activity(), graph.character) else {
132        return base;
133    };
134    let character = art.character();
135    for k in 0..200u64 {
136        let t = base + k * 50;
137        let st = state_at(a, graph.seed, t, &|s| character.one_shot_ms(&a.id, s));
138        if st.state != a.animation.start {
139            continue;
140        }
141        let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
142        if let Some(anim) = character.animation(&a.id, &st.state)
143            && anim.frame_index_at(t - st.since_ms, looping) == 0
144        {
145            return t;
146        }
147    }
148    base
149}
150
151/// The character's current frame and where it sits on screen: the art's origin
152/// (feet row, body centre) aligned inside the layout box, mirrored when it faces
153/// left. All character art comes through `Character`.
154struct Pose<'a> {
155    frame: &'a Frame,
156    state: String,
157    /// Screen pixel of the origin pixel's top-left corner.
158    x0: i32,
159    y0: i32,
160    sc: i32,
161    mirror: bool,
162}
163
164impl Pose<'_> {
165    /// Screen position of the centre of frame pixel `(col, row)`.
166    fn screen(&self, col: i32, row: i32) -> (i32, i32) {
167        let (ox, oy) = self.frame.origin();
168        let dx = (col - ox) * if self.mirror { -1 } else { 1 };
169        (
170            self.x0 + dx * self.sc + self.sc / 2,
171            self.y0 + (row - oy) * self.sc + self.sc / 2,
172        )
173    }
174}
175
176/// Picks the frame for the activity state at `t` (state machine when live, the
177/// loop script when looping) and places it.
178fn character_pose<'a>(
179    graph: &SceneGraph,
180    art: &'a dyn SceneArt,
181    s: &SpriteInstance,
182    t_ms: u64,
183    clock: Clock,
184) -> Option<Pose<'a>> {
185    let character = art.character();
186    let (anim, state, elapsed, looping) = match (art.activity(), clock) {
187        (Some(a), Clock::Loop(loop_ms)) => {
188            let script = LoopScript::new(a, character, loop_ms);
189            let (state, elapsed) = script.at(t_ms);
190            (
191                character.animation(&a.id, state),
192                state.to_string(),
193                elapsed,
194                true,
195            )
196        }
197        (Some(a), Clock::Live) => {
198            let st = state_at(a, graph.seed, t_ms, &|state| {
199                character.one_shot_ms(&a.id, state)
200            });
201            let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
202            (
203                character.animation(&a.id, &st.state),
204                st.state.clone(),
205                t_ms - st.since_ms,
206                looping,
207            )
208        }
209        (None, _) => (
210            character.animation("", "idle"),
211            "idle".to_string(),
212            t_ms,
213            true,
214        ),
215    };
216    let frame = anim?.frame_at(elapsed, looping);
217    let sc = s.scale as i32;
218    Some(Pose {
219        frame,
220        state,
221        x0: s.x + (CHARACTER_BOX.0 as i32 / 2) * sc,
222        y0: s.y + (CHARACTER_BOX.1 as i32 - 1) * sc,
223        sc,
224        mirror: s.mirror,
225    })
226}
227
228/// The activity's `[[effects]]` for the current state, at their anchors on the
229/// current frame. Particles snap to cells like the embers.
230fn draw_effects(
231    img: &mut IndexedImage,
232    graph: &SceneGraph,
233    art: &dyn SceneArt,
234    atlas: &GlyphAtlas,
235    pose: &Pose,
236    t_ms: u64,
237) {
238    let Some(a) = art.activity() else {
239        return;
240    };
241    let g = &graph.grid;
242    let dir = if pose.mirror { -1.0 } else { 1.0 };
243    for (i, e) in a.effects.iter().enumerate() {
244        if !e.active_in(&pose.state) {
245            continue;
246        }
247        let (Some(&(ax, ay)), Some(preset)) =
248            (pose.frame.anchors.get(&e.at), Preset::from_id(&e.preset))
249        else {
250            continue;
251        };
252        let (cx, cy) = pose.screen(ax, ay);
253        let seed = graph.seed.wrapping_add(i as u64 + 1);
254        for p in preset_particles(preset, seed, t_ms) {
255            let x = f64::from(cx) + p.dx * dir * f64::from(pose.sc);
256            let y = f64::from(cy) + p.dy * f64::from(pose.sc);
257            let col = ((x - f64::from(g.origin_x)) / f64::from(g.cell_w)).floor();
258            let row = ((y - f64::from(g.origin_y)) / f64::from(g.cell_h)).floor();
259            if col < 0.0 || row < 0.0 || col >= f64::from(g.cols) || row >= f64::from(g.rows) {
260                continue;
261            }
262            draw_particle(
263                img,
264                graph,
265                atlas,
266                col as u32,
267                row as u32,
268                p.glyph,
269                p.level,
270                preset == Preset::Steam,
271                true,
272            );
273        }
274    }
275}
276
277fn draw_pose(img: &mut IndexedImage, pose: &Pose, palette: &IndexedPalette) {
278    let f = pose.frame;
279    let (ox, oy) = f.origin();
280    let (x0, y0, sc, s) = (pose.x0, pose.y0, pose.sc, pose);
281    let (w, h) = (img.width as i32, img.height as i32);
282    for row in 0..f.height {
283        for col in 0..f.width {
284            let Some(rgb) = f.pixel(col, row) else {
285                continue;
286            };
287            let idx = palette
288                .sprite_index(rgb)
289                .expect("character colour in palette");
290            let dx = (col as i32 - ox) * if s.mirror { -1 } else { 1 };
291            let px = x0 + dx * sc;
292            let py = y0 + (row as i32 - oy) * sc;
293            for y in py.max(0)..(py + sc).min(h) {
294                let line = (y * w) as usize;
295                for x in px.max(0)..(px + sc).min(w) {
296                    img.pixels[line + x as usize] = idx;
297                }
298            }
299        }
300    }
301}
302
303fn draw_sprite(
304    img: &mut IndexedImage,
305    s: &SpriteInstance,
306    art: &dyn SceneArt,
307    palette: &IndexedPalette,
308) {
309    let Some(map) = art.prop(s.kind) else {
310        return;
311    };
312    let (w, h) = (img.width as i32, img.height as i32);
313    let scale = s.scale as i32;
314    let (mw, mh) = (map.width(), map.height());
315    for my in 0..mh {
316        for mx in 0..mw {
317            let sx = if s.mirror { mw - 1 - mx } else { mx };
318            let Some(rgb) = map.pixel(sx, my) else {
319                continue;
320            };
321            let idx = palette.sprite_index(rgb).expect("sprite colour in palette");
322            let px = s.x + mx as i32 * scale;
323            let py = s.y + my as i32 * scale;
324            for y in py.max(0)..(py + scale).min(h) {
325                let line = (y * w) as usize;
326                for x in px.max(0)..(px + scale).min(w) {
327                    img.pixels[line + x as usize] = idx;
328                }
329            }
330        }
331    }
332}