Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

7.9 KB
Raw Blame
//! RustCord: glyphs shaped by the font's own hinting.
//!
//! Chrome on Windows draws text through DirectWrite, which runs a font's
//! TrueType instructions in the vertical direction ("natural symmetric"
//! rendering): lowercase letters are stretched to a whole number of pixels,
//! round letters stop overshooting the baseline, and horizontal strokes land
//! on whole pixel rows. Discord's font (gg sans) is hinted for exactly that:
//! at 16 px its x-height of 7.52 px becomes 8 px. Drawing the plain outlines
//! instead (as ab_glyph does) gives smaller, softer letters with blurred tops
//! and bottoms.
//!
//! Here the instructions are run by `skrifa` (vertical only, advance widths
//! untouched, so layout doesn't change) and the resulting outline is filled
//! by ab_glyph's rasterizer, like any other glyph.

use ab_glyph_rasterizer::{point, Point, Rasterizer};
use skrifa::{
    instance::{LocationRef, Size},
    outline::{DrawSettings, Engine, HintingInstance, HintingOptions, OutlinePen, SmoothMode, Target},
    FontRef, GlyphId, MetadataProvider, Tag,
};

/// A hinted font at one size.
pub struct Hinted {
    data: &'static [u8],
    index: u32,
    instance: HintingInstance,
}

/// A glyph's coverage: `width` × `height` values in 0..=1, the top-left one
/// at (`min_x`, `min_y`) from the glyph's origin on the baseline (y down).
pub struct Raster {
    pub min_x: i32,
    pub min_y: i32,
    pub width: usize,
    pub height: usize,
    pub coverage: Vec<f32>,
}

enum Segment {
    Line(Point, Point),
    Quad(Point, Point, Point),
    Cubic(Point, Point, Point, Point),
}

/// Collects an outline, scaled in x and with y pointing down.
struct Collect {
    x_scale: f32,
    start: Point,
    at: Point,
    segments: Vec<Segment>,
}

impl Collect {
    fn p(&self, x: f32, y: f32) -> Point {
        point(x * self.x_scale, -y)
    }
}

impl OutlinePen for Collect {
    fn move_to(&mut self, x: f32, y: f32) {
        self.close();
        self.start = self.p(x, y);
        self.at = self.start;
    }

    fn line_to(&mut self, x: f32, y: f32) {
        let to = self.p(x, y);
        self.segments.push(Segment::Line(self.at, to));
        self.at = to;
    }

    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
        let (c, to) = (self.p(cx0, cy0), self.p(x, y));
        self.segments.push(Segment::Quad(self.at, c, to));
        self.at = to;
    }

    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
        let (c0, c1, to) = (self.p(cx0, cy0), self.p(cx1, cy1), self.p(x, y));
        self.segments.push(Segment::Cubic(self.at, c0, c1, to));
        self.at = to;
    }

    fn close(&mut self) {
        if self.at != self.start {
            self.segments.push(Segment::Line(self.at, self.start));
            self.at = self.start;
        }
    }
}

impl Hinted {
    /// `None` for fonts without TrueType instructions (they are drawn from
    /// their plain outlines).
    pub fn new(data: &'static [u8], index: u32, pixels_per_em: f32) -> Option<Self> {
        Self::with_mode(data, index, pixels_per_em, 0)
    }

    /// (`mode` picks the hinting target; the others are for comparing.)
    pub fn with_mode(data: &'static [u8], index: u32, pixels_per_em: f32, mode: u8) -> Option<Self> {
        let font = FontRef::from_index(data, index).ok()?;
        font.table_data(Tag::new(b"fpgm"))?;
        font.table_data(Tag::new(b"glyf"))?;
        let smooth = |mode, symmetric_rendering| Target::Smooth { mode, symmetric_rendering, preserve_linear_metrics: true };
        let target = match mode {
            // ClearType-style: instructions move points vertically only.
            0 => smooth(SmoothMode::Lcd, false),
            1 => smooth(SmoothMode::Lcd, true),
            2 => smooth(SmoothMode::Normal, false),
            3 => smooth(SmoothMode::Normal, true),
            4 => smooth(SmoothMode::Light, true),
            5 => smooth(SmoothMode::VerticalLcd, true),
            _ => Target::Mono,
        };
        let options = HintingOptions { engine: Engine::Interpreter, target };
        let instance = HintingInstance::new(&font.outline_glyphs(), Size::new(pixels_per_em), LocationRef::default(), options).ok()?;
        Some(Self { data, index, instance })
    }

