Skip to main content

sim_engine/text/font/
raster.rs

1use super::*;
2use ab_glyph::{Outline, OutlineCurve, Point, PxScaleFactor, point};
3use rustybuzz::ttf_parser::OutlineBuilder;
4
5/// Grayscale coverage at physical-pixel resolution, relative to baseline zero.
6/// Coverage is linear alpha (0..255), not an sRGB intensity or premultiplied RGB.
7#[derive(Debug)]
8pub struct RasterizedGlyph {
9    width: u32,
10    height: u32,
11    bearing_x: i32,
12    bearing_y: i32,
13    coverage: Vec<u8>,
14}
15
16impl RasterizedGlyph {
17    /// Physical bitmap width; zero for an empty outline such as a space.
18    pub const fn width(&self) -> u32 {
19        self.width
20    }
21    /// Physical bitmap height; zero for an empty outline such as a space.
22    pub const fn height(&self) -> u32 {
23        self.height
24    }
25    /// Left bitmap edge relative to the physical baseline origin; may be negative.
26    pub const fn bearing_x(&self) -> i32 {
27        self.bearing_x
28    }
29    /// Top bitmap edge relative to the physical baseline origin, positive downward.
30    pub const fn bearing_y(&self) -> i32 {
31        self.bearing_y
32    }
33    /// Row-major linear alpha, exactly width times height bytes.
34    pub fn coverage(&self) -> &[u8] {
35        &self.coverage
36    }
37    /// Owned coverage Vec capacity in bytes.
38    pub fn allocation_bytes(&self) -> usize {
39        self.coverage.capacity()
40    }
41}
42
43pub(super) fn rasterize(
44    font: &FontFace,
45    glyph_id: u16,
46    style: &TextStyle,
47    budget: &TextLayoutBudget,
48) -> Result<RasterizedGlyph, FontError> {
49    if usize::from(glyph_id) >= font.glyph_count {
50        return Err(FontError::InvalidGlyph { glyph_id });
51    }
52    let face = rustybuzz::ttf_parser::Face::parse(font.font_data(), 0)
53        .map_err(|_| FontError::InvalidFont)?;
54    let factor =
55        style.physical_em_size() / font.font.units_per_em().ok_or(FontError::InvalidFont)?;
56    if !factor.is_normal() || factor <= 0.0 {
57        return Err(FontError::InvalidScale);
58    }
59    let id = rustybuzz::ttf_parser::GlyphId(glyph_id);
60    if face.is_color_glyph(id) || face.glyph_svg_image(id).is_some() {
61        return Err(FontError::UnsupportedGlyph { glyph_id });
62    }
63    let mut counter = OutlineSink::new(factor, budget.max_outline_segments());
64    let bounds = face.outline_glyph(id, &mut counter);
65    counter.finish();
66    check(
67        FontBudgetResource::OutlineSegments,
68        counter.commands,
69        budget.max_outline_segments(),
70    )?;
71    if !counter.valid {
72        return Err(FontError::InvalidGeometry);
73    }
74    let Some(bounds) = bounds else {
75        if face.glyph_raster_image(id, u16::MAX).is_some() {
76            return Err(FontError::UnsupportedGlyph { glyph_id });
77        }
78        if counter.commands != 0 {
79            return Err(FontError::InvalidFont);
80        }
81        return Ok(RasterizedGlyph {
82            width: 0,
83            height: 0,
84            bearing_x: 0,
85            bearing_y: 0,
86            coverage: Vec::new(),
87        });
88    };
89    let scale_factor = PxScaleFactor {
90        horizontal: factor,
91        vertical: factor,
92    };
93    let mut outline = Outline {
94        bounds: ab_glyph::Rect {
95            min: point(f32::from(bounds.x_min), f32::from(bounds.y_max)),
96            max: point(f32::from(bounds.x_max), f32::from(bounds.y_min)),
97        },
98        curves: Vec::new(),
99    };
100    let pixels = outline.px_bounds(scale_factor, point(0.0, 0.0));
101    let left = pixel_coordinate(pixels.min.x)?;
102    let top = pixel_coordinate(pixels.min.y)?;
103    let right = pixel_coordinate(pixels.max.x)?;
104    let bottom = pixel_coordinate(pixels.max.y)?;
105    let width = u32::try_from(i64::from(right) - i64::from(left))
106        .map_err(|_| FontError::InvalidGeometry)?;
107    let height = u32::try_from(i64::from(bottom) - i64::from(top))
108        .map_err(|_| FontError::InvalidGeometry)?;
109    let count = (width as usize)
110        .checked_mul(height as usize)
111        .ok_or(FontError::InvalidGeometry)?;
112    check(
113        FontBudgetResource::GlyphPixels,
114        count,
115        budget.max_glyph_pixels(),
116    )?;
117    // ab_glyph_rasterizer uses count+4 f32 cells. Check its arithmetic as well
118    // as the public u8 payload before handing it the dimensions.
119    count
120        .checked_add(4)
121        .and_then(|cells| cells.checked_mul(std::mem::size_of::<f32>()))
122        .filter(|bytes| *bytes <= isize::MAX as usize)
123        .ok_or(FontError::InvalidGeometry)?;
124    if width == 0 || height == 0 {
125        return Ok(RasterizedGlyph {
126            width: 0,
127            height: 0,
128            bearing_x: left,
129            bearing_y: top,
130            coverage: Vec::new(),
131        });
132    }
133    let mut sink = OutlineSink::new(factor, counter.commands);
134    reserve(&mut sink.curves, counter.commands)?;
135    sink.collect = true;
136    let second_bounds = face.outline_glyph(id, &mut sink);
137    sink.finish();
138    if !sink.valid || sink.commands != counter.commands || second_bounds != Some(bounds) {
139        return Err(FontError::InvalidFont);
140    }
141    outline.curves = sink.curves;
142    let mut coverage = Vec::new();
143    reserve(&mut coverage, count)?;
144    coverage.resize(count, 0);
145    let glyph = ab_glyph::Glyph {
146        id: ab_glyph::GlyphId(glyph_id),
147        scale: ab_glyph::PxScale::from(style.physical_em_size()),
148        position: point(0.0, 0.0),
149    };
150    // OutlinedGlyph's explicit scale factor is font-units -> pixels. PxScale's
151    // font-height convention must not be mistaken for the API's em convention.
152    let outlined = ab_glyph::OutlinedGlyph::new(glyph, outline, scale_factor);
153    let mut valid = true;
154    outlined.draw(|x, y, alpha| {
155        if !alpha.is_finite() || x >= width || y >= height {
156            valid = false;
157            return;
158        }
159        coverage[y as usize * width as usize + x as usize] =
160            (alpha.clamp(0.0, 1.0) * 255.0).round() as u8;
161    });
162    if !valid {
163        return Err(FontError::InvalidGeometry);
164    }
165    Ok(RasterizedGlyph {
166        width,
167        height,
168        bearing_x: left,
169        bearing_y: top,
170        coverage,
171    })
172}
173
174fn pixel_coordinate(value: f32) -> Result<i32, FontError> {
175    if !value.is_finite()
176        || f64::from(value) < f64::from(i32::MIN)
177        || f64::from(value) > f64::from(i32::MAX)
178    {
179        Err(FontError::InvalidGeometry)
180    } else {
181        Ok(value as i32)
182    }
183}
184
185/// The first traversal counts commands and checks coordinates without allocating
186/// curves. The second writes only into reserved storage. Dependency traversal
187/// itself cannot be interrupted through OutlineBuilder and is not a CPU sandbox.
188struct OutlineSink {
189    factor: f32,
190    limit: usize,
191    commands: usize,
192    curves: Vec<OutlineCurve>,
193    collect: bool,
194    valid: bool,
195    last: Point,
196    start: Option<Point>,
197}
198
199impl OutlineSink {
200    fn new(factor: f32, limit: usize) -> Self {
201        Self {
202            factor,
203            limit,
204            commands: 0,
205            curves: Vec::new(),
206            collect: false,
207            valid: true,
208            last: point(0.0, 0.0),
209            start: None,
210        }
211    }
212    fn command(&mut self) {
213        self.commands = self.commands.saturating_add(1);
214    }
215    fn position(&mut self, x: f32, y: f32) -> Point {
216        self.valid &= [x, y].into_iter().all(|value| {
217            value.is_finite()
218                && (f64::from(value) * f64::from(self.factor)).abs() < f64::from(i32::MAX)
219        });
220        point(x, y)
221    }
222    fn curve(&mut self, curve: OutlineCurve) {
223        if self.collect {
224            if self.commands <= self.limit && self.curves.len() < self.curves.capacity() {
225                self.curves.push(curve);
226            } else {
227                self.valid = false;
228            }
229        }
230    }
231    fn finish(&mut self) {
232        if self.start.is_some() {
233            self.close();
234        }
235    }
236}
237
238impl OutlineBuilder for OutlineSink {
239    fn move_to(&mut self, x: f32, y: f32) {
240        self.command();
241        self.last = self.position(x, y);
242        self.start = Some(self.last);
243    }
244    fn line_to(&mut self, x: f32, y: f32) {
245        self.command();
246        let end = self.position(x, y);
247        self.curve(OutlineCurve::Line(self.last, end));
248        self.last = end;
249    }
250    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
251        self.command();
252        let control = self.position(x1, y1);
253        let end = self.position(x, y);
254        self.curve(OutlineCurve::Quad(self.last, control, end));
255        self.last = end;
256    }
257    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
258        self.command();
259        let control1 = self.position(x1, y1);
260        let control2 = self.position(x2, y2);
261        let end = self.position(x, y);
262        self.curve(OutlineCurve::Cubic(self.last, control1, control2, end));
263        self.last = end;
264    }
265    fn close(&mut self) {
266        if let Some(start) = self.start.take() {
267            self.command();
268            self.curve(OutlineCurve::Line(self.last, start));
269        }
270    }
271}