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