authoravatarclover caruso<git@paperclover.net>2026-12-01 16:13:14-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 16:27:14-08:00
log40ca636e5b89a2ea337f81f7bf69a53369e33f88
treeb055e7376436096eaf34325f6ed0d6f57d68eea2
parent6b08e39c45b70bb37ac6c03d0ed2c5a44f430957
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): harden text_engine font/glyph cache, NGon NaN guard, multiplies_by_mask, and blur_glow select loads


7 files changed, 359 insertions(+), 60 deletions(-)

crates/engine/src/eval/composite.rs+3-3
...@@ -673,13 +673,13 @@ fn roi_from_consumer(...@@ -673,13 +673,13 @@ fn roi_from_consumer(
673 if port != "Input" {673 if port != "Input" {
674 return None;674 return None;
675 }675 }
676 if Engine::resolve_effect_mask_id(comp, n).is_some() {
677 return Some(RoiBox::canvas(canvas_size));
678 }
676 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;679 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
677 if blend <= 1e-6 {680 if blend <= 1e-6 {
678 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);681 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
679 }682 }
680 if Engine::resolve_effect_mask_id(comp, n).is_some() {
681 return Some(RoiBox::canvas(canvas_size));
682 }
683 let amount = comp.eval_number(n, "Amount", time, 0.0, expr);683 let amount = comp.eval_number(n, "Amount", time, 0.0, expr);
684 let amt_x = comp.eval_number(n, "XAmount", time, amount, expr) as f32;684 let amt_x = comp.eval_number(n, "XAmount", time, amount, expr) as f32;
685 let amt_y = if comp.eval_number(n, "LockXY", time, 1.0, expr) > 0.5 {685 let amt_y = if comp.eval_number(n, "LockXY", time, 1.0, expr) > 0.5 {
crates/engine/src/eval/transform.rs+2-2
...@@ -890,7 +890,7 @@ impl Engine {...@@ -890,7 +890,7 @@ impl Engine {
890890
891 /// `MultiplyByMask` zeroes outside the EffectMask even when the effect itself is an identity.891 /// `MultiplyByMask` zeroes outside the EffectMask even when the effect itself is an identity.
892 pub(super) fn multiplies_by_mask(&self, comp: &Comp, node: &Node, time: f64) -> bool {892 pub(super) fn multiplies_by_mask(&self, comp: &Comp, node: &Node, time: f64) -> bool {
893 node.connected_node("EffectMask").is_some()893 Self::resolve_effect_mask_id(comp, node).is_some()
894 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5894 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5
895 }895 }
896896
...@@ -1007,7 +1007,7 @@ impl Engine {...@@ -1007,7 +1007,7 @@ impl Engine {
1007 return src;1007 return src;
1008 }1008 }
1009 let skip = self.process_skip(comp, node, time);1009 let skip = self.process_skip(comp, node, time);
1010 if skip.iter().all(|&s| s > 0.5) {1010 if skip.iter().all(|&s| s > 0.5) && !self.multiplies_by_mask(comp, node, time) {
1011 return src;1011 return src;
1012 }1012 }
1013 let src = self.crop_to_canvas(enc, src);1013 let src = self.crop_to_canvas(enc, src);
crates/engine/src/eval/warps.rs+1-1
...@@ -150,7 +150,7 @@ impl Engine {...@@ -150,7 +150,7 @@ impl Engine {
150 return src;150 return src;
151 }151 }
152 let skip = self.process_skip(comp, node, time);152 let skip = self.process_skip(comp, node, time);
153 if skip.iter().all(|&s| s > 0.5) {153 if skip.iter().all(|&s| s > 0.5) && !mbm_flag {
154 return src;154 return src;
155 }155 }
156 let src = self.crop_to_canvas(enc, src);156 let src = self.crop_to_canvas(enc, src);
crates/engine/src/particles/raster.rs+61-2
...@@ -641,9 +641,9 @@ fn rasterize_single_band(...@@ -641,9 +641,9 @@ fn rasterize_single_band(
641 let angle = (-dy).atan2(dx) - phase;641 let angle = (-dy).atan2(dx) - phase;
642 let off = angle.rem_euclid(spike_period);642 let off = angle.rem_euclid(spike_period);
643 let to_spike = off.min(spike_period - off);643 let to_spike = off.min(spike_period - off);
644 let shape_w = (1.0 - to_spike * inv_half_period).powf(sharpness) as f32;644 let shape_w = (1.0 - to_spike * inv_half_period).max(0.0).powf(sharpness) as f32;
645 let pa = env_a * shape_w;645 let pa = env_a * shape_w;
646 if pa <= 1e-5 {646 if !(pa > 1e-5) {
647 continue;647 continue;
648 }648 }
649 let inv_a = 1.0 - pa;649 let inv_a = 1.0 - pa;
...@@ -942,3 +942,62 @@ fn draw_bitmap_band(...@@ -942,3 +942,62 @@ fn draw_bitmap_band(
942 }942 }
943 }943 }
944}944}
945
946#[cfg(test)]
947mod tests {
948 use super::*;
949
950 #[test]
951 fn ngon_spike_midpoint_non_integer_sharpness_produces_no_nan() {
952 let w = 32usize;
953 let h = 32usize;
954 let mut out = vec![0u8; w * h * 4];
955 let mut accum = vec![0.0_f32; w * h * 4];
956 let cx = 16.5;
957 let cy = 16.5;
958
959 // Test multiple odd/non-power-of-two side counts where inv_half_period = 2 / spike_period
960 // can round up at off == spike_period * 0.5 and make (1.0 - to_spike * inv_half_period) < 0.
961 for &sides in &[3.0_f64, 5.0, 6.0, 7.0, 9.0] {
962 let spike_period = std::f64::consts::TAU / sides;
963 let inv_half_period = 2.0 / spike_period;
964 let sharpness = 4.5 * (3.0 / sides).powf(2.8);
965 // At pixel (17, 16), dx = 1.0, dy = 0.0 -> atan2 = 0.0, so phase = -0.5 * spike_period
966 // forces off = 0.5 * spike_period (exact spike midpoint).
967 let phase = -0.5 * spike_period;
968 let cmds = [
969 DrawCmd {
970 min_x: 8,
971 max_x: 24,
972 min_y: 8,
973 max_y: 24,
974 color: [1.0, 0.5, 0.25, 1.0],
975 shape: DrawShape::NGon {
976 cx,
977 cy,
978 inv_two_sigma_sq: 0.05,
979 inv_half_period,
980 spike_period,
981 phase,
982 sharpness,
983 },
984 },
985 // Blend an opaque point on (17, 16) afterwards; if accum had NaN it would poison dst.
986 DrawCmd {
987 min_x: 17,
988 max_x: 17,
989 min_y: 16,
990 max_y: 16,
991 color: [0.0, 1.0, 0.0, 1.0],
992 shape: DrawShape::Point,
993 },
994 ];
995 out.fill(0);
996 accum.fill(0.0);
997 rasterize_single_band(&mut out, &mut accum, w, 0, h, &cmds, &[]);
998 assert!(accum.iter().all(|v| v.is_finite()), "NaN/Inf leaked into accum for sides={sides}");
999 let idx = (16 * w + 17) * 4;
1000 assert_eq!(&out[idx..idx + 4], &[0, 255, 0, 255], "midpoint pixel poisoned for sides={sides}");
1001 }
1002 }
1003}
crates/engine/src/shaders/blur_glow.wgsl+18-17
...@@ -118,11 +118,12 @@ fn run_blur_pass(gid: vec2<u32>) {...@@ -118,11 +118,12 @@ fn run_blur_pass(gid: vec2<u32>) {
118 let has_mask = u.p[1].y > 0.5;118 let has_mask = u.p[1].y > 0.5;
119 let m = clamp(read_mask(gid.xy, dims, u.p[1].y, u.p[1].z) * u.p[1].x, 0.0, 1.0);119 let m = clamp(read_mask(gid.xy, dims, u.p[1].y, u.p[1].z) * u.p[1].x, 0.0, 1.0);
120 if (u.p[0].w > 1.5) {120 if (u.p[0].w > 1.5) {
121 let orig = select(121 var orig: vec4<f32>;
122 textureLoad(src_a, vec2<i32>(gid.xy), 0),122 if (u.p[2].x > 0.5) {
123 textureLoad(src_b, vec2<i32>(gid.xy), 0),123 orig = textureLoad(src_b, vec2<i32>(gid.xy), 0);
124 u.p[2].x > 0.5,124 } else {
125 );125 orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
126 }
126 if (m <= 1e-6) {127 if (m <= 1e-6) {
127 store_dst(vec2<i32>(gid.xy), orig);128 store_dst(vec2<i32>(gid.xy), orig);
128 return;129 return;
...@@ -132,11 +133,12 @@ fn run_blur_pass(gid: vec2<u32>) {...@@ -132,11 +133,12 @@ fn run_blur_pass(gid: vec2<u32>) {
132 return;133 return;
133 }134 }
134 if (has_mask && m <= 1e-6) {135 if (has_mask && m <= 1e-6) {
135 let orig = select(136 var orig: vec4<f32>;
136 textureLoad(src_a, vec2<i32>(gid.xy), 0),137 if (u.p[2].x > 0.5) {
137 textureLoad(src_b, vec2<i32>(gid.xy), 0),138 orig = textureLoad(src_b, vec2<i32>(gid.xy), 0);
138 u.p[2].x > 0.5,139 } else {
139 );140 orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
141 }
140 store_dst(vec2<i32>(gid.xy), orig);142 store_dst(vec2<i32>(gid.xy), orig);
141 return;143 return;
142 }144 }
...@@ -273,15 +275,14 @@ fn run_blur_pass(gid: vec2<u32>) {...@@ -273,15 +275,14 @@ fn run_blur_pass(gid: vec2<u32>) {
273 }275 }
274 }276 }
275277
276 if (u.p[1].y < 0.5 && u.p[1].x >= 0.9999) {278 if (u.p[1].y < 0.5 && u.p[1].x >= 1.0) {
277 store_dst(vec2<i32>(gid.xy), acc);279 store_dst(vec2<i32>(gid.xy), acc);
278 return;280 return;
279 }281 }
280 let orig = select(282 var orig = center;
281 center,283 if (u.p[2].x > 0.5) {
282 textureLoad(src_b, vec2<i32>(gid.xy), 0),284 orig = textureLoad(src_b, vec2<i32>(gid.xy), 0);
283 u.p[2].x > 0.5,285 }
284 );
285 let out_col = mix(orig, acc, m);286 let out_col = mix(orig, acc, m);
286 store_dst(vec2<i32>(gid.xy), out_col);287 store_dst(vec2<i32>(gid.xy), out_col);
287}288}
...@@ -492,7 +493,7 @@ fn dir_blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -492,7 +493,7 @@ fn dir_blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
492 store_dst(vec2<i32>(gid.xy), unprocessed);493 store_dst(vec2<i32>(gid.xy), unprocessed);
493 return;494 return;
494 }495 }
495 if (abs(length_v) < 1e-5 && abs(angle) < 1e-5) {496 if (abs(length_v) < 1e-5 && abs(angle) < 1e-5 && glow <= 1e-4) {
496 let out_col = select(orig, orig * m, mbm);497 let out_col = select(orig, orig * m, mbm);
497 store_dst(vec2<i32>(gid.xy), select(out_col, unprocessed, skip));498 store_dst(vec2<i32>(gid.xy), select(out_col, unprocessed, skip));
498 return;499 return;
crates/engine/src/shaders/composite.wgsl+2-2
...@@ -382,8 +382,8 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -382,8 +382,8 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
382 let fg = merge_sample_fg(src_b, fg_fu, edges, u.p[4], nearest, size);382 let fg = merge_sample_fg(src_b, fg_fu, edges, u.p[4], nearest, size);
383383
384 // Fast path for the common Normal + Over + Gain=1.0 + no mask + Blend=1.0 case.384 // Fast path for the common Normal + Over + Gain=1.0 + no mask + Blend=1.0 case.
385 if (mode == 0 && op == 0 && gain >= 0.9999 && has_mask < 0.5 && blend >= 0.9999 && !mbm && burn_in == 0.0) {385 if (mode == 0 && op == 0 && gain >= 1.0 && has_mask < 0.5 && blend >= 1.0 && !mbm && burn_in == 0.0) {
386 let fg_rgb = select(fg.rgb * mix(fg.a, 1.0, sub_add), fg.rgb, sub_add >= 0.9999);386 let fg_rgb = select(fg.rgb * mix(fg.a, 1.0, sub_add), fg.rgb, sub_add >= 1.0);
387 let out_col = vec4<f32>(fg_rgb + bg.rgb * (1.0 - fg.a), fg.a + bg.a * (1.0 - fg.a));387 let out_col = vec4<f32>(fg_rgb + bg.rgb * (1.0 - fg.a), fg.a + bg.a * (1.0 - fg.a));
388 store_dst(vec2<i32>(gid.xy), out_col);388 store_dst(vec2<i32>(gid.xy), out_col);
389 return;389 return;
crates/engine/src/text_engine.rs+272-33
...@@ -36,19 +36,15 @@ impl Font {...@@ -36,19 +36,15 @@ impl Font {
36 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {36 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {
37 {37 {
38 let cache = font_cache().lock().unwrap();38 let cache = font_cache().lock().unwrap();
39 if let Some(hit) = cache.get(&(family.to_owned(), style.to_owned())) {39 if let Some(hit) = cache.1.get(&(family.to_owned(), style.to_owned())) {
40 return hit.clone();40 return hit.clone();
41 }41 }
42 }42 }
43 let resolved = {43 let (resolved, resolved_gen) = {
44 let mut reg = registry().write().unwrap();44 let mut reg = registry().write().unwrap();
45 resolve_lazy(&mut reg, family, style).map(Arc::new)45 (resolve_lazy(&mut reg, family, style).map(Arc::new), reg.generation)
46 };46 };
47 let mut cache = font_cache().lock().unwrap();47 cache_resolved_font(family, style, resolved, resolved_gen)
48 let entry = cache
49 .entry((family.to_owned(), style.to_owned()))
50 .or_insert_with(|| resolved.clone());
51 entry.clone()
52 }48 }
5349
54 pub fn face(&self) -> Face<'_> {50 pub fn face(&self) -> Face<'_> {
...@@ -63,6 +59,7 @@ impl Font {...@@ -63,6 +59,7 @@ impl Font {
63struct FontRegistry {59struct FontRegistry {
64 db: fontdb::Database,60 db: fontdb::Database,
65 aliases: HashMap<String, Vec<fontdb::ID>>,61 aliases: HashMap<String, Vec<fontdb::ID>>,
62 generation: u64,
66 #[cfg(not(target_arch = "wasm32"))]63 #[cfg(not(target_arch = "wasm32"))]
67 system_fonts_loaded: bool,64 system_fonts_loaded: bool,
68 #[cfg(not(target_arch = "wasm32"))]65 #[cfg(not(target_arch = "wasm32"))]
...@@ -78,6 +75,7 @@ impl FontRegistry {...@@ -78,6 +75,7 @@ impl FontRegistry {
78 Self {75 Self {
79 db: fontdb::Database::new(),76 db: fontdb::Database::new(),
80 aliases: HashMap::new(),77 aliases: HashMap::new(),
78 generation: 0,
81 #[cfg(not(target_arch = "wasm32"))]79 #[cfg(not(target_arch = "wasm32"))]
82 system_fonts_loaded: false,80 system_fonts_loaded: false,
83 #[cfg(not(target_arch = "wasm32"))]81 #[cfg(not(target_arch = "wasm32"))]
...@@ -98,11 +96,35 @@ impl FontRegistry {...@@ -98,11 +96,35 @@ impl FontRegistry {
98 }96 }
99}97}
10098
101fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> {99type FontCacheMap = HashMap<(String, String), Option<Arc<Font>>>;
102 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();100
101fn font_cache() -> &'static Mutex<(u64, FontCacheMap)> {
102 static CACHE: OnceLock<Mutex<(u64, FontCacheMap)>> = OnceLock::new();
103 CACHE.get_or_init(Default::default)103 CACHE.get_or_init(Default::default)
104}104}
105105
106fn cache_resolved_font(
107 family: &str,
108 style: &str,
109 resolved: Option<Arc<Font>>,
110 resolved_gen: u64,
111) -> Option<Arc<Font>> {
112 let mut cache = font_cache().lock().unwrap();
113 if cache.0 != resolved_gen {
114 if cache.0 < resolved_gen {
115 cache.0 = resolved_gen;
116 cache.1.clear();
117 } else {
118 return resolved;
119 }
120 }
121 let entry = cache
122 .1
123 .entry((family.to_owned(), style.to_owned()))
124 .or_insert_with(|| resolved.clone());
125 entry.clone()
126}
127
106fn registry() -> &'static RwLock<FontRegistry> {128fn registry() -> &'static RwLock<FontRegistry> {
107 static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new();129 static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new();
108 REG.get_or_init(|| RwLock::new(FontRegistry::new()))130 REG.get_or_init(|| RwLock::new(FontRegistry::new()))
...@@ -207,6 +229,8 @@ fn is_style_suffix(rest: &str) -> bool {...@@ -207,6 +229,8 @@ fn is_style_suffix(rest: &str) -> bool {
207 "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy",229 "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy",
208 "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow",230 "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow",
209 "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps",231 "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps",
232 "b", "i", "z", "l", "sl", "sb", "cond", "display", "text",
233 "100", "200", "300", "400", "500", "600", "700", "800", "900",
210 ];234 ];
211 rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p))235 rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p))
212}236}
...@@ -249,17 +273,23 @@ fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) {...@@ -249,17 +273,23 @@ fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) {
249/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime273/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime
250/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.274/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.
251pub fn register_font_bytes(bytes: Vec<u8>) {275pub fn register_font_bytes(bytes: Vec<u8>) {
252 {276 let new_gen = {
253 let mut reg = registry().write().unwrap();277 let mut reg = registry().write().unwrap();
254 reg.db.load_font_data(bytes);278 reg.db.load_font_data(bytes);
279 reg.generation += 1;
280 reg.generation
281 };
282 let mut cache = font_cache().lock().unwrap();
283 if cache.0 < new_gen {
284 cache.0 = new_gen;
285 cache.1.clear();
255 }286 }
256 font_cache().lock().unwrap().clear();
257}287}
258288
259/// Registers font bytes under an explicit family alias in addition to its embedded family names,289/// Registers font bytes under an explicit family alias in addition to its embedded family names,
260/// and clears the resolution cache.290/// and clears the resolution cache.
261pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {291pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
262 {292 let new_gen = {
263 let mut reg = registry().write().unwrap();293 let mut reg = registry().write().unwrap();
264 let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect();294 let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect();
265 reg.db.load_font_data(bytes);295 reg.db.load_font_data(bytes);
...@@ -272,8 +302,14 @@ pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {...@@ -272,8 +302,14 @@ pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
272 .extend(added);302 .extend(added);
273 }303 }
274 }304 }
305 reg.generation += 1;
306 reg.generation
307 };
308 let mut cache = font_cache().lock().unwrap();
309 if cache.0 < new_gen {
310 cache.0 = new_gen;
311 cache.1.clear();
275 }312 }
276 font_cache().lock().unwrap().clear();
277}313}
278314
279/// CSS-style weight and italic flag for a Fusion style name.315/// CSS-style weight and italic flag for a Fusion style name.
...@@ -375,7 +411,15 @@ fn try_pick_family_lazy(...@@ -375,7 +411,15 @@ fn try_pick_family_lazy(
375 load_family_candidates(reg, &fam_norm);411 load_family_candidates(reg, &fam_norm);
376 }412 }
377 }413 }
378 pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic)414 let picked = pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic);
415 #[cfg(not(target_arch = "wasm32"))]
416 if let Some(id) = picked {
417 if !reg.system_fonts_loaded && !is_exact_face_match(&reg.db, id, wanted_style, weight, italic) {
418 reg.ensure_system_fonts_loaded();
419 return pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic);
420 }
421 }
422 picked
379}423}
380424
381fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> {425fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> {
...@@ -386,7 +430,13 @@ fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Fon...@@ -386,7 +430,13 @@ fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Fon
386 .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic)));430 .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic)));
387431
388 #[cfg(not(target_arch = "wasm32"))]432 #[cfg(not(target_arch = "wasm32"))]
389 if id.is_none() && !family.is_empty() && !reg.system_fonts_loaded {433 if !family.is_empty()
434 && !reg.system_fonts_loaded
435 && match id {
436 None => true,
437 Some(found) => !is_exact_face_match(&reg.db, found, &wanted, weight, italic),
438 }
439 {
390 reg.ensure_system_fonts_loaded();440 reg.ensure_system_fonts_loaded();
391 id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic)441 id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic)
392 .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic)));442 .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic)));
...@@ -941,6 +991,7 @@ const GLYPH_BASELINE_ANCHOR: f32 = 256.0;...@@ -941,6 +991,7 @@ const GLYPH_BASELINE_ANCHOR: f32 = 256.0;
941const GLYPH_BASELINE_ANCHOR_I32: i32 = 256;991const GLYPH_BASELINE_ANCHOR_I32: i32 = 256;
942const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;992const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;
943const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024;993const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024;
994const MAX_GLYPH_COORD: f32 = 8_388_608.0;
944995
945#[derive(Clone, Copy, PartialEq, Eq, Hash)]996#[derive(Clone, Copy, PartialEq, Eq, Hash)]
946struct GlyphCacheKey {997struct GlyphCacheKey {
...@@ -960,8 +1011,9 @@ struct CachedGlyphCoverage {...@@ -960,8 +1011,9 @@ struct CachedGlyphCoverage {
960}1011}
9611012
962struct GlyphCache {1013struct GlyphCache {
963 map: HashMap<GlyphCacheKey, Arc<CachedGlyphCoverage>>,1014 map: HashMap<GlyphCacheKey, (u64, Arc<CachedGlyphCoverage>)>,
964 order: VecDeque<GlyphCacheKey>,1015 order: VecDeque<(u64, GlyphCacheKey)>,
1016 next_stamp: u64,
965 total_bytes: usize,1017 total_bytes: usize,
966}1018}
9671019
...@@ -970,29 +1022,58 @@ impl GlyphCache {...@@ -970,29 +1022,58 @@ impl GlyphCache {
970 Self {1022 Self {
971 map: HashMap::new(),1023 map: HashMap::new(),
972 order: VecDeque::new(),1024 order: VecDeque::new(),
1025 next_stamp: 0,
973 total_bytes: 0,1026 total_bytes: 0,
974 }1027 }
975 }1028 }
9761029
977 fn get(&self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> {1030 fn compact_order(&mut self) {
978 self.map.get(key).cloned()1031 let mut live: Vec<(u64, GlyphCacheKey)> =
1032 self.map.iter().map(|(k, (s, _))| (*s, *k)).collect();
1033 live.sort_unstable_by_key(|&(s, _)| s);
1034 self.order.clear();
1035 self.order.extend(live);
1036 }
1037
1038 fn get(&mut self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> {
1039 let (stamp, val) = self.map.get_mut(key)?;
1040 self.next_stamp += 1;
1041 *stamp = self.next_stamp;
1042 self.order.push_back((self.next_stamp, *key));
1043 let out = Arc::clone(val);
1044 if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 {
1045 self.compact_order();
1046 }
1047 Some(out)
979 }1048 }
9801049
981 fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) {1050 fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) {
982 if val.bytes > MAX_GLYPH_CACHE_BYTES || self.map.contains_key(&key) {1051 if val.bytes > MAX_GLYPH_CACHE_BYTES {
1052 return;
1053 }
1054 if let Some((stamp, _)) = self.map.get_mut(&key) {
1055 self.next_stamp += 1;
1056 *stamp = self.next_stamp;
1057 self.order.push_back((self.next_stamp, key));
1058 if self.order.len() > MAX_GLYPH_CACHE_ENTRIES * 4 {
1059 self.compact_order();
1060 }
983 return;1061 return;
984 }1062 }
985 while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES {1063 while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES {
986 let Some(old_key) = self.order.pop_front() else {1064 let Some((s, old_key)) = self.order.pop_front() else {
987 break;1065 break;
988 };1066 };
989 if let Some(removed) = self.map.remove(&old_key) {1067 if self.map.get(&old_key).is_some_and(|(cur_s, _)| *cur_s == s) {
990 self.total_bytes = self.total_bytes.saturating_sub(removed.bytes);1068 if let Some((_, removed)) = self.map.remove(&old_key) {
1069 self.total_bytes = self.total_bytes.saturating_sub(removed.bytes);
1070 }
991 }1071 }
992 }1072 }
1073 self.next_stamp += 1;
993 self.total_bytes += val.bytes;1074 self.total_bytes += val.bytes;
994 self.order.push_back(key);1075 self.order.push_back((self.next_stamp, key));
995 self.map.insert(key, val);1076 self.map.insert(key, (self.next_stamp, val));
996 }1077 }
997}1078}
9981079
...@@ -1001,11 +1082,32 @@ fn glyph_cache() -> &'static Mutex<GlyphCache> {...@@ -1001,11 +1082,32 @@ fn glyph_cache() -> &'static Mutex<GlyphCache> {
1001 CACHE.get_or_init(|| Mutex::new(GlyphCache::new()))1082 CACHE.get_or_init(|| Mutex::new(GlyphCache::new()))
1002}1083}
10031084
1085fn quantize_subpixel(coord: f32) -> Option<(i32, f32)> {
1086 if !coord.is_finite() || coord.abs() > MAX_GLYPH_COORD {
1087 return None;
1088 }
1089 let mut ix = coord.floor() as i32;
1090 let fx = (coord - ix as f32).clamp(0.0, 1.0);
1091 let mut qx = (fx * 16.0).round() as i32;
1092 if qx >= 16 {
1093 ix += 1;
1094 qx = 0;
1095 }
1096 Some((ix, qx as f32 * (1.0 / 16.0)))
1097}
1098
1004fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) {1099fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) {
1005 let ix = spec.abs_x.floor() as i32;1100 let (Some((ix, fx)), Some((iy, fy))) = (quantize_subpixel(spec.abs_x), quantize_subpixel(spec.abs_y)) else {
1006 let iy = spec.abs_y.floor() as i32;1101 return (
1007 let fx = spec.abs_x - ix as f32;1102 0,
1008 let fy = spec.abs_y - iy as f32;1103 0,
1104 Arc::new(CachedGlyphCoverage {
1105 fill: None,
1106 stroke: None,
1107 bytes: 0,
1108 }),
1109 );
1110 };
10091111
1010 let total_lean = spec.font.lean + spec.shear;1112 let total_lean = spec.font.lean + spec.shear;
1011 let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean };1113 let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean };
...@@ -1245,8 +1347,8 @@ pub fn rasterize_text_plus_rich(...@@ -1245,8 +1347,8 @@ pub fn rasterize_text_plus_rich(
1245 let top = c.top.saturating_add(oy);1347 let top = c.top.saturating_add(oy);
1246 min_x = min_x.min(left.saturating_sub(pad));1348 min_x = min_x.min(left.saturating_sub(pad));
1247 min_y = min_y.min(top.saturating_sub(pad));1349 min_y = min_y.min(top.saturating_sub(pad));
1248 max_x = max_x.max((left + c.width as i32).saturating_add(pad));1350 max_x = max_x.max(left.saturating_add(c.width as i32).saturating_add(pad));
1249 max_y = max_y.max((top + c.height as i32).saturating_add(pad));1351 max_y = max_y.max(top.saturating_add(c.height as i32).saturating_add(pad));
1250 };1352 };
12511353
1252 let mut placed = Vec::with_capacity(specs.len());1354 let mut placed = Vec::with_capacity(specs.len());
...@@ -2353,7 +2455,8 @@ mod tests {...@@ -2353,7 +2455,8 @@ mod tests {
2353 let tight_canvas = composite_onto_canvas(tsz, torig, &trgba);2455 let tight_canvas = composite_onto_canvas(tsz, torig, &trgba);
2354 let legacy_canvas = composite_onto_canvas(lsz, lorig, &lrgba);2456 let legacy_canvas = composite_onto_canvas(lsz, lorig, &lrgba);
2355 for (i, (&a, &b)) in tight_canvas.iter().zip(legacy_canvas.iter()).enumerate() {2457 for (i, (&a, &b)) in tight_canvas.iter().zip(legacy_canvas.iter()).enumerate() {
2356 assert!(a.abs_diff(b) <= 4, "legacy parity diff at byte {i}: {a} vs {b}");2458 // 1/16 px subpixel quantization in `cached_glyph_coverage` can shift x/y by <= 1/32 px each (~16 u8 levels).
2459 assert!(a.abs_diff(b) <= 16, "legacy parity diff at byte {i}: {a} vs {b}");
2357 }2460 }
2358 let (psz_plain, porig_plain, prgba_plain) = rasterize_text_plus_rich(dims, &p_rich, 80);2461 let (psz_plain, porig_plain, prgba_plain) = rasterize_text_plus_rich(dims, &p_rich, 80);
2359 assert_eq!(tight_canvas, composite_onto_canvas(psz_plain, porig_plain, &prgba_plain));2462 assert_eq!(tight_canvas, composite_onto_canvas(psz_plain, porig_plain, &prgba_plain));
...@@ -2515,4 +2618,140 @@ mod tests {...@@ -2515,4 +2618,140 @@ mod tests {
2515 }2618 }
2516 assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}");2619 assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}");
2517 }2620 }
2621
2622 #[test]
2623 fn glyph_cache_subpixel_quantization_and_lru_eviction() {
2624 assert_eq!(quantize_subpixel(10.99), Some((11, 0.0)));
2625 assert_eq!(quantize_subpixel(-0.01), Some((0, 0.0)));
2626 assert_eq!(quantize_subpixel(10.01), quantize_subpixel(10.02));
2627
2628 let font = Font::find("Helvetica", "Regular").expect("system font");
2629 let gid = font.face().glyph_index('A').expect("glyph A");
2630 let make_spec = |x: f32, y: f32| GlyphSpec {
2631 font: Arc::clone(&font),
2632 glyph_id: gid,
2633 font_px: 42.0,
2634 abs_x: x,
2635 abs_y: y,
2636 shear: 0.0,
2637 outline_w: 0.0,
2638 };
2639 let (ix1, iy1, cov1) = cached_glyph_coverage(&make_spec(100.01, 200.01), false);
2640 let (ix2, iy2, cov2) = cached_glyph_coverage(&make_spec(100.02, 200.02), false);
2641 assert_eq!((ix1, iy1), (100, 200));
2642 assert_eq!((ix2, iy2), (100, 200));
2643 assert!(Arc::ptr_eq(&cov1, &cov2), "jitter within 1/16 px must share cached coverage");
2644
2645 // Verify LRU eviction (touching key 0 keeps it alive when capacity is exceeded).
2646 let mut cache = GlyphCache::new();
2647 let make_key = |i: u16| GlyphCacheKey {
2648 font_id: 777,
2649 glyph_id: i,
2650 size_bits: 42.0_f32.to_bits(),
2651 lean_bits: 0,
2652 stroke_bits: 0,
2653 sub_x_bits: 0,
2654 sub_y_bits: 0,
2655 };
2656 let make_entry = || {
2657 Arc::new(CachedGlyphCoverage {
2658 fill: Some(Coverage {
2659 left: 0,
2660 top: 0,
2661 width: 4,
2662 height: 4,
2663 data: vec![255; 16],
2664 }),
2665 stroke: None,
2666 bytes: 16,
2667 })
2668 };
2669 for i in 0..MAX_GLYPH_CACHE_ENTRIES {
2670 cache.insert(make_key(i as u16), make_entry());
2671 }
2672 // Touch key 0 so key 1 becomes the least recently used entry.
2673 assert!(cache.get(&make_key(0)).is_some());
2674 cache.insert(make_key(MAX_GLYPH_CACHE_ENTRIES as u16), make_entry());
2675 assert!(cache.get(&make_key(0)).is_some(), "recently touched entry must survive LRU eviction");
2676 assert!(cache.get(&make_key(1)).is_none(), "least recently used entry must be evicted");
2677 }
2678
2679 #[test]
2680 fn register_font_bytes_generation_prevents_stale_cache_poisoning() {
2681 let base = Font::find("Helvetica", "Regular").expect("system fallback font");
2682 let gen0 = registry().read().unwrap().generation;
2683 register_font_bytes_with_name("FissionGenRaceFont", base.data.clone());
2684 let gen1 = registry().read().unwrap().generation;
2685 assert!(gen1 > gen0);
2686
2687 // Simulate a thread that finished resolve_lazy at gen0 before register_font_bytes_with_name ran.
2688 let _ = cache_resolved_font("FissionGenRaceFont", "Regular", None, gen0);
2689 {
2690 let cache = font_cache().lock().unwrap();
2691 assert_eq!(cache.0, gen1);
2692 assert!(
2693 !cache.1.contains_key(&("FissionGenRaceFont".to_owned(), "Regular".to_owned())),
2694 "stale pre-registration result must not poison font_cache"
2695 );
2696 }
2697 assert!(Font::find("FissionGenRaceFont", "Regular").is_some());
2698 }
2699
2700 #[test]
2701 fn extreme_off_canvas_coords_never_overflow_i32() {
2702 for bad in [
2703 f32::NAN,
2704 f32::INFINITY,
2705 f32::NEG_INFINITY,
2706 f32::MAX,
2707 f32::MIN,
2708 1e15,
2709 -1e15,
2710 (i32::MAX as f32) * 2.0,
2711 (i32::MIN as f32) * 2.0,
2712 ] {
2713 assert_eq!(quantize_subpixel(bad), None);
2714 }
2715
2716 let font = Font::find("Helvetica", "Regular").expect("system font");
2717 let gid = font.face().glyph_index('A').expect("glyph A");
2718 for (ax, ay) in [(1e20_f32, 0.0_f32), (0.0, -1e20), (f32::NAN, 10.0), (f32::INFINITY, f32::NEG_INFINITY)] {
2719 let spec = GlyphSpec {
2720 font: Arc::clone(&font),
2721 glyph_id: gid,
2722 font_px: 32.0,
2723 abs_x: ax,
2724 abs_y: ay,
2725 shear: 0.0,
2726 outline_w: 0.0,
2727 };
2728 let (ix, iy, cov) = cached_glyph_coverage(&spec, false);
2729 assert_eq!((ix, iy), (0, 0));
2730 assert!(cov.fill.is_none() && cov.stroke.is_none());
2731 }
2732
2733 let p = RichTextPlusParams {
2734 text: "Far",
2735 font_family: "Helvetica",
2736 font_style: "Regular",
2737 size_norm: 0.08,
2738 tracking: 1.0,
2739 line_spacing: 1.0,
2740 center: [1e12, -1e12],
2741 h_lcr: 0.0,
2742 v_tcb: 0.0,
2743 fill_rgba: [1.0; 4],
2744 write_on_start: 0.0,
2745 write_on_end: 1.0,
2746 shear_x: 0.0,
2747 cls: &[],
2748 outline_rgba: [0.0; 4],
2749 outline_thickness_norm: 0.0,
2750 outline_enabled: false,
2751 soft_fill: [0.0; 3],
2752 soft_outline: [0.0; 3],
2753 baseline_at_center: false,
2754 };
2755 assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0]));
2756 }
2518}2757}