    /// The font's glyph for a character (for tests and tools).
    pub fn glyph_id(&self, c: char) -> Option<u16> {
        let font = FontRef::from_index(self.data, self.index).ok()?;
        font.charmap().map(c).map(|g| g.to_u32() as u16)
    }

    /// The glyph's coverage with `x_scale` samples per pixel across.
    pub fn raster(&self, glyph_id: u16, x_scale: f32) -> Option<Raster> {
        let font = FontRef::from_index(self.data, self.index).ok()?;
        let glyph = font.outline_glyphs().get(GlyphId::new(glyph_id as u32))?;
        let mut pen = Collect { x_scale, start: point(0.0, 0.0), at: point(0.0, 0.0), segments: Vec::new() };
        glyph.draw(DrawSettings::hinted(&self.instance, false), &mut pen).ok()?;
        pen.close();
        if pen.segments.is_empty() {
            return None;
        }
        let (mut lo, mut hi) = (point(f32::MAX, f32::MAX), point(f32::MIN, f32::MIN));
        let mut see = |p: &Point| {
            lo = point(lo.x.min(p.x), lo.y.min(p.y));
            hi = point(hi.x.max(p.x), hi.y.max(p.y));
        };
        for s in &pen.segments {
            match s {
                Segment::Line(a, b) => [a, b].into_iter().for_each(&mut see),
                Segment::Quad(a, b, c) => [a, b, c].into_iter().for_each(&mut see),
                Segment::Cubic(a, b, c, d) => [a, b, c, d].into_iter().for_each(&mut see),
            }
        }
        let (min_x, min_y) = (lo.x.floor() as i32, lo.y.floor() as i32);
        let width = (hi.x.ceil() as i32 - min_x).max(0) as usize;
        let height = (hi.y.ceil() as i32 - min_y).max(0) as usize;
        if width == 0 || height == 0 || width > 4096 || height > 4096 {
            return None;
        }
        let shift = |p: &Point| point(p.x - min_x as f32, p.y - min_y as f32);
        let mut rasterizer = Rasterizer::new(width, height);
        for s in &pen.segments {
            match s {
                Segment::Line(a, b) => rasterizer.draw_line(shift(a), shift(b)),
                Segment::Quad(a, b, c) => rasterizer.draw_quad(shift(a), shift(b), shift(c)),
                Segment::Cubic(a, b, c, d) => rasterizer.draw_cubic(shift(a), shift(b), shift(c), shift(d)),
            }
        }
        let mut coverage = vec![0.0; width * height];
        rasterizer.for_each_pixel_2d(|x, y, v| coverage[y as usize * width + x as usize] = v);
        Some(Raster { min_x, min_y, width, height, coverage })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Prints glyphs as Chrome-style rows (`cargo test -p epaint hinted_glyphs -- --nocapture`),
    /// and checks what hinting is for: whole-pixel letter heights.
    #[test]
    fn hinted_glyphs() {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../../apps/rustcord/fonts/rrsans/rrsans.ttf");
        let Ok(bytes) = std::fs::read(path) else { return };
        let data: &'static [u8] = Box::leak(bytes.into_boxed_slice());
        let hinted = Hinted::new(data, 0, 16.0).expect("gg sans is hinted");
        let font = FontRef::from_index(data, 0).unwrap();
        for ch in ['H', 'o', 'l', 'e', 'x'] {
            let gid = font.charmap().map(ch).unwrap().to_u32() as u16;
            let r = hinted.raster(gid, 1.0).unwrap();
            println!("{ch}: {}x{} at ({}, {})", r.width, r.height, r.min_x, r.min_y);
            for y in 0..r.height {
                let row: String = (0..r.width).map(|x| format!("{:3} ", (r.coverage[y * r.width + x] * 100.0).round() as i32)).collect();
                println!("  {row}");
            }
        }
        // 'x' is exactly the x-height: 7.52 px unhinted, 8 px hinted.
        let x = hinted.raster(font.charmap().map('x').unwrap().to_u32() as u16, 1.0).unwrap();
        assert_eq!((x.min_y, x.height), (-8, 8));
    }
}