Skip to main content

sim_engine/text/
font.rs

1//! Single-font horizontal shaping and bounded grayscale outline rasterization.
2
3use ab_glyph::Font;
4
5mod config;
6mod raster;
7#[cfg(test)]
8mod tests;
9pub use config::{
10    FontBudget, FontBudgetResource, FontError, TextDirection, TextLayoutBudget, TextStyle,
11};
12use config::{check, reserve};
13pub use raster::RasterizedGlyph;
14
15/// One owned TTF/OpenType outline face (collection index zero).
16///
17/// Source bytes are retained once inside ab_glyph; rustybuzz borrows those bytes
18/// while shaping. The source Vec capacity is checked before parsing. Font
19/// discovery, fallback selection, variable-font axes, color/bitmap glyphs,
20/// wrapping and bidi paragraph layout are outside this API.
21/// Cloning shares the original bytes and parsed font without copying them.
22#[derive(Debug, Clone)]
23pub struct FontFace {
24    font: std::sync::Arc<ab_glyph::FontVec>,
25    source_capacity: usize,
26    glyph_count: usize,
27}
28
29impl FontFace {
30    /// Loads already-read TTF/OTF bytes without duplicating their backing storage.
31    /// The caller owns filesystem/network I/O and font licensing.
32    pub fn from_bytes(bytes: Vec<u8>, budget: FontBudget) -> Result<Self, FontError> {
33        check(
34            FontBudgetResource::FontBytes,
35            bytes.capacity(),
36            budget.max_font_bytes(),
37        )?;
38        let face =
39            rustybuzz::ttf_parser::Face::parse(&bytes, 0).map_err(|_| FontError::InvalidFont)?;
40        let tables = face.tables();
41        if tables.glyf.is_none() && tables.cff.is_none() && tables.cff2.is_none() {
42            return Err(FontError::InvalidFont);
43        }
44        let glyph_count = usize::from(face.number_of_glyphs());
45        check(
46            FontBudgetResource::FontGlyphs,
47            glyph_count,
48            budget.max_font_glyphs(),
49        )?;
50        if face.units_per_em() == 0 || face.ascender() <= face.descender() {
51            return Err(FontError::InvalidFont);
52        }
53        let source_capacity = bytes.capacity();
54        let font = ab_glyph::FontVec::try_from_vec(bytes).map_err(|_| FontError::InvalidFont)?;
55        Ok(Self {
56            font: std::sync::Arc::new(font),
57            source_capacity,
58            glyph_count,
59        })
60    }
61
62    /// Original font bytes, borrowed without an additional owned copy.
63    pub fn font_data(&self) -> &[u8] {
64        self.font.as_slice()
65    }
66    /// Source Vec capacity referenced by this handle; clones share it.
67    /// Dependency-parsed metadata is excluded.
68    pub const fn allocation_bytes(&self) -> usize {
69        self.source_capacity
70    }
71    /// Number of font-local glyph identifiers, including the missing-glyph entry.
72    pub const fn glyph_count(&self) -> usize {
73        self.glyph_count
74    }
75
76    /// Shapes a horizontal single-script directional run at baseline `(0, 0)`.
77    ///
78    /// Positions/advances use logical pixels, with positive y downward. Kerning,
79    /// ligatures and combining-mark offsets come from rustybuzz/OpenType tables.
80    /// Auto infers one direction/script, not a mixed-direction bidi paragraph.
81    /// Newlines, controls and missing glyphs return errors; spaces retain advance.
82    /// DPI changes raster resolution, not logical layout or kerning decisions.
83    pub fn shape_line(
84        &self,
85        text: &str,
86        style: &TextStyle,
87        budget: &TextLayoutBudget,
88    ) -> Result<ShapedLine, FontError> {
89        check(
90            FontBudgetResource::TextBytes,
91            text.len(),
92            budget.max_text_bytes().min(u32::MAX as usize),
93        )?;
94        for (byte_index, character) in text.char_indices() {
95            if character.is_control() || matches!(character, '\u{2028}' | '\u{2029}') {
96                return Err(FontError::UnsupportedText { byte_index });
97            }
98        }
99        let face =
100            rustybuzz::Face::from_slice(self.font.as_slice(), 0).ok_or(FontError::InvalidFont)?;
101        let factor = f64::from(style.logical_em_size().get()) / f64::from(face.units_per_em());
102        let ascent = represent(f64::from(face.ascender()) * factor)?;
103        let descent = represent(f64::from(face.descender()) * factor)?;
104        let line_height = represent(
105            (f64::from(face.ascender()) - f64::from(face.descender()) + f64::from(face.line_gap()))
106                * factor,
107        )?;
108        if line_height <= 0.0 {
109            return Err(FontError::InvalidFont);
110        }
111        let mut input = rustybuzz::UnicodeBuffer::new();
112        input.push_str(text);
113        match style.direction() {
114            TextDirection::Auto => {}
115            TextDirection::Ltr => input.set_direction(rustybuzz::Direction::LeftToRight),
116            TextDirection::Rtl => input.set_direction(rustybuzz::Direction::RightToLeft),
117        }
118        input.guess_segment_properties();
119        let output = rustybuzz::shape(&face, &[], input);
120        check(
121            FontBudgetResource::ShapedGlyphs,
122            output.len(),
123            budget.max_shaped_glyphs(),
124        )?;
125        let mut glyphs = Vec::new();
126        reserve(&mut glyphs, output.len())?;
127        let mut pen_x = 0.0f64;
128        let mut pen_y = 0.0f64;
129        for (information, position) in output.glyph_infos().iter().zip(output.glyph_positions()) {
130            if information.glyph_id == 0 {
131                return Err(FontError::MissingGlyph {
132                    byte_index: information.cluster as usize,
133                });
134            }
135            let glyph_id =
136                u16::try_from(information.glyph_id).map_err(|_| FontError::InvalidGeometry)?;
137            glyphs.push(ShapedGlyph {
138                glyph_id,
139                logical_x: represent((pen_x + f64::from(position.x_offset)) * factor)?,
140                logical_y: represent(-(pen_y + f64::from(position.y_offset)) * factor)?,
141                cluster: information.cluster as usize,
142            });
143            pen_x += f64::from(position.x_advance);
144            pen_y += f64::from(position.y_advance);
145        }
146        Ok(ShapedLine {
147            glyphs,
148            advance: represent(pen_x * factor)?,
149            ascent,
150            descent,
151            line_height,
152        })
153    }
154
155    /// Rasterizes one glyph at physical em size and baseline `(0, 0)`.
156    /// Outlines are preflighted without allocating curves; pixel bounds and
157    /// command counts are checked before bounded curve and coverage allocations.
158    /// No hinting or subpixel-position variants are applied. Empty outlines
159    /// (for example spaces) return an empty bitmap, not a missing-glyph error.
160    pub fn rasterize_glyph(
161        &self,
162        glyph_id: u16,
163        style: &TextStyle,
164        budget: &TextLayoutBudget,
165    ) -> Result<RasterizedGlyph, FontError> {
166        raster::rasterize(self, glyph_id, style, budget)
167    }
168}
169
170/// A shaped glyph's font-local identity and baseline-relative logical placement.
171#[derive(Debug, Clone, Copy, PartialEq)]
172pub struct ShapedGlyph {
173    glyph_id: u16,
174    logical_x: f32,
175    logical_y: f32,
176    cluster: usize,
177}
178
179impl ShapedGlyph {
180    /// Identifier in the FontFace that produced this line.
181    pub const fn glyph_id(self) -> u16 {
182        self.glyph_id
183    }
184    /// Baseline-relative horizontal origin, in logical pixels.
185    pub const fn logical_x(self) -> f32 {
186        self.logical_x
187    }
188    /// Baseline-relative vertical origin, in logical pixels, positive downward.
189    pub const fn logical_y(self) -> f32 {
190        self.logical_y
191    }
192    /// Original UTF-8 byte offset associated with this shaped cluster.
193    pub const fn cluster(self) -> usize {
194        self.cluster
195    }
196}
197
198/// Immutable shaped placement; rasterization and GPU ownership are separate.
199#[derive(Debug)]
200pub struct ShapedLine {
201    glyphs: Vec<ShapedGlyph>,
202    advance: f32,
203    ascent: f32,
204    descent: f32,
205    line_height: f32,
206}
207
208impl ShapedLine {
209    /// Shaper output order. Drawing this sequence at its offsets preserves marks.
210    pub fn glyphs(&self) -> &[ShapedGlyph] {
211        &self.glyphs
212    }
213    /// Horizontal pen advance in logical pixels, including whitespace.
214    pub const fn advance(&self) -> f32 {
215        self.advance
216    }
217    /// Signed font ascender in logical pixels; normally positive above baseline.
218    pub const fn ascent(&self) -> f32 {
219        self.ascent
220    }
221    /// Signed font descender in logical pixels; normally negative below baseline.
222    pub const fn descent(&self) -> f32 {
223        self.descent
224    }
225    /// Font-recommended line spacing in logical pixels, including line gap.
226    pub const fn line_height(&self) -> f32 {
227        self.line_height
228    }
229    /// Library-owned glyph metadata Vec capacity in bytes.
230    pub fn allocation_bytes(&self) -> usize {
231        self.glyphs
232            .capacity()
233            .saturating_mul(std::mem::size_of::<ShapedGlyph>())
234    }
235}
236
237fn represent(value: f64) -> Result<f32, FontError> {
238    let result = value as f32;
239    if result.is_finite() {
240        Ok(result)
241    } else {
242        Err(FontError::InvalidGeometry)
243    }
244}