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