From 5b0fbec41677dc5af9701e68de03272348546b84 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:55:01 -0800 Subject: [PATCH 1/3] Retype: glyphs drawn alike in several fonts count as one outline in near matching Near matching compared a shape with the 256 glyphs closest to it in proportion, over every indexed face. Faces that draw the same glyphs (Noto families sharing their Latin dots, copies of a font under other names) each took places among the 256, and when glyphs tied, which of them kept a place depended on an unstable selection. A simplified period, turned with its line, ranks near the 240th place among the faces craft-fonts supplies, so each face loaded after them pushed some fonts' periods out: with four copies of Source Sans 3 loaded, Source Sans 3's period was no longer compared and Retype left the period of "no." an outline. In a full vectorcraft-engine test run the test fonts that other tests load into the shared font database did this to turned_near_matched_round_glyphs_keep_the_line_turn. Each indexed glyph now carries a hash of its outline. Ranking groups the glyphs drawn alike into one outline, keeps the 256 closest outlines with every glyph of each, and breaks ties by index order. A group is fitted once and its poses go to each of its glyphs, so the comparisons spent do not grow with the number of faces that draw the outline. docs/mcp.md describes the limit as 256 outlines. --- crates/text/src/retype.rs | 168 ++++++++++++++++++++++++++++++-------- docs/mcp.md | 4 +- 2 files changed, 138 insertions(+), 34 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index deeebbd519..b020a3827f 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -79,7 +79,8 @@ 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; /// Contours [`clusters`] reads, at most: past it, none. const MAX_CLUSTER_CONTOURS: usize = 1024; @@ -173,6 +174,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 +288,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 +311,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,11 +499,12 @@ 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); once + /// they are spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -529,20 +533,33 @@ impl RetypeIndex { } }; let near = self.ranked_near(&s, &mut work); + // The glyph fitted last and its poses: the glyphs drawn alike after it take them. + let mut last: Option<(&Entry, Option)> = None; for (_, e) in near { - if work == 0 { - break; - } 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, _)| drawn_alike(l, e)).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((e, p.clone())); + p + } + }; + let Some((pose, residual, rest)) = posed else { continue }; let m = GlyphMatch { face: face.clone(), gid: e.gid, @@ -568,11 +585,13 @@ 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. + /// 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`; once it is spent, the glyphs not yet ranked are left out. fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -595,24 +614,40 @@ 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> = 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) { 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(); + let found = same.iter().copied().find(|k| outlines.get(*k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e))); + match found.and_then(|k| outlines.get_mut(k)) { + Some(o) => o.1.push((i, e)), + None => { + 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().flat_map(|(d, glyphs)| glyphs.into_iter().map(move |(_, e)| (d, 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. @@ -625,6 +660,38 @@ 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 { + 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 { @@ -2106,6 +2173,41 @@ 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), 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 = alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).len() as u64; + let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire); + assert_eq!(spent(&index), spent(&alone) + 40 * ranked * 2); + } + #[test] fn a_face_past_its_near_share_keeps_the_glyphs_closest_to_the_shapes() { // One glyph of the face is indexed for near matching: the one closest to a simplified o, diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..fdf4720f1c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13420,7 +13420,9 @@ 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. 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 From 3e0a3f6cc71937c307863fb14b6c04b067ea11ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 04:14:24 -0800 Subject: [PATCH 2/3] Retype: outline comparisons in near matching count toward its work limit Near matching groups the glyphs drawn alike by a hash of their outline and compares each glyph's outline with the outlines in its hash bucket. Those comparisons were not counted toward the work limit, and the hash is not collision-resistant: a font with many glyphs whose outlines hash alike made each new glyph compare with every outline before it, so the work grew with the square of the glyph count. Each comparison now takes one unit per element of the glyph's outline from the work limit, and a glyph is compared with at most 4 outlines of one hash; past them, it is an outline of its own. docs/mcp.md describes the new count. The engine test helper lines_in_family took the line's face from RetypeIndex::matches, which keeps the first 16 matches over every face. When other tests had loaded more than 16 copies of Source Sans 3 that draw the i alike, the family the test asked for could fall past them, and the helper would use another face, without its kerning, so a_word_space_after_a_glyph_kerned_toward_it_is_kept_past_the_glyphs_measured could fail in a full engine run with craft-fonts. The helper now reads all_matches, as Retype does. --- crates/engine/src/cmd/retype_tests.rs | 5 +- crates/text/src/retype.rs | 85 +++++++++++++++++++++++---- docs/mcp.md | 3 +- 3 files changed, 78 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5f89bc1284..f5deb6b600 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1926,11 +1926,12 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec = 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)); } diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index b020a3827f..c000cce127 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -82,6 +82,9 @@ const NEAR_SHAPE_WORK: u64 = 50_000_000; /// 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; @@ -503,8 +506,9 @@ impl RetypeIndex { /// 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); once - /// they are spent, the glyphs not yet ranked or compared are left out. + /// 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 { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -591,7 +595,9 @@ impl RetypeIndex { /// 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`; once it is spent, the glyphs not yet ranked are left out. + /// 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. fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -622,11 +628,32 @@ impl RetypeIndex { let Some(left) = work.checked_sub(cost) else { break }; *work = left; let same = by_drawn.entry(e.drawn).or_default(); - let found = same.iter().copied().find(|k| outlines.get(*k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e))); + // 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 => { - same.push(outlines.len()); + // 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)])); } } @@ -2197,15 +2224,46 @@ mod tests { 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), the comparisons spent are those of Source Sans 3 - // alone. + // (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 = alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).len() as u64; + let ranked: u64 = + alone.ranked_near(&near_signature(&simple).unwrap(), &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 * 2); + assert_eq!(spent(&index), spent(&alone) + 40 * ranked); + } + + #[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 = (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::>()); + 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, &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, &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] @@ -2479,9 +2537,12 @@ 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, &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, &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, &mut work).len(), 1); diff --git a/docs/mcp.md b/docs/mcp.md index fdf4720f1c..93c53b4eeb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13424,7 +13424,8 @@ matched whole only. Near matching compares a shape with the glyphs of at most th 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. 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. 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 From bf562e37170495327dfbc34d57b7cba92e2b0409 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:27:38 -0800 Subject: [PATCH 3/3] Retype: near matching reuses poses by outline group without comparing again ranked_near now returns each glyph's outline group with it, and near_matches reuses the last fitted poses when the group matches instead of comparing the two outlines again. The outline comparisons all happen in ranked_near, where each one is charged to the shape's allowance, so the 50 million and 2 billion limits cover them. A new test counts the outline comparisons near_matches makes beyond ranking. --- crates/text/src/retype.rs | 57 +++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 11 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index c000cce127..f27fc5e561 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -537,11 +537,12 @@ impl RetypeIndex { } }; let near = self.ranked_near(&s, &mut work); - // The glyph fitted last and its poses: the glyphs drawn alike after it take them. - let mut last: Option<(&Entry, Option)> = None; - for (_, e) in near { + // 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)> = None; + for (_, outline, e) in near { let Some(face) = self.faces.get(e.face) else { continue }; - let alike = last.as_ref().filter(|(l, _)| drawn_alike(l, e)).map(|(_, p)| p.clone()); + let alike = last.as_ref().filter(|(l, _)| *l == outline).map(|(_, p)| p.clone()); let posed = match alike { Some(p) => p, None => { @@ -559,7 +560,7 @@ impl RetypeIndex { .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((e, p.clone())); + last = Some((outline, p.clone())); p } }; @@ -597,8 +598,9 @@ impl RetypeIndex { /// 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. - fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { + /// 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. + fn ranked_near(&self, s: &Signature, 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); @@ -665,7 +667,7 @@ impl RetypeIndex { outlines.truncate(NEAR_FITS); } outlines.sort_by(order); - outlines.into_iter().flat_map(|(d, glyphs)| glyphs.into_iter().map(move |(_, e)| (d, e))).collect() + outlines.into_iter().enumerate().flat_map(|(k, (d, glyphs))| glyphs.into_iter().map(move |(_, e)| (d, k, e))).collect() } } @@ -689,6 +691,8 @@ 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 } @@ -1818,6 +1822,8 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] thread_local! { /// How many readings [`signatures`] tried on this thread, kept or not. static READINGS_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many outline comparisons [`drawn_alike`] made on this thread. + static OUTLINES_COMPARED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The first reading of `path` (for tests). @@ -2231,11 +2237,39 @@ mod tests { assert_eq!(found.len(), alone_found.len() * faces.len()); let mut all = u64::MAX; let ranked: u64 = - alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, e)| 2 + e.outline.elements().len() as u64).sum(); + alone.ranked_near(&near_signature(&simple).unwrap(), &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(), &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 @@ -2540,8 +2574,9 @@ mod tests { let ranked = index.ranked_near(&s, &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(); + 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;