Skip to main content

beamterm_data/
glyph.rs

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