From 38e98e43c0f61e4ca9db8739fdc90bc84f996b2e Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Tue, 13 Oct 2026 09:58:53 -0600 Subject: [PATCH 1/6] Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out Display lists are built on all cores, but every text looked its font up, and every character its font lacks (all of a CJK text's) its fallback font, glyph outline and glyph mesh, through shared tables behind global locks; text-heavy drawings spent most of the build waiting on them. Font lookups, fallback faces, FONTALT, glyph outlines and glyph meshes now have per-thread caches in front of the shared ones (a generation counter empties them when fonts or FONTALT/FONTFALLBACK change). On screen, filled glyphs outside the area being looked at are left out, as hatch patterns already are (the canvas builds again when the view leaves that area); plots and exports keep every glyph. Zoomed in, every glyph of every text was filled at that zoom's detail and drawn each frame, i.e. on every mouse move. Synthetic 3.8 MB drawing (24,000 TEXT and 2,500 MTEXT in Chinese, 30,000 lines), macOS, Apple silicon: display list at fit 335 -> 103 ms; triangles at 16x zoom 11.2 M -> 0.44 M, at 64x 19.0 M -> 45 k. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/craft_fonts.rs | 8 +++ crates/fonts/src/ttf.rs | 104 +++++++++++++++++++++++++++++++- crates/render/src/lib.rs | 10 +++ crates/render/src/tests.rs | 17 ++++++ crates/render/src/text.rs | 36 +++++++++++ 5 files changed, 173 insertions(+), 2 deletions(-) diff --git a/crates/fonts/src/craft_fonts.rs b/crates/fonts/src/craft_fonts.rs index fb290775f..982f347a6 100644 --- a/crates/fonts/src/craft_fonts.rs +++ b/crates/fonts/src/craft_fonts.rs @@ -64,6 +64,14 @@ mod tests { let _ = crate::ttf::fallback_for('\u{65E5}'); } + #[test] + fn lookups_cached_per_thread_see_a_font_registered_later() { + // Asked before it exists (cached as missing), then registered: found. + assert!(crate::ttf::find("CADCraft Late Test").is_none()); + crate::ttf::register_static("cadcraftlatetest-regular", &TINY_SFNT); + assert!(crate::ttf::find("CADCraft Late Test").is_some()); + } + #[test] fn no_barred_family_is_embedded() { // AGENTS.md: no Adobe fonts. Noto Sans CJK is Source Han Sans; `build.rs` skips them. diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 62759c1b0..f3ca81584 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -14,8 +14,10 @@ //! On native builds both start from the `CADCRAFT_FONTALT` / `CADCRAFT_FONTFALLBACK` //! environment variables. +use std::cell::RefCell; use std::collections::HashMap; use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock}; use cadcraft_geom::Vec2; @@ -471,6 +473,7 @@ pub fn register(name: &str, bytes: Vec) { g.files.insert(key(name), Arc::new(bytes)); g.resolved.clear(); g.fallback = Fallback::default(); + changed(); } /// Register font bytes that live for the whole process under a name; they are copied only when @@ -483,6 +486,7 @@ pub(crate) fn register_static(name: &str, bytes: &'static [u8]) { g.paths.insert(k, Source::Static(bytes)); g.resolved.clear(); g.fallback = Fallback::default(); + changed(); } /// Normalise a style font name ("arial.ttf", "Arial", "ARIALBD.TTF") to a lookup key. @@ -496,9 +500,66 @@ fn is_stroke_name(k: &str) -> bool { k.is_empty() || k.ends_with(".shx") || k == crate::BUILTIN_FONT.to_ascii_lowercase() || k == "txt" || k == "simplex" || k == "romans" } +/// Bumped whenever a font lookup can answer differently (a font registered, FONTALT or +/// FONTFALLBACK changed), so the per-thread caches start over. +static GENERATION: AtomicU64 = AtomicU64::new(0); + +fn changed() { + GENERATION.fetch_add(1, Ordering::Relaxed); +} + +/// Most entries each per-thread cache holds before it starts over. +const MAX_LOCAL: usize = 8192; + +/// Per-thread answers of [`find`] (by the name as given) and [`fallback_for`]. Display lists are +/// built on all cores and look a font up for every text and a fallback for every character a +/// text's font lacks (all of a CJK text's): through the shared tables each lookup took global +/// locks, so text-heavy drawings spent most of their build waiting on them (#662, #666). +#[derive(Default)] +struct Local { + generation: u64, + find: HashMap>, + fallback: HashMap>, + /// FONTALT, asked for every text whose font isn't installed. + alt: Option, + /// Glyph outlines, in front of the shared [`glyph_cache`] (whose lock every core reads). + glyphs: HashMap>, +} + +thread_local! { + static LOCAL: RefCell = RefCell::new(Local::default()); +} + +/// `f` on this thread's cache, emptied first when lookups changed since it was filled. +fn local(f: impl FnOnce(&mut Local) -> R) -> R { + LOCAL.with(|l| { + let mut l = l.borrow_mut(); + let generation = GENERATION.load(Ordering::Relaxed); + if l.generation != generation { + *l = Local { generation, ..Local::default() }; + } + f(&mut l) + }) +} + /// A face of an installed (or registered) font by file name or family name. Stroke-font names /// (".shx", empty) return `None`. pub fn find(name: &str) -> Option { + if let Some(r) = local(|l| l.find.get(name).cloned()) { + return r; + } + let r = find_shared(name); + local(|l| { + if l.find.len() >= MAX_LOCAL { + l.find.clear(); + } + l.find.insert(name.to_string(), r.clone()); + }); + r +} + +/// [`find`] through the shared table. +fn find_shared(name: &str) -> Option { let k = key(name); if is_stroke_name(&k) { return None; @@ -546,12 +607,18 @@ fn split_list(s: &str) -> Vec { /// FONTALT: the font used for a text style font that can't be found. Empty = the built-in /// stroke font. pub fn font_alt() -> String { - prefs().alt.clone() + if let Some(a) = local(|l| l.alt.clone()) { + return a; + } + let a = prefs().alt.clone(); + local(|l| l.alt = Some(a.clone())); + a } /// Set FONTALT ("" or "." clears it). pub fn set_font_alt(name: &str) { prefs().alt = clean_name(name); + changed(); } /// FONTFALLBACK: fonts tried first for characters a text's font lacks, comma-separated. @@ -562,6 +629,7 @@ pub fn fallback_fonts() -> String { /// Set FONTFALLBACK from a comma- or semicolon-separated list ("" or "." clears it). pub fn set_fallback_fonts(list: &str) { prefs().fallback = split_list(list); + changed(); } /// Characters worth a fallback search (not spaces, controls or private-use code points). @@ -576,6 +644,21 @@ pub fn fallback_for(c: char) -> Option { if !wants_fallback(c) { return None; } + if let Some(r) = local(|l| l.fallback.get(&c).cloned()) { + return r; + } + let r = fallback_shared(c); + local(|l| { + if l.fallback.len() >= MAX_LOCAL { + l.fallback.clear(); + } + l.fallback.insert(c, r.clone()); + }); + r +} + +/// [`fallback_for`] through the shared tables. +fn fallback_shared(c: char) -> Option { let (list, alt) = { let p = prefs(); (p.fallback.clone(), p.alt.clone()) @@ -614,7 +697,8 @@ enum GlyphKey { /// Cached glyph outlines keyed by (font bytes address, length, face, glyph). Fonts live for the /// whole process in the font table, so the address identifies them. A read-write lock: display /// lists are built on all cores and nearly every lookup is a hit, which a mutex serialized. -type GlyphCache = HashMap<(usize, usize, u32, GlyphKey), Arc>; +type GlyphCache = HashMap>; +type GlyphCacheKey = (usize, usize, u32, GlyphKey); fn glyph_cache() -> &'static RwLock { static C: OnceLock> = OnceLock::new(); @@ -714,6 +798,22 @@ pub fn glyph_contours(face: &Face, gid: u16) -> Arc<[Vec]> { fn outline(face: &Face, k: GlyphKey) -> Arc { let key = (face.bytes.as_ptr() as usize, face.bytes.len(), face.index, k); + if let Some(g) = local(|l| l.glyphs.get(&key).cloned()) { + return g; + } + let g = outline_shared(face, key); + local(|l| { + if l.glyphs.len() >= MAX_LOCAL { + l.glyphs.clear(); + } + l.glyphs.insert(key, g.clone()); + }); + g +} + +/// [`outline`] through the shared cache. +fn outline_shared(face: &Face, key: GlyphCacheKey) -> Arc { + let k = key.3; if let Some(g) = glyph_cache().read().unwrap_or_else(PoisonError::into_inner).get(&key) { return g.clone(); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8dadabe88..de9068391 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -398,10 +398,20 @@ impl Builder<'_> { // Plots note which filled outlines are font glyphs (see `DisplayList::texts`). let mut text = sh.text.iter().peekable(); let pixel = if self.plotting { 0.0 } else { self.opts.min_dash * 0.5 }; + // On screen, glyphs outside the area being looked at are left out, as hatch patterns + // are: a text-heavy drawing zoomed in otherwise filled every glyph of every text at the + // detail of that zoom (tens of millions of triangles, drawn every frame), and the canvas + // builds again when the view leaves the area (#666). + let view = if self.plotting { None } else { self.opts.view }; for (i, g) in sh.glyphs.iter().enumerate() { if fill { while text.next_if(|t| t.outline < i).is_some() {} let glyph = text.next_if(|t| t.outline == i); + if let (Some(t), Some(v)) = (glyph, view) + && !crate::text::may_show(crate::text::placement(t, ctx.xf), &v) + { + continue; + } let at = self.list.prims.len(); let len = if let Some(t) = glyph { let xf = crate::text::placement(t, ctx.xf); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ee22abb3c..b5fadc96c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -276,6 +276,23 @@ fn system_font() -> Option<&'static str> { ["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find(|n| cadcraft_fonts::ttf::find(n).is_some()) } +/// #666: on screen, filled glyphs outside the area being looked at are left out (the canvas +/// builds again when the view leaves it); plots and builds without a view keep every glyph. +#[test] +fn glyphs_outside_the_view_are_left_out_of_screen_builds_only() { + let Some(font) = system_font() else { return }; + let d = text_doc(font, "OH"); + let tris = |o: &Options| build(&d, &Space::Model, o).prims.iter().filter(|p| p.kind == Kind::Tris).count(); + let all = tris(&Options::default()); + assert!(all > 0); + let near = Options { view: Some(Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(3.0, 2.0))), ..Options::default() }; + assert_eq!(tris(&near), all, "a view over the text keeps it"); + let far = Options { view: Some(Bounds2::new(Vec2::new(100.0, 100.0), Vec2::new(110.0, 110.0))), ..Options::default() }; + assert_eq!(tris(&far), 0, "a view far from the text leaves its glyphs out"); + let plot = build_plot(&d, &Space::Model, &far); + assert_eq!(plot.prims.iter().filter(|p| p.kind == Kind::Tris).count(), all, "plots keep every glyph"); +} + #[test] fn truetype_text_is_filled_or_outlined() { let Some(font) = system_font() else { return }; diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 6595e145f..2aa18a7c3 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -54,6 +54,15 @@ pub(super) fn placement(g: &TextGlyph, xf: Mat3) -> Mat3 { xf.then_before(Mat3 { a: g.x.x / 1000.0, b: g.x.y / 1000.0, c: g.y.x / 1000.0, d: g.y.y / 1000.0, e: g.origin.x, f: g.origin.y }) } +/// Whether a glyph placed by `xf` (font units, 1000 per em) can reach into `view`: its em box, +/// with an em of margin all round for glyphs that reach outside it, overlaps the area. +pub(super) fn may_show(xf: Mat3, view: &Bounds2) -> bool { + let corners = [Vec2::new(-1000.0, -1000.0), Vec2::new(2000.0, -1000.0), Vec2::new(2000.0, 2000.0), Vec2::new(-1000.0, 2000.0)]; + let b = Bounds2::from_points(corners.map(|c| xf.apply(c))); + // A placement that isn't finite is left to the mesh code, which handles it. + b.is_empty() || !b.min.is_finite() || !b.max.is_finite() || b.intersects(view) +} + fn detail(xf: Mat3, pixel: f64) -> Detail { // The Frobenius norm bounds the largest stretch, including shear, mirroring and unequal // block scales. A font-unit error below pixel / stretch is below a pixel in every direction. @@ -68,9 +77,36 @@ fn detail(xf: Mat3, pixel: f64) -> Detail { if !tolerance.is_finite() || tolerance < 0.0625 { Detail::Full } else { Detail::Reduced(tolerance.log2().floor().clamp(-4.0, 16.0) as i16) } } +/// Most meshes each thread keeps in front of the shared cache. +const MAX_LOCAL_ENTRIES: usize = 4096; + +thread_local! { + /// This thread's meshes, in front of the shared [`cache`]: display lists are built on all + /// cores, and every placed glyph reading the shared lock made text-heavy drawings (CJK text + /// is all filled glyphs) wait on it (#662, #666). Entries keep their face alive like the + /// shared ones, so a key's address is never reused while it is here. + static LOCAL: std::cell::RefCell> = std::cell::RefCell::new(HashMap::new()); +} + pub(super) fn mesh(g: &TextGlyph, xf: Mat3, pixel: f64) -> Arc { let detail = detail(xf, pixel); let key = (g.face.bytes.as_ptr() as usize, g.face.bytes.len(), g.face.index, g.gid, detail); + if let Some(m) = LOCAL.with(|l| l.borrow().get(&key).map(|e| e.mesh.clone())) { + return m; + } + let m = mesh_shared(g, key, detail); + LOCAL.with(|l| { + let mut l = l.borrow_mut(); + if l.len() >= MAX_LOCAL_ENTRIES { + l.clear(); + } + l.insert(key, Entry { _face: g.face.clone(), mesh: m.clone() }); + }); + m +} + +/// [`mesh`] through the shared cache. +fn mesh_shared(g: &TextGlyph, key: Key, detail: Detail) -> Arc { if let Some(entry) = cache().read().unwrap_or_else(PoisonError::into_inner).entries.get(&key) { return entry.mesh.clone(); } From e57786e726e8e1f3b813fda888e11a2a393502fd Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Fri, 23 Oct 2026 07:44:08 -0600 Subject: [PATCH 2/6] Per-thread caches: bound meshes by bytes; don't keep a stale font lookup Each thread's text meshes were capped at 4096 entries but not by size; CJK text at full detail could hold hundreds of MB per core. They are now capped at 16 MiB per thread (with the shared cache's size estimate), and a mesh above a quarter of that is read from the shared cache instead. A font lookup that ran while a font was being registered could keep the old answer (a "not found") on that thread until the next change. The generation is read before the lookup, and the answer is kept only under that generation, so a lookup overtaken by a change starts over. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/ttf.rs | 58 ++++++++++++++++++++++++++++--- crates/render/src/text.rs | 72 ++++++++++++++++++++++++++++++++------- 2 files changed, 113 insertions(+), 17 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index c93ca4cff..289e67bc1 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -508,7 +508,31 @@ fn is_stroke_name(k: &str) -> bool { static GENERATION: AtomicU64 = AtomicU64::new(0); fn changed() { - GENERATION.fetch_add(1, Ordering::Relaxed); + // Release: a thread that sees the new generation also sees what changed. + GENERATION.fetch_add(1, Ordering::Release); +} + +/// The generation now, taken before a lookup whose answer [`keep`] may cache. +fn generation() -> u64 { + GENERATION.load(Ordering::Acquire) +} + +/// `f` on this thread's cache, only when lookups haven't changed since `seen` ([`generation`] +/// before the lookup): an answer found while a font was being registered may be the old one, and +/// is used once but not kept. +fn keep(seen: u64, f: impl FnOnce(&mut Local)) { + LOCAL.with(|l| { + let mut l = l.borrow_mut(); + // Kept under `seen` itself: should lookups change after this check, the next lookup + // finds a newer generation and starts over without it. + if generation() != seen { + return; + } + if l.generation != seen { + *l = Local { generation: seen, ..Local::default() }; + } + f(&mut l); + }); } /// Most entries each per-thread cache holds before it starts over. @@ -537,7 +561,7 @@ thread_local! { fn local(f: impl FnOnce(&mut Local) -> R) -> R { LOCAL.with(|l| { let mut l = l.borrow_mut(); - let generation = GENERATION.load(Ordering::Relaxed); + let generation = generation(); if l.generation != generation { *l = Local { generation, ..Local::default() }; } @@ -551,8 +575,9 @@ pub fn find(name: &str) -> Option { if let Some(r) = local(|l| l.find.get(name).cloned()) { return r; } + let seen = generation(); let r = find_shared(name); - local(|l| { + keep(seen, |l| { if l.find.len() >= MAX_LOCAL { l.find.clear(); } @@ -613,8 +638,9 @@ pub fn font_alt() -> String { if let Some(a) = local(|l| l.alt.clone()) { return a; } + let seen = generation(); let a = prefs().alt.clone(); - local(|l| l.alt = Some(a.clone())); + keep(seen, |l| l.alt = Some(a.clone())); a } @@ -650,8 +676,9 @@ pub fn fallback_for(c: char) -> Option { if let Some(r) = local(|l| l.fallback.get(&c).cloned()) { return r; } + let seen = generation(); let r = fallback_shared(c); - local(|l| { + keep(seen, |l| { if l.fallback.len() >= MAX_LOCAL { l.fallback.clear(); } @@ -1099,3 +1126,24 @@ mod geometry_budget_tests { assert!(shaped.text.is_empty()); } } + +#[cfg(test)] +mod local_cache_tests { + use super::*; + + /// An answer looked up while lookups changed (a font registered meanwhile) is not kept: the + /// thread asks again instead of keeping a stale "not found". + #[test] + fn a_lookup_overtaken_by_a_change_is_not_kept() { + let seen = generation(); + changed(); + keep(seen, |l| l.alt = Some("stale".into())); + assert_ne!(local(|l| l.alt.clone()), Some("stale".to_string())); + let now = generation(); + keep(now, |l| l.alt = Some("fresh".into())); + // Kept unless yet another change came in between (other tests may register fonts). + if generation() == now { + assert_eq!(local(|l| l.alt.clone()), Some("fresh".to_string())); + } + } +} diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 2aa18a7c3..d6e9775e1 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -79,32 +79,64 @@ fn detail(xf: Mat3, pixel: f64) -> Detail { /// Most meshes each thread keeps in front of the shared cache. const MAX_LOCAL_ENTRIES: usize = 4096; +/// Most memory each thread's meshes hold: display lists are built on every core, and CJK text at +/// full detail makes large meshes, so a count alone doesn't bound it. A mesh above a quarter of +/// it is read from the shared cache each time instead. +const MAX_LOCAL_BYTES: usize = 16 << 20; + +#[derive(Default)] +struct Local { + entries: HashMap, + bytes: usize, +} thread_local! { /// This thread's meshes, in front of the shared [`cache`]: display lists are built on all /// cores, and every placed glyph reading the shared lock made text-heavy drawings (CJK text /// is all filled glyphs) wait on it (#662, #666). Entries keep their face alive like the /// shared ones, so a key's address is never reused while it is here. - static LOCAL: std::cell::RefCell> = std::cell::RefCell::new(HashMap::new()); + static LOCAL: std::cell::RefCell = std::cell::RefCell::new(Local::default()); } pub(super) fn mesh(g: &TextGlyph, xf: Mat3, pixel: f64) -> Arc { let detail = detail(xf, pixel); let key = (g.face.bytes.as_ptr() as usize, g.face.bytes.len(), g.face.index, g.gid, detail); - if let Some(m) = LOCAL.with(|l| l.borrow().get(&key).map(|e| e.mesh.clone())) { + if let Some(m) = LOCAL.with(|l| l.borrow().entries.get(&key).map(|e| e.mesh.clone())) { return m; } let m = mesh_shared(g, key, detail); LOCAL.with(|l| { - let mut l = l.borrow_mut(); - if l.len() >= MAX_LOCAL_ENTRIES { - l.clear(); - } - l.insert(key, Entry { _face: g.face.clone(), mesh: m.clone() }); + let l = &mut *l.borrow_mut(); + remember(&mut l.entries, &mut l.bytes, key, || Entry { _face: g.face.clone(), mesh: m.clone() }, mesh_bytes(&m)); }); m } +/// Keep `value` (about `bytes` of memory) in a per-thread cache holding `total` bytes: started +/// over when it would pass [`MAX_LOCAL_ENTRIES`] or [`MAX_LOCAL_BYTES`], and a value above a +/// quarter of the budget isn't kept at all. +fn remember(entries: &mut HashMap, total: &mut usize, key: Key, value: impl FnOnce() -> T, bytes: usize) { + if bytes > MAX_LOCAL_BYTES / 4 { + return; + } + if entries.len() >= MAX_LOCAL_ENTRIES || total.saturating_add(bytes) > MAX_LOCAL_BYTES { + entries.clear(); + *total = 0; + } + if entries.insert(key, value()).is_none() { + *total = total.saturating_add(bytes); + } +} + +/// About how much memory a cached mesh holds (its points and triangles as allocated). +fn mesh_bytes(mesh: &Mesh) -> usize { + let points = mesh.contours.iter().map(Vec::capacity).sum::().saturating_add(mesh.triangles.capacity()); + points + .saturating_mul(std::mem::size_of::()) + .saturating_add(mesh.contours.len().saturating_mul(std::mem::size_of::>())) + .saturating_add(std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::()) +} + /// [`mesh`] through the shared cache. fn mesh_shared(g: &TextGlyph, key: Key, detail: Detail) -> Arc { if let Some(entry) = cache().read().unwrap_or_else(PoisonError::into_inner).entries.get(&key) { @@ -129,11 +161,7 @@ fn mesh_shared(g: &TextGlyph, key: Key, detail: Detail) -> Arc { } }; let mesh = Arc::new(Mesh { triangles: triangulate(&contours), contours }); - let points = mesh.contours.iter().map(Vec::capacity).sum::().saturating_add(mesh.triangles.capacity()); - let bytes = points - .saturating_mul(std::mem::size_of::()) - .saturating_add(mesh.contours.len().saturating_mul(std::mem::size_of::>())) - .saturating_add(std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::()); + let bytes = mesh_bytes(&mesh); if bytes <= MAX_CACHE_BYTES { let mut c = cache().write().unwrap_or_else(PoisonError::into_inner); if c.entries.len() >= MAX_ENTRIES || c.bytes.saturating_add(bytes) > MAX_CACHE_BYTES { @@ -226,3 +254,23 @@ fn triangulate(contours: &[Vec]) -> Vec { } buffers.indices.into_iter().filter_map(|i| buffers.vertices.get(usize::from(i)).copied()).collect() } + +#[cfg(test)] +mod local_cache_tests { + use super::*; + + /// Each thread's meshes stay within [`MAX_LOCAL_BYTES`], and a mesh too large for it isn't kept. + #[test] + fn a_threads_meshes_stay_within_their_byte_budget() { + let (mut entries, mut total) = (HashMap::new(), 0usize); + let key = |i: u16| (0usize, 0usize, 0u32, i, Detail::Full); + let big = MAX_LOCAL_BYTES / 8; + for i in 0..100 { + remember(&mut entries, &mut total, key(i), || (), big); + assert!(total <= MAX_LOCAL_BYTES, "{total}"); + assert_eq!(total, entries.len() * big); + } + remember(&mut entries, &mut total, key(500), || (), MAX_LOCAL_BYTES / 2); + assert!(!entries.contains_key(&key(500)), "a mesh above a quarter of the budget isn't kept"); + } +} From 9a1bd48a2658ab726113b5645ea79db95e51a18a Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Fri, 23 Oct 2026 08:10:30 -0600 Subject: [PATCH 3/6] Per-thread glyph outlines: bound them by points Each thread kept up to 8192 glyph outlines in front of the shared cache with no size limit, and held them after the shared cache let them go. They are now held within MAX_SHAPED_POINTS / 16 points per thread, and an outline above a quarter of that is read from the shared cache instead. The generation test reads the cache before checking the generation, so another test's change in between can't fail it. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/ttf.rs | 53 +++++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 289e67bc1..f34f37cd2 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -551,8 +551,15 @@ struct Local { alt: Option, /// Glyph outlines, in front of the shared [`glyph_cache`] (whose lock every core reads). glyphs: HashMap>, + /// The points of the outlines in `glyphs`, held within [`MAX_LOCAL_GLYPH_POINTS`]. + glyph_points: usize, } +/// Most outline points each thread keeps in front of the shared cache: a part of its budget, since +/// every core has its own and they keep outlines alive after the shared cache lets them go. An +/// outline above a quarter of it is read from the shared cache each time. +const MAX_LOCAL_GLYPH_POINTS: usize = MAX_SHAPED_POINTS / 16; + thread_local! { static LOCAL: RefCell = RefCell::new(Local::default()); } @@ -868,15 +875,28 @@ fn outline(face: &Face, k: GlyphKey) -> Arc { return g; } let g = outline_shared(face, key); - local(|l| { - if l.glyphs.len() >= MAX_LOCAL { - l.glyphs.clear(); - } - l.glyphs.insert(key, g.clone()); - }); + local(|l| l.keep_glyph(key, &g)); g } +impl Local { + /// Keep an outline in front of the shared cache, within [`MAX_LOCAL`] entries and + /// [`MAX_LOCAL_GLYPH_POINTS`] points (started over when either would be passed); an outline + /// above a quarter of the points isn't kept. + fn keep_glyph(&mut self, key: GlyphCacheKey, g: &Arc) { + if g.points > MAX_LOCAL_GLYPH_POINTS / 4 { + return; + } + if self.glyphs.len() >= MAX_LOCAL || self.glyph_points.saturating_add(g.points) > MAX_LOCAL_GLYPH_POINTS { + self.glyphs.clear(); + self.glyph_points = 0; + } + if self.glyphs.insert(key, g.clone()).is_none() { + self.glyph_points = self.glyph_points.saturating_add(g.points); + } + } +} + /// [`outline`] through the shared cache. fn outline_shared(face: &Face, key: GlyphCacheKey) -> Arc { let k = key.3; @@ -1142,8 +1162,27 @@ mod local_cache_tests { let now = generation(); keep(now, |l| l.alt = Some("fresh".into())); // Kept unless yet another change came in between (other tests may register fonts). + let cached = local(|l| l.alt.clone()); if generation() == now { - assert_eq!(local(|l| l.alt.clone()), Some("fresh".to_string())); + assert_eq!(cached, Some("fresh".to_string())); } } + + /// Each thread's outlines stay within [`MAX_LOCAL_GLYPH_POINTS`], and an outline too large + /// for it isn't kept. + #[test] + fn a_threads_outlines_stay_within_their_point_budget() { + let mut l = Local::default(); + let key = |i: u32| (0usize, 0usize, 0u32, GlyphKey::Id(i)); + let big = MAX_LOCAL_GLYPH_POINTS / 8; + let g = Arc::new(GlyphOutline { points: big, cap: 1.0, ..Default::default() }); + for i in 0..100 { + l.keep_glyph(key(i), &g); + assert!(l.glyph_points <= MAX_LOCAL_GLYPH_POINTS, "{}", l.glyph_points); + assert_eq!(l.glyph_points, l.glyphs.len() * big); + } + let huge = Arc::new(GlyphOutline { points: MAX_LOCAL_GLYPH_POINTS / 2, cap: 1.0, ..Default::default() }); + l.keep_glyph(key(500), &huge); + assert!(!l.glyphs.contains_key(&key(500)), "an outline above a quarter of the budget isn't kept"); + } } From e5dd7290e9cbe7d16e0fdfe138d77904a040591f Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Thu, 29 Oct 2026 10:53:41 -0600 Subject: [PATCH 4/6] Cull glyphs by their own ink box, not a fixed em margin Screen builds left out a filled glyph when a fixed font-unit box (-1000..2000) placed by its transform missed the view, so ink reaching more than an em past its box (flourishes, long ligatures, tall stacks, large operators) vanished when the view saw only that part. Each outline now records its font-unit bounds once as it is built, exposed as ttf::glyph_bounds through the same per-thread and shared outline caches, and may_show places those four corners instead: exact, and still four points per glyph however long its outline. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/ttf.rs | 13 +++++++++++-- crates/render/src/lib.rs | 2 +- crates/render/src/text.rs | 35 +++++++++++++++++++++++++++++++---- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index c2ea723f7..a146dd1d6 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -19,7 +19,7 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock}; -use cadcraft_geom::Vec2; +use cadcraft_geom::{Bounds2, Vec2}; use skrifa::instance::{LocationRef, Size}; use skrifa::outline::{DrawSettings, OutlinePen}; use skrifa::raw::FileRef; @@ -707,6 +707,8 @@ fn fallback_shared(c: char) -> Option { pub(crate) struct GlyphOutline { pub(crate) contours: Arc<[Vec]>, points: usize, + /// The extent of `contours`, found once as the outline is built (empty when it has none). + bounds: Bounds2, pub(crate) advance: f64, pub(crate) cap: f64, /// The font maps the character (false: the missing-glyph shape). @@ -858,6 +860,12 @@ pub fn glyph_contours(face: &Face, gid: u16) -> Arc<[Vec]> { glyph_by_id(face, u32::from(gid)).contours.clone() } +/// The extent of [`glyph_contours`] in the same font units (empty for a glyph without ink), so +/// renderers can test a placement against a view without visiting the outline's points. +pub fn glyph_bounds(face: &Face, gid: u16) -> Bounds2 { + glyph_by_id(face, u32::from(gid)).bounds +} + /// Load or build a glyph outline with bounded flattening, retaining its advance even when contours are discarded. /// Cache insertion clears existing entries when the glyph-count or aggregate point allowance would be exceeded. fn outline(face: &Face, k: GlyphKey) -> Arc { @@ -908,7 +916,8 @@ fn outline_shared(face: &Face, key: GlyphCacheKey) -> Arc { let advance = f64::from(f.glyph_metrics(Size::new(UPEM), LocationRef::default()).advance_width(gid).unwrap_or(UPEM * 0.5)); let (cap, mapped, gid) = (cap_height(&f), mapped.is_some(), gid.to_u32()); let points = pen.contours.iter().map(Vec::len).sum(); - let g = Arc::new(GlyphOutline { points, contours: pen.contours.into(), advance, cap, mapped, gid, face: Some(face.clone()) }); + let bounds = Bounds2::from_points(pen.contours.iter().flatten().copied()); + let g = Arc::new(GlyphOutline { points, bounds, contours: pen.contours.into(), advance, cap, mapped, gid, face: Some(face.clone()) }); let mut cache = glyph_cache().write().unwrap_or_else(PoisonError::into_inner); if cache.glyphs.len() >= MAX_CACHED_GLYPHS || cache.points.saturating_add(points) > MAX_SHAPED_POINTS { cache.glyphs.clear(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 560ec56d4..4de5b8e95 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -234,7 +234,7 @@ impl Builder<'_> { while text.next_if(|t| t.outline < i).is_some() {} let glyph = text.next_if(|t| t.outline == i); if let (Some(t), Some(v)) = (glyph, view) - && !crate::text::may_show(crate::text::placement(t, ctx.xf), &v) + && !crate::text::may_show(crate::text::placement(t, ctx.xf), cadcraft_fonts::ttf::glyph_bounds(&t.face, t.gid), &v) { continue; } diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index d6e9775e1..1fe650ffd 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -54,10 +54,16 @@ pub(super) fn placement(g: &TextGlyph, xf: Mat3) -> Mat3 { xf.then_before(Mat3 { a: g.x.x / 1000.0, b: g.x.y / 1000.0, c: g.y.x / 1000.0, d: g.y.y / 1000.0, e: g.origin.x, f: g.origin.y }) } -/// Whether a glyph placed by `xf` (font units, 1000 per em) can reach into `view`: its em box, -/// with an em of margin all round for glyphs that reach outside it, overlaps the area. -pub(super) fn may_show(xf: Mat3, view: &Bounds2) -> bool { - let corners = [Vec2::new(-1000.0, -1000.0), Vec2::new(2000.0, -1000.0), Vec2::new(2000.0, 2000.0), Vec2::new(-1000.0, 2000.0)]; +/// Whether a glyph whose ink spans `ink` (font units, 1000 per em; see [`ttf::glyph_bounds`]) +/// can reach into `view` when placed by `xf`: the placed corners of its ink box overlap the +/// area. The box is the outline's own, so flourishes, tall stacks and large operators that +/// reach far outside the em are kept, and testing it costs four points however long the +/// outline is. A glyph without ink shows nothing. +pub(super) fn may_show(xf: Mat3, ink: Bounds2, view: &Bounds2) -> bool { + if ink.is_empty() { + return false; + } + let corners = [ink.min, Vec2::new(ink.max.x, ink.min.y), ink.max, Vec2::new(ink.min.x, ink.max.y)]; let b = Bounds2::from_points(corners.map(|c| xf.apply(c))); // A placement that isn't finite is left to the mesh code, which handles it. b.is_empty() || !b.min.is_finite() || !b.max.is_finite() || b.intersects(view) @@ -255,6 +261,27 @@ fn triangulate(contours: &[Vec]) -> Vec { buffers.indices.into_iter().filter_map(|i| buffers.vertices.get(usize::from(i)).copied()).collect() } +#[cfg(test)] +mod view_tests { + use super::*; + + /// A glyph's own ink box decides whether it can show: ink reaching well past its em (a + /// flourish, a tall stack, a large operator) is kept when the view sees only that part. + #[test] + fn glyph_ink_beyond_the_em_keeps_the_glyph_in_view() { + // An em of one drawing unit with its origin at (0, 0). + let xf = Mat3 { a: 0.001, b: 0.0, c: 0.0, d: 0.001, e: 0.0, f: 0.0 }; + let ink = Bounds2::new(Vec2::new(-3000.0, -3000.0), Vec2::new(4000.0, 4000.0)); + let overhang = Bounds2::new(Vec2::new(3.0, 3.0), Vec2::new(3.5, 3.5)); + assert!(may_show(xf, ink, &overhang), "the view sees only the ink outside the em"); + let past = Bounds2::new(Vec2::new(4.5, 4.5), Vec2::new(5.0, 5.0)); + assert!(!may_show(xf, ink, &past), "a view past the ink leaves the glyph out"); + let em = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(1000.0, 1000.0)); + assert!(!may_show(xf, em, &overhang), "an em-sized glyph is left out of the same view"); + assert!(!may_show(xf, Bounds2::EMPTY, &overhang), "a glyph without ink shows nothing"); + } +} + #[cfg(test)] mod local_cache_tests { use super::*; From 7941757ed300d2ff10e02f17f740bb59dc9c17a3 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Thu, 29 Oct 2026 19:36:45 -0600 Subject: [PATCH 5/6] Check every placed glyph corner before building its bounds Bounds2 skips non-finite points, so a glyph with one overflowing corner could be culled from the few corners left. Any non-finite corner now leaves the glyph to the mesh code. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/text.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 3a1e9a0ae..f41388d62 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -64,9 +64,14 @@ pub(super) fn may_show(xf: Mat3, ink: Bounds2, view: &Bounds2) -> bool { return false; } let corners = [ink.min, Vec2::new(ink.max.x, ink.min.y), ink.max, Vec2::new(ink.min.x, ink.max.y)]; - let b = Bounds2::from_points(corners.map(|c| xf.apply(c))); - // A placement that isn't finite is left to the mesh code, which handles it. - b.is_empty() || !b.min.is_finite() || !b.max.is_finite() || b.intersects(view) + let placed = corners.map(|c| xf.apply(c)); + // A placement that isn't finite is left to the mesh code, which handles it. Bounds skip + // non-finite points, so every corner is checked before they are built. + if placed.iter().any(|p| !p.is_finite()) { + return true; + } + let b = Bounds2::from_points(placed); + b.is_empty() || b.intersects(view) } fn detail(xf: Mat3, pixel: f64) -> Detail { @@ -281,6 +286,11 @@ mod view_tests { let em = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(1000.0, 1000.0)); assert!(!may_show(xf, em, &overhang), "an em-sized glyph is left out of the same view"); assert!(!may_show(xf, Bounds2::EMPTY, &overhang), "a glyph without ink shows nothing"); + // One corner lands within f64, the far one overflows: the glyph is left to the mesh code. + let huge = Mat3 { a: 1.0e305, b: 0.0, c: 0.0, d: 1.0e305, e: 0.0, f: 0.0 }; + let wide = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(1.0e4, 1.0e4)); + let far = Bounds2::new(Vec2::new(-10.0, -10.0), Vec2::new(-5.0, -5.0)); + assert!(may_show(huge, wide, &far), "an overflowing corner keeps the glyph"); } } From d8c37cc6c1d3d55ed0e9ea003e676e707ee8f3ea Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Thu, 29 Oct 2026 19:40:18 -0600 Subject: [PATCH 6/6] Format dim/linear.rs as rustfmt does Main's fmt check fails on it since #2302; this keeps the PR's gate green. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/dim/linear.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/crates/render/src/dim/linear.rs b/crates/render/src/dim/linear.rs index 8127aef8f..da1b2a746 100644 --- a/crates/render/src/dim/linear.rs +++ b/crates/render/src/dim/linear.rs @@ -151,9 +151,7 @@ fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { state.side_out = if (config.dimension.defpt.xy() - state.p1).dot(state.n) >= 0.0 { state.n } else { -state.n }; state.text_axis = Vec2::from_angle(state.angle); let clearance = |axis: Vec2, across: f64| { - config.gap - + state.text_width * state.text_axis.dot(axis).abs() / 2.0 - + state.text_height * state.text_axis.perp().dot(axis).abs() * across + config.gap + state.text_width * state.text_axis.dot(axis).abs() / 2.0 + state.text_height * state.text_axis.perp().dot(axis).abs() * across }; // Empirical #2004 match: 0.595× height with SHX and 0.601× with TrueType. let off_along = |axis: Vec2| clearance(axis, if st.text_above == 1 { 0.6 } else { 0.5 }); @@ -186,11 +184,8 @@ fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { // Half the text height either way, whatever DIMTAD says (#2222). let clear = clearance(state.side_out, 0.5); let lift = clear + 2.0 * config.arrow_size.max(config.tick_size); - state.text_mid = if st.text_move == 1 { - mid + state.side_out * lift + state.u * state.half_extent - } else { - mid + state.side_out * (lift + clear) - }; + state.text_mid = + if st.text_move == 1 { mid + state.side_out * lift + state.u * state.half_extent } else { mid + state.side_out * (lift + clear) }; } else if !config.dimension.user_text_pos { state.text_mid = state.along_center + state.offset; }