clairlune_render/
frame.rs1use crate::IndexedImage;
6use crate::atlas::GlyphAtlas;
7use crate::palette::{IndexedPalette, LEVELS, ink_level};
8use clairlune_scene::{SceneGraph, SpriteInstance};
9
10pub fn render_frame(
12 background: &IndexedImage,
13 graph: &SceneGraph,
14 atlas: &GlyphAtlas,
15 palette: &IndexedPalette,
16 t_ms: u64,
17) -> IndexedImage {
18 let mut img = background.clone();
19 for (col, row, p) in graph.particles_at(t_ms) {
20 draw_particle(&mut img, graph, atlas, col, row, p.glyph, p.level);
21 }
22 for sprite in &graph.sprites {
23 draw_sprite(&mut img, sprite, palette);
24 }
25 img
26}
27
28fn draw_particle(
30 img: &mut IndexedImage,
31 graph: &SceneGraph,
32 atlas: &GlyphAtlas,
33 col: u32,
34 row: u32,
35 glyph: u8,
36 level: u8,
37) {
38 let g = &graph.grid;
39 let shade =
40 ((u32::from(level.min(LEVELS)) * 255 + u32::from(LEVELS) / 2) / u32::from(LEVELS)) as u8;
41 let mask = atlas.mask(glyph);
42 let (x0, y0) = (g.origin_x + col * g.cell_w, g.origin_y + row * g.cell_h);
43 let w = img.width as usize;
44 for my in 0..g.cell_h {
45 let y = y0 + my;
46 let rt = graph.lighting.row_terms(y);
47 for mx in 0..g.cell_w {
48 let x = x0 + mx;
49 let band = graph.lighting.band_in_row(&rt, x);
50 let lvl = ink_level(mask[(my * g.cell_w + mx) as usize], shade);
51 img.pixels[y as usize * w + x as usize] = if lvl > 0 {
52 IndexedPalette::ember(band, lvl)
53 } else {
54 band
55 };
56 }
57 }
58}
59
60fn draw_sprite(img: &mut IndexedImage, s: &SpriteInstance, palette: &IndexedPalette) {
61 let map = s.kind.map();
62 let (w, h) = (img.width as i32, img.height as i32);
63 let scale = s.scale as i32;
64 for my in 0..map.height {
65 for mx in 0..map.width {
66 let sx = if s.mirror { map.width - 1 - mx } else { mx };
67 let Some(rgb) = map.pixel(sx, my) else {
68 continue;
69 };
70 let idx = palette.sprite_index(rgb).expect("sprite colour in palette");
71 let px = s.x + mx as i32 * scale;
72 let py = s.y + my as i32 * scale;
73 for y in py.max(0)..(py + scale).min(h) {
74 let line = (y * w) as usize;
75 for x in px.max(0)..(px + scale).min(w) {
76 img.pixels[line + x as usize] = idx;
77 }
78 }
79 }
80 }
81}