text_typeset/atlas/cache.rs
1use std::collections::HashMap;
2
3use etagere::AllocId;
4
5use crate::types::FontFaceId;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
8#[non_exhaustive]
9pub struct GlyphCacheKey {
10 pub font_face_id: FontFaceId,
11 pub glyph_id: u16,
12 pub size_bits: u32,
13 /// Font weight (variation axis) so that e.g. Inter Regular and Inter
14 /// Bold produce separate cache entries even though they share the
15 /// same `font_face_id` and `glyph_id` in a variable font.
16 pub weight: u32,
17 /// Whether the bitmap was rasterized with hinting. Rasters produced
18 /// under a raster scale (zoomed content) are unhinted, and the same
19 /// *physical* size can be reached both ways — 7px at raster_scale 2
20 /// and 14px at raster_scale 1 share `size_bits` but must not share
21 /// a bitmap.
22 pub hinted: bool,
23 /// Whether the text asks for italic: an upright face is rasterized
24 /// slanted for it (see `crate::font::synthesis`), and the slanted bitmap
25 /// must not stand in for the upright one.
26 pub italic: bool,
27 /// Which of the [`SUBPIXEL_BINS`](crate::atlas::rasterizer::SUBPIXEL_BINS)
28 /// horizontal offsets the bitmap was rasterized at: the glyph's pen
29 /// position fell that many quarters of a pixel past a pixel edge (see
30 /// [`split_subpixel_x`](crate::atlas::rasterizer::split_subpixel_x)).
31 /// `0` for a glyph drawn at a whole pixel, which is every glyph of a
32 /// scaled (unhinted) raster.
33 pub subpixel_x: u8,
34 /// Whether the bitmap is fitted to the pixel grid on both axes
35 /// ([`GlyphRendering::Crisp`](crate::GlyphRendering::Crisp)): it must not
36 /// stand in for the vertically-hinted one, nor the other way round.
37 pub crisp: bool,
38}
39
40impl GlyphCacheKey {
41 pub fn new(font_face_id: FontFaceId, glyph_id: u16, size_px: f32) -> Self {
42 Self {
43 font_face_id,
44 glyph_id,
45 size_bits: size_px.to_bits(),
46 weight: 400,
47 hinted: true,
48 italic: false,
49 subpixel_x: 0,
50 crisp: false,
51 }
52 }
53
54 pub fn with_weight(
55 font_face_id: FontFaceId,
56 glyph_id: u16,
57 size_px: f32,
58 weight: u32,
59 hinted: bool,
60 ) -> Self {
61 Self {
62 font_face_id,
63 glyph_id,
64 size_bits: size_px.to_bits(),
65 weight,
66 hinted,
67 italic: false,
68 subpixel_x: 0,
69 crisp: false,
70 }
71 }
72
73 /// [`with_weight`](Self::with_weight) for text that asks for italic when
74 /// `italic`.
75 pub fn with_style(
76 font_face_id: FontFaceId,
77 glyph_id: u16,
78 size_px: f32,
79 weight: u32,
80 hinted: bool,
81 italic: bool,
82 ) -> Self {
83 Self {
84 italic,
85 ..Self::with_weight(font_face_id, glyph_id, size_px, weight, hinted)
86 }
87 }
88
89 /// This key for the bitmap rasterized `bin` quarters of a pixel to the
90 /// right (see [`split_subpixel_x`](crate::atlas::rasterizer::split_subpixel_x)).
91 /// This key for the crisp bitmap of the glyph (see
92 /// [`GlyphRendering::Crisp`](crate::GlyphRendering::Crisp)).
93 pub fn crisp(self) -> Self {
94 Self {
95 crisp: true,
96 subpixel_x: 0,
97 ..self
98 }
99 }
100
101 pub fn at_subpixel_x(self, bin: u8) -> Self {
102 Self {
103 subpixel_x: bin,
104 ..self
105 }
106 }
107}
108
109pub struct CachedGlyph {
110 pub alloc_id: AllocId,
111 pub atlas_x: u32,
112 pub atlas_y: u32,
113 pub width: u32,
114 pub height: u32,
115 pub placement_left: i32,
116 pub placement_top: i32,
117 pub is_color: bool,
118 /// Frame generation when this glyph was last used.
119 pub last_used: u64,
120}
121
122/// A glyph removed by [`GlyphCache::evict_unused`]: the allocator id to
123/// deallocate plus the atlas rectangle the glyph occupied. Consumers that
124/// retain glyph quads across frames (paint caches) key their invalidation
125/// off the eviction; the rect lets debug builds poison-fill freed pixels
126/// so stale-UV sampling is visually unmistakable.
127#[derive(Clone, Copy, Debug)]
128#[non_exhaustive]
129pub struct EvictedGlyph {
130 pub alloc_id: AllocId,
131 pub atlas_x: u32,
132 pub atlas_y: u32,
133 pub width: u32,
134 pub height: u32,
135}
136
137/// Glyph cache with LRU eviction.
138///
139/// Tracks a frame generation counter. Each `get` marks the glyph as used
140/// in the current generation. `evict_unused` removes glyphs not used
141/// for `max_idle_frames` generations and deallocates their atlas space.
142pub struct GlyphCache {
143 pub(crate) entries: HashMap<GlyphCacheKey, CachedGlyph>,
144 generation: u64,
145 last_eviction_generation: u64,
146}
147
148/// Number of frames a glyph can go unused before being evicted.
149const MAX_IDLE_FRAMES: u64 = 120; // ~2 seconds at 60fps
150
151impl Default for GlyphCache {
152 fn default() -> Self {
153 Self::new()
154 }
155}
156
157impl GlyphCache {
158 pub fn new() -> Self {
159 Self {
160 entries: HashMap::new(),
161 generation: 0,
162 last_eviction_generation: 0,
163 }
164 }
165
166 /// Advance the frame generation counter. Call once per render frame.
167 pub fn advance_generation(&mut self) {
168 self.generation += 1;
169 }
170
171 pub fn generation(&self) -> u64 {
172 self.generation
173 }
174
175 /// Look up a cached glyph, marking it as used in the current generation.
176 pub fn get(&mut self, key: &GlyphCacheKey) -> Option<&CachedGlyph> {
177 if let Some(entry) = self.entries.get_mut(key) {
178 entry.last_used = self.generation;
179 Some(entry)
180 } else {
181 None
182 }
183 }
184
185 /// Look up without marking as used (for read-only queries).
186 pub fn peek(&self, key: &GlyphCacheKey) -> Option<&CachedGlyph> {
187 self.entries.get(key)
188 }
189
190 pub fn insert(&mut self, key: GlyphCacheKey, mut glyph: CachedGlyph) {
191 glyph.last_used = self.generation;
192 self.entries.insert(key, glyph);
193 }
194
195 /// Evict glyphs unused for MAX_IDLE_FRAMES generations.
196 /// Returns the evicted entries — each carries the `AllocId` to
197 /// deallocate from the atlas plus the atlas rectangle it occupied
198 /// (the bucketed allocator cannot resolve a rectangle from an
199 /// `AllocId` after the fact, so the rect is captured here, before
200 /// the entry is dropped; debug builds use it to poison-fill the
201 /// freed pixels).
202 /// Only runs the actual eviction scan every 60 calls (~1 second at 60fps)
203 /// to avoid iterating the entire cache on every render.
204 pub fn evict_unused(&mut self) -> Vec<EvictedGlyph> {
205 // Only scan every 60 generations (~1 second at 60fps)
206 if self.generation - self.last_eviction_generation < 60 {
207 return Vec::new();
208 }
209 self.last_eviction_generation = self.generation;
210
211 let threshold = self.generation.saturating_sub(MAX_IDLE_FRAMES);
212 let mut evicted = Vec::new();
213
214 self.entries.retain(|_key, glyph| {
215 if glyph.last_used < threshold {
216 evicted.push(EvictedGlyph {
217 alloc_id: glyph.alloc_id,
218 atlas_x: glyph.atlas_x,
219 atlas_y: glyph.atlas_y,
220 width: glyph.width,
221 height: glyph.height,
222 });
223 false
224 } else {
225 true
226 }
227 });
228
229 evicted
230 }
231
232 /// Emergency eviction when the atlas is full: drop every glyph not
233 /// used in the *current* generation, regardless of the idle window.
234 ///
235 /// Unlike [`evict_unused`](Self::evict_unused) this runs
236 /// unconditionally (no every-60-generations gate) — it is only
237 /// called when an allocation has already failed at the atlas size
238 /// cap, where the alternative is silently dropping the new glyph.
239 /// Glyphs touched this generation are still referenced by quads in
240 /// the frame being built and must survive.
241 pub fn evict_for_pressure(&mut self) -> Vec<EvictedGlyph> {
242 let current = self.generation;
243 let mut evicted = Vec::new();
244
245 self.entries.retain(|_key, glyph| {
246 if glyph.last_used < current {
247 evicted.push(EvictedGlyph {
248 alloc_id: glyph.alloc_id,
249 atlas_x: glyph.atlas_x,
250 atlas_y: glyph.atlas_y,
251 width: glyph.width,
252 height: glyph.height,
253 });
254 false
255 } else {
256 true
257 }
258 });
259
260 evicted
261 }
262
263 pub fn len(&self) -> usize {
264 self.entries.len()
265 }
266
267 pub fn is_empty(&self) -> bool {
268 self.entries.is_empty()
269 }
270
271 /// Mark multiple glyphs as used in the current generation without
272 /// returning their data. Used by callers that cache glyph output
273 /// externally (e.g. per-widget paint caches) and need to keep the
274 /// glyphs alive in the atlas even though they don't re-measure them
275 /// every frame.
276 pub fn touch(&mut self, keys: &[GlyphCacheKey]) {
277 let current = self.generation;
278 for key in keys {
279 if let Some(entry) = self.entries.get_mut(key) {
280 entry.last_used = current;
281 }
282 }
283 }
284}