Skip to main content

clairlune_scene/
graph.rs

1//! The scene graph: a resolution-specific, theme-specific description of what to
2//! draw. Static layers are a grid of glyph cells; animated elements are sprite
3//! instances and particle emitters.
4
5use crate::palette::{PaletteFamily, Theme};
6use crate::particles::{Emitter, Particle};
7use crate::placeholder::{CAMPFIRE, CLAWD_PLACEHOLDER, LANTERN, LOG_SEAT, PixelMap, TELESCOPE};
8use crate::recipe::TimeOfDay;
9
10/// Advance width of the bundled monospace font (JetBrains Mono) per em.
11pub const ADVANCE_RATIO: f64 = 0.6;
12/// Font pixel size relative to the cell height.
13pub const FONT_TO_CELL: f64 = 0.9;
14/// Target number of rows, so the look is consistent from 720p to 4K.
15pub const TARGET_ROWS: u32 = 108;
16pub const MIN_CELL_W: u32 = 6;
17pub const MIN_CELL_H: u32 = 11;
18
19/// Number of background bands (vignette + glow, quantised).
20pub const BANDS: u8 = 8;
21/// Width of the ordered-dither zone around each band edge, in bands.
22const DITHER_WIDTH: f64 = 0.4;
23/// 4x4 Bayer matrix.
24const BAYER4: [[u8; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
25
26/// Cell grid geometry for one output size.
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct GridSpec {
29    pub cols: u32,
30    pub rows: u32,
31    pub cell_w: u32,
32    pub cell_h: u32,
33    /// Pixel offset of the grid, centring it in the image.
34    pub origin_x: u32,
35    pub origin_y: u32,
36    /// Font size in pixels used to rasterize the glyph atlas.
37    pub font_px: f64,
38}
39
40/// Grid for a pixel size: about [`TARGET_ROWS`] rows, never smaller than 6x11 cells.
41pub fn grid_spec(width: u32, height: u32) -> GridSpec {
42    let cell_h = ((f64::from(height) / f64::from(TARGET_ROWS)).round() as u32).max(MIN_CELL_H);
43    let font_px = f64::from(cell_h) * FONT_TO_CELL;
44    let cell_w = ((font_px * ADVANCE_RATIO).round() as u32).max(MIN_CELL_W);
45    let cols = width / cell_w;
46    let rows = height / cell_h;
47    GridSpec {
48        cols,
49        rows,
50        cell_w,
51        cell_h,
52        origin_x: (width - cols * cell_w) / 2,
53        origin_y: (height - rows * cell_h) / 2,
54        font_px,
55    }
56}
57
58/// One character cell. `glyph` indexes `glyphs::GLYPHS`; `shade` is ink strength.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub struct Cell {
61    pub glyph: u8,
62    pub shade: u8,
63}
64
65/// Radial warm light around a light source.
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub struct Glow {
68    pub cx: f64,
69    pub cy: f64,
70    pub radius: f64,
71}
72
73/// Vignette and glow, quantised into [`BANDS`] background bands.
74///
75/// Band coordinate `c` is continuous in `[0, 8)`: the vignette contributes up to
76/// 4 (bands 0-3, brighter toward the centre) and the glow pulls `c` toward 8
77/// (bands 4-7, warmer toward the light). Ink in bands 4-7 is tinted toward the
78/// accent, so glow and glyph tint come from one lookup.
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct Lighting {
81    pub vignette_cx: f64,
82    pub vignette_cy: f64,
83    pub vignette_rx: f64,
84    pub vignette_ry: f64,
85    pub glow: Option<Glow>,
86}
87
88/// Row-invariant terms of the band computation.
89#[derive(Clone, Copy, Debug)]
90pub struct RowTerms {
91    vy2: f64,
92    gy2: f64,
93    bayer_row: usize,
94}
95
96impl Lighting {
97    #[inline]
98    pub fn row_terms(&self, py: u32) -> RowTerms {
99        let y = f64::from(py) + 0.5;
100        let vy = (y - self.vignette_cy) / self.vignette_ry;
101        let gy2 = match self.glow {
102            Some(g) => {
103                let d = y - g.cy;
104                d * d
105            }
106            None => 0.0,
107        };
108        RowTerms {
109            vy2: vy * vy,
110            gy2,
111            bayer_row: (py & 3) as usize,
112        }
113    }
114
115    /// Background band of pixel `(px, py)`. [`Lighting::fill_row`] must agree exactly.
116    #[inline]
117    pub fn band_in_row(&self, rt: &RowTerms, px: u32) -> u8 {
118        let x = f64::from(px) + 0.5;
119        let vx = (x - self.vignette_cx) / self.vignette_rx;
120        let q = (vx * vx + rt.vy2).min(1.0);
121        let v = 1.0 - q;
122        let cv = 3.999 * v * v;
123        let c = match self.glow {
124            Some(g) => {
125                let dx = x - g.cx;
126                let r2 = (dx * dx + rt.gy2) / (g.radius * g.radius);
127                if r2 < 1.0 {
128                    let t = 1.0 - r2;
129                    cv + t * t * (7.999 - cv)
130                } else {
131                    cv
132                }
133            }
134            None => cv,
135        };
136        let b = BAYER4[rt.bayer_row][(px & 3) as usize];
137        let d = ((f64::from(b) + 0.5) / 16.0 - 0.5) * DITHER_WIDTH;
138        (c + d).floor().clamp(0.0, f64::from(BANDS - 1)) as u8
139    }
140
141    /// Background band of one pixel.
142    pub fn band_at(&self, px: u32, py: u32) -> u8 {
143        self.band_in_row(&self.row_terms(py), px)
144    }
145
146    /// Fills one image row with band indices.
147    pub fn fill_row(&self, py: u32, out: &mut [u8]) {
148        let rt = self.row_terms(py);
149        for (px, o) in out.iter_mut().enumerate() {
150            *o = self.band_in_row(&rt, px as u32);
151        }
152    }
153}
154
155/// What a sprite instance shows.
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub enum SpriteKind {
158    /// The character (placeholder pixel map in M1).
159    Character,
160    Campfire,
161    /// Unattended variant: an empty log seat by the fire.
162    LogSeat,
163    Telescope,
164    Lantern,
165}
166
167impl SpriteKind {
168    /// Every kind, so palettes can reserve all sprite colours up front.
169    pub const ALL: [SpriteKind; 5] = [
170        SpriteKind::Character,
171        SpriteKind::Campfire,
172        SpriteKind::LogSeat,
173        SpriteKind::Telescope,
174        SpriteKind::Lantern,
175    ];
176
177    pub fn map(self) -> &'static PixelMap {
178        match self {
179            SpriteKind::Character => &CLAWD_PLACEHOLDER,
180            SpriteKind::Campfire => &CAMPFIRE,
181            SpriteKind::LogSeat => &LOG_SEAT,
182            SpriteKind::Telescope => &TELESCOPE,
183            SpriteKind::Lantern => &LANTERN,
184        }
185    }
186}
187
188/// How the character moves over time.
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum Motion {
191    /// Fixed spot (left edge x).
192    Stationary { x: i32 },
193    /// Walks back and forth between two left-edge positions; one round trip per period.
194    Pace {
195        x_min: i32,
196        x_max: i32,
197        period_ms: u64,
198    },
199}
200
201/// The character's placement as a pure function of time.
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub struct CharacterTrack {
204    /// Top edge (feet on the ground line).
205    pub y: i32,
206    pub scale: u32,
207    pub motion: Motion,
208    /// Facing when stationary (toward the main prop).
209    pub face_left: bool,
210}
211
212impl CharacterTrack {
213    /// Sprite placement at `t_ms`. Integer arithmetic only.
214    pub fn at(&self, t_ms: u64) -> SpriteInstance {
215        let (x, mirror) = match self.motion {
216            Motion::Stationary { x } => (x, self.face_left),
217            Motion::Pace {
218                x_min,
219                x_max,
220                period_ms,
221            } => {
222                let span = i64::from(x_max - x_min);
223                let half = (period_ms / 2).max(1) as i64;
224                let ph = (t_ms % period_ms.max(1)) as i64;
225                if ph < half {
226                    ((i64::from(x_min) + span * ph / half) as i32, false)
227                } else {
228                    ((i64::from(x_max) - span * (ph - half) / half) as i32, true)
229                }
230            }
231        };
232        SpriteInstance {
233            kind: SpriteKind::Character,
234            x,
235            y: self.y,
236            scale: self.scale,
237            mirror,
238        }
239    }
240
241    /// Leftmost and rightmost left-edge positions over all time.
242    pub fn x_range(&self) -> (i32, i32) {
243        match self.motion {
244            Motion::Stationary { x } => (x, x),
245            Motion::Pace { x_min, x_max, .. } => (x_min, x_max),
246        }
247    }
248}
249
250/// A sprite placed in the image at an integer nearest-neighbour scale.
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252pub struct SpriteInstance {
253    pub kind: SpriteKind,
254    /// Top-left pixel.
255    pub x: i32,
256    pub y: i32,
257    pub scale: u32,
258    pub mirror: bool,
259}
260
261impl SpriteInstance {
262    pub fn width(&self) -> u32 {
263        self.kind.map().width * self.scale
264    }
265    pub fn height(&self) -> u32 {
266        self.kind.map().height * self.scale
267    }
268}
269
270/// Everything needed to render one scene at one size and theme.
271#[derive(Clone, Debug)]
272pub struct SceneGraph {
273    pub width: u32,
274    pub height: u32,
275    pub theme: Theme,
276    pub tod: TimeOfDay,
277    pub buddy: bool,
278    pub family: PaletteFamily,
279    pub grid: GridSpec,
280    /// Row-major, `grid.cols * grid.rows`.
281    pub cells: Vec<Cell>,
282    pub lighting: Lighting,
283    /// The activity id, or `None` for an archetype-first fallback scene.
284    pub activity: Option<String>,
285    /// Activity props, drawn in both Buddy states.
286    pub props: Vec<SpriteInstance>,
287    /// Unattended variant, drawn only with Buddy off.
288    pub unattended: Vec<SpriteInstance>,
289    /// The character's track (always laid out; drawn only with Buddy on).
290    pub character: Option<CharacterTrack>,
291    pub emitters: Vec<Emitter>,
292    /// Pixel y of the platform's top surface (where feet stand).
293    pub ground_y: i32,
294    /// Hero time in milliseconds: the frame used for stills and thumbnails.
295    pub t_hero_ms: u64,
296    /// Seamless loop length for periodic elements.
297    pub loop_ms: u64,
298}
299
300impl SceneGraph {
301    #[inline]
302    pub fn cell(&self, col: u32, row: u32) -> Cell {
303        self.cells[(row * self.grid.cols + col) as usize]
304    }
305
306    /// Sprites to draw at `t`, back to front: props, then the character (Buddy
307    /// on) or the unattended variant (Buddy off).
308    pub fn sprites_at(&self, t_ms: u64) -> Vec<SpriteInstance> {
309        let mut out = self.props.clone();
310        if self.buddy {
311            out.extend(self.character.map(|c| c.at(t_ms)));
312        } else {
313            out.extend_from_slice(&self.unattended);
314        }
315        out
316    }
317
318    /// Particles at time `t`, snapped to cells, as `(col, row, particle)`.
319    pub fn particles_at(&self, t_ms: u64) -> Vec<(u32, u32, Particle)> {
320        let g = &self.grid;
321        let mut out = Vec::new();
322        for e in &self.emitters {
323            for p in e.sample(t_ms) {
324                let cx = (p.x - f64::from(g.origin_x)) / f64::from(g.cell_w);
325                let cy = (p.y - f64::from(g.origin_y)) / f64::from(g.cell_h);
326                if cx < 0.0 || cy < 0.0 {
327                    continue;
328                }
329                let (col, row) = (cx.floor() as u32, cy.floor() as u32);
330                if col < g.cols && row < g.rows {
331                    out.push((col, row, p));
332                }
333            }
334        }
335        out
336    }
337}