Skip to main content

clairlune_render/
atlas.rs

1//! Glyph atlas: every glyph of `glyphs::GLYPHS` rasterized once into a cell-sized
2//! alpha mask.
3//!
4//! The rasterizer is our own: `skrifa` gives unscaled, unhinted outlines in font
5//! units, and coverage is an 8x8 supersampled non-zero winding test. It only uses
6//! `+ - * /` and comparisons on f64, which are IEEE-exact, so masks are
7//! byte-identical on every OS and CPU. (A SIMD rasterizer with separate x86 and
8//! ARM paths would not guarantee that.)
9
10use clairlune_scene::glyphs::GLYPHS;
11use clairlune_scene::{GridSpec, SceneGraph};
12use skrifa::instance::{LocationRef, Size};
13use skrifa::outline::{DrawSettings, OutlinePen};
14use skrifa::{FontRef, MetadataProvider};
15
16/// The bundled monospace font (JetBrains Mono Regular, SIL OFL 1.1).
17pub static FONT_DATA: &[u8] = include_bytes!("../assets/fonts/JetBrainsMono-Regular.ttf");
18
19/// The katakana the `kana` letter set is drawn in: M PLUS 1 Code's, cut
20/// down to them (SIL OFL 1.1, assets/fonts/ClairluneKana-OFL.txt).
21pub static KANA_FONT: &[u8] = include_bytes!("../assets/fonts/ClairluneKana.ttf");
22
23/// Samples per pixel along each axis.
24const SUPERSAMPLE: u32 = 8;
25/// Line segments per quadratic / cubic curve.
26const QUAD_STEPS: u32 = 8;
27const CUBIC_STEPS: u32 = 12;
28/// Room below the baseline reserved for descenders, in em.
29const DESCENT_ROOM_EM: f64 = 0.22;
30
31/// Alpha masks for every glyph at one cell size.
32#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
33pub struct GlyphAtlas {
34    pub cell_w: u32,
35    pub cell_h: u32,
36    masks: Vec<u8>,
37}
38
39#[derive(Debug)]
40pub enum AtlasError {
41    Font(skrifa::raw::ReadError),
42}
43
44impl std::fmt::Display for AtlasError {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match self {
47            AtlasError::Font(e) => write!(f, "font parse error: {e}"),
48        }
49    }
50}
51
52impl std::error::Error for AtlasError {}
53
54impl GlyphAtlas {
55    /// Atlas for a grid, using the bundled font.
56    pub fn for_grid(spec: &GridSpec) -> Self {
57        Self::with_font(FONT_DATA, spec.cell_w, spec.cell_h, spec.font_px)
58            .expect("bundled font parses")
59    }
60
61    /// The atlas a scene's glyphs are drawn with: in its letter set.
62    pub fn for_graph(graph: &SceneGraph) -> Self {
63        Self::for_letters(&graph.grid, &graph.letters)
64    }
65
66    /// Atlas for a grid in a letter set (`clairlune_scene::glyphs::LETTERS`):
67    /// the bundled font's characters, katakana from the kana font, narrowed
68    /// to the cell, and braille drawn as dots.
69    pub fn for_letters(spec: &GridSpec, letters: &str) -> Self {
70        let chars = clairlune_scene::glyphs::letters(letters);
71        let (w, h) = (spec.cell_w, spec.cell_h);
72        let mut atlas = Self::rasterize_chars(FONT_DATA, &chars, w, h, spec.font_px, false)
73            .expect("bundled font parses");
74        let len = (w * h) as usize;
75        let kana: Vec<char> = chars
76            .iter()
77            .map(|&c| if is_kana(c) { c } else { ' ' })
78            .collect();
79        if kana.iter().any(|&c| c != ' ') {
80            let k = Self::rasterize_chars(KANA_FONT, &kana, w, h, spec.font_px, true)
81                .expect("bundled kana font parses");
82            for (i, _) in kana.iter().enumerate().filter(|(_, c)| **c != ' ') {
83                atlas.masks[i * len..(i + 1) * len]
84                    .copy_from_slice(&k.masks[i * len..(i + 1) * len]);
85            }
86        }
87        for (i, &c) in chars.iter().enumerate() {
88            if let Some(dots) = braille_dots(c) {
89                braille(dots, w, h, &mut atlas.masks[i * len..(i + 1) * len]);
90            }
91        }
92        atlas
93    }
94
95    /// Atlas from arbitrary font bytes.
96    pub fn with_font(
97        font: &[u8],
98        cell_w: u32,
99        cell_h: u32,
100        font_px: f64,
101    ) -> Result<Self, AtlasError> {
102        Self::with_chars(font, &GLYPHS, cell_w, cell_h, font_px)
103    }
104
105    /// An atlas of these characters (mask `i` is `chars[i]`'s), for text
106    /// beyond the scene's glyphs, such as a signature.
107    pub fn with_chars(
108        font: &[u8],
109        chars: &[char],
110        cell_w: u32,
111        cell_h: u32,
112        font_px: f64,
113    ) -> Result<Self, AtlasError> {
114        Self::rasterize_chars(font, chars, cell_w, cell_h, font_px, false)
115    }
116
117    /// With `narrow`, a glyph wider than the cell is narrowed to fit it.
118    fn rasterize_chars(
119        font: &[u8],
120        chars: &[char],
121        cell_w: u32,
122        cell_h: u32,
123        font_px: f64,
124        narrow: bool,
125    ) -> Result<Self, AtlasError> {
126        let face = FontRef::new(font).map_err(AtlasError::Font)?;
127        // Everything in font units; we scale ourselves with f64.
128        let location = LocationRef::default();
129        let metrics = face.metrics(Size::unscaled(), location);
130        let glyph_metrics = face.glyph_metrics(Size::unscaled(), location);
131        let outlines = face.outline_glyphs();
132        let charmap = face.charmap();
133        let upm = f64::from(metrics.units_per_em);
134        let scale = font_px / upm;
135        let cap = metrics.cap_height.map_or(0.73 * upm, f64::from);
136        let content = (cap + DESCENT_ROOM_EM * upm) * scale;
137        let baseline = (f64::from(cell_h) - content) * 0.5 + cap * scale;
138        let cell_len = (cell_w * cell_h) as usize;
139        let mut masks = vec![0u8; cell_len * chars.len()];
140        for (i, &ch) in chars.iter().enumerate() {
141            if ch == ' ' {
142                continue;
143            }
144            let Some(id) = charmap.map(ch) else {
145                continue;
146            };
147            let Some(glyph) = outlines.get(id) else {
148                continue;
149            };
150            let mut advance = f64::from(glyph_metrics.advance_width(id).unwrap_or(0.0)) * scale;
151            let room = f64::from(cell_w) * 0.94;
152            let sx = if narrow && advance > room {
153                room / advance
154            } else {
155                1.0
156            };
157            advance *= sx;
158            let mut outline = Flattener {
159                segs: Vec::new(),
160                ox: (f64::from(cell_w) - advance) * 0.5,
161                baseline,
162                scale,
163                sx,
164                cur: (0.0, 0.0),
165                start: (0.0, 0.0),
166            };
167            let settings = DrawSettings::unhinted(Size::unscaled(), location);
168            if glyph.draw(settings, &mut outline).is_err() {
169                continue;
170            }
171            rasterize(
172                &outline.segs,
173                cell_w,
174                cell_h,
175                &mut masks[i * cell_len..(i + 1) * cell_len],
176            );
177        }
178        Ok(Self {
179            cell_w,
180            cell_h,
181            masks,
182        })
183    }
184
185    /// Whether it is whole glyphs at this cell size, at least the empty one.
186    /// (A saved atlas may have fewer glyphs than today's table: an older one.)
187    pub fn fits(&self, cell_w: u32, cell_h: u32) -> bool {
188        let len = (cell_w as usize).saturating_mul(cell_h as usize);
189        (self.cell_w, self.cell_h) == (cell_w, cell_h)
190            && len > 0
191            && self.masks.len() >= len
192            && self.masks.len().is_multiple_of(len)
193    }
194
195    /// Row-major alpha mask (`cell_w * cell_h`) of a glyph id. A glyph an
196    /// older saved atlas doesn't have draws as the empty cell.
197    #[inline]
198    pub fn mask(&self, glyph: u8) -> &[u8] {
199        let len = (self.cell_w * self.cell_h) as usize;
200        let start = glyph as usize * len;
201        self.masks
202            .get(start..start + len)
203            .unwrap_or(&self.masks[..len])
204    }
205}
206
207#[derive(Clone, Copy, Debug)]
208struct Seg {
209    x0: f64,
210    y0: f64,
211    x1: f64,
212    y1: f64,
213}
214
215/// Collects an outline as line segments in cell pixel space (y down).
216struct Flattener {
217    segs: Vec<Seg>,
218    ox: f64,
219    baseline: f64,
220    scale: f64,
221    /// How much narrower than the font draws it (1: as drawn).
222    sx: f64,
223    cur: (f64, f64),
224    start: (f64, f64),
225}
226
227impl Flattener {
228    fn map(&self, x: f32, y: f32) -> (f64, f64) {
229        (
230            self.ox + f64::from(x) * self.scale * self.sx,
231            self.baseline - f64::from(y) * self.scale,
232        )
233    }
234
235    fn push(&mut self, p: (f64, f64)) {
236        if p != self.cur {
237            self.segs.push(Seg {
238                x0: self.cur.0,
239                y0: self.cur.1,
240                x1: p.0,
241                y1: p.1,
242            });
243        }
244        self.cur = p;
245    }
246}
247
248impl OutlinePen for Flattener {
249    fn move_to(&mut self, x: f32, y: f32) {
250        let p = self.map(x, y);
251        self.cur = p;
252        self.start = p;
253    }
254
255    fn line_to(&mut self, x: f32, y: f32) {
256        let p = self.map(x, y);
257        self.push(p);
258    }
259
260    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
261        let p0 = self.cur;
262        let c = self.map(x1, y1);
263        let p1 = self.map(x, y);
264        for i in 1..=QUAD_STEPS {
265            let t = f64::from(i) / f64::from(QUAD_STEPS);
266            let u = 1.0 - t;
267            let px = u * u * p0.0 + 2.0 * u * t * c.0 + t * t * p1.0;
268            let py = u * u * p0.1 + 2.0 * u * t * c.1 + t * t * p1.1;
269            self.push((px, py));
270        }
271    }
272
273    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
274        let p0 = self.cur;
275        let c1 = self.map(x1, y1);
276        let c2 = self.map(x2, y2);
277        let p1 = self.map(x, y);
278        for i in 1..=CUBIC_STEPS {
279            let t = f64::from(i) / f64::from(CUBIC_STEPS);
280            let u = 1.0 - t;
281            let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
282            let px = a * p0.0 + b * c1.0 + c * c2.0 + d * p1.0;
283            let py = a * p0.1 + b * c1.1 + c * c2.1 + d * p1.1;
284            self.push((px, py));
285        }
286    }
287
288    fn close(&mut self) {
289        let s = self.start;
290        self.push(s);
291    }
292}
293
294/// Non-zero winding coverage, `SUPERSAMPLE`² samples per pixel, into `out` (0..=255).
295fn rasterize(segs: &[Seg], w: u32, h: u32, out: &mut [u8]) {
296    let s = SUPERSAMPLE;
297    let mut counts = vec![0u32; (w * h) as usize];
298    let mut xs: Vec<(f64, i32)> = Vec::with_capacity(32);
299    for py in 0..h {
300        for sy in 0..s {
301            let y = f64::from(py) + (f64::from(sy) + 0.5) / f64::from(s);
302            xs.clear();
303            for g in segs {
304                let crosses = (g.y0 <= y && y < g.y1) || (g.y1 <= y && y < g.y0);
305                if crosses {
306                    let t = (y - g.y0) / (g.y1 - g.y0);
307                    let dir = if g.y1 > g.y0 { 1 } else { -1 };
308                    xs.push((g.x0 + t * (g.x1 - g.x0), dir));
309                }
310            }
311            if xs.is_empty() {
312                continue;
313            }
314            xs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
315            let mut winding = 0;
316            let mut k = 0;
317            let row = (py * w) as usize;
318            for px in 0..w {
319                for sx in 0..s {
320                    let x = f64::from(px) + (f64::from(sx) + 0.5) / f64::from(s);
321                    while k < xs.len() && xs[k].0 <= x {
322                        winding += xs[k].1;
323                        k += 1;
324                    }
325                    if winding != 0 {
326                        counts[row + px as usize] += 1;
327                    }
328                }
329            }
330        }
331    }
332    let total = s * s;
333    for (o, &c) in out.iter_mut().zip(&counts) {
334        *o = ((c * 255 + total / 2) / total) as u8;
335    }
336}
337
338/// Katakana, drawn from the kana font.
339fn is_kana(c: char) -> bool {
340    ('\u{30A0}'..='\u{30FF}').contains(&c)
341}
342
343/// A braille character's dots (bit 0 is dot 1), if it is one.
344fn braille_dots(c: char) -> Option<u8> {
345    let v = u32::from(c);
346    (0x2801..=0x28FF).contains(&v).then(|| (v - 0x2800) as u8)
347}
348
349/// Draws braille dots as round dots: two columns of four, over the height
350/// the letters take, the same at every size (supersampled, f64 only, so
351/// the same on every machine).
352fn braille(dots: u8, w: u32, h: u32, out: &mut [u8]) {
353    // Dot n's column and row (Unicode's order: 1-3 and 7 down the left, 4-6
354    // and 8 down the right).
355    const PLACE: [(u32, u32); 8] = [
356        (0, 0),
357        (0, 1),
358        (0, 2),
359        (1, 0),
360        (1, 1),
361        (1, 2),
362        (0, 3),
363        (1, 3),
364    ];
365    let (fw, fh) = (f64::from(w), f64::from(h));
366    let r = (fw * 0.14).min(fh * 0.07);
367    let centres: Vec<(f64, f64)> = PLACE
368        .iter()
369        .enumerate()
370        .filter(|(n, _)| dots & (1 << n) != 0)
371        .map(|(_, &(c, row))| {
372            (
373                fw * (0.3 + 0.4 * f64::from(c)),
374                fh * (0.17 + 0.2 * f64::from(row)),
375            )
376        })
377        .collect();
378    let s = f64::from(SUPERSAMPLE);
379    for y in 0..h {
380        for x in 0..w {
381            let mut hit = 0u32;
382            for sy in 0..SUPERSAMPLE {
383                for sx in 0..SUPERSAMPLE {
384                    let px = f64::from(x) + (f64::from(sx) + 0.5) / s;
385                    let py = f64::from(y) + (f64::from(sy) + 0.5) / s;
386                    if centres
387                        .iter()
388                        .any(|&(cx, cy)| (px - cx) * (px - cx) + (py - cy) * (py - cy) <= r * r)
389                    {
390                        hit += 1;
391                    }
392                }
393            }
394            out[(y * w + x) as usize] =
395                ((hit * 255 + SUPERSAMPLE * SUPERSAMPLE / 2) / (SUPERSAMPLE * SUPERSAMPLE)) as u8;
396        }
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use clairlune_scene::glyphs::{EMPTY, id};
404    use clairlune_scene::grid_spec;
405
406    fn ink(atlas: &GlyphAtlas, g: u8) -> u32 {
407        atlas.mask(g).iter().map(|&a| u32::from(a)).sum()
408    }
409
410    #[test]
411    fn glyphs_have_ink_and_space_is_empty() {
412        let atlas = GlyphAtlas::for_grid(&grid_spec(3840, 2160));
413        assert_eq!(ink(&atlas, EMPTY), 0);
414        for g in 1..GLYPHS.len() as u8 {
415            assert!(
416                ink(&atlas, g) > 0,
417                "glyph {:?} is blank",
418                GLYPHS[g as usize]
419            );
420        }
421        // Heavier glyphs carry more ink than light ones.
422        assert!(ink(&atlas, id('@')) > ink(&atlas, id('.')));
423        assert!(ink(&atlas, id('#')) > ink(&atlas, id('-')));
424    }
425
426    #[test]
427    fn every_letter_set_has_ink_where_its_glyphs_do() {
428        let spec = clairlune_scene::graph::grid_spec(1920, 1080);
429        let text = GlyphAtlas::for_grid(&spec);
430        assert_eq!(GlyphAtlas::for_letters(&spec, "text"), text);
431        for set in clairlune_scene::glyphs::LETTERS {
432            let a = GlyphAtlas::for_letters(&spec, set);
433            for (g, c) in clairlune_scene::glyphs::letters(set).iter().enumerate() {
434                let g = g as u8;
435                assert_eq!(ink(&a, g) == 0, g == EMPTY, "{set}: {c:?} ({g})");
436            }
437        }
438        // Braille is dots: one dot inks less than all eight.
439        let b = GlyphAtlas::for_letters(&spec, "braille");
440        assert!(ink(&b, id('.')) * 4 < ink(&b, id('@')));
441    }
442
443    #[test]
444    fn atlas_is_deterministic() {
445        let spec = grid_spec(640, 360);
446        assert_eq!(GlyphAtlas::for_grid(&spec), GlyphAtlas::for_grid(&spec));
447    }
448}