mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 04:25:52 -05:00
Merge pull request #10250 from dotCooCoo/fix/retype-period-font-order
Retype: glyphs drawn alike in several fonts count as one outline in near matching
This commit is contained in:
3 files changed
+252
-49
No files matched your search
@@ -1933,7 +1933,8 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line
|
||||
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
|
||||
let fonts: Vec<String> = family.into_iter().map(str::to_string).collect();
|
||||
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &fonts), &wanted);
|
||||
let first = index.matches(&pieces[0].path);
|
||||
// Every match, as Retype reads them: the first MAX_CANDIDATES can all be faces drawn alike.
|
||||
let first = index.all_matches(&pieces[0].path);
|
||||
let face = match family {
|
||||
Some(f) => first.iter().find(|m| m.face.family == f).unwrap_or_else(|| panic!("the first glyph matches no glyph of {f}")),
|
||||
None => &first[0],
|
||||
@@ -1942,7 +1943,7 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line
|
||||
.id();
|
||||
let mut lines: Vec<super::Line> = vec![];
|
||||
for pc in &pieces {
|
||||
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
|
||||
let cands: Vec<_> = index.all_matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
|
||||
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
|
||||
lines.extend(super::new_line(pc, &cands, 0.0));
|
||||
}
|
||||
|
||||
+239
-40
@@ -79,8 +79,12 @@ pub const MAX_NEAR_KEYS: usize = 1024;
|
||||
const NEAR_WORK: u64 = 2_000_000_000;
|
||||
/// Point comparisons near matching makes for one shape, at most.
|
||||
const NEAR_SHAPE_WORK: u64 = 50_000_000;
|
||||
/// Glyphs one shape is near matched against, at most: those closest to it in proportion.
|
||||
/// Outlines one shape is near matched against, at most: those closest to it in proportion, each
|
||||
/// with every glyph drawn as it is.
|
||||
const NEAR_FITS: usize = 256;
|
||||
/// Outlines with one [`outline_hash`] that near matching compares a glyph's outline with, at most:
|
||||
/// past them, a glyph whose outline hashes alike is an outline of its own.
|
||||
const MAX_HASH_CLASHES: usize = 4;
|
||||
/// Contours [`clusters`] reads, at most: past it, none.
|
||||
const MAX_CLUSTER_CONTOURS: usize = 1024;
|
||||
|
||||
@@ -173,6 +177,8 @@ struct Entry {
|
||||
sig: Signature,
|
||||
/// The glyph's outline in font units, for the whole-outline check.
|
||||
outline: BezPath,
|
||||
/// [`outline_hash`] of `outline`: glyphs drawn alike hash alike.
|
||||
drawn: u64,
|
||||
/// Whether the glyph was indexed for its exact key: only these take part in exact matching,
|
||||
/// and the ones indexed only for near matching ([`RetypeIndex::near_matches`]) do not.
|
||||
exact: bool,
|
||||
@@ -285,7 +291,7 @@ impl RetypeIndex {
|
||||
if keys.contains(&key) {
|
||||
let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid));
|
||||
if let Some(sig) = signatures(&outline, false).into_iter().next() {
|
||||
entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true });
|
||||
entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: true });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -308,7 +314,7 @@ impl RetypeIndex {
|
||||
break 'faces;
|
||||
}
|
||||
if let Some(sig) = signatures(&outline, false).into_iter().next() {
|
||||
entries.push(Entry { face: fi, gid, ch, sig, outline, exact: false });
|
||||
entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -496,17 +502,19 @@ impl RetypeIndex {
|
||||
/// shape need not be built as the glyph is. Upright ones first, then the closest; the other
|
||||
/// turns a glyph fits in (at most 7) are kept in [`GlyphMatch::alts`]; at most
|
||||
/// [`MAX_CANDIDATES`] for each face. Empty for a tolerance of 0 or less, and for shapes of more
|
||||
/// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion
|
||||
/// (the spread-to-length ratio, and the share of the length each contour has), closest first,
|
||||
/// in at most 50 million point comparisons, and the index's calls make at most 2 billion in
|
||||
/// all (ranking a glyph by proportion counts as one per contour and one more); once they are
|
||||
/// spent, the glyphs not yet ranked or compared are left out.
|
||||
/// than 8 contours. A shape is compared with the glyphs of at most the 256 outlines closest to
|
||||
/// it in proportion (the spread-to-length ratio, and the share of the length each contour has),
|
||||
/// closest first; glyphs drawn alike, in several faces or in one, are one outline and are fitted
|
||||
/// once. A shape takes at most 50 million point comparisons, and the index's calls make at most
|
||||
/// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more, and
|
||||
/// comparing its outline with one of at most 4 others with the same hash as one per element of
|
||||
/// its outline); once they are spent, the glyphs not yet ranked or compared are left out.
|
||||
pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec<GlyphMatch> {
|
||||
self.near_matches_among(shape, tolerance, None)
|
||||
}
|
||||
|
||||
/// [`Self::near_matches`] among the glyphs of the indexed face with id `face` alone: the 256
|
||||
/// of its glyphs closest to `shape` in proportion, which the glyphs of the other faces cannot
|
||||
/// [`Self::near_matches`] among the glyphs of the indexed face with id `face` alone: the glyphs
|
||||
/// of the 256 of its outlines closest to `shape` in proportion, which the glyphs of the other faces cannot
|
||||
/// crowd out. Empty when the index does not hold that face.
|
||||
pub fn near_matches_in(&self, shape: &BezPath, tolerance: f64, face: u32) -> Vec<GlyphMatch> {
|
||||
match self.faces.iter().position(|f| f.id() == face) {
|
||||
@@ -544,20 +552,34 @@ impl RetypeIndex {
|
||||
}
|
||||
};
|
||||
let near = self.ranked_near(&s, only, &mut work);
|
||||
for (_, e) in near {
|
||||
if work == 0 {
|
||||
break;
|
||||
}
|
||||
// The outline fitted last and its poses: the glyphs drawn alike after it take them, with no
|
||||
// second comparison of their outlines.
|
||||
let mut last: Option<(usize, Option<NearPoses>)> = None;
|
||||
for (_, outline, e) in near {
|
||||
let Some(face) = self.faces.get(e.face) else { continue };
|
||||
let fits = near_fit(&e.sig, &s, tolerance, &mut work);
|
||||
let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol));
|
||||
let Some(flat) = flat.as_ref() else { break };
|
||||
// Every turn the glyph fits the shape at, nearest upright first: the first is its
|
||||
// pose, the others its alternatives (a glyph that looks alike turned).
|
||||
let mut poses =
|
||||
fits.into_iter().filter(|f| f.1 <= tolerance).filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))).take(MAX_NEAR_POSES);
|
||||
let Some((pose, residual)) = poses.next() else { continue };
|
||||
let rest: Vec<(Pose, f64)> = poses.collect();
|
||||
let alike = last.as_ref().filter(|(l, _)| *l == outline).map(|(_, p)| p.clone());
|
||||
let posed = match alike {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
if work == 0 {
|
||||
break;
|
||||
}
|
||||
let fits = near_fit(&e.sig, &s, tolerance, &mut work);
|
||||
let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol));
|
||||
let Some(flat) = flat.as_ref() else { break };
|
||||
// Every turn the glyph fits the shape at, nearest upright first: the first is its
|
||||
// pose, the others its alternatives (a glyph that looks alike turned).
|
||||
let mut poses = fits
|
||||
.into_iter()
|
||||
.filter(|f| f.1 <= tolerance)
|
||||
.filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r)))
|
||||
.take(MAX_NEAR_POSES);
|
||||
let p = poses.next().map(|(pose, residual)| (pose, residual, poses.collect()));
|
||||
last = Some((outline, p.clone()));
|
||||
p
|
||||
}
|
||||
};
|
||||
let Some((pose, residual, rest)) = posed else { continue };
|
||||
let m = GlyphMatch {
|
||||
face: face.clone(),
|
||||
gid: e.gid,
|
||||
@@ -583,12 +605,18 @@ impl RetypeIndex {
|
||||
out.into_iter().map(|(_, m)| m).collect()
|
||||
}
|
||||
|
||||
/// The glyphs of as many contours as near-matching shape `s` that are closest to it in
|
||||
/// proportion, at most [`NEAR_FITS`], closest first: their spread-to-length ratio, and the
|
||||
/// share of the length each contour has, longest first. Ranking a glyph takes one comparison
|
||||
/// per contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are
|
||||
/// left out. With `only`, the glyphs of that face (an index into `faces`) alone.
|
||||
fn ranked_near(&self, s: &Signature, only: Option<usize>, work: &mut u64) -> Vec<(f64, &Entry)> {
|
||||
/// The glyphs of as many contours as near-matching shape `s` whose outlines are among the
|
||||
/// [`NEAR_FITS`] outlines closest to it in proportion, closest first: their spread-to-length
|
||||
/// ratio, and the share of the length each contour has, longest first. Glyphs drawn alike (one
|
||||
/// outline in several faces, or in several glyphs of one face) are one outline and come
|
||||
/// together, in index order, so copies of a font do not crowd out the glyphs of the faces they
|
||||
/// copy; outlines as close come in index order. Ranking a glyph takes one comparison per
|
||||
/// contour, and one more, from `work`, and comparing its outline with one that hashes alike (at
|
||||
/// most [`MAX_HASH_CLASHES`] of them) one per element of its outline; once it is spent, the
|
||||
/// glyphs not yet ranked are left out. Each glyph comes with its distance and the number of
|
||||
/// its outline in the list, the same for every glyph drawn alike. With `only`, the glyphs of
|
||||
/// that face (an index into `faces`) alone.
|
||||
fn ranked_near(&self, s: &Signature, only: Option<usize>, work: &mut u64) -> Vec<(f64, usize, &Entry)> {
|
||||
let Some(list) = self.buckets.get(&s.contours) else { return vec![] };
|
||||
let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK);
|
||||
let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK);
|
||||
@@ -610,27 +638,64 @@ impl RetypeIndex {
|
||||
if d.is_finite() { d } else { f64::INFINITY }
|
||||
};
|
||||
let cost = s.contours as u64 + 1;
|
||||
let mut near: Vec<(f64, &Entry)> = vec![];
|
||||
for e in list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi) {
|
||||
// Each outline with its distance and its glyphs, in the order they are ranked; the list
|
||||
// is sorted by invariant and then by index, so each outline's first glyph is its lowest.
|
||||
let mut outlines: Vec<(f64, Vec<(usize, &Entry)>)> = vec![];
|
||||
let mut by_drawn: HashMap<u64, Vec<usize>> = HashMap::new();
|
||||
for (i, e) in list.iter().skip(start).filter_map(|i| Some((*i, self.entries.get(*i)?))).take_while(|(_, e)| e.sig.invariant <= hi) {
|
||||
if only.is_some_and(|f| e.face != f) {
|
||||
continue;
|
||||
}
|
||||
let Some(left) = work.checked_sub(cost) else { break };
|
||||
*work = left;
|
||||
near.push((apart(e), e));
|
||||
let same = by_drawn.entry(e.drawn).or_default();
|
||||
// Each outline that hashes alike is compared with this one in full, one comparison per
|
||||
// element of its outline.
|
||||
let compare = e.outline.elements().len() as u64;
|
||||
let (mut found, mut spent) = (None, false);
|
||||
for k in same.iter().copied() {
|
||||
let Some(left) = work.checked_sub(compare) else {
|
||||
spent = true;
|
||||
break;
|
||||
};
|
||||
*work = left;
|
||||
if outlines.get(k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e)) {
|
||||
found = Some(k);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if spent {
|
||||
break;
|
||||
}
|
||||
match found.and_then(|k| outlines.get_mut(k)) {
|
||||
Some(o) => o.1.push((i, e)),
|
||||
None => {
|
||||
// Past MAX_HASH_CLASHES outlines that hash alike, the others are not compared:
|
||||
// each is an outline of its own.
|
||||
if same.len() < MAX_HASH_CLASHES {
|
||||
same.push(outlines.len());
|
||||
}
|
||||
outlines.push((apart(e), vec![(i, e)]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if near.len() > NEAR_FITS {
|
||||
near.select_nth_unstable_by(NEAR_FITS, |a, b| a.0.total_cmp(&b.0));
|
||||
near.truncate(NEAR_FITS);
|
||||
let first = |o: &(f64, Vec<(usize, &Entry)>)| o.1.first().map_or(usize::MAX, |(i, _)| *i);
|
||||
let order = |a: &(f64, Vec<(usize, &Entry)>), b: &(f64, Vec<(usize, &Entry)>)| a.0.total_cmp(&b.0).then(first(a).cmp(&first(b)));
|
||||
if outlines.len() > NEAR_FITS {
|
||||
outlines.select_nth_unstable_by(NEAR_FITS, order);
|
||||
outlines.truncate(NEAR_FITS);
|
||||
}
|
||||
near.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
near
|
||||
outlines.sort_by(order);
|
||||
outlines.into_iter().enumerate().flat_map(|(k, (d, glyphs))| glyphs.into_iter().map(move |(_, e)| (d, k, e))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives.
|
||||
const MAX_NEAR_POSES: usize = 8;
|
||||
|
||||
/// A near-matched glyph's pose and leftover distance, and its other poses, each with its own.
|
||||
type NearPoses = (Pose, f64, Vec<(Pose, f64)>);
|
||||
|
||||
/// `out` (each match with its face's index) without the matches past the first
|
||||
/// [`MAX_CANDIDATES`] of each face, so faces drawn alike (copies of one font under other names)
|
||||
/// do not crowd out the glyphs of the faces after them.
|
||||
@@ -643,6 +708,40 @@ fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether glyphs `a` and `b` are drawn alike: the same outline in font units.
|
||||
fn drawn_alike(a: &Entry, b: &Entry) -> bool {
|
||||
#[cfg(test)]
|
||||
OUTLINES_COMPARED.set(OUTLINES_COMPARED.get() + 1);
|
||||
a.drawn == b.drawn && a.outline == b.outline
|
||||
}
|
||||
|
||||
/// A hash of `outline`'s elements and points: outlines drawn alike hash alike.
|
||||
fn outline_hash(outline: &BezPath) -> u64 {
|
||||
// FNV-1a, as `key_and_count`; a rare clash only compares two outlines in full.
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
let mut add = |v: u64| {
|
||||
for b in v.to_le_bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
};
|
||||
for el in outline.elements() {
|
||||
let (tag, pts) = match *el {
|
||||
PathEl::MoveTo(p) => (0, [p, p, p]),
|
||||
PathEl::LineTo(p) => (1, [p, p, p]),
|
||||
PathEl::QuadTo(a, b) => (2, [a, b, b]),
|
||||
PathEl::CurveTo(a, b, c) => (3, [a, b, c]),
|
||||
PathEl::ClosePath => (4, [Point::ZERO; 3]),
|
||||
};
|
||||
add(tag);
|
||||
for p in pts {
|
||||
add(p.x.to_bits());
|
||||
add(p.y.to_bits());
|
||||
}
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// Entry `e`'s pose on near-matching shape `s` at scaled turn `z`, when its whole outline, so
|
||||
/// placed, lies within `tol` of the shape's (`flat`).
|
||||
fn near_pose(e: &Entry, s: &Signature, z: (f64, f64), flat: &Flat, tol: f64) -> Option<Pose> {
|
||||
@@ -1742,6 +1841,8 @@ fn sample(cs: &[(Vec<PathSeg>, Vec<f64>)], starts: &[Vec<usize>], pick: &[usize]
|
||||
thread_local! {
|
||||
/// How many readings [`signatures`] tried on this thread, kept or not.
|
||||
static READINGS_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many outline comparisons [`drawn_alike`] made on this thread.
|
||||
static OUTLINES_COMPARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The first reading of `path` (for tests).
|
||||
@@ -2124,6 +2225,100 @@ mod tests {
|
||||
assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "near: {} matches", found.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_drawn_alike_in_many_faces_are_all_near_matched() {
|
||||
// Source Sans 3 Regular first, then 40 copies of it under other names: each face has nine
|
||||
// glyphs close to a period in proportion, 369 in all, more than the 256 near matching
|
||||
// compares a shape with, but nine outlines.
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let source = db.face("Source Sans 3", "Regular").unwrap();
|
||||
let mut faces = vec![source.clone()];
|
||||
for i in 0..40 {
|
||||
let family = format!("Alike {i} Sans");
|
||||
db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Alike{i}Sans-Regular"))).unwrap());
|
||||
faces.push(db.face(&family, "Regular").unwrap());
|
||||
}
|
||||
let gid = source.mapped_chars().iter().find(|(c, _)| *c == '.').map(|(_, g)| *g).unwrap();
|
||||
// Turned a half turn, as a line of type set upside down.
|
||||
let period =
|
||||
Affine::translate((300.0, 200.0)) * Affine::rotate(std::f64::consts::PI) * Affine::scale(0.04) * db.outline_uncached(&source, gid);
|
||||
let simple = simplified(&period, 0.05);
|
||||
let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]);
|
||||
let found = index.near_matches(&simple, 0.02);
|
||||
for f in &faces {
|
||||
assert!(found.iter().any(|m| m.ch == '.' && m.face.id() == f.id()), "{}: no period among {} matches", f.family, found.len());
|
||||
}
|
||||
// Each outline is fitted once, however many faces draw it: past ranking the copies' glyphs
|
||||
// (two comparisons each, for one contour, and one per element of the outline for comparing
|
||||
// it with Source Sans 3's), the comparisons spent are those of Source Sans 3 alone.
|
||||
let alone = RetypeIndex::build_near(&db, [source], &BTreeSet::new(), &[near_key(&simple).unwrap()]);
|
||||
let alone_found = alone.near_matches(&simple, 0.02);
|
||||
assert_eq!(found.len(), alone_found.len() * faces.len());
|
||||
let mut all = u64::MAX;
|
||||
let ranked: u64 =
|
||||
alone.ranked_near(&near_signature(&simple).unwrap(), None, &mut all).iter().map(|(_, _, e)| 2 + e.outline.elements().len() as u64).sum();
|
||||
let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire);
|
||||
assert_eq!(spent(&index), spent(&alone) + 40 * ranked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_drawn_alike_are_not_compared_again_after_ranking() {
|
||||
// Source Sans 3 Regular and 30 copies of it: ranking compares each copy's outlines with
|
||||
// the first face's and charges every comparison; fitting reuses the poses by outline and
|
||||
// compares no outline again.
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let source = db.face("Source Sans 3", "Regular").unwrap();
|
||||
let mut faces = vec![source.clone()];
|
||||
for i in 0..30 {
|
||||
let family = format!("Again {i} Sans");
|
||||
db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Again{i}Sans-Regular"))).unwrap());
|
||||
faces.push(db.face(&family, "Regular").unwrap());
|
||||
}
|
||||
let gid = source.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap();
|
||||
let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&source, gid);
|
||||
let simple = simplified(&shape, 0.05);
|
||||
let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]);
|
||||
OUTLINES_COMPARED.set(0);
|
||||
let mut all = u64::MAX;
|
||||
let ranked = index.ranked_near(&near_signature(&simple).unwrap(), None, &mut all);
|
||||
let in_ranking = OUTLINES_COMPARED.get();
|
||||
assert!(ranked.len() > faces.len(), "{} ranked", ranked.len());
|
||||
OUTLINES_COMPARED.set(0);
|
||||
let found = index.near_matches(&simple, 0.02);
|
||||
assert!(found.iter().any(|m| m.ch == 'o'), "no o among {} matches", found.len());
|
||||
assert_eq!(OUTLINES_COMPARED.get(), in_ranking, "outlines compared outside the charged ranking");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlines_whose_hashes_clash_are_compared_within_the_work_budget() {
|
||||
// 5,000 glyphs of one square each, moved apart, all given the same outline hash: each is
|
||||
// compared with at most MAX_HASH_CLASHES of the others, and each comparison is charged.
|
||||
let square = |i: usize| Affine::translate((i as f64, 0.0)) * kurbo::Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1);
|
||||
let n = 5_000;
|
||||
let entries: Vec<Entry> = (0..n)
|
||||
.map(|i| Entry { face: 0, gid: i as u32, ch: 'a', sig: signature(&square(i)).unwrap(), outline: square(i), drawn: 7, exact: false })
|
||||
.collect();
|
||||
let elements = square(0).elements().len() as u64;
|
||||
let s = signature(&square(0)).unwrap();
|
||||
let cost = s.contours as u64 + 1;
|
||||
let mut buckets = HashMap::new();
|
||||
buckets.insert(s.contours, (0..n).collect::<Vec<usize>>());
|
||||
let index = RetypeIndex { faces: vec![], entries, buckets, by_glyph: HashMap::new(), near_work: AtomicU64::new(NEAR_WORK) };
|
||||
let mut work = u64::MAX;
|
||||
let ranked = index.ranked_near(&s, None, &mut work);
|
||||
assert_eq!(ranked.len(), NEAR_FITS, "each square is an outline of its own");
|
||||
let compared: u64 = (0..n as u64).map(|i| i.min(MAX_HASH_CLASHES as u64)).sum();
|
||||
assert_eq!(u64::MAX - work, n as u64 * cost + compared * elements);
|
||||
// With too little work left for the comparisons, ranking stops where it runs out.
|
||||
let mut work = n as u64 * cost / 4;
|
||||
let short = index.ranked_near(&s, None, &mut work);
|
||||
assert!(short.len() < NEAR_FITS, "{} ranked", short.len());
|
||||
assert!(work < cost + elements, "{work} left");
|
||||
// Near matching the shape spends at most one shape's allowance and returns.
|
||||
index.near_matches(&square(0), 0.02);
|
||||
assert!(NEAR_WORK - index.near_work.load(Ordering::Acquire) <= NEAR_SHAPE_WORK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn near_matches_in_one_face_find_its_glyphs_however_many_faces_are_drawn_alike() {
|
||||
// Source Sans 3 Regular last, after 95 copies of it under other names: every face has
|
||||
@@ -2422,9 +2617,13 @@ mod tests {
|
||||
let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]);
|
||||
let s = near_signature(&shape).unwrap();
|
||||
let mut all = u64::MAX;
|
||||
let ranked = index.ranked_near(&s, None, &mut all).len();
|
||||
assert!(ranked >= 1, "the o is ranked");
|
||||
assert_eq!(u64::MAX - all, ranked as u64 * 3, "each glyph of two contours takes three");
|
||||
let ranked = index.ranked_near(&s, None, &mut all);
|
||||
assert!(!ranked.is_empty(), "the o is ranked");
|
||||
// The Greek omicron is drawn as the o: it is also compared with the o's outline.
|
||||
let compared =
|
||||
|i: usize, e: &Entry| if ranked[..i].iter().any(|(_, _, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 };
|
||||
let spent: u64 = ranked.iter().enumerate().map(|(i, (_, _, e))| 3 + compared(i, e)).sum();
|
||||
assert_eq!(u64::MAX - all, spent, "each glyph of two contours takes three, and one per element for each comparison");
|
||||
// Enough to rank one glyph of two contours and nothing more.
|
||||
let mut work = 4;
|
||||
assert_eq!(index.ranked_near(&s, None, &mut work).len(), 1);
|
||||
|
||||
+10
-7
@@ -13658,14 +13658,17 @@ glyphs may become separate objects that paint the overlap twice. When the split
|
||||
shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32
|
||||
for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours
|
||||
or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are
|
||||
matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at
|
||||
matched whole only. Near matching compares a shape with the glyphs of at most the 256 outlines closest to it in
|
||||
proportion; glyphs drawn alike (copies of one font under other names, or one outline under several characters) are one
|
||||
outline and are fitted once. It takes at
|
||||
most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one
|
||||
comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. Those 256 can
|
||||
all be glyphs of other fonts drawn alike (a period or a dot): a shape matched whole, whose matches are all near
|
||||
matches in other fonts than that of the line before it, is also compared with the 256 glyphs of that line's font
|
||||
closest to it in proportion when it does not join the line, and joins the line when one of them fits. A shape with an
|
||||
exact match, a shape split into several glyphs, a shape that matches no glyph at all and a shape after an unmatched
|
||||
shape are not compared again. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in
|
||||
comparison per contour and one more, and comparing its outline with one of at most 4 others that hash alike counting
|
||||
as one per element of its outline; past them, the glyphs not yet ranked or compared are left out. Those 256 outlines
|
||||
can all be glyphs of other fonts drawn alike (a period or a dot): a shape matched whole, whose matches are all near
|
||||
matches in other fonts than that of the line before it, is also compared with the glyphs of the 256 outlines of that
|
||||
line's font closest to it in proportion when it does not join the line, and joins the line when one of them fits. A
|
||||
shape with an exact match, a shape split into several glyphs, a shape that matches no glyph at all and a shape after an
|
||||
unmatched shape are not compared again. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in
|
||||
selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that
|
||||
limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768
|
||||
are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes
|
||||
|
||||
Reference in new issue
Block a user