diff --git a/crates/fonts/src/craft_fonts.rs b/crates/fonts/src/craft_fonts.rs index 7d81af2d2..7a60db488 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 951c86e8e..a3b8b3017 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -22,11 +22,13 @@ //! Fonts) are searched first: a font placed there wins over an installed one with the same file //! name. +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; +use cadcraft_geom::{Bounds2, Vec2}; use skrifa::instance::{LocationRef, Size}; use skrifa::outline::{DrawSettings, OutlinePen}; use skrifa::raw::FileRef; @@ -498,6 +500,8 @@ pub fn rescan() { g.face_names.clear(); drop(g); GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // The per-thread lookup caches start over too: the folders' fonts are gone from the shared tables. + changed(); // SHX files in the same folders: the SHX font table looks there too. crate::shx::set_font_dirs(shx_dirs(&user_dirs())); } @@ -835,6 +839,7 @@ pub fn register(name: &str, bytes: Vec) { g.registered.insert(k); 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 @@ -848,6 +853,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. @@ -867,9 +873,98 @@ fn is_stroke_name(k: &str) -> bool { || 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 LOOKUP_GENERATION: AtomicU64 = AtomicU64::new(0); + +fn changed() { + // Release: a thread that sees the new generation also sees what changed. + LOOKUP_GENERATION.fetch_add(1, Ordering::Release); +} + +/// The generation now, taken before a lookup whose answer [`keep`] may cache. +fn lookup_generation() -> u64 { + LOOKUP_GENERATION.load(Ordering::Acquire) +} + +/// `f` on this thread's cache, only when lookups haven't changed since `seen` ([`lookup_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 lookup_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. +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>, + /// 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()); +} + +/// `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 = lookup_generation(); + 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 seen = lookup_generation(); + let r = find_shared(name); + keep(seen, |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; @@ -919,12 +1014,19 @@ 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 seen = lookup_generation(); + let a = prefs().alt.clone(); + keep(seen, |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. @@ -935,6 +1037,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). @@ -949,6 +1052,22 @@ 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 seen = lookup_generation(); + let r = fallback_shared(c); + keep(seen, |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()) @@ -969,6 +1088,8 @@ pub fn fallback_for(c: char) -> Option { pub(crate) struct GlyphOutline { pub(crate) contours: Arc<[Vec]>, pub(crate) 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). @@ -988,9 +1109,10 @@ 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 GlyphCacheKey = (usize, usize, u32, GlyphKey); #[derive(Default)] struct GlyphCache { - glyphs: HashMap<(usize, usize, u32, GlyphKey), Arc>, + glyphs: HashMap>, points: usize, } @@ -1163,10 +1285,45 @@ 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 { 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| 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; if let Some(g) = glyph_cache().read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&key) { return g.clone(); } @@ -1184,7 +1341,8 @@ fn outline(face: &Face, k: GlyphKey) -> 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(); @@ -1601,6 +1759,46 @@ mod geometry_budget_tests { } } +#[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 = lookup_generation(); + changed(); + keep(seen, |l| l.alt = Some("stale".into())); + assert_ne!(local(|l| l.alt.clone()), Some("stale".to_string())); + let now = lookup_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 lookup_generation() == now { + 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"); + } +} + #[cfg(all(test, not(target_arch = "wasm32")))] mod scan_tests { use super::*; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 407b77b4a..81ee3ffe1 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -285,10 +285,20 @@ impl<'a> Builder<'a> { // 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), cadcraft_fonts::ttf::glyph_bounds(&t.face, t.gid), &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 1094895f4..0b52012cb 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -282,6 +282,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"); +} + // ---------- a fixture TrueType font: no font file, no installed font ---------- /// A closed ellipse round (500, 350), wound by `clockwise`: one contour of a glyph outline. diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 6a4361ed6..d1b3d20ed 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -54,6 +54,26 @@ 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 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 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 { // 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 +88,68 @@ 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; +/// 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(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().entries.get(&key).map(|e| e.mesh.clone())) { + return m; + } + let m = mesh_shared(g, key, detail); + LOCAL.with(|l| { + 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) { return entry.mesh.clone(); } @@ -93,11 +172,7 @@ pub(super) fn mesh(g: &TextGlyph, xf: Mat3, pixel: f64) -> 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 { @@ -193,6 +268,52 @@ 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"); + // 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"); + } +} + +#[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"); + } +} + /// [`triangulate`] for a glyph outline already placed in drawing coordinates (complex-script /// runs carry no [`TextGlyph`]): tessellated relative to its first point so f32 keeps the /// precision. Outlines past the limits [`mesh`] applies keep the slab filler.