beamterm_data/
glyph.rs

1use compact_str::{CompactString, ToCompactString};
2
3/// Represents a single character glyph in a font atlas texture.
4///
5/// A `Glyph` contains the metadata needed to locate and identify a character
6/// within a font atlas texture. Each glyph has a unique ID that maps
7/// to its coordinates in a WebGL `TEXTURE_2D_ARRAY`.
8///
9/// # ASCII Optimization
10/// For ASCII characters, the glyph ID directly corresponds to the character's
11/// ASCII value, enabling fast lookups without hash table lookups. Non-ASCII
12/// characters are assigned sequential IDs starting from a base value.
13///
14/// # Glyph ID Bit Layout (16-bit)
15///
16/// | Bit(s) | Flag Name     | Hex Mask | Binary Mask           | Description               |
17/// |--------|---------------|----------|-----------------------|---------------------------|
18/// | 0-9    | GLYPH_ID      | `0x03FF` | `0000_0011_1111_1111` | Base glyph identifier     |
19/// | 10     | BOLD          | `0x0400` | `0000_0100_0000_0000` | Bold font style           |
20/// | 11     | ITALIC        | `0x0800` | `0000_1000_0000_0000` | Italic font style         |
21/// | 12     | EMOJI         | `0x1000` | `0001_0000_0000_0000` | Emoji character flag      |
22/// | 13     | UNDERLINE     | `0x2000` | `0010_0000_0000_0000` | Underline effect          |
23/// | 14     | STRIKETHROUGH | `0x4000` | `0100_0000_0000_0000` | Strikethrough effect      |
24/// | 15     | RESERVED      | `0x8000` | `1000_0000_0000_0000` | Reserved for future use   |
25///
26/// - The first 10 bits (0-9) represent the base glyph ID, allowing for 1024 unique glyphs.
27/// - Emoji glyphs implicitly clear any other font style bits.
28/// - The fragment shader uses the glyph ID to decode the texture coordinates and effects.
29///
30/// ## Glyph ID Encoding Examples
31///
32/// | Character   | Style            | Binary Representation | Hex Value | Description         |
33/// |-------------|------------------|-----------------------|-----------|---------------------|
34/// | 'A' (0x41)  | Normal           | `0000_0000_0100_0001` | `0x0041`  | Plain 'A'           |
35/// | 'A' (0x41)  | Bold             | `0000_0100_0100_0001` | `0x0441`  | Bold 'A'            |
36/// | 'A' (0x41)  | Bold + Italic    | `0000_1100_0100_0001` | `0x0C41`  | Bold italic 'A'     |
37/// | 'A' (0x41)  | Bold + Underline | `0010_0100_0100_0001` | `0x2441`  | Bold underlined 'A' |
38/// | '🚀' (0x81) | Emoji            | `0001_0000_1000_0001` | `0x1081`  | "rocket" emoji      |
39#[derive(Debug, Eq, Clone, PartialEq)]
40pub struct Glyph {
41    /// The glyph ID; encodes the 3d texture coordinates
42    pub id: u16,
43    /// The style of the glyph, e.g., bold, italic
44    pub style: FontStyle,
45    /// The character
46    pub symbol: CompactString,
47    /// The pixel coordinates of the glyph in the texture
48    pub pixel_coords: (i32, i32),
49    /// Indicates if the glyph is an emoji
50    pub is_emoji: bool,
51}
52
53#[rustfmt::skip]
54impl Glyph {
55    /// The ID is used as a short-lived placeholder until the actual ID is assigned.
56    pub const UNASSIGNED_ID: u16 = 0xFFFF;
57
58    /// Glyph ID mask - extracts the base glyph identifier (bits 0-9).
59    /// Supports 1024 unique base glyphs (0x000 to 0x3FF) in the texture atlas.
60    pub const GLYPH_ID_MASK: u16       = 0b0000_0011_1111_1111; // 0x03FF
61    /// Glyph ID mask for emoji - extracts the base glyph identifier (bits 0-11).
62    /// Supports 2048 emoji glyphs (0x000 to 0xFFF) occupying two slots each in the texture atlas.
63    pub const GLYPH_ID_EMOJI_MASK: u16 = 0b0001_1111_1111_1111; // 0x1FFF
64    /// Bold flag - selects the bold variant of the glyph from the texture atlas.
65    pub const BOLD_FLAG: u16           = 0b0000_0100_0000_0000; // 0x0400
66    /// Italic flag - selects the italic variant of the glyph from the texture atlas.
67    pub const ITALIC_FLAG: u16         = 0b0000_1000_0000_0000; // 0x0800
68    /// Emoji flag - indicates this glyph represents an emoji character requiring special handling.
69    pub const EMOJI_FLAG: u16          = 0b0001_0000_0000_0000; // 0x1000
70    /// Underline flag - renders a horizontal line below the character baseline.
71    pub const UNDERLINE_FLAG: u16      = 0b0010_0000_0000_0000; // 0x2000
72    /// Strikethrough flag - renders a horizontal line through the middle of the character.
73    pub const STRIKETHROUGH_FLAG: u16  = 0b0100_0000_0000_0000; // 0x4000
74}
75
76impl Glyph {
77    /// Creates a new glyph with the specified symbol and pixel coordinates.
78    pub fn new(symbol: &str, style: FontStyle, pixel_coords: (i32, i32)) -> Self {
79        let first_char = symbol.chars().next().unwrap();
80        let id = if symbol.len() == 1 && first_char.is_ascii() {
81            // Use a different ID for non-ASCII characters
82            first_char as u16 | style.style_mask()
83        } else {
84            Self::UNASSIGNED_ID
85        };
86
87        Self {
88            id,
89            symbol: symbol.to_compact_string(),
90            style,
91            pixel_coords,
92            is_emoji: false,
93        }
94    }
95
96    pub fn new_with_id(
97        base_id: u16,
98        symbol: &str,
99        style: FontStyle,
100        pixel_coords: (i32, i32),
101    ) -> Self {
102        Self {
103            id: base_id | style.style_mask(),
104            symbol: symbol.to_compact_string(),
105            style,
106            pixel_coords,
107            is_emoji: (base_id & Self::EMOJI_FLAG) != 0,
108        }
109    }
110
111    pub fn new_emoji(base_id: u16, symbol: &str, pixel_coords: (i32, i32)) -> Self {
112        Self {
113            id: base_id | Self::EMOJI_FLAG,
114            symbol: symbol.to_compact_string(),
115            style: FontStyle::Normal, // Emoji glyphs do not have style variants
116            pixel_coords,
117            is_emoji: true,
118        }
119    }
120
121    /// Returns true if this glyph represents a single ASCII character.
122    pub fn is_ascii(&self) -> bool {
123        self.symbol.len() == 1 && self.symbol.chars().next().unwrap().is_ascii()
124    }
125
126    /// Returns the base glyph ID without style flags.
127    ///
128    /// For non-emoji glyphs, this masks off the style bits (bold/italic) using
129    /// [`GLYPH_ID_MASK`](Self::GLYPH_ID_MASK) to extract just the base identifier (bits 0-9).
130    /// For emoji glyphs, returns the full ID since emoji don't use style variants.
131    ///
132    /// # Examples
133    ///
134    /// ```
135    /// use beamterm_data::{Glyph, FontStyle};
136    ///
137    /// // Bold 'A' (0x0441) -> base ID 0x41
138    /// let bold_a = Glyph::new_with_id(0x41, "A", FontStyle::Bold, (0, 0));
139    /// assert_eq!(bold_a.id, 0x441);
140    /// assert_eq!(bold_a.base_id(), 0x041);
141    ///
142    /// // Emoji retains full ID
143    /// let emoji = Glyph::new_emoji(0x00, "🚀", (0, 0));
144    /// assert_eq!(emoji.base_id(), 0x1000); // includes EMOJI_FLAG
145    /// ```
146    pub fn base_id(&self) -> u16 {
147        if self.is_emoji {
148            self.id & Self::GLYPH_ID_EMOJI_MASK
149        } else {
150            self.id & Self::GLYPH_ID_MASK
151        }
152    }
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum GlyphEffect {
157    /// No special effect applied to the glyph.
158    None = 0x0,
159    /// Underline effect applied below the glyph.
160    Underline = 0x2000,
161    /// Strikethrough effect applied through the glyph.
162    Strikethrough = 0x4000,
163}
164
165impl GlyphEffect {
166    pub fn from_u16(v: u16) -> GlyphEffect {
167        match v {
168            0x0000 => GlyphEffect::None,
169            0x2000 => GlyphEffect::Underline,
170            0x4000 => GlyphEffect::Strikethrough,
171            0x6000 => GlyphEffect::Strikethrough,
172            _ => GlyphEffect::None,
173        }
174    }
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
178pub enum FontStyle {
179    Normal = 0x0000,
180    Bold = 0x0400,
181    Italic = 0x0800,
182    BoldItalic = 0x0C00,
183}
184
185impl FontStyle {
186    pub const MASK: u16 = 0x0C00;
187
188    pub const ALL: [FontStyle; 4] =
189        [FontStyle::Normal, FontStyle::Bold, FontStyle::Italic, FontStyle::BoldItalic];
190
191    pub fn from_u16(v: u16) -> FontStyle {
192        match v {
193            0x0000 => FontStyle::Normal,
194            0x0400 => FontStyle::Bold,
195            0x0800 => FontStyle::Italic,
196            0x0C00 => FontStyle::BoldItalic,
197            _ => panic!("Invalid font style value: {v}"),
198        }
199    }
200
201    pub(super) fn from_ordinal(ordinal: u8) -> FontStyle {
202        match ordinal {
203            0 => FontStyle::Normal,
204            1 => FontStyle::Bold,
205            2 => FontStyle::Italic,
206            3 => FontStyle::BoldItalic,
207            _ => panic!("Invalid font style ordinal: {ordinal}"),
208        }
209    }
210
211    pub(super) const fn ordinal(&self) -> usize {
212        match self {
213            FontStyle::Normal => 0,
214            FontStyle::Bold => 1,
215            FontStyle::Italic => 2,
216            FontStyle::BoldItalic => 3,
217        }
218    }
219
220    /// Returns the style bits for this font style, used to encode the style in the glyph ID.
221    pub const fn style_mask(&self) -> u16 {
222        *self as u16
223    }
224}