Skip to main content

font_shape/
glyph.rs

1//! Glyph rasterization: from a [`font_model`] outline to a coverage bitmap.
2//!
3//! A glyph arrives in font units, y **up**, on a baseline. This module converts
4//! it to device pixels, y **down**, and fills it with the scanline rasteriser.
5//! Everything between the two lives in **26.6 fixed point** — 26 integer bits
6//! and 6 fractional bits, so one pixel is exactly `64`:
7//!
8//! ```
9//! use font_shape::{from_fixed, to_fixed};
10//!
11//! assert_eq!(font_shape::PIXEL, 64);
12//! assert_eq!(to_fixed(1.0), 64);            // one pixel
13//! assert_eq!(to_fixed(0.5), 32);            // half a pixel
14//! assert_eq!(from_fixed(96), 1.5);          // and back
15//! ```
16//!
17//! Fixed point is not decoration: it is what makes a glyph land on the same
18//! pixel grid at 12 pt and at 144 pt, and what makes
19//! [`Hinting::GridFit`] mean "snap to the pixel grid" rather than "round a
20//! float and hope".
21//!
22//! # Scale
23//!
24//! The scale from font units to 26.6 units is
25//! `size_px · 64 / units_per_em`, from [`fixed_scale`]. Everything else in
26//! this module is a multiply by that number.
27//!
28//! ```
29//! use font_shape::fixed_scale;
30//!
31//! // A 1000-units-per-em font at 16 px: one font unit is 16/1000 px.
32//! let s = fixed_scale(16.0, 1000).unwrap();
33//! assert!((s - 16.0 * 64.0 / 1000.0).abs() < 1e-4, "{s}");
34//!
35//! // A zero units-per-em font has no scale at all.
36//! assert!(fixed_scale(16.0, 0).is_err());
37//! ```
38
39use alloc::vec::Vec;
40
41use font_model::{Font, FontMetrics, GlyphId, Outline};
42
43use crate::affine::Affine2D;
44use crate::error::ShapeError;
45use crate::path::{Path2D, PathBuilder};
46use crate::raster::{fill_path, mask_coverage, FillRule, MAX_MASK_ELEMENTS};
47
48/// The number of fractional bits in a 26.6 fixed-point value.
49pub const PIXEL_FP_BITS: u32 = 6;
50
51/// One pixel, in 26.6 fixed point.
52pub const PIXEL: i32 = 1 << PIXEL_FP_BITS;
53
54/// How a glyph's outline is snapped to the pixel grid.
55///
56/// Hinting is a *discretion*, not a default: unhinted rendering is what a
57/// modern rasteriser wants, and grid fitting is what reproduces a bitmap-era
58/// look. Both are offered, and neither is applied behind the caller's back.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum Hinting {
61    /// Leave the outline where the scale puts it. Every edge gets
62    /// antialiased coverage, and a stem that should be 1.3 px wide is 1.3 px
63    /// wide. The default.
64    #[default]
65    None,
66    /// Snap every outline point — control points included — to the nearest
67    /// pixel boundary, and round advances and bearings to whole pixels.
68    ///
69    /// This is a coarse integer-grid fit, not TrueType's interpreter: it snaps
70    /// points, it does not walk instructions. What it buys is crisp stems and
71    /// integer advances at the small sizes where hinting matters.
72    GridFit,
73}
74
75impl Hinting {
76    /// The opposite mode, for a toggle.
77    #[must_use]
78    pub const fn toggled(self) -> Hinting {
79        match self {
80            Hinting::None => Hinting::GridFit,
81            Hinting::GridFit => Hinting::None,
82        }
83    }
84
85    /// True for [`Hinting::GridFit`].
86    #[must_use]
87    pub const fn is_grid_fit(self) -> bool {
88        matches!(self, Hinting::GridFit)
89    }
90}
91
92/// `value` as a 26.6 fixed-point integer, rounded to nearest and saturating.
93///
94/// ```
95/// use font_shape::to_fixed;
96///
97/// assert_eq!(to_fixed(0.0), 0);
98/// assert_eq!(to_fixed(10.0), 640);
99/// assert_eq!(to_fixed(-0.25), -16);
100/// // Non-finite input cannot be represented; it becomes zero rather than a
101/// // wild number that would blow up every later multiply.
102/// assert_eq!(to_fixed(f32::NAN), 0);
103/// assert_eq!(to_fixed(f32::INFINITY), i32::MAX);
104/// ```
105#[must_use]
106pub fn to_fixed(value: f32) -> i32 {
107    if value.is_nan() {
108        return 0;
109    }
110    let scaled = libm::roundf(value * PIXEL as f32);
111    // Saturate rather than wrap: a glyph at 1e9 px is off-screen, not an
112    // integer-overflow bug report.
113    if scaled >= i32::MAX as f32 {
114        return i32::MAX;
115    }
116    if scaled <= i32::MIN as f32 {
117        return i32::MIN;
118    }
119    scaled as i32
120}
121
122/// A value that is *already* in 26.6 units, rounded to the nearest integer.
123///
124/// [`to_fixed`] takes pixels and scales them up; this one takes 26.6 units and
125/// only rounds. [`fixed_scale`] returns a 26.6-per-font-unit factor, so this
126/// is what a scale multiplication must use.
127#[must_use]
128pub fn to_26_6(value: f32) -> i32 {
129    to_fixed(value / PIXEL as f32)
130}
131
132/// A 26.6 fixed-point integer back to pixels.
133///
134/// ```
135/// use font_shape::from_fixed;
136///
137/// assert_eq!(from_fixed(0), 0.0);
138/// assert_eq!(from_fixed(64), 1.0);
139/// assert_eq!(from_fixed(-32), -0.5);
140/// ```
141#[must_use]
142pub fn from_fixed(value: i32) -> f32 {
143    value as f32 / PIXEL as f32
144}
145
146/// Snap a 26.6 value to the nearest pixel boundary.
147///
148/// ```
149/// use font_shape::grid_fit;
150///
151/// assert_eq!(grid_fit(100), 128);   // 1.5625 px -> 2 px
152/// assert_eq!(grid_fit(40), 64);     // 0.625 px  -> 1 px
153/// assert_eq!(grid_fit(30), 0);      // 0.469 px  -> 0 px
154/// ```
155#[must_use]
156pub const fn grid_fit(value: i32) -> i32 {
157    let snapped = if value >= 0 {
158        (value + (PIXEL / 2)) / PIXEL
159    } else {
160        -((-value + (PIXEL / 2)) / PIXEL)
161    };
162    snapped * PIXEL
163}
164
165/// The scale from font units to 26.6 fixed-point units: `size_px · 64 / upem`.
166///
167/// # Errors
168/// [`ShapeError::DegenerateUnitsPerEm`] when `units_per_em` is zero, and
169/// [`ShapeError::InvalidScale`] when `size_px` is zero, negative, NaN, or
170/// infinite — every one of which would produce an empty or infinite glyph.
171///
172/// ```
173/// use font_shape::fixed_scale;
174///
175/// // A 2048-unit em at 24 px: one font unit is 24/2048 px, or 0.75 of a
176/// // 26.6 unit.
177/// let s = fixed_scale(24.0, 2048).unwrap();
178/// assert!((s - 0.75).abs() < 1e-6, "{s}");
179/// ```
180#[allow(clippy::result_large_err)]
181pub fn fixed_scale(size_px: f32, units_per_em: u16) -> Result<f32, ShapeError> {
182    if units_per_em == 0 {
183        return Err(ShapeError::DegenerateUnitsPerEm);
184    }
185    if !size_px.is_finite() || size_px <= 0.0 {
186        return Err(ShapeError::InvalidScale { scale: size_px });
187    }
188    Ok(size_px * PIXEL as f32 / f32::from(units_per_em))
189}
190
191/// A glyph's coverage: 8 bits per pixel, with the placement a caller needs to
192/// put it back into a text run.
193///
194/// ```
195/// use font_shape::{rasterize_outline, GlyphBitmap};
196///
197/// let mut outline = font_model::Outline::new();
198/// let mut p = font_model::Path::starting_at(0.0, 0.0);
199/// p.line_to(1000.0, 0.0);
200/// p.line_to(1000.0, 1000.0);
201/// p.line_to(0.0, 1000.0);
202/// p.close();
203/// outline.push_contour(p);
204///
205/// // A 1000-upem glyph drawn 10 px tall.
206/// let bmp = rasterize_outline(&outline, 1000, 10.0, font_shape::Hinting::None).unwrap();
207/// assert_eq!(bmp.height(), 10);
208/// assert_eq!(bmp.width(), 10);
209/// assert_eq!(bmp.left(), 0);
210/// assert_eq!(bmp.top(), 10, "the ink starts at the baseline");
211/// assert_eq!(bmp.coverage().len(), 100);
212/// // It is a solid 10x10 block, so the ink is the full area.
213/// assert!((bmp.ink() - 100.0).abs() < 1e-6, "{}", bmp.ink());
214/// ```
215#[derive(Debug, Clone, PartialEq, Eq, Default)]
216pub struct GlyphBitmap {
217    width: u32,
218    height: u32,
219    left: i32,
220    top: i32,
221    coverage: Vec<u8>,
222}
223
224impl GlyphBitmap {
225    /// An empty bitmap: no pixels, no ink, at the origin.
226    #[must_use]
227    pub const fn empty() -> Self {
228        GlyphBitmap {
229            width: 0,
230            height: 0,
231            left: 0,
232            top: 0,
233            coverage: Vec::new(),
234        }
235    }
236
237    /// Build from raw parts. The mask must be exactly `width × height` long.
238    #[must_use]
239    pub const fn new(width: u32, height: u32, left: i32, top: i32, coverage: Vec<u8>) -> Self {
240        GlyphBitmap {
241            width,
242            height,
243            left,
244            top,
245            coverage,
246        }
247    }
248
249    /// Width in pixels.
250    #[must_use]
251    pub const fn width(&self) -> u32 {
252        self.width
253    }
254
255    /// Height in pixels.
256    #[must_use]
257    pub const fn height(&self) -> u32 {
258        self.height
259    }
260
261    /// Columns from the pen position to the bitmap's left edge. May be
262    /// negative: a glyph can overhang to the left of its origin.
263    #[must_use]
264    pub const fn left(&self) -> i32 {
265        self.left
266    }
267
268    /// Rows from the baseline up to the bitmap's top edge.
269    #[must_use]
270    pub const fn top(&self) -> i32 {
271        self.top
272    }
273
274    /// The coverage bytes, row-major from the top-left.
275    #[must_use]
276    pub fn coverage(&self) -> &[u8] {
277        &self.coverage
278    }
279
280    /// Consume the bitmap and take its coverage bytes.
281    #[must_use]
282    pub fn into_coverage(self) -> Vec<u8> {
283        self.coverage
284    }
285
286    /// True when there are no pixels at all — a blank glyph, a zero-size
287    /// raster, or a space.
288    #[must_use]
289    pub fn is_empty(&self) -> bool {
290        self.width == 0 || self.height == 0 || self.coverage.is_empty()
291    }
292
293    /// The total ink, in pixels: `coverage / 255` summed.
294    ///
295    /// For a shape this is its area, which is the property
296    /// [`fill_path`](crate::fill_path) is built to hold.
297    #[must_use]
298    pub fn ink(&self) -> f64 {
299        mask_coverage(&self.coverage) / 255.0
300    }
301
302    /// The coverage at `(x, y)`, or `0` outside the bitmap.
303    ///
304    /// ```
305    /// use font_shape::GlyphBitmap;
306    ///
307    /// let b = GlyphBitmap::new(2, 1, 0, 0, vec![10, 200]);
308    /// assert_eq!(b.coverage_at(0, 0), 10);
309    /// assert_eq!(b.coverage_at(1, 0), 200);
310    /// assert_eq!(b.coverage_at(2, 0), 0, "out of bounds reads as empty");
311    /// assert_eq!(b.coverage_at(0, 9), 0);
312    /// ```
313    #[must_use]
314    pub fn coverage_at(&self, x: u32, y: u32) -> u8 {
315        if x >= self.width || y >= self.height {
316            return 0;
317        }
318        let idx = y as usize * self.width as usize + x as usize;
319        self.coverage.get(idx).copied().unwrap_or(0)
320    }
321
322    /// One row of coverage, or an empty slice when the row is off the bitmap.
323    #[must_use]
324    pub fn row(&self, y: u32) -> &[u8] {
325        if y >= self.height {
326            return &[];
327        }
328        let start = y as usize * self.width as usize;
329        let end = start + self.width as usize;
330        self.coverage.get(start..end).unwrap_or(&[])
331    }
332
333    /// The tight ink bounds in bitmap pixels, or `None` when nothing is drawn.
334    ///
335    /// ```
336    /// use font_shape::GlyphBitmap;
337    ///
338    /// // A 4x3 block whose middle 2x2 is ink.
339    /// let b = GlyphBitmap::new(4, 3, 0, 0, vec![
340    ///     0, 0, 0, 0,
341    ///     0, 255, 255, 0,
342    ///     0, 255, 255, 0,
343    /// ]);
344    /// assert_eq!(b.ink_bounds(), Some((1, 1, 2, 2)));
345    /// assert_eq!(GlyphBitmap::empty().ink_bounds(), None);
346    /// ```
347    #[must_use]
348    pub fn ink_bounds(&self) -> Option<(u32, u32, u32, u32)> {
349        if self.is_empty() {
350            return None;
351        }
352        let mut x0 = u32::MAX;
353        let mut y0 = u32::MAX;
354        let mut x1 = 0u32;
355        let mut y1 = 0u32;
356        let mut any = false;
357        for y in 0..self.height {
358            for (x, &v) in self.row(y).iter().enumerate() {
359                if v > 0 {
360                    let x = x as u32;
361                    x0 = x0.min(x);
362                    x1 = x1.max(x);
363                    y0 = y0.min(y);
364                    y1 = y1.max(y);
365                    any = true;
366                }
367            }
368        }
369        if any {
370            Some((x0, y0, x1 - x0 + 1, y1 - y0 + 1))
371        } else {
372            None
373        }
374    }
375
376    /// Translate the bitmap without touching its pixels.
377    #[must_use]
378    pub const fn translated(mut self, dx: i32, dy: i32) -> Self {
379        self.left += dx;
380        self.top += dy;
381        self
382    }
383}
384
385/// The device-space path for a font outline: pixels, y **down**, origin on the
386/// baseline at the glyph's x origin.
387///
388/// The outline's own y-up coordinates are negated, so a glyph that sits above
389/// the baseline lands at negative y in the returned path — which is what
390/// [`fill_path`](crate::fill_path) wants.
391///
392/// # Errors
393/// [`ShapeError::InvalidScale`] for a non-positive or non-finite `size_px`.
394///
395/// ```
396/// use font_shape::{glyph_path_from_outline, Hinting};
397///
398/// let mut outline = font_model::Outline::new();
399/// let mut p = font_model::Path::starting_at(0.0, 0.0);
400/// p.line_to(500.0, 0.0);
401/// p.line_to(500.0, 1000.0);
402/// p.close();
403/// outline.push_contour(p);
404///
405/// // 1000 units per em at 8 px: the glyph is 4 px wide and 8 px tall, above
406/// // the baseline, so its y range is [-8, 0].
407/// let path = glyph_path_from_outline(&outline, 1000, 8.0, Hinting::None).unwrap();
408/// let b = path.bbox().unwrap();
409/// assert_eq!(b.min_x, 0.0);
410/// assert_eq!(b.width(), 4.0);
411/// assert_eq!(b.min_y, -8.0);
412/// assert_eq!(b.max_y, 0.0);
413/// ```
414#[allow(clippy::result_large_err)]
415pub fn glyph_path_from_outline(
416    outline: &Outline,
417    units_per_em: u16,
418    size_px: f32,
419    hinting: Hinting,
420) -> Result<Path2D, ShapeError> {
421    let scale = fixed_scale(size_px, units_per_em)?;
422    let mut b = PathBuilder::new();
423    for contour in outline.contours() {
424        let mut started = false;
425        for cmd in contour.commands() {
426            let project = |x: f32, y: f32| -> (f32, f32) {
427                // `scale` is already 26.6 units per font unit, so
428                // the product *is* the fixed-point value: round it there
429                // rather than going back through float pixels, which would
430                // quantise twice.
431                let fx = to_26_6(x * scale);
432                let fy = to_26_6(-y * scale);
433                let (fx, fy) = if hinting.is_grid_fit() {
434                    (grid_fit(fx), grid_fit(fy))
435                } else {
436                    (fx, fy)
437                };
438                (from_fixed(fx), from_fixed(fy))
439            };
440            match *cmd {
441                font_model::Command::MoveTo(x, y) => {
442                    let (x, y) = project(x, y);
443                    b.move_to(x, y);
444                    started = true;
445                }
446                font_model::Command::LineTo(x, y) => {
447                    let (x, y) = project(x, y);
448                    if started {
449                        b.line_to(x, y);
450                    }
451                }
452                font_model::Command::QuadTo(cx, cy, x, y) => {
453                    let (cx, cy) = project(cx, cy);
454                    let (x, y) = project(x, y);
455                    if started {
456                        b.quad_to(cx, cy, x, y);
457                    }
458                }
459                font_model::Command::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
460                    let (c1x, c1y) = project(c1x, c1y);
461                    let (c2x, c2y) = project(c2x, c2y);
462                    let (x, y) = project(x, y);
463                    if started {
464                        b.cubic_to(c1x, c1y, c2x, c2y, x, y);
465                    }
466                }
467                font_model::Command::Close => {
468                    if started {
469                        b.close();
470                    }
471                    started = false;
472                }
473            }
474        }
475    }
476    Ok(b.build())
477}
478
479/// The device-space path for a glyph in a font.
480///
481/// # Errors
482/// [`ShapeError::UnknownGlyph`] when the font has no such glyph, plus
483/// whatever [`glyph_path_from_outline`] reports.
484///
485/// ```
486/// use font_model::{Font, Glyph, GlyphId, Outline, Path};
487/// use font_shape::{glyph_path, Hinting};
488///
489/// let mut outline = Outline::new();
490/// let mut p = Path::starting_at(0.0, 0.0);
491/// p.line_to(500.0, 0.0);
492/// p.line_to(500.0, 700.0);
493/// p.close();
494/// outline.push_contour(p);
495///
496/// let font = Font::builder()
497///     .units_per_em(1000)
498///     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
499///     .glyph(Glyph::new(GlyphId::new(1), 500, 0, outline))
500///     .build()
501///     .unwrap();
502///
503/// // At 12 px the 500-unit glyph is 6 px wide and 8.4 px tall, sitting above
504/// // the baseline, so the path's box has a negative top.
505/// let path = glyph_path(&font, GlyphId::new(1), 12.0, Hinting::None).unwrap();
506/// let b = path.bbox().expect("a glyph with ink has a bbox");
507/// assert!(b.max_x - b.min_x <= 6.0 && b.max_x - b.min_x >= 5.9, "{b:?}");
508/// assert!(b.max_y <= 0.01 && b.min_y < -8.0, "{b:?}");
509/// ```
510#[allow(clippy::result_large_err)]
511pub fn glyph_path(
512    font: &Font,
513    glyph: GlyphId,
514    size_px: f32,
515    hinting: Hinting,
516) -> Result<Path2D, ShapeError> {
517    let g = font.glyph(glyph).ok_or(ShapeError::UnknownGlyph {
518        glyph: glyph.to_u32(),
519        glyph_count: font.glyph_count(),
520    })?;
521    glyph_path_from_outline(g.outline(), font.units_per_em(), size_px, hinting)
522}
523
524/// Rasterize an outline into a bitmap placed relative to the baseline.
525///
526/// The returned bitmap's [`left`](GlyphBitmap::left) and
527/// [`top`](GlyphBitmap::top) are relative to the glyph origin: `left` counts
528/// columns to the left of the pen, `top` counts rows above the baseline. A
529/// glyph with no contours — a space — gives an empty bitmap, not an error.
530///
531/// # Errors
532/// [`ShapeError::InvalidScale`] for a bad size, and
533/// [`ShapeError::RasterTooLarge`] when the glyph's own bounding box is larger
534/// than [`MAX_MASK_ELEMENTS`] pixels.
535#[allow(clippy::result_large_err)]
536pub fn rasterize_outline(
537    outline: &Outline,
538    units_per_em: u16,
539    size_px: f32,
540    hinting: Hinting,
541) -> Result<GlyphBitmap, ShapeError> {
542    // Validate the size before touching the outline, so a bad size is the
543    // same error whichever entry point the caller used.
544    let _ = fixed_scale(size_px, units_per_em)?;
545    if outline.contours().is_empty() {
546        return Ok(GlyphBitmap::empty());
547    }
548    let path = glyph_path_from_outline(outline, units_per_em, size_px, hinting)?;
549    let Some(bbox) = path.bbox() else {
550        return Ok(GlyphBitmap::empty());
551    };
552    // A non-finite bound means hostile geometry reached the transform. There
553    // is no honest raster of it, and the alternative — a width derived from
554    // infinity — is a gigabyte allocation. Report no ink instead.
555    if bbox.is_empty()
556        || !bbox.min_x.is_finite()
557        || !bbox.min_y.is_finite()
558        || !bbox.max_x.is_finite()
559        || !bbox.max_y.is_finite()
560    {
561        return Ok(GlyphBitmap::empty());
562    }
563    let left = floor_i32(bbox.min_x);
564    let right = ceil_i32(bbox.max_x);
565    // Rows above the baseline: the bitmap's top edge.
566    let top = ceil_i32(-bbox.min_y);
567    // Rows below: its bottom edge, which is at a *negative* offset.
568    let bottom = floor_i32(-bbox.max_y);
569    let width_i = right - left;
570    let height_i = top - bottom;
571    if width_i <= 0 || height_i <= 0 {
572        return Ok(GlyphBitmap::empty());
573    }
574    let (Ok(width_u), Ok(height_u)) = (u32::try_from(width_i), u32::try_from(height_i)) else {
575        return Ok(GlyphBitmap::empty());
576    };
577    let pixels = (width_u as usize).saturating_mul(height_u as usize);
578    if pixels > MAX_MASK_ELEMENTS {
579        return Err(ShapeError::RasterTooLarge {
580            pixels,
581            limit: MAX_MASK_ELEMENTS,
582        });
583    }
584    // Move the ink so the bitmap's own (0, 0) is its top-left corner. `left`
585    // and `top` are pixel counts already, not 26.6 values.
586    let placed = path.transformed(&Affine2D::translate(-(left as f32), top as f32));
587    let mask = fill_path(&placed, FillRule::NonZero, width_u, height_u)?;
588    Ok(GlyphBitmap::new(width_u, height_u, left, top, mask))
589}
590
591/// Rasterize a glyph from a font.
592///
593/// # Errors
594/// [`ShapeError::UnknownGlyph`] when the font has no such glyph, plus
595/// whatever [`rasterize_outline`] reports.
596///
597/// ```
598/// use font_model::{Font, Glyph, GlyphId, Outline, Path};
599/// use font_shape::{rasterize_glyph, Hinting};
600///
601/// let mut outline = Outline::new();
602/// let mut p = Path::starting_at(0.0, 0.0);
603/// p.line_to(500.0, 0.0);
604/// p.line_to(500.0, 700.0);
605/// p.close();
606/// outline.push_contour(p);
607///
608/// let font = Font::builder()
609///     .units_per_em(1000)
610///     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
611///     .glyph(Glyph::new(GlyphId::new(1), 500, 0, outline))
612///     .build()
613///     .unwrap();
614///
615/// let bmp = rasterize_glyph(&font, GlyphId::new(1), 20.0, Hinting::None).unwrap();
616/// assert_eq!((bmp.width(), bmp.height()), (10, 14));
617/// assert_eq!(bmp.top(), 14);
618/// assert!(bmp.ink() > 0.0, "the glyph has ink");
619/// assert_eq!(bmp.coverage().len(), (bmp.width() * bmp.height()) as usize);
620///
621/// // `.notdef` here has no contours, so it has no bitmap at all.
622/// let blank = rasterize_glyph(&font, GlyphId::NOTDEF, 16.0, Hinting::None).unwrap();
623/// assert!(blank.is_empty());
624///
625/// // And a glyph past the store is a typed error, not a panic.
626/// assert!(rasterize_glyph(&font, GlyphId::new(9), 16.0, Hinting::None).is_err());
627/// ```
628#[allow(clippy::result_large_err)]
629pub fn rasterize_glyph(
630    font: &Font,
631    glyph: GlyphId,
632    size_px: f32,
633    hinting: Hinting,
634) -> Result<GlyphBitmap, ShapeError> {
635    let g = font.glyph(glyph).ok_or(ShapeError::UnknownGlyph {
636        glyph: glyph.to_u32(),
637        glyph_count: font.glyph_count(),
638    })?;
639    rasterize_outline(g.outline(), font.units_per_em(), size_px, hinting)
640}
641
642/// The device pixel size of the em square at `size_px`.
643#[must_use]
644pub fn em_size_px(size_px: f32) -> f32 {
645    if size_px.is_finite() && size_px > 0.0 {
646        size_px
647    } else {
648        0.0
649    }
650}
651
652/// Font metrics in device pixels, y down, origin on the baseline.
653///
654/// Ascender and descender are returned as they are used: `ascent` is a
655/// **positive** number of pixels above the baseline, `descent` a positive
656/// number below it.
657///
658/// # Errors
659/// [`ShapeError::InvalidScale`] for a non-positive or non-finite size.
660///
661/// ```
662/// use font_shape::scaled_metrics;
663///
664/// let font = font_model::build_stub_font(&[b'A' as u32]).unwrap();
665/// let m = scaled_metrics(&font, 16.0).unwrap();
666/// assert!(m.ascent > 0.0 && m.descent > 0.0);
667/// // The em square is 16 px tall, so the line fits inside it.
668/// assert!(m.line_height >= m.ascent + m.descent);
669/// ```
670#[allow(clippy::result_large_err)]
671pub fn scaled_metrics(font: &Font, size_px: f32) -> Result<DeviceMetrics, ShapeError> {
672    if !size_px.is_finite() || size_px <= 0.0 {
673        return Err(ShapeError::InvalidScale { scale: size_px });
674    }
675    let scale = size_px / f32::from(font.units_per_em().max(1));
676    Ok(DeviceMetrics::from_font(font.metrics(), scale))
677}
678
679/// Font metrics resolved to device pixels.
680#[derive(Debug, Clone, Copy, PartialEq)]
681pub struct DeviceMetrics {
682    /// Pixels above the baseline to the ascender.
683    pub ascent: f32,
684    /// Pixels below the baseline to the descender, as a positive number.
685    pub descent: f32,
686    /// Pixels of extra leading between lines.
687    pub line_gap: f32,
688    /// `ascent + descent + line_gap`: the recommended distance between
689    /// consecutive baselines.
690    pub line_height: f32,
691}
692
693impl DeviceMetrics {
694    /// Scale a [`FontMetrics`] by `scale` (pixels per font unit).
695    #[must_use]
696    pub fn from_font(m: &FontMetrics, scale: f32) -> Self {
697        let ascent = f32::from(m.ascender) * scale;
698        let descent = -f32::from(m.descender) * scale;
699        let line_gap = f32::from(m.line_gap) * scale;
700        DeviceMetrics {
701            ascent,
702            descent,
703            line_gap,
704            line_height: ascent + descent + line_gap,
705        }
706    }
707}
708
709/// `floor` as an `i32`, saturating.
710fn floor_i32(v: f32) -> i32 {
711    if v.is_nan() {
712        return 0;
713    }
714    if v <= i32::MIN as f32 {
715        return i32::MIN;
716    }
717    if v >= i32::MAX as f32 {
718        return i32::MAX;
719    }
720    libm::floorf(v) as i32
721}
722
723/// `ceil` as an `i32`, saturating.
724fn ceil_i32(v: f32) -> i32 {
725    if v.is_nan() {
726        return 0;
727    }
728    if v <= i32::MIN as f32 {
729        return i32::MIN;
730    }
731    if v >= i32::MAX as f32 {
732        return i32::MAX;
733    }
734    libm::ceilf(v) as i32
735}
736
737#[cfg(test)]
738mod tests {
739    #![allow(
740        clippy::unwrap_used,
741        clippy::expect_used,
742        clippy::panic,
743        clippy::indexing_slicing,
744        clippy::float_cmp
745    )]
746    use super::{
747        em_size_px, fixed_scale, from_fixed, glyph_path, glyph_path_from_outline, grid_fit,
748        rasterize_glyph, rasterize_outline, scaled_metrics, to_fixed, DeviceMetrics, GlyphBitmap,
749        Hinting, PIXEL,
750    };
751    use crate::error::ShapeError;
752    use alloc::string::ToString;
753    use alloc::vec;
754    use alloc::vec::Vec;
755    use font_model::{Command, Font, Glyph, GlyphId, Outline, Path};
756
757    // Test harness: assertions legitimately panic; the lib target stays
758    // lint-clean.
759
760    fn close(a: f32, b: f32) -> bool {
761        (a - b).abs() < 1e-4
762    }
763
764    /// A square from (x0, y0) to (x1, y1) in font units, y up.
765    fn square(x0: f32, y0: f32, x1: f32, y1: f32) -> Outline {
766        let mut outline = Outline::new();
767        let mut p = Path::starting_at(x0, y0);
768        p.line_to(x1, y0);
769        p.line_to(x1, y1);
770        p.line_to(x0, y1);
771        p.close();
772        outline.push_contour(p);
773        outline
774    }
775
776    #[test]
777    fn fixed_point_round_trips() {
778        assert_eq!(PIXEL, 64);
779        for v in [0.0f32, 0.5, 1.0, 1.25, -0.75, 100.0, 1.0 / 64.0] {
780            assert!(close(from_fixed(to_fixed(v)), v), "{v}");
781        }
782        assert_eq!(to_fixed(1.0), PIXEL);
783        assert_eq!(from_fixed(PIXEL), 1.0);
784        // Every 26.6 value is a multiple of 1/64 px.
785        assert_eq!(to_fixed(0.25), 16);
786        // Rounding is half-away-from-zero, so the round trip is exact to
787        // within half a quantisation step: 1/128 of a pixel.
788        assert!(close(from_fixed(to_fixed(-0.007_812_5)), -0.015_625));
789    }
790
791    #[test]
792    fn fixed_point_saturates_instead_of_wrapping() {
793        assert_eq!(to_fixed(f32::NAN), 0);
794        assert_eq!(to_fixed(f32::INFINITY), i32::MAX);
795        assert_eq!(to_fixed(f32::NEG_INFINITY), i32::MIN);
796        assert_eq!(to_fixed(1e18), i32::MAX);
797        assert_eq!(to_fixed(-1e18), i32::MIN);
798        assert!(from_fixed(i32::MAX).is_finite());
799        assert!(from_fixed(i32::MIN).is_finite());
800    }
801
802    #[test]
803    fn grid_fit_snaps_to_the_pixel_grid() {
804        assert_eq!(grid_fit(0), 0);
805        assert_eq!(grid_fit(32), 64);
806        assert_eq!(grid_fit(-32), -64);
807        assert_eq!(grid_fit(100), 128);
808        assert_eq!(grid_fit(31), 0);
809        assert_eq!(grid_fit(-31), 0);
810        assert_eq!(grid_fit(95), 64);
811        // Snapping is idempotent.
812        for v in [-500, -64, -1, 0, 1, 33, 200] {
813            assert_eq!(grid_fit(grid_fit(v)), grid_fit(v), "{v}");
814        }
815    }
816
817    #[test]
818    fn fixed_scale_is_size_times_sixty_four_over_upem() {
819        assert!(close(fixed_scale(16.0, 1000).expect("scale"), 1.024));
820        assert!(close(fixed_scale(24.0, 2048).expect("scale"), 0.75));
821        // Half size, half scale.
822        let a = fixed_scale(12.0, 1000).expect("scale");
823        let b = fixed_scale(24.0, 1000).expect("scale");
824        assert!(close(a, b * 0.5));
825    }
826
827    #[test]
828    fn fixed_scale_rejects_degenerate_inputs() {
829        assert_eq!(
830            fixed_scale(16.0, 0).unwrap_err(),
831            ShapeError::DegenerateUnitsPerEm
832        );
833        for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] {
834            assert!(
835                matches!(fixed_scale(bad, 1000), Err(ShapeError::InvalidScale { .. })),
836                "{bad}"
837            );
838        }
839    }
840
841    #[test]
842    fn glyph_path_flips_y_and_scales() {
843        // 1000 upem at 100 px: a 1000-unit square is 100 px, above the
844        // baseline, so y runs from -100 to 0.
845        let outline = square(0.0, 0.0, 1000.0, 1000.0);
846        let path = glyph_path_from_outline(&outline, 1000, 100.0, Hinting::None).expect("path");
847        let b = path.bbox().expect("bbox");
848        assert_eq!(b.min_x, 0.0);
849        assert_eq!(b.min_y, -100.0);
850        assert_eq!(b.max_x, 100.0);
851        assert_eq!(b.max_y, 0.0);
852    }
853
854    #[test]
855    fn glyph_path_carries_curves_through() {
856        let mut outline = Outline::new();
857        let mut p = Path::starting_at(0.0, 0.0);
858        p.cubic_to(500.0, 500.0, 1000.0, 500.0, 1000.0, 0.0);
859        p.close();
860        outline.push_contour(p);
861        let path = glyph_path_from_outline(&outline, 1000, 100.0, Hinting::None).expect("path");
862        // A quad and a cubic both survive as curves, not polylines.
863        assert!(path
864            .commands()
865            .iter()
866            .any(|c| matches!(c, crate::PathCommand::CubicTo(..))));
867        let b = path.bbox().expect("bbox");
868        assert!(b.min_y < -10.0, "the curve bows up: {b:?}");
869    }
870
871    #[test]
872    fn grid_fit_snaps_the_whole_outline_to_pixels() {
873        let outline = square(0.0, 0.0, 1000.0, 1000.0);
874        let path = glyph_path_from_outline(&outline, 1000, 7.3, Hinting::GridFit).expect("path");
875        for cmd in path.commands() {
876            if let Some((x, y)) = cmd.end_point() {
877                assert!(close(x, libm::roundf(x)), "x {x} is not a whole pixel");
878                assert!(close(y, libm::roundf(y)), "y {y} is not a whole pixel");
879            }
880        }
881        // And the unhinted version generally is not.
882        let raw = glyph_path_from_outline(&outline, 1000, 7.3, Hinting::None).expect("path");
883        let snapped = path.bbox().expect("bbox");
884        let plain = raw.bbox().expect("bbox");
885        // Unhinted, the glyph is 7.3 px — up to the 26.6 quantisation of
886        // 1/64 px, which is the fixed-point grid the glyph is snapped to.
887        assert!((plain.width() - 7.3).abs() < 0.02, "{plain:?}");
888        assert!((plain.height() - 7.3).abs() < 0.02, "{plain:?}");
889        assert_eq!(snapped.width(), 7.0, "grid fit rounds 7.3 down to 7");
890        assert_eq!(snapped.height(), 7.0, "{snapped:?}");
891    }
892
893    #[test]
894    fn grid_fit_can_change_the_measured_size_by_a_pixel() {
895        // 7.3 px snaps to 7; 7.8 px snaps to 8.
896        let outline = square(0.0, 0.0, 1000.0, 1000.0);
897        let small = glyph_path_from_outline(&outline, 1000, 7.8, Hinting::GridFit)
898            .expect("path")
899            .bbox()
900            .expect("bbox");
901        assert!(close(small.width(), 8.0), "{small:?}");
902    }
903
904    #[test]
905    fn rasterized_square_is_exact_and_placed() {
906        // A 20 px square sitting on the baseline at x = 0.
907        let outline = square(0.0, 0.0, 1000.0, 1000.0);
908        let bmp = rasterize_outline(&outline, 1000, 20.0, Hinting::None).expect("raster");
909        assert_eq!(bmp.width(), 20);
910        assert_eq!(bmp.height(), 20);
911        assert_eq!(bmp.left(), 0);
912        assert_eq!(bmp.top(), 20, "20 rows above the baseline");
913        assert!((bmp.ink() - 400.0).abs() < 1e-6, "ink {}", bmp.ink());
914        // The baseline row is the bottom row and is solid; above it, nothing.
915        assert_eq!(bmp.coverage_at(0, 19), 255);
916        assert_eq!(bmp.coverage_at(19, 0), 255);
917        assert!(!bmp.is_empty());
918    }
919
920    #[test]
921    fn bitmap_placement_follows_the_glyph_origin() {
922        // A square from x = 100..300 of a 1000-unit glyph at 10 px: 10 px
923        // wide, starting 1 px right of the pen.
924        let outline = square(100.0, 0.0, 300.0, 1000.0);
925        let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
926        assert_eq!(bmp.left(), 1);
927        assert_eq!(bmp.width(), 2);
928        assert_eq!(bmp.top(), 10);
929        // A negative overhang: ink left of the origin.
930        let outline = square(-250.0, 0.0, 250.0, 1000.0);
931        let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
932        // 2.5 px of overhang left and right, so the bitmap spans six columns
933        // even though the ink covers five of them.
934        assert_eq!(bmp.left(), -3);
935        assert_eq!(bmp.width(), 6);
936        assert_eq!(bmp.coverage_at(0, 0), 128, "half-covered left edge");
937        assert_eq!(bmp.coverage_at(5, 0), 128, "half-covered right edge");
938        assert!((bmp.ink() - 50.0).abs() < 0.05, "ink {}", bmp.ink());
939    }
940
941    #[test]
942    fn below_baseline_ink_extends_the_bitmap_downward() {
943        // From -300 to +100 units at 10 px the ink spans y = -3..1 px, so it
944        // reaches 1 px above the baseline and 3 px below it: `top` counts the
945        // rows above, `height` the whole box.
946        let outline = square(0.0, -300.0, 1000.0, 100.0);
947        let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
948        assert_eq!(bmp.top(), 1);
949        assert_eq!(bmp.height(), 4);
950        assert_eq!(bmp.coverage_at(0, 0), 255, "above the baseline");
951        assert_eq!(bmp.coverage_at(0, 3), 255, "below the baseline");
952        assert!((bmp.ink() - 40.0).abs() < 0.05, "ink {}", bmp.ink());
953    }
954
955    #[test]
956    fn empty_outline_is_an_empty_bitmap_not_an_error() {
957        let bmp = rasterize_outline(&Outline::new(), 1000, 12.0, Hinting::None).expect("raster");
958        assert!(bmp.is_empty());
959        assert_eq!(bmp.width(), 0);
960        assert_eq!(bmp.ink(), 0.0);
961        // A contour that is a single point has no area either.
962        // A contour that is one point and nothing else. It has a bounding box
963        // but no area, so the honest answer is a bitmap with pixels and no ink.
964        let mut outline = Outline::new();
965        let mut p = Path::starting_at(100.0, 100.0);
966        p.close();
967        outline.push_contour(p);
968        let bmp = rasterize_outline(&outline, 1000, 12.0, Hinting::None).expect("raster");
969        assert!(bmp.ink() == 0.0, "a lone point has no ink");
970        assert!(bmp.ink_bounds().is_none(), "and no ink bounds");
971    }
972
973    #[test]
974    fn raster_size_errors_are_typed() {
975        let outline = square(0.0, 0.0, 1000.0, 1000.0);
976        assert!(matches!(
977            rasterize_outline(&outline, 1000, 0.0, Hinting::None),
978            Err(ShapeError::InvalidScale { .. })
979        ));
980        assert!(matches!(
981            rasterize_outline(&outline, 0, 12.0, Hinting::None),
982            Err(ShapeError::DegenerateUnitsPerEm)
983        ));
984        // A glyph 100 000 px tall is refused rather than allocated.
985        assert!(matches!(
986            rasterize_outline(&outline, 1000, 100_000.0, Hinting::None),
987            Err(ShapeError::RasterTooLarge { .. })
988        ));
989    }
990
991    #[test]
992    fn glyph_ink_tracks_the_outline_area() {
993        // A 500 x 400 unit glyph at 20 px is a 10 x 8 px rectangle: 80 px of
994        // ink. The analytic filler makes that exact.
995        let outline = square(0.0, 0.0, 500.0, 400.0);
996        let bmp = rasterize_outline(&outline, 1000, 20.0, Hinting::None).expect("raster");
997        assert_eq!(bmp.width(), 10);
998        assert_eq!(bmp.height(), 8);
999        assert!((bmp.ink() - 80.0).abs() < 1e-6, "ink {}", bmp.ink());
1000        // Scale by 3: 9x the area.
1001        let big = rasterize_outline(&outline, 1000, 60.0, Hinting::None).expect("raster");
1002        assert!((big.ink() - 80.0 * 9.0).abs() < 1e-6, "ink {}", big.ink());
1003    }
1004
1005    #[test]
1006    fn rasterize_glyph_goes_through_the_font() {
1007        let mut outline = square(0.0, 0.0, 1000.0, 1000.0);
1008        let font = Font::builder()
1009            .units_per_em(1000)
1010            .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
1011            .glyph(Glyph::new(GlyphId::new(1), 1000, 0, outline.clone()))
1012            .build()
1013            .expect("font");
1014        let bmp = rasterize_glyph(&font, GlyphId::new(1), 10.0, Hinting::None).expect("raster");
1015        assert_eq!(bmp.width(), 10);
1016        assert!((bmp.ink() - 100.0).abs() < 1e-6, "ink {}", bmp.ink());
1017        outline.contours_mut().clear();
1018        assert_eq!(outline.contours().len(), 0);
1019        // A missing glyph is a typed error, with the count in it.
1020        match rasterize_glyph(&font, GlyphId::new(9), 10.0, Hinting::None).unwrap_err() {
1021            ShapeError::UnknownGlyph { glyph, glyph_count } => {
1022                assert_eq!(glyph, 9);
1023                assert_eq!(glyph_count, 2);
1024            }
1025            other => panic!("expected UnknownGlyph, got {other:?}"),
1026        }
1027        assert_eq!(
1028            ShapeError::UnknownGlyph {
1029                glyph: 9,
1030                glyph_count: 2
1031            }
1032            .to_string(),
1033            "glyph 9 requested but the font holds only 2"
1034        );
1035    }
1036
1037    #[test]
1038    fn glyph_path_from_a_font() {
1039        let font = Font::builder()
1040            .units_per_em(1000)
1041            .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
1042            .glyph(Glyph::new(
1043                GlyphId::new(1),
1044                1000,
1045                0,
1046                square(0.0, 0.0, 500.0, 500.0),
1047            ))
1048            .build()
1049            .expect("font");
1050        let path = glyph_path(&font, GlyphId::new(1), 100.0, Hinting::None).expect("path");
1051        let b = path.bbox().expect("bbox");
1052        assert_eq!(b.width(), 50.0);
1053        assert_eq!(b.height(), 50.0);
1054        assert_eq!(b.min_y, -50.0, "the ink sits above the baseline");
1055        // `.notdef` is blank in this font, so it has no path to speak of.
1056        let blank = glyph_path(&font, GlyphId::NOTDEF, 12.0, Hinting::None).expect("path");
1057        assert!(blank.bbox().is_none() || blank.bbox().is_some_and(|r| r.is_empty()));
1058        // A glyph past the store is an error.
1059        assert!(glyph_path(&font, GlyphId::new(7), 12.0, Hinting::None).is_err());
1060    }
1061
1062    #[test]
1063    fn bitmap_accessors_are_bounds_checked() {
1064        let bmp = GlyphBitmap::new(
1065            4,
1066            3,
1067            1,
1068            2,
1069            vec![
1070                0, 0, 0, 0, //
1071                0, 255, 255, 0, //
1072                0, 255, 255, 0, //
1073            ],
1074        );
1075        assert_eq!(bmp.coverage().len(), 12);
1076        assert_eq!(bmp.row(0).len(), 4);
1077        assert_eq!(bmp.row(1)[1], 255);
1078        assert!(bmp.row(3).is_empty());
1079        assert_eq!(bmp.coverage_at(3, 2), 0);
1080        assert_eq!(bmp.ink_bounds(), Some((1, 1, 2, 2)));
1081        assert!((bmp.ink() - 4.0).abs() < 1e-9);
1082        let moved = bmp.clone().translated(5, -5);
1083        assert_eq!(moved.left(), 6);
1084        assert_eq!(moved.top(), -3);
1085        assert_eq!(
1086            moved.coverage(),
1087            bmp.coverage(),
1088            "translation moves nothing else"
1089        );
1090        assert_eq!(moved.into_coverage().len(), 12);
1091        assert_eq!(GlyphBitmap::default(), GlyphBitmap::empty());
1092        // A mask shorter than its declared size must not panic.
1093        let short = GlyphBitmap::new(100, 100, 0, 0, Vec::new());
1094        assert_eq!(short.coverage_at(50, 50), 0);
1095        assert!(short.row(50).is_empty());
1096        assert_eq!(short.ink_bounds(), None);
1097        assert!(short.ink() == 0.0);
1098    }
1099
1100    #[test]
1101    fn ink_bounds_is_none_for_a_blank_glyph() {
1102        let blank = GlyphBitmap::new(4, 4, 0, 0, vec![0u8; 16]);
1103        assert_eq!(blank.ink_bounds(), None);
1104        assert!(!blank.is_empty(), "it has pixels, just no ink");
1105        // A single fully covered pixel is a 1x1 bound.
1106        let dot = GlyphBitmap::new(2, 2, 0, 0, vec![0, 0, 0, 255]);
1107        assert_eq!(dot.ink_bounds(), Some((1, 1, 1, 1)));
1108    }
1109
1110    #[test]
1111    fn hinting_modes_toggle_and_report() {
1112        assert_eq!(Hinting::default(), Hinting::None);
1113        assert!(!Hinting::None.is_grid_fit());
1114        assert!(Hinting::GridFit.is_grid_fit());
1115        assert_eq!(Hinting::None.toggled(), Hinting::GridFit);
1116        assert_eq!(Hinting::GridFit.toggled(), Hinting::None);
1117    }
1118
1119    #[test]
1120    fn scaled_metrics_are_in_pixels() {
1121        let m = font_model::FontMetrics {
1122            ascender: 800,
1123            descender: -200,
1124            line_gap: 100,
1125            ..font_model::FontMetrics::default()
1126        };
1127        let d = DeviceMetrics::from_font(&m, 0.02);
1128        assert!(close(d.ascent, 16.0));
1129        assert!(close(d.descent, 4.0));
1130        assert!(close(d.line_gap, 2.0));
1131        assert!(close(d.line_height, 22.0));
1132        // Through the font.
1133        let font = font_model::build_stub_font(&[b'A' as u32]).expect("font");
1134        let d = scaled_metrics(&font, 1000.0).expect("metrics");
1135        assert!(close(d.ascent, f32::from(font.metrics().ascender)));
1136        assert!(matches!(
1137            scaled_metrics(&font, 0.0),
1138            Err(ShapeError::InvalidScale { .. })
1139        ));
1140        assert!(matches!(
1141            scaled_metrics(&font, f32::NAN),
1142            Err(ShapeError::InvalidScale { .. })
1143        ));
1144    }
1145
1146    #[test]
1147    fn em_size_is_the_size_itself_when_sane() {
1148        assert_eq!(em_size_px(12.0), 12.0);
1149        assert_eq!(em_size_px(0.0), 0.0);
1150        assert_eq!(em_size_px(-1.0), 0.0);
1151        assert_eq!(em_size_px(f32::NAN), 0.0);
1152        assert_eq!(em_size_px(f32::INFINITY), 0.0);
1153    }
1154
1155    #[test]
1156    fn non_finite_outline_coordinates_do_not_panic() {
1157        // A NaN coordinate never reaches the path: `to_26_6` maps NaN to zero,
1158        // so the degenerate segment is simply absent.
1159        let mut outline = Outline::new();
1160        let mut p = Path::starting_at(0.0, 0.0);
1161        p.line_to(f32::NAN, 100.0);
1162        p.line_to(500.0, 500.0);
1163        p.close();
1164        outline.push_contour(p);
1165        let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
1166        assert!(bmp.ink() > 0.0, "the good part still draws");
1167
1168        // An infinite coordinate saturates the fixed-point conversion to
1169        // `i32::MAX`, so the glyph's box becomes enormous — and an enormous
1170        // glyph is a typed refusal, not an allocation. Either outcome is
1171        // total; neither panics.
1172        let mut wide = Outline::new();
1173        let mut q = Path::starting_at(0.0, 0.0);
1174        q.line_to(f32::INFINITY, 100.0);
1175        q.close();
1176        wide.push_contour(q);
1177        match rasterize_outline(&wide, 1000, 10.0, Hinting::None) {
1178            Ok(bmp) => assert!(bmp.is_empty() || bmp.ink() >= 0.0),
1179            Err(e) => assert!(
1180                matches!(e, ShapeError::RasterTooLarge { .. }),
1181                "unexpected error: {e:?}"
1182            ),
1183        }
1184    }
1185
1186    #[test]
1187    fn contours_without_a_move_to_are_skipped() {
1188        // A contour whose first command is a line has no start point to
1189        // transform from, so it contributes nothing rather than guessing.
1190        let mut outline = Outline::new();
1191        let mut p = Path::new();
1192        p.push(Command::LineTo(100.0, 100.0));
1193        p.push(Command::Close);
1194        outline.push_contour(p);
1195        let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
1196        assert!(bmp.ink() == 0.0, "ink {}", bmp.ink());
1197    }
1198
1199    #[test]
1200    fn a_glyph_scales_linearly_with_size() {
1201        let outline = square(0.0, 0.0, 1000.0, 1000.0);
1202        let mut prev: Option<f64> = None;
1203        for size in [1.0f32, 2.0, 4.0, 8.0, 16.0, 32.0] {
1204            let bmp = rasterize_outline(&outline, 1000, size, Hinting::None).expect("raster");
1205            assert_eq!(bmp.width() as f32, size, "width at {size}");
1206            assert_eq!(bmp.height() as f32, size, "height at {size}");
1207            assert!(close(bmp.top() as f32, size), "top {}", bmp.top());
1208            if let Some(p) = prev {
1209                assert!((bmp.ink() / p - 4.0).abs() < 1e-9, "doubling the size");
1210            }
1211            prev = Some(bmp.ink());
1212        }
1213    }
1214}