use std::sync::Arc;
use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{DrawSettings, HintingInstance, HintingOptions, OutlinePen};
use skrifa::raw::TableProvider;
use skrifa::{FontRef, GlyphId, MetadataProvider};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HintingPolicy {
#[default]
None,
Embedded,
Auto,
}
pub const AUTO_HINT_MAX_PPEM: f32 = 50.0;
impl HintingPolicy {
pub fn should_hint(self, ppem: f32, axis_aligned: bool) -> bool {
if !axis_aligned || !ppem.is_finite() || ppem <= 0.0 {
return false;
}
match self {
HintingPolicy::None => false,
HintingPolicy::Embedded => true,
HintingPolicy::Auto => ppem <= AUTO_HINT_MAX_PPEM,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutlineVerb {
MoveTo,
LineTo,
QuadTo,
CurveTo,
Close,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Outline {
pub verbs: Vec<OutlineVerb>,
pub points: Vec<[f32; 2]>,
}
impl Outline {
pub fn is_empty(&self) -> bool {
self.verbs.is_empty()
}
pub fn bounds(&self) -> Option<[f32; 4]> {
let first = *self.points.first()?;
let mut bounds = [first[0], first[1], first[0], first[1]];
for &[x, y] in &self.points[1..] {
bounds[0] = bounds[0].min(x);
bounds[1] = bounds[1].min(y);
bounds[2] = bounds[2].max(x);
bounds[3] = bounds[3].max(y);
}
Some(bounds)
}
pub fn oblique(&mut self, shear: f32) {
if shear == 0.0 {
return;
}
for p in &mut self.points {
p[0] += shear * p[1];
}
}
pub fn embolden(&mut self, strength: f32) {
if strength <= 0.0 || self.points.is_empty() {
return;
}
let mut contours: Vec<(usize, usize)> = Vec::new(); let mut start = 0usize;
let mut pt = 0usize;
for verb in &self.verbs {
let step = match verb {
OutlineVerb::MoveTo => {
if pt > start {
contours.push((start, pt));
}
start = pt;
1
}
OutlineVerb::LineTo => 1,
OutlineVerb::QuadTo => 2,
OutlineVerb::CurveTo => 3,
OutlineVerb::Close => 0,
};
pt += step;
}
if pt > start {
contours.push((start, pt.min(self.points.len())));
}
let mut best_area = 0.0f64;
for &(s, e) in &contours {
let mut area = 0.0f64;
for i in s..e {
let a = self.points[i];
let b = self.points[if i + 1 == e { s } else { i + 1 }];
area += a[0] as f64 * b[1] as f64 - b[0] as f64 * a[1] as f64;
}
if area.abs() > best_area.abs() {
best_area = area;
}
}
let sign: f32 = if best_area >= 0.0 { 1.0 } else { -1.0 };
let half = strength * 0.5;
let old = self.points.clone();
for &(s, e) in &contours {
let n = e - s;
if n < 2 {
continue;
}
for i in 0..n {
let cur = old[s + i];
let mut prev = cur;
for k in 1..n {
let c = old[s + (i + n - k) % n];
if c != cur {
prev = c;
break;
}
}
let mut next = cur;
for k in 1..n {
let c = old[s + (i + k) % n];
if c != cur {
next = c;
break;
}
}
if prev == cur || next == cur {
continue; }
let norm = |d: [f32; 2]| -> Option<[f32; 2]> {
let l = (d[0] * d[0] + d[1] * d[1]).sqrt();
(l > 1e-6).then(|| [d[0] / l, d[1] / l])
};
let Some(din) = norm([cur[0] - prev[0], cur[1] - prev[1]]) else {
continue;
};
let Some(dout) = norm([next[0] - cur[0], next[1] - cur[1]]) else {
continue;
};
let n_in = [sign * din[1], -sign * din[0]];
let n_out = [sign * dout[1], -sign * dout[0]];
let bis = [n_in[0] + n_out[0], n_in[1] + n_out[1]];
let l = (bis[0] * bis[0] + bis[1] * bis[1]).sqrt();
let (dir, dist) = if l > 1e-3 {
([bis[0] / l, bis[1] / l], (half * 2.0 / l).min(half * 2.0))
} else {
(n_in, half)
};
self.points[s + i][0] += dir[0] * dist;
self.points[s + i][1] += dir[1] * dist;
}
}
}
}
impl OutlinePen for Outline {
fn move_to(&mut self, x: f32, y: f32) {
self.verbs.push(OutlineVerb::MoveTo);
self.points.push([x, y]);
}
fn line_to(&mut self, x: f32, y: f32) {
self.verbs.push(OutlineVerb::LineTo);
self.points.push([x, y]);
}
fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
self.verbs.push(OutlineVerb::QuadTo);
self.points.push([cx0, cy0]);
self.points.push([x, y]);
}
fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
self.verbs.push(OutlineVerb::CurveTo);
self.points.push([cx0, cy0]);
self.points.push([cx1, cy1]);
self.points.push([x, y]);
}
fn close(&mut self) {
self.verbs.push(OutlineVerb::Close);
}
}
#[derive(Debug, Clone)]
pub struct FontProgram {
data: Arc<[u8]>,
units_per_em: u16,
num_glyphs: u16,
kind: ProgramKind,
name_index: Arc<std::sync::OnceLock<std::collections::HashMap<Box<[u8]>, u32>>>,
gid_to_char: Arc<std::sync::OnceLock<std::collections::HashMap<u32, char>>>,
}
#[derive(Debug, Clone)]
enum ProgramKind {
Sfnt { index: u32, wrapped_bare_cff: bool },
Type1(crate::font::type1::SharedType1),
}
fn valid_units_per_em(upem: u16) -> bool {
(16..=16384).contains(&upem)
}
impl FontProgram {
pub fn parse(data: Arc<[u8]>) -> Option<Self> {
Self::parse_indexed(data, 0)
}
pub fn parse_indexed(data: Arc<[u8]>, index: u32) -> Option<Self> {
let sfnt = Self::font_ref_at(&data, index).and_then(|font| {
let upem = font
.metrics(Size::unscaled(), LocationRef::default())
.units_per_em;
Some((upem, font.maxp().ok()?.num_glyphs()))
});
if let Some((units_per_em, num_glyphs)) = sfnt.filter(|&(upem, _)| valid_units_per_em(upem))
{
return Some(Self {
data,
units_per_em,
num_glyphs,
kind: ProgramKind::Sfnt {
index,
wrapped_bare_cff: false,
},
name_index: Arc::default(),
gid_to_char: Arc::default(),
});
}
if crate::font::cff::is_bare_cff(&data)
&& let Some(wrapped) = crate::font::cff::wrap_bare_cff(&data)
{
let wrapped: Arc<[u8]> = Arc::from(wrapped);
let info = Self::font_ref_at(&wrapped, 0).and_then(|font| {
let upem = font
.metrics(Size::unscaled(), LocationRef::default())
.units_per_em;
Some((upem, font.maxp().ok()?.num_glyphs()))
});
if let Some((units_per_em, num_glyphs)) =
info.filter(|&(upem, _)| valid_units_per_em(upem))
{
return Some(Self {
data: wrapped,
units_per_em,
num_glyphs,
kind: ProgramKind::Sfnt {
index: 0,
wrapped_bare_cff: true,
},
name_index: Arc::default(),
gid_to_char: Arc::default(),
});
}
}
let t1 = crate::font::type1::Type1Font::parse(&data)?;
Some(Self {
units_per_em: t1.units_per_em(),
num_glyphs: t1.num_glyphs(),
kind: ProgramKind::Type1(Arc::new(t1)),
data,
name_index: Arc::default(),
gid_to_char: Arc::default(),
})
}
pub fn is_type1(&self) -> bool {
matches!(self.kind, ProgramKind::Type1(_))
}
pub fn retained_bytes(&self) -> usize {
let parsed = match &self.kind {
ProgramKind::Type1(t1) => t1.heap_bytes(),
ProgramKind::Sfnt { .. } => 0,
};
self.data.len() + parsed
}
pub fn benefits_from_parse_cache(&self) -> bool {
matches!(
self.kind,
ProgramKind::Type1(_)
| ProgramKind::Sfnt {
wrapped_bare_cff: true,
..
}
)
}
fn font_ref_at(data: &[u8], index: u32) -> Option<FontRef<'_>> {
match skrifa::raw::FileRef::new(data).ok()? {
skrifa::raw::FileRef::Font(f) => (index == 0).then_some(f),
skrifa::raw::FileRef::Collection(c) => c.get(index).ok(),
}
}
fn font_ref(&self) -> Option<FontRef<'_>> {
let index = match self.kind {
ProgramKind::Sfnt { index, .. } => index,
ProgramKind::Type1(_) => return None,
};
Self::font_ref_at(&self.data, index)
}
pub fn units_per_em(&self) -> u16 {
self.units_per_em
}
pub fn num_glyphs(&self) -> u16 {
self.num_glyphs
}
pub fn outline(&self, glyph_id: u32) -> Option<Outline> {
if let ProgramKind::Type1(t1) = &self.kind {
return t1.outline(glyph_id);
}
let font = self.font_ref()?;
Self::outline_from(&font.outline_glyphs(), glyph_id)
}
pub fn outlines(&self, glyph_ids: &[u32]) -> Vec<Option<Outline>> {
if let ProgramKind::Type1(t1) = &self.kind {
return glyph_ids.iter().map(|&g| t1.outline(g)).collect();
}
let Some(font) = self.font_ref() else {
return vec![None; glyph_ids.len()];
};
let glyphs = font.outline_glyphs();
glyph_ids
.iter()
.map(|&g| Self::outline_from(&glyphs, g))
.collect()
}
pub fn outlines_hinted(&self, glyph_ids: &[u32], ppem: f32) -> Option<Vec<Option<Outline>>> {
if matches!(self.kind, ProgramKind::Type1(_)) {
return None;
}
let font = self.font_ref()?;
let glyphs = font.outline_glyphs();
let size = Size::new(ppem);
let instance = HintingInstance::new(
&glyphs,
size,
LocationRef::default(),
HintingOptions::default(),
)
.ok()?;
Some(
glyph_ids
.iter()
.map(|&g| {
let glyph = glyphs.get(GlyphId::new(g))?;
let mut outline = Outline::default();
glyph
.draw(DrawSettings::hinted(&instance, false), &mut outline)
.ok()?;
(!outline.is_empty()).then_some(outline)
})
.collect(),
)
}
pub fn gid_for_char(&self, c: char) -> Option<u32> {
if let ProgramKind::Type1(t1) = &self.kind {
return t1.gid_for_char(c);
}
let font = self.font_ref()?;
font.charmap().map(c).map(|g| g.to_u32()).or_else(|| {
let code = crate::font::encoding::macroman_code_for_char(c)?;
self.native_byte_cmap_gid(code, true)
})
}
pub fn char_for_gid(&self, glyph_id: u32) -> Option<char> {
if glyph_id == 0 {
return None;
}
let map = self.gid_to_char.get_or_init(|| {
let mut map: std::collections::HashMap<u32, char> = std::collections::HashMap::new();
let Some(font) = self.font_ref() else {
return map;
};
for (codepoint, gid) in font.charmap().mappings() {
let gid = gid.to_u32();
if gid == 0 {
continue;
}
let scalar = if (0xF000..=0xF0FF).contains(&codepoint) {
codepoint - 0xF000
} else {
codepoint
};
if scalar < 0x20 || (0x7F..=0x9F).contains(&scalar) {
continue;
}
let Some(ch) = char::from_u32(scalar) else {
continue;
};
match map.get(&gid) {
Some(&existing) if !reverse_char_is_better(ch, existing) => {}
_ => {
map.insert(gid, ch);
}
}
}
map
});
map.get(&glyph_id).copied()
}
pub fn gid_for_name(&self, name: &[u8]) -> Option<u32> {
if let ProgramKind::Type1(t1) = &self.kind {
return t1.gid_for_name(name);
}
let index = self.name_index.get_or_init(|| {
let mut map: std::collections::HashMap<Box<[u8]>, u32> =
std::collections::HashMap::new();
if let Some(font) = self.font_ref()
&& let Ok(post) = font.post()
{
for gid in 0..self.num_glyphs {
if let Some(n) = post.glyph_name(skrifa::raw::types::GlyphId16::new(gid)) {
map.entry(n.as_bytes().into()).or_insert(gid as u32);
}
}
}
map
});
index.get(name).copied()
}
pub fn advance(&self, glyph_id: u32) -> Option<f32> {
if let ProgramKind::Type1(t1) = &self.kind {
return t1.advance(glyph_id);
}
let font = self.font_ref()?;
font.glyph_metrics(Size::unscaled(), LocationRef::default())
.advance_width(GlyphId::new(glyph_id))
}
pub fn gid_for_code(&self, code: u8) -> Option<u32> {
if let ProgramKind::Type1(t1) = &self.kind {
return t1.gid_for_code(code);
}
let font = self.font_ref()?;
let cm = font.charmap();
cm.map(code as u32)
.or_else(|| cm.map(0xF000 | code as u32))
.map(|g| g.to_u32())
.or_else(|| self.native_byte_cmap_gid(code, false))
}
fn native_byte_cmap_gid(&self, code: u8, prefer_mac: bool) -> Option<u32> {
let data: &[u8] = &self.data;
let u16at = |o: usize| -> Option<u32> {
Some(((*data.get(o)? as u32) << 8) | *data.get(o + 1)? as u32)
};
let u32at = |o: usize| -> Option<u32> { Some((u16at(o)? << 16) | u16at(o + 2)?) };
let mut base = 0usize;
if data.get(0..4)? == b"ttcf" {
let index = match self.kind {
ProgramKind::Sfnt { index, .. } => index as usize,
ProgramKind::Type1(_) => return None,
};
base = u32at(12 + 4 * index)? as usize;
}
let tag = data.get(base..base + 4)?;
if tag != [0x00, 0x01, 0x00, 0x00] && tag != *b"true" && tag != *b"OTTO" {
return None;
}
let num_tables = u16at(base + 4)? as usize;
let mut cmap = None;
for i in 0..num_tables {
let rec = base + 12 + 16 * i;
if data.get(rec..rec + 4)? == b"cmap" {
cmap = Some(u32at(rec + 8)? as usize);
break;
}
}
let cmap = cmap?;
let n_sub = u16at(cmap + 2)? as usize;
let priorities = if prefer_mac {
[(1, 0), (3, 1), (3, 10), (0, 3), (0, 4), (0, 0)]
} else {
[(3, 1), (3, 10), (1, 0), (0, 3), (0, 4), (0, 0)]
};
for (platform, encoding) in priorities {
for i in 0..n_sub {
let rec = cmap + 4 + 8 * i;
if u16at(rec)? != platform || u16at(rec + 2)? != encoding {
continue;
}
let sub = cmap + u32at(rec + 4)? as usize;
let gid = match u16at(sub)? {
0 => *data.get(sub + 6 + code as usize)? as u32,
6 => {
let first = u16at(sub + 6)?;
let count = u16at(sub + 8)?;
let c = code as u32;
if c < first || c >= first + count {
continue;
}
u16at(sub + 10 + 2 * (c - first) as usize)?
}
_ => continue,
};
if gid != 0 {
return Some(gid);
}
}
}
None
}
fn outline_from(
glyphs: &skrifa::outline::OutlineGlyphCollection,
glyph_id: u32,
) -> Option<Outline> {
let glyph = glyphs.get(GlyphId::new(glyph_id))?;
let mut out = Outline::default();
glyph
.draw(
DrawSettings::unhinted(Size::unscaled(), LocationRef::default()),
&mut out,
)
.ok()?;
if out.is_empty() { None } else { Some(out) }
}
}
fn reverse_char_is_better(candidate: char, current: char) -> bool {
let pua = |c: char| ('\u{E000}'..='\u{F8FF}').contains(&c);
match (pua(candidate), pua(current)) {
(false, true) => true,
(true, false) => false,
_ => (candidate as u32) < (current as u32),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::test_support::fonts::minimal_ttf;
#[test]
fn parses_and_reports_metrics() {
let prog = FontProgram::parse(minimal_ttf().into()).expect("parse");
assert_eq!(prog.units_per_em(), 1000);
assert_eq!(prog.num_glyphs(), 2);
}
#[test]
fn oblique_shears_points_by_y() {
let mut o = Outline {
verbs: vec![OutlineVerb::MoveTo, OutlineVerb::LineTo, OutlineVerb::Close],
points: vec![[0.0, 0.0], [100.0, 500.0]],
};
o.oblique(0.2);
assert_eq!(o.points[0], [0.0, 0.0]);
assert_eq!(o.points[1], [200.0, 500.0]);
}
#[test]
fn embolden_grows_outer_contours_and_shrinks_holes() {
let sq = |a: f32, b: f32, ccw: bool| -> Vec<[f32; 2]> {
let pts = vec![[a, a], [b, a], [b, b], [a, b]];
if ccw {
pts
} else {
pts.into_iter().rev().collect()
}
};
let mut verbs = Vec::new();
let mut points = Vec::new();
for contour in [sq(100.0, 900.0, true), sq(400.0, 600.0, false)] {
verbs.push(OutlineVerb::MoveTo);
verbs.extend(std::iter::repeat_n(OutlineVerb::LineTo, contour.len() - 1));
verbs.push(OutlineVerb::Close);
points.extend(contour);
}
let mut o = Outline { verbs, points };
o.embolden(70.0);
assert!(
o.points[0][0] < 100.0 && o.points[0][1] < 100.0,
"{:?}",
o.points[0]
);
assert!(
o.points[0][0] > 100.0 - 71.0,
"bounded miter: {:?}",
o.points[0]
);
for p in &o.points[4..8] {
let (dx, dy) = (p[0] - 500.0, p[1] - 500.0);
assert!(
dx.abs() < 100.0 - 20.0 && dy.abs() < 100.0 - 20.0,
"hole must shrink: {p:?}"
);
}
}
#[test]
fn mac_only_cmap_resolves_through_the_native_fallback() {
let prog =
FontProgram::parse(crate::test_support::fonts::minimal_ttf_mac_cmap_only().into())
.expect("parse");
assert_eq!(prog.gid_for_code(0x41), Some(1), "raw byte through (1,0)");
assert_eq!(
prog.gid_for_char('A'),
Some(1),
"unicode -> MacRoman -> (1,0)"
);
assert_eq!(prog.gid_for_code(0x42), None, "unmapped code stays notdef");
}
#[test]
fn microsoft_format_6_cmap_resolves_raw_codes() {
let mut ttf = crate::test_support::fonts::minimal_ttf_mac_cmap_only();
patch_only_cmap_platform(&mut ttf, 3, 1);
let prog = FontProgram::parse(ttf.into()).expect("parse");
assert_eq!(
prog.gid_for_code(0x41),
Some(1),
"raw byte through Microsoft (3,1) format 6"
);
}
fn patch_only_cmap_platform(ttf: &mut [u8], platform: u16, encoding: u16) {
let num_tables = u16::from_be_bytes([ttf[4], ttf[5]]) as usize;
for i in 0..num_tables {
let rec = 12 + i * 16;
if &ttf[rec..rec + 4] == b"cmap" {
let off = u32::from_be_bytes(ttf[rec + 8..rec + 12].try_into().unwrap()) as usize;
ttf[off + 4..off + 6].copy_from_slice(&platform.to_be_bytes());
ttf[off + 6..off + 8].copy_from_slice(&encoding.to_be_bytes());
return;
}
}
panic!("no cmap table");
}
#[test]
fn extracts_triangle_glyph_outline() {
let prog = FontProgram::parse(minimal_ttf().into()).expect("parse");
assert!(prog.outline(0).is_none());
let o = prog.outline(1).expect("glyph 1 outline");
assert_eq!(o.verbs[0], OutlineVerb::MoveTo);
assert!(o.verbs.contains(&OutlineVerb::Close));
let xs: Vec<f32> = o.points.iter().map(|p| p[0]).collect();
assert!(xs.iter().cloned().fold(f32::MAX, f32::min) <= 100.5);
assert!(xs.iter().cloned().fold(f32::MIN, f32::max) >= 899.5);
}
#[test]
fn garbage_bytes_do_not_parse() {
assert!(FontProgram::parse(vec![0u8; 32].into()).is_none());
}
#[test]
fn valid_units_per_em_matches_freetype_range() {
assert!(!valid_units_per_em(0));
assert!(!valid_units_per_em(14));
assert!(!valid_units_per_em(15));
assert!(valid_units_per_em(16));
assert!(valid_units_per_em(1000));
assert!(valid_units_per_em(2048));
assert!(valid_units_per_em(16384));
assert!(!valid_units_per_em(16385));
}
#[test]
fn out_of_range_units_per_em_is_rejected() {
let mut ttf = minimal_ttf();
patch_units_per_em(&mut ttf, 14);
assert!(
FontProgram::parse(ttf.into()).is_none(),
"unitsPerEm=14 must be rejected"
);
assert!(FontProgram::parse(minimal_ttf().into()).is_some());
}
fn patch_units_per_em(ttf: &mut [u8], upem: u16) {
let num_tables = u16::from_be_bytes([ttf[4], ttf[5]]) as usize;
for i in 0..num_tables {
let rec = 12 + i * 16;
if &ttf[rec..rec + 4] == b"head" {
let off = u32::from_be_bytes(ttf[rec + 8..rec + 12].try_into().unwrap()) as usize;
ttf[off + 18..off + 20].copy_from_slice(&upem.to_be_bytes());
return;
}
}
panic!("no head table");
}
#[test]
fn char_for_gid_reverses_the_cmap() {
let prog = FontProgram::parse(minimal_ttf().into()).expect("parse");
let gid = prog.gid_for_char('A').expect("'A' resolves");
assert_eq!(prog.char_for_gid(gid), Some('A'));
assert_eq!(prog.char_for_gid(0), None, "notdef has no identity");
}
}
#[cfg(test)]
mod hinting_tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::font::standard::StandardFont;
fn helvetica() -> FontProgram {
StandardFont::Helvetica
.program()
.expect("bundled face parses")
}
#[test]
fn policy_gates_on_ppem_and_alignment() {
for p in [
HintingPolicy::None,
HintingPolicy::Embedded,
HintingPolicy::Auto,
] {
assert!(
!p.should_hint(12.0, false),
"{p:?} must not hint skewed text"
);
assert!(!p.should_hint(0.0, true), "{p:?} must not hint a zero ppem");
}
assert!(!HintingPolicy::None.should_hint(12.0, true));
assert!(HintingPolicy::Embedded.should_hint(400.0, true));
assert!(HintingPolicy::Auto.should_hint(12.0, true));
assert!(HintingPolicy::Auto.should_hint(AUTO_HINT_MAX_PPEM, true));
assert!(!HintingPolicy::Auto.should_hint(AUTO_HINT_MAX_PPEM + 0.1, true));
assert!(HintingPolicy::Auto.should_hint(10.0 * 300.0 / 72.0, true));
assert!(!HintingPolicy::Auto.should_hint(10.0 * 600.0 / 72.0, true));
}
#[test]
fn hinted_outlines_are_in_pixels_and_differ_from_unhinted() {
let f = helvetica();
let gid = f.gid_for_char('H').unwrap();
let ppem = 12.0;
let hinted = f
.outlines_hinted(&[gid], ppem)
.expect("hinting instance builds")[0]
.clone()
.expect("'H' hints to an outline");
let unhinted = f.outline(gid).expect("'H' has an outline");
let extent = |o: &Outline| {
o.points
.iter()
.fold(0f32, |m, p| m.max(p[0].abs()).max(p[1].abs()))
};
assert!(extent(&unhinted) > 100.0, "design units");
assert!(
extent(&hinted) < 30.0,
"pixels at 12ppem: {}",
extent(&hinted)
);
assert_eq!(hinted.verbs, unhinted.verbs, "hinting preserves contours");
}
#[test]
fn hinting_snaps_stems_to_the_grid() {
let f = helvetica();
let gid = f.gid_for_char('H').unwrap();
let ppem = 16.0;
let hinted = f.outlines_hinted(&[gid], ppem).unwrap()[0].clone().unwrap();
let off_grid = |o: &Outline| {
let n = o.points.len() as f32;
o.points
.iter()
.map(|p| (p[1] - p[1].round()).abs())
.sum::<f32>()
/ n
};
let scaled = {
let mut o = f.outline(gid).unwrap();
let s = ppem / f.units_per_em() as f32;
for p in &mut o.points {
p[0] *= s;
p[1] *= s;
}
o
};
assert!(
off_grid(&hinted) < off_grid(&scaled),
"hinted y {} should sit closer to the grid than scaled y {}",
off_grid(&hinted),
off_grid(&scaled)
);
}
#[test]
fn hinting_is_deterministic() {
let f = helvetica();
let gids: Vec<u32> = "Hamburg"
.chars()
.filter_map(|c| f.gid_for_char(c))
.collect();
let a = f.outlines_hinted(&gids, 14.0).unwrap();
let b = f.outlines_hinted(&gids, 14.0).unwrap();
assert_eq!(a, b, "same font, same ppem => identical outlines");
}
}