Skip to main content

crcbl_ui/
text.rs

1//! Glyph atlas and text layout for the immediate-mode UI.
2//!
3//! Provides a built-in monospace bitmap font (the "engine font") with glyph
4//! metrics and a simple text-layout function that produces positioned glyph
5//! indices for the draw list.
6//!
7//! # Beside real fonts, not replaced by them
8//!
9//! [`crate::font`] parses and rasterises an outline font, and that is what a
10//! tree span draws when a stylesheet gives it `font-family: sans-serif`. This
11//! pixel font is still the one the menus, the console, the debug panel, the
12//! widgets, [`crate::readout::ReadoutPanel`] (through `default.css`) and every
13//! sample's hand-drawn HUD draw with, and the initial `font-family`.
14
15use glam::Vec2;
16
17// ---------------------------------------------------------------------------
18// Glyph metrics
19// ---------------------------------------------------------------------------
20
21/// Metrics for a single glyph in the atlas.
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct GlyphMetrics {
24    /// Width of the glyph bitmap in pixels.
25    pub width: u32,
26    /// Height of the glyph bitmap in pixels.
27    pub height: u32,
28    /// Horizontal offset from the cursor position to the left edge of the
29    /// glyph bitmap.
30    pub bearing_x: i32,
31    /// Vertical offset from the baseline to the top of the glyph bitmap.
32    pub bearing_y: i32,
33    /// Horizontal advance — how far the cursor moves after this glyph.
34    pub advance: f32,
35}
36
37impl GlyphMetrics {
38    /// The bounding rectangle for this glyph, relative to the cursor position.
39    ///
40    /// `cursor` is a **baseline** position: `bearing_y` is measured up from the
41    /// baseline, so the returned `min.y` sits above `cursor.y`.
42    #[must_use]
43    pub fn rect(&self, cursor: Vec2) -> (Vec2, Vec2) {
44        self.rect_scaled(cursor, 1.0)
45    }
46
47    /// The bounding rectangle for this glyph at `scale`, relative to the
48    /// baseline position `cursor`.
49    ///
50    /// Only the glyph's own extents are scaled — `cursor` is already in final
51    /// screen space, so scaling it again would move the anchor with the font
52    /// size.
53    #[must_use]
54    pub fn rect_scaled(&self, cursor: Vec2, scale: f32) -> (Vec2, Vec2) {
55        let min = Vec2::new(
56            cursor.x + self.bearing_x as f32 * scale,
57            cursor.y - self.bearing_y as f32 * scale,
58        );
59        let max = Vec2::new(
60            min.x + self.width as f32 * scale,
61            min.y + self.height as f32 * scale,
62        );
63        (min, max)
64    }
65}
66
67// ---------------------------------------------------------------------------
68// FontAtlas
69// ---------------------------------------------------------------------------
70
71/// A simple monospace bitmap font atlas.
72///
73/// The built-in engine font is a fixed-pitch 8×13 px bitmap covering ASCII
74/// 32–126, plus a trailing `.notdef` box. Glyphs are arranged in a single row
75/// in the atlas texture.
76///
77/// # Atlas layout
78///
79/// Each glyph is `GLYPH_WIDTH × GLYPH_HEIGHT` pixels. They are packed
80/// left-to-right, one row, in ASCII order, with `.notdef` last. The total atlas
81/// width is `GLYPH_WIDTH * GLYPH_COUNT` pixels.
82pub struct FontAtlas {
83    /// Glyph metrics for each atlas column, indexed by [`glyph_index`].
84    metrics: Vec<GlyphMetrics>,
85    /// Atlas texture dimensions in pixels (width, height).
86    pub texture_size: (u32, u32),
87}
88
89/// Number of printable-ASCII glyphs in the built-in atlas (32–126 inclusive).
90pub const ASCII_GLYPH_COUNT: usize = 95;
91
92/// Atlas column of the `.notdef` glyph — the fallback drawn for every codepoint
93/// outside ASCII 32–126.
94pub const NOTDEF_INDEX: usize = ASCII_GLYPH_COUNT;
95
96/// Number of glyphs in the built-in atlas: printable ASCII plus `.notdef`.
97pub const GLYPH_COUNT: usize = ASCII_GLYPH_COUNT + 1;
98
99/// First ASCII codepoint in the atlas.
100pub const FIRST_CHAR: u8 = 32;
101
102/// Last ASCII codepoint in the atlas.
103pub const LAST_CHAR: u8 = 126;
104
105/// Width of each glyph in the built-in bitmap font.
106pub const GLYPH_WIDTH: u32 = 8;
107
108/// Height of each glyph in the built-in bitmap font.
109pub const GLYPH_HEIGHT: u32 = 13;
110
111/// Horizontal advance for each glyph (pixels from one cursor position to the
112/// next).
113pub const GLYPH_ADVANCE: f32 = 10.0;
114
115/// Line height (vertical advance from one line to the next).
116pub const LINE_HEIGHT: f32 = 16.0;
117
118/// Ascender height in pixels (baseline to top of capital letter).
119pub const ASCENDER: i32 = 10;
120
121/// The atlas column a codepoint renders from.
122///
123/// Codepoints outside the printable-ASCII range map to [`NOTDEF_INDEX`]. The
124/// test is on the **codepoint**, not on a truncated byte: `'Ł'` (U+0141) and
125/// `'A'` (U+0041) share a low byte but are not the same glyph.
126#[must_use]
127pub fn glyph_index(c: char) -> usize {
128    let cp = c as u32;
129    if cp >= FIRST_CHAR as u32 && cp <= LAST_CHAR as u32 {
130        (cp - FIRST_CHAR as u32) as usize
131    } else {
132        NOTDEF_INDEX
133    }
134}
135
136/// Metrics returned when the atlas holds no glyph at all — an empty glyph that
137/// advances nothing, so a degenerate atlas lays text out as nothing rather than
138/// panicking.
139static EMPTY_GLYPH: GlyphMetrics = GlyphMetrics {
140    width: 0,
141    height: 0,
142    bearing_x: 0,
143    bearing_y: 0,
144    advance: 0.0,
145};
146
147impl FontAtlas {
148    /// Create the built-in monospace font atlas.
149    #[must_use]
150    pub fn built_in() -> Self {
151        let mut metrics: Vec<GlyphMetrics> = (FIRST_CHAR..=LAST_CHAR)
152            .map(|c| {
153                let w = if c <= b' ' { 0 } else { GLYPH_WIDTH };
154                GlyphMetrics {
155                    width: w,
156                    height: GLYPH_HEIGHT,
157                    bearing_x: 1,
158                    bearing_y: ASCENDER,
159                    advance: GLYPH_ADVANCE,
160                }
161            })
162            .collect();
163        // `.notdef`, drawn for anything outside printable ASCII.
164        metrics.push(GlyphMetrics {
165            width: GLYPH_WIDTH,
166            height: GLYPH_HEIGHT,
167            bearing_x: 1,
168            bearing_y: ASCENDER,
169            advance: GLYPH_ADVANCE,
170        });
171
172        let texture_size = (GLYPH_WIDTH * GLYPH_COUNT as u32, GLYPH_HEIGHT);
173        Self {
174            metrics,
175            texture_size,
176        }
177    }
178
179    /// Look up the metrics for a character.
180    ///
181    /// Any codepoint outside ASCII 32–126 — including control characters and
182    /// everything non-Latin — resolves to the `.notdef` box.
183    #[must_use]
184    pub fn glyph(&self, c: char) -> &GlyphMetrics {
185        let idx = glyph_index(c);
186        self.metrics
187            .get(idx)
188            .or_else(|| self.metrics.get(NOTDEF_INDEX))
189            .or_else(|| self.metrics.first())
190            .unwrap_or(&EMPTY_GLYPH)
191    }
192
193    /// Measure the width of a string in pixels at the given scale.
194    ///
195    /// `scale` is a multiplier relative to the baked-in glyph size (1.0 =
196    /// natural pixel size). Multi-line text measures as its **widest** line, not
197    /// as the sum of every line.
198    #[must_use]
199    pub fn text_width(&self, text: &str, scale: f32) -> f32 {
200        let mut widest = 0.0f32;
201        let mut line = 0.0f32;
202        for c in text.chars() {
203            if c == '\n' {
204                widest = widest.max(line);
205                line = 0.0;
206                continue;
207            }
208            line += self.glyph(c).advance * scale;
209        }
210        widest.max(line)
211    }
212
213    /// Number of lines a string lays out to (always at least one).
214    #[must_use]
215    pub fn line_count(&self, text: &str) -> usize {
216        1 + text.chars().filter(|&c| c == '\n').count()
217    }
218
219    /// Layout text into screen-space glyph positions.
220    ///
221    /// `pos` is the **top-left anchor** of the first line's em box — the same
222    /// anchor [`DrawCommand::Text::pos`] documents — not a baseline. The
223    /// baseline is derived from it as `pos.y + ASCENDER * scale`.
224    ///
225    /// Returns a list of `(char, min, max)` quads where `min`/`max` are the
226    /// screen-space corners of each glyph, with `min` the top-left corner in
227    /// the Y-down screen convention.
228    ///
229    /// [`DrawCommand::Text::pos`]: crate::draw_list::DrawCommand::Text
230    pub fn layout_line(&self, text: &str, pos: Vec2, scale: f32) -> Vec<(char, Vec2, Vec2)> {
231        let mut out = Vec::with_capacity(text.len());
232        out.extend(self.glyph_positions(text, pos, scale));
233        out
234    }
235
236    /// Positions bitmap glyphs without building an intermediate layout vector.
237    pub(crate) fn glyph_positions<'a>(
238        &'a self,
239        text: &'a str,
240        pos: Vec2,
241        scale: f32,
242    ) -> impl Iterator<Item = (char, Vec2, Vec2)> + 'a {
243        // `cursor` is a baseline position; `pos` is the top of the em box.
244        let mut cursor = Vec2::new(pos.x, pos.y + ASCENDER as f32 * scale);
245        text.chars().filter_map(move |c| {
246            if c == '\n' {
247                cursor.x = pos.x;
248                cursor.y += LINE_HEIGHT * scale;
249                return None;
250            }
251            let g = self.glyph(c);
252            let quad = if g.width > 0 {
253                let (min, max) = g.rect_scaled(cursor, scale);
254                Some((c, min, max))
255            } else {
256                None
257            };
258            cursor.x += g.advance * scale;
259            quad
260        })
261    }
262
263    /// Number of glyphs in the atlas.
264    #[must_use]
265    pub fn len(&self) -> usize {
266        self.metrics.len()
267    }
268
269    /// Whether the atlas is empty.
270    #[must_use]
271    pub fn is_empty(&self) -> bool {
272        self.metrics.is_empty()
273    }
274
275    /// UV u-coordinate of the left edge of the given glyph in the atlas
276    /// texture (range [0, 1]).
277    ///
278    /// Codepoints with no glyph resolve to `.notdef`, so the result is always
279    /// inside `[0, 1]`.
280    #[must_use]
281    pub fn glyph_u_min(&self, c: char) -> f32 {
282        let atlas_w = self.texture_size.0 as f32;
283        if atlas_w == 0.0 {
284            return 0.0;
285        }
286        let col = glyph_index(c) as u32;
287        (col * GLYPH_WIDTH) as f32 / atlas_w
288    }
289
290    /// UV u-coordinate of the right edge of the given glyph in the atlas
291    /// texture (range [0, 1]).
292    ///
293    /// Codepoints with no glyph resolve to `.notdef`, so the result is always
294    /// inside `[0, 1]`.
295    #[must_use]
296    pub fn glyph_u_max(&self, c: char) -> f32 {
297        let atlas_w = self.texture_size.0 as f32;
298        if atlas_w == 0.0 {
299            return 0.0;
300        }
301        let col = glyph_index(c) as u32;
302        ((col + 1) * GLYPH_WIDTH) as f32 / atlas_w
303    }
304
305    /// Generate the atlas texture pixel data as R8_UNORM bytes.
306    ///
307    /// Returns `(width, height, data)` where `data` is row-major, one byte per
308    /// pixel. 0 = transparent, 255 = fully opaque glyph.
309    #[must_use]
310    pub fn glyph_bitmap(&self) -> (u32, u32, Vec<u8>) {
311        let (w, h) = self.texture_size;
312        let mut data = vec![0u8; (w * h) as usize];
313
314        for glyph_idx in 0..GLYPH_COUNT {
315            let rows = glyph_rows_at(glyph_idx);
316            let x_offset = glyph_idx as u32 * GLYPH_WIDTH;
317            for (row, &row_bits) in rows.iter().enumerate() {
318                for col in 0..GLYPH_WIDTH as usize {
319                    let bit = (row_bits >> (7 - col)) & 1;
320                    let px = (x_offset + col as u32) as usize;
321                    let py = row;
322                    data[py * w as usize + px] = if bit != 0 { 255 } else { 0 };
323                }
324            }
325        }
326        (w, h, data)
327    }
328}
329
330// ---------------------------------------------------------------------------
331// Embedded 8×13 bitmap font (row-major bit patterns, MSB = leftmost pixel)
332// ---------------------------------------------------------------------------
333
334/// The `.notdef` glyph: a hollow box, drawn for every codepoint the atlas has
335/// no bitmap for.
336const NOTDEF_ROWS: [u8; 13] = [
337    0xFE, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
338];
339
340/// Returns the 13 row bytes for the atlas column `index`.
341///
342/// Columns `0..ASCII_GLYPH_COUNT` are printable ASCII in order; the last is
343/// `.notdef`.
344fn glyph_rows_at(index: usize) -> [u8; 13] {
345    if index < ASCII_GLYPH_COUNT {
346        glyph_rows(char::from(FIRST_CHAR + index as u8))
347    } else {
348        NOTDEF_ROWS
349    }
350}
351
352/// Returns the 13 row bytes for the given ASCII character.
353///
354/// Each byte encodes one row of the 8-pixel-wide glyph; the MSB (bit 7) is the
355/// leftmost pixel. Only characters 32–126 are valid; others return `.notdef`.
356fn glyph_rows(c: char) -> [u8; 13] {
357    // Compact 8×13 embedded bitmap font.
358    // clang-format off
359    match c {
360        ' ' => [0x00; 13],
361        '!' => [
362            0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
363        ],
364        '"' => [
365            0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
366        ],
367        '#' => [
368            0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
369        ],
370        '$' => [
371            0x10, 0x7C, 0xD6, 0xD0, 0x7C, 0x16, 0xD6, 0x7C, 0x10, 0x00, 0x00, 0x00, 0x00,
372        ],
373        '%' => [
374            0x00, 0xE6, 0xA6, 0xEC, 0x18, 0x30, 0x6E, 0xCA, 0xCE, 0x00, 0x00, 0x00, 0x00,
375        ],
376        '&' => [
377            0x00, 0x38, 0x6C, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
378        ],
379        '\'' => [
380            0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
381        ],
382        '(' => [
383            0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00,
384        ],
385        ')' => [
386            0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
387        ],
388        '*' => [
389            0x00, 0x00, 0x10, 0xD6, 0x7C, 0x38, 0x7C, 0xD6, 0x10, 0x00, 0x00, 0x00, 0x00,
390        ],
391        '+' => [
392            0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
393        ],
394        ',' => [
395            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00,
396        ],
397        '-' => [
398            0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
399        ],
400        '.' => [
401            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
402        ],
403        '/' => [
404            0x06, 0x0C, 0x0C, 0x18, 0x18, 0x30, 0x30, 0x60, 0x60, 0x00, 0x00, 0x00, 0x00,
405        ],
406        '0' => [
407            0x7C, 0xC6, 0xCE, 0xDE, 0xF6, 0xE6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
408        ],
409        '1' => [
410            0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00,
411        ],
412        '2' => [
413            0x7C, 0xC6, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
414        ],
415        '3' => [
416            0x7C, 0xC6, 0x06, 0x3C, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
417        ],
418        '4' => [
419            0x0C, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00,
420        ],
421        '5' => [
422            0xFE, 0xC0, 0xC0, 0xFC, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
423        ],
424        '6' => [
425            0x3C, 0x60, 0xC0, 0xFC, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
426        ],
427        '7' => [
428            0xFE, 0x06, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00,
429        ],
430        '8' => [
431            0x7C, 0xC6, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
432        ],
433        '9' => [
434            0x7C, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00,
435        ],
436        ':' => [
437            0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
438        ],
439        ';' => [
440            0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
441        ],
442        '<' => [
443            0x00, 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
444        ],
445        '=' => [
446            0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
447        ],
448        '>' => [
449            0x00, 0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00,
450        ],
451        '?' => [
452            0x7C, 0xC6, 0x06, 0x0C, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
453        ],
454        '@' => [
455            0x7C, 0xC6, 0xDE, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
456        ],
457        'A' => [
458            0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
459        ],
460        'B' => [
461            0xFC, 0xC6, 0xC6, 0xFC, 0xC6, 0xC6, 0xC6, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00,
462        ],
463        'C' => [
464            0x7C, 0xC6, 0xC0, 0xC0, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
465        ],
466        'D' => [
467            0xF8, 0xCC, 0xC6, 0xC6, 0xC6, 0xC6, 0xCC, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00,
468        ],
469        'E' => [
470            0xFE, 0xC0, 0xC0, 0xFC, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
471        ],
472        'F' => [
473            0xFE, 0xC0, 0xC0, 0xFC, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00,
474        ],
475        'G' => [
476            0x7C, 0xC6, 0xC0, 0xDE, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
477        ],
478        'H' => [
479            0xC6, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
480        ],
481        'I' => [
482            0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00,
483        ],
484        'J' => [
485            0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00,
486        ],
487        'K' => [
488            0xC6, 0xCC, 0xD8, 0xF0, 0xF0, 0xD8, 0xCC, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
489        ],
490        'L' => [
491            0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
492        ],
493        'M' => [
494            0xC6, 0xEE, 0xFE, 0xD6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
495        ],
496        'N' => [
497            0xC6, 0xE6, 0xF6, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
498        ],
499        'O' => [
500            0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
501        ],
502        'P' => [
503            0xFC, 0xC6, 0xC6, 0xC6, 0xFC, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00,
504        ],
505        'Q' => [
506            0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xDE, 0xCC, 0x7A, 0x00, 0x00, 0x00, 0x00, 0x00,
507        ],
508        'R' => [
509            0xFC, 0xC6, 0xC6, 0xFC, 0xD8, 0xCC, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
510        ],
511        'S' => [
512            0x7C, 0xC6, 0xC0, 0x7C, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
513        ],
514        'T' => [
515            0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
516        ],
517        'U' => [
518            0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
519        ],
520        'V' => [
521            0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
522        ],
523        'W' => [
524            0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00,
525        ],
526        'X' => [
527            0xC6, 0xC6, 0x6C, 0x38, 0x38, 0x6C, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
528        ],
529        'Y' => [
530            0xC3, 0xC3, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
531        ],
532        'Z' => [
533            0xFE, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
534        ],
535        '[' => [
536            0x7C, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
537        ],
538        '\\' => [
539            0x60, 0x30, 0x30, 0x18, 0x18, 0x0C, 0x0C, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00,
540        ],
541        ']' => [
542            0x7C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
543        ],
544        '^' => [
545            0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
546        ],
547        '_' => [
548            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00,
549        ],
550        '`' => [
551            0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
552        ],
553        'a' => [
554            0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00,
555        ],
556        'b' => [
557            0xC0, 0xC0, 0xDC, 0xE6, 0xC6, 0xC6, 0xE6, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00,
558        ],
559        'c' => [
560            0x00, 0x00, 0x7C, 0xC6, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
561        ],
562        'd' => [
563            0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00,
564        ],
565        'e' => [
566            0x00, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
567        ],
568        'f' => [
569            0x1C, 0x36, 0x30, 0xFC, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00,
570        ],
571        'g' => [
572            0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
573        ],
574        'h' => [
575            0xC0, 0xC0, 0xDC, 0xE6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
576        ],
577        'i' => [
578            0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00,
579        ],
580        'j' => [
581            0x0C, 0x0C, 0x00, 0x0C, 0x0C, 0x0C, 0x0C, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
582        ],
583        'k' => [
584            0xC0, 0xC0, 0xCC, 0xD8, 0xF0, 0xD8, 0xCC, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
585        ],
586        'l' => [
587            0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00,
588        ],
589        'm' => [
590            0x00, 0x00, 0xEC, 0xFE, 0xD6, 0xD6, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0x00, 0x00,
591        ],
592        'n' => [
593            0x00, 0x00, 0xDC, 0xE6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
594        ],
595        'o' => [
596            0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
597        ],
598        'p' => [
599            0x00, 0x00, 0xDC, 0xE6, 0xC6, 0xE6, 0xDC, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00,
600        ],
601        'q' => [
602            0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x00,
603        ],
604        'r' => [
605            0x00, 0x00, 0xDC, 0xE6, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00,
606        ],
607        's' => [
608            0x00, 0x00, 0x7C, 0xC6, 0x70, 0x1C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
609        ],
610        't' => [
611            0x00, 0x30, 0xFC, 0x30, 0x30, 0x30, 0x36, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00,
612        ],
613        'u' => [
614            0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00,
615        ],
616        'v' => [
617            0x00, 0x00, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
618        ],
619        'w' => [
620            0x00, 0x00, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00,
621        ],
622        'x' => [
623            0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00,
624        ],
625        'y' => [
626            0x00, 0x00, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
627        ],
628        'z' => [
629            0x00, 0x00, 0xFE, 0x0C, 0x18, 0x30, 0x60, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
630        ],
631        '{' => [
632            0x0E, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00,
633        ],
634        '|' => [
635            0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
636        ],
637        '}' => [
638            0x70, 0x18, 0x18, 0x0E, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00,
639        ],
640        '~' => [
641            0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
642        ],
643        _ => NOTDEF_ROWS,
644    }
645    // clang-format on
646}
647
648impl Default for FontAtlas {
649    fn default() -> Self {
650        Self::built_in()
651    }
652}
653
654impl std::fmt::Debug for FontAtlas {
655    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
656        f.debug_struct("FontAtlas")
657            .field("glyph_count", &self.len())
658            .field("texture_size", &self.texture_size)
659            .finish()
660    }
661}
662
663// ---------------------------------------------------------------------------
664// Tests
665// ---------------------------------------------------------------------------
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670
671    #[test]
672    fn built_in_atlas_has_ascii_plus_notdef() {
673        let atlas = FontAtlas::built_in();
674        assert_eq!(atlas.len(), GLYPH_COUNT);
675        assert_eq!(GLYPH_COUNT, ASCII_GLYPH_COUNT + 1);
676    }
677
678    #[test]
679    fn space_glyph_has_zero_width() {
680        let atlas = FontAtlas::built_in();
681        let g = atlas.glyph(' ');
682        assert_eq!(g.width, 0);
683        assert!((g.advance - GLYPH_ADVANCE).abs() < 0.001);
684    }
685
686    #[test]
687    fn letter_a_has_positive_width() {
688        let atlas = FontAtlas::built_in();
689        let g = atlas.glyph('A');
690        assert_eq!(g.width, GLYPH_WIDTH);
691        assert_eq!(g.height, GLYPH_HEIGHT);
692    }
693
694    #[test]
695    fn out_of_range_char_returns_notdef() {
696        let atlas = FontAtlas::built_in();
697        // Control characters, and anything past ASCII 126, get the box.
698        for c in ['\0', '\u{7f}', 'é', '€', 'Ł', 'ġ'] {
699            assert_eq!(glyph_index(c), NOTDEF_INDEX, "{c:?} should be .notdef");
700            let g = atlas.glyph(c);
701            assert_eq!(g.width, GLYPH_WIDTH, "{c:?} should draw the box");
702        }
703    }
704
705    /// The bug: `(c as u8)` kept only the low byte, so U+0141 rendered `'A'`
706    /// (U+0041) and U+0121 rendered `'!'` (U+0021).
707    #[test]
708    fn non_ascii_does_not_alias_onto_an_ascii_glyph() {
709        let atlas = FontAtlas::built_in();
710        assert_ne!(atlas.glyph_u_min('Ł'), atlas.glyph_u_min('A'));
711        assert_ne!(atlas.glyph_u_min('ġ'), atlas.glyph_u_min('!'));
712    }
713
714    /// Out-of-range codepoints used to produce `u_min > 1.0`, which samples
715    /// outside the atlas.
716    #[test]
717    fn glyph_uvs_stay_inside_the_atlas_for_any_codepoint() {
718        let atlas = FontAtlas::built_in();
719        for c in ['\0', 'é', '€', 'Ł', '\u{10ffff}', 'A', ' ', '~'] {
720            let (u_min, u_max) = (atlas.glyph_u_min(c), atlas.glyph_u_max(c));
721            assert!(
722                (0.0..=1.0).contains(&u_min) && (0.0..=1.0).contains(&u_max) && u_min < u_max,
723                "{c:?}: u range {u_min}..{u_max} escapes the atlas"
724            );
725        }
726    }
727
728    #[test]
729    fn text_width_single_char() {
730        let atlas = FontAtlas::built_in();
731        let w = atlas.text_width("A", 1.0);
732        assert!((w - GLYPH_ADVANCE).abs() < 0.001);
733    }
734
735    #[test]
736    fn text_width_multiple_chars() {
737        let atlas = FontAtlas::built_in();
738        let w = atlas.text_width("ABC", 1.0);
739        assert!((w - GLYPH_ADVANCE * 3.0).abs() < 0.001);
740    }
741
742    #[test]
743    fn text_width_scales_linearly_with_the_scale_it_is_given() {
744        let atlas = FontAtlas::built_in();
745        let w1 = atlas.text_width("Hi", 1.0);
746        let w2 = atlas.text_width("Hi", 2.0);
747        assert!((w2 - w1 * 2.0).abs() < 0.001);
748    }
749
750    #[test]
751    fn layout_line_produces_glyphs() {
752        let atlas = FontAtlas::built_in();
753        let glyphs = atlas.layout_line("AB", Vec2::ZERO, 1.0);
754        assert_eq!(glyphs.len(), 2);
755        // 'A' should start after bearing_x.
756        assert!((glyphs[0].1.x - 1.0).abs() < 0.001);
757        // The horizontal advance between glyphs should be GLYPH_ADVANCE.
758        assert!(
759            (glyphs[1].1.x - glyphs[0].1.x - GLYPH_ADVANCE).abs() < 0.001,
760            "expected horizontal advance {}, got {}",
761            GLYPH_ADVANCE,
762            glyphs[1].1.x - glyphs[0].1.x,
763        );
764    }
765
766    /// The bug: `min`/`max` were multiplied by `scale` on top of a `cursor`
767    /// that already carried `pos` plus a scaled advance, so the position came
768    /// out as `pos.x * scale + i * advance * scale²` — the anchor moved with
769    /// the font size and the advance scaled twice.
770    #[test]
771    fn layout_line_scales_extents_but_not_the_anchor() {
772        let atlas = FontAtlas::built_in();
773        let glyphs = atlas.layout_line("AB", Vec2::new(100.0, 200.0), 2.0);
774        assert_eq!(glyphs.len(), 2);
775
776        // First glyph: x = 100 + bearing_x(1) * 2, y = 200 (top of the em box,
777        // since bearing_y == ASCENDER for every glyph in this font).
778        assert!((glyphs[0].1.x - 102.0).abs() < 0.001, "{:?}", glyphs[0].1);
779        assert!((glyphs[0].1.y - 200.0).abs() < 0.001, "{:?}", glyphs[0].1);
780        // Extents scale exactly once: 8×13 at 2.0 → 16×26.
781        assert!((glyphs[0].2.x - glyphs[0].1.x - 16.0).abs() < 0.001);
782        assert!((glyphs[0].2.y - glyphs[0].1.y - 26.0).abs() < 0.001);
783        // Advance scales exactly once: 10 → 20, not 40.
784        assert!(
785            (glyphs[1].1.x - glyphs[0].1.x - GLYPH_ADVANCE * 2.0).abs() < 0.001,
786            "advance scaled twice: {}",
787            glyphs[1].1.x - glyphs[0].1.x
788        );
789    }
790
791    /// `pos` is the top-left anchor of the em box, not a baseline: a glyph must
792    /// never be laid out above the position it was asked for.
793    #[test]
794    fn layout_line_anchor_is_the_top_left_not_the_baseline() {
795        let atlas = FontAtlas::built_in();
796        let pos = Vec2::new(10.0, 100.0);
797        for scale in [0.5, 1.0, 2.0] {
798            let glyphs = atlas.layout_line("Hi", pos, scale);
799            for (c, min, max) in glyphs {
800                assert!(min.y >= pos.y - 0.001, "{c:?} at scale {scale}: {min:?}");
801                assert!(
802                    max.y <= pos.y + LINE_HEIGHT * scale + 0.001,
803                    "{c:?} at scale {scale}: {max:?}"
804                );
805            }
806        }
807    }
808
809    #[test]
810    fn layout_line_handles_newline() {
811        let atlas = FontAtlas::built_in();
812        let glyphs = atlas.layout_line("A\nB", Vec2::ZERO, 1.0);
813        assert_eq!(glyphs.len(), 2);
814        // The vertical advance between lines should be LINE_HEIGHT.
815        assert!(
816            (glyphs[1].1.y - glyphs[0].1.y - LINE_HEIGHT).abs() < 0.001,
817            "expected vertical advance {}, got {}",
818            LINE_HEIGHT,
819            glyphs[1].1.y - glyphs[0].1.y,
820        );
821    }
822
823    #[test]
824    fn empty_string_layout_is_empty() {
825        let atlas = FontAtlas::built_in();
826        let glyphs = atlas.layout_line("", Vec2::ZERO, 1.0);
827        assert!(glyphs.is_empty());
828    }
829
830    #[test]
831    fn text_width_of_multiline_is_the_widest_line() {
832        let atlas = FontAtlas::built_in();
833        // Not 5 * advance: the two lines are measured separately.
834        let w = atlas.text_width("AB\nCDE", 1.0);
835        assert!(
836            (w - GLYPH_ADVANCE * 3.0).abs() < 0.001,
837            "expected the widest line ({}), got {w}",
838            GLYPH_ADVANCE * 3.0
839        );
840        assert_eq!(atlas.line_count("AB\nCDE"), 2);
841        assert_eq!(atlas.line_count("one line"), 1);
842    }
843
844    #[test]
845    fn the_font_atlas_debug_output_reports_its_glyph_count() {
846        let atlas = FontAtlas::built_in();
847        let s = format!("{atlas:?}");
848        assert!(s.contains(&format!("glyph_count: {GLYPH_COUNT}")));
849    }
850
851    #[test]
852    fn glyph_u_min_for_first_char_is_zero() {
853        let atlas = FontAtlas::built_in();
854        // ' ' is the first glyph, at column 0.
855        let u = atlas.glyph_u_min(' ');
856        assert!((u - 0.0).abs() < 0.001);
857    }
858
859    #[test]
860    fn glyph_u_max_for_the_notdef_column_is_one() {
861        let atlas = FontAtlas::built_in();
862        // `.notdef` is the last column, so any unmapped codepoint ends the atlas.
863        let u = atlas.glyph_u_max('€');
864        assert!((u - 1.0).abs() < 0.001, "got {u}");
865        // '~' is the last *ASCII* glyph, one column before it.
866        let u = atlas.glyph_u_max('~');
867        assert!(
868            (u - ASCII_GLYPH_COUNT as f32 / GLYPH_COUNT as f32).abs() < 0.001,
869            "got {u}"
870        );
871    }
872
873    #[test]
874    fn glyph_u_for_letter_a_is_contiguous() {
875        let atlas = FontAtlas::built_in();
876        let u_max = atlas.glyph_u_max('A'); // column 33
877        let u_min_b = atlas.glyph_u_min('B'); // column 34
878        assert!((u_max - u_min_b).abs() < 0.001);
879    }
880}