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    BOOK_CLOSED, CAMP_STOVE, CAMPFIRE, CLAWD_PLACEHOLDER, COFFEE_MUG, FALLEN_HAT, GUITAR_REST,
9    LANTERN, LOG_SEAT, PixelMap, 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    BookClosed,
177    GuitarRest,
178}
179
180impl SpriteKind {
181    /// Every kind, so palettes can reserve all sprite colours up front.
182    pub const ALL: [SpriteKind; 11] = [
183        SpriteKind::Character,
184        SpriteKind::Campfire,
185        SpriteKind::LogSeat,
186        SpriteKind::Telescope,
187        SpriteKind::Lantern,
188        SpriteKind::Spellbook,
189        SpriteKind::CampStove,
190        SpriteKind::CoffeeMug,
191        SpriteKind::FallenHat,
192        SpriteKind::BookClosed,
193        SpriteKind::GuitarRest,
194    ];
195
196    /// Layout box in sprite pixels. The character's box is the drawn art's
197    /// (body plus arms, feet included), not the placeholder's.
198    pub fn box_size(self) -> (u32, u32) {
199        match self {
200            SpriteKind::Character => CHARACTER_BOX,
201            other => (other.map().width, other.map().height),
202        }
203    }
204
205    pub fn map(self) -> &'static PixelMap {
206        match self {
207            SpriteKind::Character => &CLAWD_PLACEHOLDER,
208            SpriteKind::Campfire => &CAMPFIRE,
209            SpriteKind::LogSeat => &LOG_SEAT,
210            SpriteKind::Telescope => &TELESCOPE,
211            SpriteKind::Lantern => &LANTERN,
212            SpriteKind::Spellbook => &SPELLBOOK,
213            SpriteKind::CampStove => &CAMP_STOVE,
214            SpriteKind::CoffeeMug => &COFFEE_MUG,
215            SpriteKind::FallenHat => &FALLEN_HAT,
216            SpriteKind::BookClosed => &BOOK_CLOSED,
217            SpriteKind::GuitarRest => &GUITAR_REST,
218        }
219    }
220}
221
222/// How the character moves over time.
223#[derive(Clone, Copy, Debug, PartialEq, Eq)]
224pub enum Motion {
225    /// Fixed spot (left edge x).
226    Stationary { x: i32 },
227    /// Walks back and forth between two left-edge positions; one round trip per period.
228    Pace {
229        x_min: i32,
230        x_max: i32,
231        period_ms: u64,
232    },
233}
234
235/// The character's placement as a pure function of time.
236#[derive(Clone, Copy, Debug, PartialEq, Eq)]
237pub struct CharacterTrack {
238    /// Top edge (feet on the ground line).
239    pub y: i32,
240    pub scale: u32,
241    pub motion: Motion,
242    /// Facing when stationary (toward the main prop).
243    pub face_left: bool,
244}
245
246impl CharacterTrack {
247    /// Sprite placement at `t_ms`. Integer arithmetic only.
248    pub fn at(&self, t_ms: u64) -> SpriteInstance {
249        let (x, mirror) = match self.motion {
250            Motion::Stationary { x } => (x, self.face_left),
251            Motion::Pace {
252                x_min,
253                x_max,
254                period_ms,
255            } => {
256                let span = i64::from(x_max - x_min);
257                let half = (period_ms / 2).max(1) as i64;
258                let ph = (t_ms % period_ms.max(1)) as i64;
259                if ph < half {
260                    ((i64::from(x_min) + span * ph / half) as i32, false)
261                } else {
262                    ((i64::from(x_max) - span * (ph - half) / half) as i32, true)
263                }
264            }
265        };
266        SpriteInstance {
267            kind: SpriteKind::Character,
268            x,
269            y: self.y,
270            scale: self.scale,
271            mirror,
272        }
273    }
274
275    /// Leftmost and rightmost left-edge positions over all time.
276    pub fn x_range(&self) -> (i32, i32) {
277        match self.motion {
278            Motion::Stationary { x } => (x, x),
279            Motion::Pace { x_min, x_max, .. } => (x_min, x_max),
280        }
281    }
282}
283
284/// A sprite placed in the image at an integer nearest-neighbour scale.
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
286pub struct SpriteInstance {
287    pub kind: SpriteKind,
288    /// Top-left pixel.
289    pub x: i32,
290    pub y: i32,
291    pub scale: u32,
292    pub mirror: bool,
293}
294
295impl SpriteInstance {
296    pub fn width(&self) -> u32 {
297        self.kind.box_size().0 * self.scale
298    }
299    pub fn height(&self) -> u32 {
300        self.kind.box_size().1 * self.scale
301    }
302}
303
304/// Everything needed to render one scene at one size and theme.
305#[derive(Clone, Debug)]
306pub struct SceneGraph {
307    pub width: u32,
308    pub height: u32,
309    pub theme: Theme,
310    pub tod: TimeOfDay,
311    pub buddy: bool,
312    /// The recipe seed (drives the character's state machine).
313    pub seed: u64,
314    pub family: PaletteFamily,
315    pub grid: GridSpec,
316    /// Row-major, `grid.cols * grid.rows`.
317    pub cells: Vec<Cell>,
318    pub lighting: Lighting,
319    /// The activity id, or `None` for an archetype-first fallback scene.
320    pub activity: Option<String>,
321    /// Activity props, drawn in both Buddy states.
322    pub props: Vec<SpriteInstance>,
323    /// Unattended variant, drawn only with Buddy off.
324    pub unattended: Vec<SpriteInstance>,
325    /// The character's track (always laid out; drawn only with Buddy on).
326    pub character: Option<CharacterTrack>,
327    pub emitters: Vec<Emitter>,
328    /// Pixel y of the platform's top surface (where feet stand).
329    pub ground_y: i32,
330    /// Hero time in milliseconds: the frame used for stills and thumbnails.
331    pub t_hero_ms: u64,
332    /// Seamless loop length for periodic elements.
333    pub loop_ms: u64,
334}
335
336impl SceneGraph {
337    #[inline]
338    pub fn cell(&self, col: u32, row: u32) -> Cell {
339        self.cells[(row * self.grid.cols + col) as usize]
340    }
341
342    /// Sprites to draw at `t`, back to front: props, then the character (Buddy
343    /// on) or the unattended variant (Buddy off).
344    pub fn sprites_at(&self, t_ms: u64) -> Vec<SpriteInstance> {
345        let mut out = self.props.clone();
346        if self.buddy {
347            out.extend(self.character.map(|c| c.at(t_ms)));
348        } else {
349            out.extend_from_slice(&self.unattended);
350        }
351        out
352    }
353
354    /// Particles at time `t`, snapped to cells, as `(col, row, particle)`.
355    pub fn particles_at(&self, t_ms: u64) -> Vec<(u32, u32, Particle)> {
356        let g = &self.grid;
357        let mut out = Vec::new();
358        for e in &self.emitters {
359            for p in e.sample(t_ms) {
360                let cx = (p.x - f64::from(g.origin_x)) / f64::from(g.cell_w);
361                let cy = (p.y - f64::from(g.origin_y)) / f64::from(g.cell_h);
362                if cx < 0.0 || cy < 0.0 {
363                    continue;
364                }
365                let (col, row) = (cx.floor() as u32, cy.floor() as u32);
366                if col < g.cols && row < g.rows {
367                    out.push((col, row, p));
368                }
369            }
370        }
371        out
372    }
373}