Compare commits

..
Author SHA1 Message Date
FredApps b3bc4a7618 Merge pull request #997 from aldozar/perf/cjk-text
Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out (#666, #662)
2026-11-26 13:43:40 +01:00
FredApps e66cdcec29 Merge main into perf/cjk-text
Conflicts: crates/fonts/src/ttf.rs (main made OutlineMesh's points pub(crate); kept that and this PR's bounds field) and crates/render/src/tests.rs (kept this PR's #666 view test and main's fixture-font section).

Main also added a public font-set GENERATION/generation() for redraws (2c979eb1), which clashed by name with this PR's private lookup-cache counter. Renamed this PR's counter to LOOKUP_GENERATION/lookup_generation(), and set_font_dirs now also calls changed() so the per-thread caches drop fonts from removed folders.

cargo test -p cadcraft-fonts -p cadcraft-render and cargo fmt --check pass locally.
2026-11-26 19:31:45 +07:00
Aldo ZarateandClaude Opus 5.5 06491fc757 Merge upstream/main into perf/cjk-text
ttf.rs keeps both test modules: the thread cache's and main's font
directory scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:03:34 -06:00
Aldo ZarateandClaude Opus 5.5 d8c37cc6c1 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 <noreply@anthropic.com>
2026-10-29 19:40:18 -06:00
Aldo Zarate 8391c1f0de Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 19:39:48 -06:00
Aldo ZarateandClaude Opus 5.5 7941757ed3 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 <noreply@anthropic.com>
2026-10-29 19:36:45 -06:00
Aldo Zarate d325681051 Merge remote-tracking branch 'upstream/main' into perf/cjk-text
# Conflicts:
#	crates/render/src/text.rs
2026-10-29 19:25:42 -06:00
Aldo ZarateandClaude Opus 5.5 e5dd7290e9 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 <noreply@anthropic.com>
2026-10-29 10:53:41 -06:00
Aldo Zarate 000dbb4383 Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 10:41:47 -06:00
Aldo ZarateandClaude Opus 5.5 9a1bd48a26 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 <noreply@anthropic.com>
2026-10-23 08:10:30 -06:00
Aldo ZarateandClaude Opus 5.5 e57786e726 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 <noreply@anthropic.com>
2026-10-23 07:44:08 -06:00
Aldo ZarateandClaude Opus 5.5 4d3ceea73b Merge upstream/main into perf/cjk-text
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:41:29 -06:00
Aldo ZarateandClaude Opus 5.5 38e98e43c0 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 <noreply@anthropic.com>
2026-10-13 09:58:53 -06:00
8 changed files with 367 additions and 13 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@4ec2a14646b538253fd5ebe109bf463a3d31b061
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: cadcraft
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@4ec2a14646b538253fd5ebe109bf463a3d31b061
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: cadcraft
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -58,7 +58,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+8
View File
@@ -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.
+202 -4
View File
@@ -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<u8>) {
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<String, Option<Face>>,
fallback: HashMap<char, Option<Face>>,
/// FONTALT, asked for every text whose font isn't installed.
alt: Option<String>,
/// Glyph outlines, in front of the shared [`glyph_cache`] (whose lock every core reads).
glyphs: HashMap<GlyphCacheKey, Arc<GlyphOutline>>,
/// 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<Local> = RefCell::new(Local::default());
}
/// `f` on this thread's cache, emptied first when lookups changed since it was filled.
fn local<R>(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<Face> {
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<Face> {
let k = key(name);
if is_stroke_name(&k) {
return None;
@@ -919,12 +1014,19 @@ fn split_list(s: &str) -> Vec<String> {
/// 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<Face> {
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<Face> {
let (list, alt) = {
let p = prefs();
(p.fallback.clone(), p.alt.clone())
@@ -969,6 +1088,8 @@ pub fn fallback_for(c: char) -> Option<Face> {
pub(crate) struct GlyphOutline {
pub(crate) contours: Arc<[Vec<Vec2>]>,
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<GlyphOutline>>,
glyphs: HashMap<GlyphCacheKey, Arc<GlyphOutline>>,
points: usize,
}
@@ -1163,10 +1285,45 @@ pub fn glyph_contours(face: &Face, gid: u16) -> Arc<[Vec<Vec2>]> {
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<GlyphOutline> {
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<GlyphOutline>) {
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<GlyphOutline> {
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<GlyphOutline> {
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::*;
+10
View File
@@ -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);
+17
View File
@@ -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.
+126 -5
View File
@@ -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<Key, Entry>,
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<Local> = std::cell::RefCell::new(Local::default());
}
pub(super) fn mesh(g: &TextGlyph, xf: Mat3, pixel: f64) -> Arc<Mesh> {
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<T>(entries: &mut HashMap<Key, T>, 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::<usize>().saturating_add(mesh.triangles.capacity());
points
.saturating_mul(std::mem::size_of::<Vec2>())
.saturating_add(mesh.contours.len().saturating_mul(std::mem::size_of::<Vec<Vec2>>()))
.saturating_add(std::mem::size_of::<Entry>() + std::mem::size_of::<Key>() + std::mem::size_of::<Mesh>())
}
/// [`mesh`] through the shared cache.
fn mesh_shared(g: &TextGlyph, key: Key, detail: Detail) -> Arc<Mesh> {
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<Mesh> {
}
};
let mesh = Arc::new(Mesh { triangles: triangulate(&contours), contours });
let points = mesh.contours.iter().map(Vec::capacity).sum::<usize>().saturating_add(mesh.triangles.capacity());
let bytes = points
.saturating_mul(std::mem::size_of::<Vec2>())
.saturating_add(mesh.contours.len().saturating_mul(std::mem::size_of::<Vec<Vec2>>()))
.saturating_add(std::mem::size_of::<Entry>() + std::mem::size_of::<Key>() + std::mem::size_of::<Mesh>());
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<Vec2>]) -> Vec<Vec2> {
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.