From cf80c118712c43ae747b7bc714d297109f5e0ad0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 23:05:44 -0800 Subject: [PATCH] Retype: a compound tries its other complete splits when the paint check rejects the first two A compound path whose split with the longest runs and split with the shortest runs both failed the paint check stayed an outline, even when another complete split (AB and CD for groups A, B, C and D) passed it. The split search now checks the other complete splits in order, at most 32 per shape for exact matches and 32 for near matches, and looks each run of groups up at most once, only when the search reaches it. --- crates/engine/src/cmd/retype.rs | 191 +++++++++++++++++++++----- crates/engine/src/cmd/retype_tests.rs | 69 ++++++++++ docs/mcp.md | 4 +- 3 files changed, 225 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 563678293e..69272c1928 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1147,6 +1147,10 @@ fn partial_lines(lines: &[Vec], glyphs_of: &std::collections::HashMap( } /// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for -/// no groups, when the groups cannot all be matched and when `together` rejects the runs of a split -/// of several parts. +/// no groups, when the groups cannot all be matched and when `together` rejects every split of +/// several parts it is asked about. The complete splits are tried with the longest runs first, +/// then with the shortest runs, then the others in order, a longer run at an earlier group first. +/// `together` is asked about at most [`MAX_SPLIT_TRIES`] splits. `find` is asked about a run only +/// when the search reaches it, and about each run at most once, so at most [`MAX_RUN`] times per +/// group. fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { - if groups.is_empty() { + let g = groups.len(); + let mut s = Splits { groups, find, found: (0..g).map(|_| (0..MAX_RUN).map(|_| None).collect()).collect(), whole: vec![None; g] }; + // A split is the runs it takes, each as (start, number of groups). + let mut first = vec![]; + if g == 0 || !s.extend(&mut first, false) { return vec![]; } - let g = groups.len(); - // The split with the longest runs first; when `together` rejects it, the one with the shortest - // runs, which is the other end of the complete splits. - for longest in [true, false] { - // From the last group back: the run that starts at each group, the longest (or shortest) - // that matches and leaves a rest that can all be matched, with its candidates. Runs past - // such a start are never tried for one whose rest cannot be matched. - let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); - for i in (0..g).rev() { - let mut lens: Vec = (1..=MAX_RUN.min(g - i)).collect(); - if longest { - lens.reverse(); + let runs_of = + |split: &[(usize, usize)]| -> Vec { split.iter().map(|&(at, n)| groups.get(at..at + n).map(joined).unwrap_or_default()).collect() }; + let accepted = 'search: { + if first.len() == 1 { + break 'search Some(first); + } + // The shortest runs are looked up only once the longest are rejected. + let mut shortest = vec![]; + let mut shortest_next = true; + let mut rest = first.clone(); + let mut candidate = Some(first.clone()); + let mut tried = 0; + while let Some(split) = candidate.take() { + if tried == MAX_SPLIT_TRIES { + break; } - for n in lens { - let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); - if !rest_ok { - continue; + tried += 1; + if together(&runs_of(&split)) { + break 'search Some(split); + } + if std::mem::take(&mut shortest_next) && s.extend(&mut shortest, true) && shortest != first { + candidate = Some(shortest.clone()); + continue; + } + candidate = loop { + if !s.advance(&mut rest) { + break None; } - let Some(run) = groups.get(i..i + n) else { continue }; - let cands = find(&joined(run)); - if !cands.is_empty() { - if let Some(c) = chosen.get_mut(i) { - *c = Some((n, cands)); + if rest != shortest { + break Some(rest.clone()); + } + }; + } + None + }; + let Some(split) = accepted else { return vec![] }; + let mut out = vec![]; + for (at, n) in split { + let Some(Some(cands)) = s.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))).map(Option::take) else { return vec![] }; + out.push(cands); + } + out +} + +/// The state of one [`split_parts`] search: each run's candidates and whether the groups from each +/// start can all be matched, each found when the search first needs it. +struct Splits<'a, M> { + groups: &'a [BezPath], + find: &'a dyn Fn(&BezPath) -> Vec, + /// By start and length less one: the run's candidates, once looked up. + found: Vec>>>, + /// By start: whether the groups from there on can all be matched, once known. + whole: Vec>, +} + +impl Splits<'_, M> { + /// Whether the run of `n` groups at `at` matches, looking it up the first time. + fn matches(&mut self, at: usize, n: usize) -> bool { + let Some(slot) = self.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))) else { return false }; + if slot.is_none() { + let cands = self.groups.get(at..at + n).map(|run| (self.find)(&joined(run))).unwrap_or_default(); + *slot = Some(cands); + } + slot.as_ref().is_some_and(|c| !c.is_empty()) + } + + /// Whether the groups from `at` on can all be matched. The search goes from `at` forward, the + /// longest run first, and no start is searched twice, so it ends after at most [`MAX_RUN`] + /// lookups and checks per group. + fn completes(&mut self, at: usize) -> bool { + let g = self.groups.len(); + if at >= g { + return at == g; + } + if let Some(known) = self.whole.get(at).copied().flatten() { + return known; + } + // From `at`: the starts still to settle, each with the run length to try next. + let mut stack: Vec<(usize, usize)> = vec![(at, MAX_RUN.min(g - at))]; + while let Some(&(i, n)) = stack.last() { + if self.whole.get(i).copied().flatten().is_some() { + stack.pop(); + continue; + } + if n == 0 { + if let Some(w) = self.whole.get_mut(i) { + *w = Some(false); + } + stack.pop(); + continue; + } + if let Some(top) = stack.last_mut() { + top.1 = n - 1; + } + if !self.matches(i, n) { + continue; + } + let next = i + n; + match if next == g { Some(true) } else { self.whole.get(next).copied().flatten() } { + Some(true) => { + if let Some(w) = self.whole.get_mut(i) { + *w = Some(true); } - break; + stack.pop(); + } + Some(false) => {} + None => { + // Settle `next` first, then try this run again. + if let Some(top) = stack.last_mut() { + top.1 = n; + } + stack.push((next, MAX_RUN.min(g - next))); } } } - let mut out = vec![]; - let mut runs = vec![]; - let mut i = 0; + self.whole.get(at).copied().flatten() == Some(true) + } + + /// Whether `n` groups at `at` are a run a complete split can take. + fn fits(&mut self, at: usize, n: usize) -> bool { + self.matches(at, n) && self.completes(at + n) + } + + /// Takes `split` on to the last group, with the longest run that fits at each start (or, with + /// `shortest`, the shortest); false when no run fits. + fn extend(&mut self, split: &mut Vec<(usize, usize)>, shortest: bool) -> bool { + let g = self.groups.len(); + let mut i = split.last().map_or(0, |&(at, n)| at + n); while i < g { - let Some(Some((n, cands))) = chosen.get_mut(i).map(Option::take) else { return vec![] }; - out.push(cands); - runs.push(groups.get(i..i + n).map(joined).unwrap_or_default()); + let most = MAX_RUN.min(g - i); + let lens: Vec = if shortest { (1..=most).collect() } else { (1..=most).rev().collect() }; + let Some(n) = lens.into_iter().find(|&n| self.fits(i, n)) else { return false }; + split.push((i, n)); i += n; } - if out.len() == 1 || together(&runs) { - return out; + true + } + + /// Moves `split` on to the next complete split, in order: the runs before the last start where + /// a shorter run fits kept, that shorter run, and the longest runs after it. False past the last. + fn advance(&mut self, split: &mut Vec<(usize, usize)>) -> bool { + while let Some((at, n)) = split.pop() { + if let Some(m) = (1..n).rev().find(|&m| self.fits(at, m)) { + split.push((at, m)); + return self.extend(split, false); + } } - // Every run a single group: the other order gives the same split. - if out.len() == g { - break; - } + false } - vec![] } /// Contour groups joined into one path. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index e5231b47b0..61cbe532bd 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1355,6 +1355,75 @@ fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() { assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty()); } +#[test] +fn a_split_between_the_longest_and_the_shortest_runs_is_tried() { + use kurbo::Shape; + // Four groups A, B, C and D. ABC and D (the longest runs first) and the four single glyphs + // (the shortest) are complete splits the paint check rejects; AB and CD is the one it accepts. + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0, 200.0, 300.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, b.x0.round() as i64, b.x1.round() as i64) { + (true, 0, 240) => vec!["ABC"], + (true, 0, 140) => vec!["AB"], + (true, 200, 340) => vec!["CD"], + (true, 0, 40) => vec!["A"], + (true, 100, 140) => vec!["B"], + (true, 200, 240) => vec!["C"], + (true, 300, 340) => vec!["D"], + _ => vec![], + } + }; + let groups = all_groups(&p); + let pairs = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 2 && runs.first().is_some_and(|r| r.bounding_box().x1.round() as i64 == 140); + assert_eq!(super::parts(&p, &groups, &find, &pairs), vec![vec!["AB"], vec!["CD"]]); +} + +#[test] +fn at_most_max_split_tries_complete_splits_are_checked() { + use kurbo::Shape; + // Twelve groups, every run of up to three of them a glyph: far more complete splits than the + // cap. The paint check is asked about the cap's number of them and no more, and each run is + // looked up at most once. + let mut p = kurbo::BezPath::new(); + for i in 0..12 { + let x = f64::from(i) * 100.0; + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let groups = all_groups(&p); + assert_eq!(groups.len(), 12); + let looked_up = std::cell::Cell::new(0usize); + let find = |_: &kurbo::BezPath| -> Vec<&'static str> { + looked_up.set(looked_up.get() + 1); + vec!["glyph"] + }; + let asked = &std::cell::Cell::new(0usize); + let accept_at = |n: usize| { + move |_: &[kurbo::BezPath]| { + asked.set(asked.get() + 1); + asked.get() == n + } + }; + // Rejected every time: the search stops at the cap. + assert!(super::split_parts(&groups, &find, &accept_at(usize::MAX)).is_empty()); + assert_eq!(asked.get(), super::MAX_SPLIT_TRIES); + assert!(looked_up.get() <= super::MAX_RUN * groups.len(), "{} lookups", looked_up.get()); + // A first split that is accepted looks up its own runs only: four runs of three groups. + asked.set(0); + looked_up.set(0); + assert_eq!(super::split_parts(&groups, &find, &accept_at(1)).len(), 4); + assert_eq!(looked_up.get(), 4); + // The last split tried is still taken; the one past the cap is not tried. + asked.set(0); + assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES)).len() > 1); + asked.set(0); + assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES + 1)).is_empty()); + assert_eq!(asked.get(), super::MAX_SPLIT_TRIES); +} + /// `path`'s contour groups, with no limit on the contours grouped. fn all_groups(path: &kurbo::BezPath) -> Vec { let mut budget = usize::MAX; diff --git a/docs/mcp.md b/docs/mcp.md index 412809d4f8..543e4472c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11336,7 +11336,9 @@ whose inner contour runs the same way as its outer one paints its center, so a r outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. The glyphs of a compound path that splits into several are set one beside another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each -other under the even-odd rule) stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours +other under the even-odd rule) stays an outline. When the split with the longest runs fails that check, the split with the +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 or 512 contours 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 most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left