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}
28
29impl GlyphCacheKey {
30 pub fn new(font_face_id: FontFaceId, glyph_id: u16, size_px: f32) -> Self {
31 Self {
32 font_face_id,
33 glyph_id,
34 size_bits: size_px.to_bits(),
35 weight: 400,
36 hinted: true,
37 italic: false,
38 }
39 }
40
41 pub fn with_weight(
42 font_face_id: FontFaceId,
43 glyph_id: u16,
44 size_px: f32,
45 weight: u32,
46 hinted: bool,
47 ) -> Self {
48 Self {
49 font_face_id,
50 glyph_id,
51 size_bits: size_px.to_bits(),
52 weight,
53 hinted,
54 italic: false,
55 }
56 }
57
58 /// [`with_weight`](Self::with_weight) for text that asks for italic when
59 /// `italic`.
60 pub fn with_style(
61 font_face_id: FontFaceId,
62 glyph_id: u16,
63 size_px: f32,
64 weight: u32,
65 hinted: bool,
66 italic: bool,
67 ) -> Self {
68 Self {
69 italic,
70 ..Self::with_weight(font_face_id, glyph_id, size_px, weight, hinted)
71 }
72 }
73}
74
75pub struct CachedGlyph {
76 pub alloc_id: AllocId,
77 pub atlas_x: u32,
78 pub atlas_y: u32,
79 pub width: u32,
80 pub height: u32,
81 pub placement_left: i32,
82 pub placement_top: i32,
83 pub is_color: bool,
84 /// Frame generation when this glyph was last used.
85 pub last_used: u64,
86}
87
88/// A glyph removed by [`GlyphCache::evict_unused`]: the allocator id to
89/// deallocate plus the atlas rectangle the glyph occupied. Consumers that
90/// retain glyph quads across frames (paint caches) key their invalidation
91/// off the eviction; the rect lets debug builds poison-fill freed pixels
92/// so stale-UV sampling is visually unmistakable.
93#[derive(Clone, Copy, Debug)]
94#[non_exhaustive]
95pub struct EvictedGlyph {
96 pub alloc_id: AllocId,
97 pub atlas_x: u32,
98 pub atlas_y: u32,
99 pub width: u32,
100 pub height: u32,
101}
102
103/// Glyph cache with LRU eviction.
104///
105/// Tracks a frame generation counter. Each `get` marks the glyph as used
106/// in the current generation. `evict_unused` removes glyphs not used
107/// for `max_idle_frames` generations and deallocates their atlas space.
108pub struct GlyphCache {
109 pub(crate) entries: HashMap<GlyphCacheKey, CachedGlyph>,
110 generation: u64,
111 last_eviction_generation: u64,
112}
113
114/// Number of frames a glyph can go unused before being evicted.
115const MAX_IDLE_FRAMES: u64 = 120; // ~2 seconds at 60fps
116
117impl Default for GlyphCache {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl GlyphCache {
124 pub fn new() -> Self {
125 Self {
126 entries: HashMap::new(),
127 generation: 0,
128 last_eviction_generation: 0,
129 }
130 }
131
132 /// Advance the frame generation counter. Call once per render frame.
133 pub fn advance_generation(&mut self) {
134 self.generation += 1;
135 }
136
137 pub fn generation(&self) -> u64 {
138 self.generation
139 }
140
141 /// Look up a cached glyph, marking it as used in the current generation.
142 pub fn get(&mut self, key: &GlyphCacheKey) -> Option<&CachedGlyph> {
143 if let Some(entry) = self.entries.get_mut(key) {
144 entry.last_used = self.generation;
145 Some(entry)
146 } else {
147 None
148 }
149 }
150
151 /// Look up without marking as used (for read-only queries).
152 pub fn peek(&self, key: &GlyphCacheKey) -> Option<&CachedGlyph> {
153 self.entries.get(key)
154 }
155
156 pub fn insert(&mut self, key: GlyphCacheKey, mut glyph: CachedGlyph) {
157 glyph.last_used = self.generation;
158 self.entries.insert(key, glyph);
159 }
160
161 /// Evict glyphs unused for MAX_IDLE_FRAMES generations.
162 /// Returns the evicted entries — each carries the `AllocId` to
163 /// deallocate from the atlas plus the atlas rectangle it occupied
164 /// (the bucketed allocator cannot resolve a rectangle from an
165 /// `AllocId` after the fact, so the rect is captured here, before
166 /// the entry is dropped; debug builds use it to poison-fill the
167 /// freed pixels).
168 /// Only runs the actual eviction scan every 60 calls (~1 second at 60fps)
169 /// to avoid iterating the entire cache on every render.
170 pub fn evict_unused(&mut self) -> Vec<EvictedGlyph> {
171 // Only scan every 60 generations (~1 second at 60fps)
172 if self.generation - self.last_eviction_generation < 60 {
173 return Vec::new();
174 }
175 self.last_eviction_generation = self.generation;
176
177 let threshold = self.generation.saturating_sub(MAX_IDLE_FRAMES);
178 let mut evicted = Vec::new();
179
180 self.entries.retain(|_key, glyph| {
181 if glyph.last_used < threshold {
182 evicted.push(EvictedGlyph {
183 alloc_id: glyph.alloc_id,
184 atlas_x: glyph.atlas_x,
185 atlas_y: glyph.atlas_y,
186 width: glyph.width,
187 height: glyph.height,
188 });
189 false
190 } else {
191 true
192 }
193 });
194
195 evicted
196 }
197
198 /// Emergency eviction when the atlas is full: drop every glyph not
199 /// used in the *current* generation, regardless of the idle window.
200 ///
201 /// Unlike [`evict_unused`](Self::evict_unused) this runs
202 /// unconditionally (no every-60-generations gate) — it is only
203 /// called when an allocation has already failed at the atlas size
204 /// cap, where the alternative is silently dropping the new glyph.
205 /// Glyphs touched this generation are still referenced by quads in
206 /// the frame being built and must survive.
207 pub fn evict_for_pressure(&mut self) -> Vec<EvictedGlyph> {
208 let current = self.generation;
209 let mut evicted = Vec::new();
210
211 self.entries.retain(|_key, glyph| {
212 if glyph.last_used < current {
213 evicted.push(EvictedGlyph {
214 alloc_id: glyph.alloc_id,
215 atlas_x: glyph.atlas_x,
216 atlas_y: glyph.atlas_y,
217 width: glyph.width,
218 height: glyph.height,
219 });
220 false
221 } else {
222 true
223 }
224 });
225
226 evicted
227 }
228
229 pub fn len(&self) -> usize {
230 self.entries.len()
231 }
232
233 pub fn is_empty(&self) -> bool {
234 self.entries.is_empty()
235 }
236
237 /// Mark multiple glyphs as used in the current generation without
238 /// returning their data. Used by callers that cache glyph output
239 /// externally (e.g. per-widget paint caches) and need to keep the
240 /// glyphs alive in the atlas even though they don't re-measure them
241 /// every frame.
242 pub fn touch(&mut self, keys: &[GlyphCacheKey]) {
243 let current = self.generation;
244 for key in keys {
245 if let Some(entry) = self.entries.get_mut(key) {
246 entry.last_used = current;
247 }
248 }
249 }
250}