Skip to main content

euv_core/font/atlas/
impl.rs

1use super::*;
2
3/// Caching lookup, bounded LRU eviction, and telemetry operations for `GlyphAtlas`.
4impl GlyphAtlas {
5    /// Losslessly packs all fields of `GlyphKey` into the low 40 bits of a `u64`.
6    ///
7    /// # Arguments
8    ///
9    /// - `GlyphKey` - Quantized glyph lookup key.
10    ///
11    /// # Returns
12    ///
13    /// - `u64` - Bijective 40-bit key representation (`0..2^40`).
14    #[inline(always)]
15    #[must_use]
16    pub(crate) fn pack_glyph_key(key: GlyphKey) -> u64 {
17        key.pack_u64()
18    }
19
20    /// Computes a fast single-multiply avalanche hash for a packed 40-bit `GlyphKey`.
21    ///
22    /// # Arguments
23    ///
24    /// - `u64` - Lossless 40-bit packed glyph key.
25    ///
26    /// # Returns
27    ///
28    /// - `usize` - Mixed hash value suitable for power-of-two bitmasking.
29    #[inline(always)]
30    #[must_use]
31    fn hash_packed_key(packed: u64) -> usize {
32        let mixed: u64 = packed.wrapping_mul(GLYPH_INDEX_HASH_MULT);
33        (mixed ^ (mixed >> 32)) as usize
34    }
35
36    /// Estimates the resident memory footprint in bytes of one rasterized glyph entry.
37    ///
38    /// # Arguments
39    ///
40    /// - `&RasterizedGlyph` - Cached coverage bitmap entry.
41    ///
42    /// # Returns
43    ///
44    /// - `usize` - Tracked byte size including coverage bytes and metadata overhead.
45    #[inline(always)]
46    #[must_use]
47    fn entry_bytes(glyph: &RasterizedGlyph) -> usize {
48        glyph
49            .get_coverage()
50            .len()
51            .saturating_add(GLYPH_ENTRY_OVERHEAD_BYTES)
52    }
53
54    /// Resolves the active resident memory budget in bytes (`GLYPH_ATLAS_DEFAULT_BUDGET_BYTES` when unset).
55    ///
56    /// # Arguments
57    ///
58    /// - `&Self` - Glyph atlas reference.
59    ///
60    /// # Returns
61    ///
62    /// - `usize` - Effective byte budget threshold.
63    #[inline(always)]
64    #[must_use]
65    pub fn effective_budget_bytes(&self) -> usize {
66        let raw: usize = self.get_budget_bytes();
67        if raw == 0 {
68            GLYPH_ATLAS_DEFAULT_BUDGET_BYTES
69        } else {
70            raw
71        }
72    }
73
74    /// Configures a bounded resident memory budget in bytes and immediately evicts cold glyphs if currently over budget.
75    ///
76    /// # Arguments
77    ///
78    /// - `&Self` - Mutable glyph atlas reference.
79    /// - `usize` - Maximum resident byte budget (clamped to `>= 1024`).
80    pub fn set_memory_budget(&mut self, max_bytes: usize) {
81        let clamped: usize = max_bytes.max(GLYPH_ATLAS_MIN_BUDGET_BYTES);
82        self.set_budget_bytes(clamped);
83        self.evict_if_over_budget();
84    }
85
86    /// Returns the cumulative cache hit ratio in `[0.0, 1.0]` (`1.0` before any lookup).
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Glyph atlas reference.
91    ///
92    /// # Returns
93    ///
94    /// - `f32` - Cache hit rate fraction.
95    #[must_use]
96    pub fn hit_rate(&self) -> f32 {
97        let hits: u64 = self.get_cache_hits();
98        let total: u64 = hits.saturating_add(self.get_cache_misses());
99        if total == 0 {
100            1.0
101        } else {
102            (hits as f32) / (total as f32)
103        }
104    }
105
106    /// Evicts least-recently-used glyphs when `resident_bytes` exceeds the active budget and slots are unpinned.
107    ///
108    /// # Arguments
109    ///
110    /// - `&Self` - Mutable glyph atlas reference.
111    pub fn evict_if_over_budget(&mut self) {
112        let budget: usize = self.effective_budget_bytes();
113        let Self {
114            resident_bytes,
115            slots_pinned,
116            entries,
117            ..
118        } = self;
119        if *slots_pinned || *resident_bytes <= budget || entries.len() <= 1 {
120            return;
121        }
122        let target: usize = (budget.saturating_mul(3) / 4).max(GLYPH_ENTRY_OVERHEAD_BYTES);
123        self.evict_lru_to_target(target);
124    }
125
126    /// Tags subsequent glyph accesses and insertions with GPU submission `fence_id` for fence-deferred reclamation.
127    ///
128    /// # Arguments
129    ///
130    /// - `&Self` - Mutable glyph atlas reference.
131    /// - `u64` - Active frame GPU fence identifier.
132    pub fn begin_frame_fence(&mut self, fence_id: u64) {
133        let Self {
134            active_fence_id, ..
135        } = self;
136        *active_fence_id = (*active_fence_id).max(fence_id);
137    }
138
139    /// Marks GPU submission `fence_id` complete and reclaims all evicted glyph allocations whose fence completed.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Mutable glyph atlas reference.
144    /// - `u64` - Completed monotonic GPU fence identifier.
145    ///
146    /// # Returns
147    ///
148    /// - `usize` - Number of deferred glyph allocations reclaimed.
149    pub fn complete_fence(&mut self, fence_id: u64) -> usize {
150        let Self {
151            completed_fence_id,
152            pending_reclaim,
153            pending_reclaim_bytes,
154            reclaimed_entries,
155            ..
156        } = self;
157        if fence_id > *completed_fence_id {
158            *completed_fence_id = fence_id;
159        }
160        let completed: u64 = *completed_fence_id;
161        let before: usize = pending_reclaim.len();
162        let mut released_bytes: usize = 0;
163        pending_reclaim.retain(|&(retire_fence, bytes): &(u64, usize)| {
164            if retire_fence <= completed {
165                released_bytes = released_bytes.saturating_add(bytes);
166                false
167            } else {
168                true
169            }
170        });
171        let reclaimed: usize = before.saturating_sub(pending_reclaim.len());
172        *pending_reclaim_bytes = pending_reclaim_bytes.saturating_sub(released_bytes);
173        *reclaimed_entries = reclaimed_entries.saturating_add(reclaimed as u64);
174        reclaimed
175    }
176
177    /// Invalidates bitmap atlas entries independently of text shaping whenever DPI scale, AA mode, or font chain changes.
178    ///
179    /// # Arguments
180    ///
181    /// - `&Self` - Mutable glyph atlas reference.
182    /// - `f32` - Active display scale factor.
183    /// - `AntialiasingMode` - Active anti-aliasing policy.
184    /// - `u64` - Active font fallback chain revision.
185    ///
186    /// # Returns
187    ///
188    /// - `bool` - `true` when atlas bitmaps were invalidated and queued for fence-deferred release.
189    pub fn invalidate_for_render_params(
190        &mut self,
191        dpi_scale: f32,
192        aa: AntialiasingMode,
193        font_chain_revision: u64,
194    ) -> bool {
195        let next_dpi_bits: u32 = dpi_scale.max(0.5).to_bits();
196        let Self {
197            active_dpi_scale_bits,
198            active_aa_mode,
199            font_chain_revision: cur_font_rev,
200            ..
201        } = self;
202        if *active_dpi_scale_bits == 0 {
203            *active_dpi_scale_bits = next_dpi_bits;
204            *active_aa_mode = aa;
205            *cur_font_rev = font_chain_revision;
206            return false;
207        }
208        let unchanged: bool = *active_dpi_scale_bits == next_dpi_bits
209            && *active_aa_mode == aa
210            && *cur_font_rev == font_chain_revision;
211        if unchanged {
212            return false;
213        }
214        *active_dpi_scale_bits = next_dpi_bits;
215        *active_aa_mode = aa;
216        *cur_font_rev = font_chain_revision;
217        self.clear_with_fence_deferral();
218        true
219    }
220
221    /// Clears all resident bitmap entries, moving in-flight GPU-referenced entries to `pending_reclaim`.
222    ///
223    /// # Arguments
224    ///
225    /// - `&Self` - Mutable glyph atlas reference.
226    fn clear_with_fence_deferral(&mut self) {
227        let Self {
228            glyph_index,
229            entries,
230            entry_last_used,
231            entry_fence_ids,
232            ascii_tables,
233            revision,
234            resident_bytes,
235            completed_fence_id,
236            pending_reclaim,
237            pending_reclaim_bytes,
238            reclaimed_entries,
239            ..
240        } = self;
241        let completed: u64 = *completed_fence_id;
242        for (idx, (_, glyph)) in entries.iter().enumerate() {
243            let bytes: usize = Self::entry_bytes(glyph);
244            let fence: u64 = entry_fence_ids.get(idx).copied().unwrap_or(0);
245            if fence > completed {
246                pending_reclaim.push((fence, bytes));
247                *pending_reclaim_bytes = pending_reclaim_bytes.saturating_add(bytes);
248            } else {
249                *reclaimed_entries = reclaimed_entries.saturating_add(1);
250            }
251        }
252        glyph_index.fill(GLYPH_INDEX_EMPTY);
253        entries.clear();
254        entry_last_used.clear();
255        entry_fence_ids.clear();
256        ascii_tables.clear();
257        *resident_bytes = 0;
258        *revision = revision.wrapping_add(1);
259    }
260
261    /// Compacts the glyph arena by evicting the coldest LRU entries until `resident_bytes <= target_bytes`, deferring reclamation of GPU in-flight bitmaps until fence completion.
262    ///
263    /// # Arguments
264    ///
265    /// - `&Self` - Mutable glyph atlas reference.
266    /// - `usize` - Target post-eviction resident byte ceiling.
267    fn evict_lru_to_target(&mut self, target_bytes: usize) {
268        let Self {
269            glyph_index,
270            entries,
271            entry_last_used,
272            entry_fence_ids,
273            ascii_tables,
274            revision,
275            resident_bytes,
276            evictions,
277            completed_fence_id,
278            pending_reclaim,
279            pending_reclaim_bytes,
280            reclaimed_entries,
281            ..
282        } = self;
283        let count: usize = entries.len();
284        if count == 0 || *resident_bytes <= target_bytes {
285            return;
286        }
287        let mut order: Vec<usize> = (0..count).collect();
288        order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
289        let mut keep: Vec<bool> = vec![true; count];
290        let mut remaining_bytes: usize = *resident_bytes;
291        let mut evicted_count: usize = 0;
292        let completed: u64 = *completed_fence_id;
293        for idx in order.into_iter() {
294            if remaining_bytes <= target_bytes {
295                break;
296            }
297            let bytes: usize = Self::entry_bytes(&entries[idx].1);
298            let fence: u64 = entry_fence_ids.get(idx).copied().unwrap_or(0);
299            if fence > completed {
300                pending_reclaim.push((fence, bytes));
301                *pending_reclaim_bytes = pending_reclaim_bytes.saturating_add(bytes);
302            } else {
303                *reclaimed_entries = reclaimed_entries.saturating_add(1);
304            }
305            remaining_bytes = remaining_bytes.saturating_sub(bytes);
306            keep[idx] = false;
307            evicted_count += 1;
308        }
309        if evicted_count == 0 {
310            return;
311        }
312        let mut write_idx: usize = 0;
313        let mut next_resident: usize = 0;
314        for (read_idx, &kept) in keep.iter().enumerate() {
315            if kept {
316                if write_idx != read_idx {
317                    entries.swap(write_idx, read_idx);
318                    if read_idx < entry_last_used.len() && write_idx < entry_last_used.len() {
319                        entry_last_used.swap(write_idx, read_idx);
320                    }
321                    if read_idx < entry_fence_ids.len() && write_idx < entry_fence_ids.len() {
322                        entry_fence_ids.swap(write_idx, read_idx);
323                    }
324                }
325                next_resident =
326                    next_resident.saturating_add(Self::entry_bytes(&entries[write_idx].1));
327                write_idx += 1;
328            }
329        }
330        entries.truncate(write_idx);
331        entry_last_used.truncate(write_idx);
332        entry_fence_ids.truncate(write_idx);
333        *resident_bytes = next_resident;
334        *evictions = evictions.saturating_add(evicted_count as u64);
335        glyph_index.fill(GLYPH_INDEX_EMPTY);
336        for (slot_idx, (key, _)) in entries.iter().enumerate() {
337            let packed_key: u64 = Self::pack_glyph_key(*key);
338            Self::insert_index(glyph_index, slot_idx + 1, packed_key, slot_idx as u32);
339        }
340        for table in ascii_tables.iter_mut() {
341            table.slots.fill(u32::MAX);
342        }
343        *revision = revision.wrapping_add(1);
344    }
345
346    /// Probes the open-addressed `glyph_index` slice for `packed_key`.
347    ///
348    /// # Arguments
349    ///
350    /// - `&[u64]` - Power-of-two open-addressed index table.
351    /// - `u64` - Lossless 40-bit packed glyph key.
352    ///
353    /// # Returns
354    ///
355    /// - `Option<u32>` - Cached arena slot index when present.
356    #[inline(always)]
357    #[must_use]
358    fn lookup_index(glyph_index: &[u64], packed_key: u64) -> Option<u32> {
359        let cap: usize = glyph_index.len();
360        if cap == 0 {
361            return None;
362        }
363        let mask: usize = cap - 1;
364        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
365        loop {
366            let entry: u64 = glyph_index[idx];
367            if entry == GLYPH_INDEX_EMPTY {
368                return None;
369            }
370            if (entry & GLYPH_INDEX_KEY_MASK) == packed_key {
371                return Some((entry >> GLYPH_INDEX_SLOT_SHIFT) as u32);
372            }
373            idx = (idx + 1) & mask;
374        }
375    }
376
377    /// Inserts `(packed_key, slot)` into the open-addressed `glyph_index` table, doubling capacity at 75% load.
378    ///
379    /// # Arguments
380    ///
381    /// - `&mut Vec<u64>` - Open-addressed index table storage.
382    /// - `usize` - Current total entry count including the newly inserted glyph.
383    /// - `u64` - Lossless 40-bit packed glyph key.
384    /// - `u32` - Arena slot index into `entries`.
385    fn insert_index(glyph_index: &mut Vec<u64>, entry_count: usize, packed_key: u64, slot: u32) {
386        let cap: usize = glyph_index.len();
387        if cap == 0 {
388            glyph_index.resize(GLYPH_INDEX_INIT_CAP, GLYPH_INDEX_EMPTY);
389        } else if entry_count * 4 > cap * 3 {
390            let new_cap: usize = cap * 2;
391            let new_mask: usize = new_cap - 1;
392            let mut grown: Vec<u64> = vec![GLYPH_INDEX_EMPTY; new_cap];
393            for old_entry in glyph_index.iter().copied() {
394                if old_entry == GLYPH_INDEX_EMPTY {
395                    continue;
396                }
397                let old_key: u64 = old_entry & GLYPH_INDEX_KEY_MASK;
398                let mut idx: usize = Self::hash_packed_key(old_key) & new_mask;
399                while grown[idx] != GLYPH_INDEX_EMPTY {
400                    idx = (idx + 1) & new_mask;
401                }
402                grown[idx] = old_entry;
403            }
404            *glyph_index = grown;
405        }
406        let mask: usize = glyph_index.len() - 1;
407        let packed_entry: u64 = packed_key | ((slot as u64) << GLYPH_INDEX_SLOT_SHIFT);
408        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
409        loop {
410            let existing: u64 = glyph_index[idx];
411            if existing == GLYPH_INDEX_EMPTY || (existing & GLYPH_INDEX_KEY_MASK) == packed_key {
412                glyph_index[idx] = packed_entry;
413                return;
414            }
415            idx = (idx + 1) & mask;
416        }
417    }
418
419    /// Packs quantized glyph style attributes into a compact 32-bit signature for ASCII table matching.
420    ///
421    /// # Arguments
422    ///
423    /// - `u16` - Quantized physical font size in tenths of a pixel.
424    /// - `bool` - Bold flag.
425    /// - `bool` - Monospace family flag.
426    /// - `bool` - Italic flag.
427    ///
428    /// # Returns
429    ///
430    /// - `u32` - Packed style signature.
431    #[inline(always)]
432    #[must_use]
433    pub(crate) fn pack_style_sig(
434        size_tenths: u16,
435        bold: bool,
436        monospace: bool,
437        italic: bool,
438    ) -> u32 {
439        (size_tenths as u32)
440            | (u32::from(bold) << 16)
441            | (u32::from(monospace) << 17)
442            | (u32::from(italic) << 18)
443    }
444
445    /// Returns the index of the `[u32; 128]` ASCII slot table matching `(size_tenths, bold, monospace, italic)`, creating it if absent.
446    ///
447    /// # Arguments
448    ///
449    /// - `&Self` - Mutable glyph atlas reference.
450    /// - `u16` - Quantized physical font size in tenths of a pixel.
451    /// - `bool` - Bold flag.
452    /// - `bool` - Monospace family flag.
453    /// - `bool` - Italic flag.
454    ///
455    /// # Returns
456    ///
457    /// - `usize` - Index inside `ascii_tables` for zero-hash ASCII glyph resolution.
458    pub(crate) fn ascii_table_index(
459        &mut self,
460        size_tenths: u16,
461        bold: bool,
462        monospace: bool,
463        italic: bool,
464    ) -> usize {
465        let style_sig: u32 = Self::pack_style_sig(size_tenths, bold, monospace, italic);
466        let Self { ascii_tables, .. } = self;
467        for (idx, table) in ascii_tables.iter().enumerate() {
468            if table.style_sig == style_sig {
469                return idx;
470            }
471        }
472        let idx: usize = ascii_tables.len();
473        ascii_tables.push(AsciiGlyphStyleTable {
474            style_sig,
475            slots: [u32::MAX; 128],
476        });
477        idx
478    }
479
480    /// Resolves an ASCII byte directly through `ascii_tables[table_idx]` with zero hash probing on hits.
481    ///
482    /// # Arguments
483    ///
484    /// - `&Self` - Mutable glyph atlas reference.
485    /// - `usize` - Style table index returned by `ascii_table_index`.
486    /// - `u8` - ASCII codepoint byte in `0..128`.
487    /// - `(u16, bool, bool, bool)` - Quantized style metadata `(size_tenths, bold, monospace, italic)`.
488    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
489    ///
490    /// # Returns
491    ///
492    /// - `u32` - Direct slot index into `entries`.
493    #[inline(always)]
494    pub(crate) fn get_or_rasterize_ascii_slot_with(
495        &mut self,
496        table_idx: usize,
497        byte: u8,
498        key_meta: (u16, bool, bool, bool),
499        provider: &dyn SystemFontProvider,
500    ) -> u32 {
501        let Self {
502            ascii_tables,
503            entry_last_used,
504            entry_fence_ids,
505            active_fence_id,
506            lru_clock,
507            cache_hits,
508            ..
509        } = self;
510        let cached: u32 = ascii_tables[table_idx].slots[byte as usize];
511        if cached != u32::MAX {
512            *cache_hits = cache_hits.wrapping_add(1);
513            *lru_clock = lru_clock.wrapping_add(1);
514            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
515                *tick = *lru_clock;
516            }
517            if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
518                *fence = (*fence).max(*active_fence_id);
519            }
520            return cached;
521        }
522        let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
523        let key: GlyphKey = GlyphKey {
524            codepoint: byte as char,
525            size_tenths,
526            bold,
527            monospace,
528            italic,
529        };
530        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
531        let Self { ascii_tables, .. } = self;
532        ascii_tables[table_idx].slots[byte as usize] = slot;
533        slot
534    }
535
536    /// Inserts a newly rasterized glyph into the arena, enforcing the bounded memory budget when unpinned.
537    ///
538    /// # Arguments
539    ///
540    /// - `&Self` - Mutable glyph atlas reference.
541    /// - `GlyphKey` - Quantized glyph lookup key.
542    /// - `u64` - Pre-packed 40-bit glyph key.
543    /// - `u32` - Pre-packed style signature for ASCII table updates.
544    /// - `RasterizedGlyph` - Newly rasterized coverage bitmap.
545    /// - `bool` - Whether a missing ASCII style table should be created automatically.
546    ///
547    /// # Returns
548    ///
549    /// - `u32` - Newly assigned arena slot index.
550    fn insert_rasterized_glyph(
551        &mut self,
552        key: GlyphKey,
553        packed_key: u64,
554        style_sig: u32,
555        glyph: RasterizedGlyph,
556        create_ascii_table: bool,
557    ) -> u32 {
558        let entry_sz: usize = Self::entry_bytes(&glyph);
559        let budget: usize = self.effective_budget_bytes();
560        let needs_evict: bool = {
561            let Self {
562                resident_bytes,
563                slots_pinned,
564                entries,
565                ..
566            } = self;
567            !*slots_pinned
568                && !entries.is_empty()
569                && resident_bytes.saturating_add(entry_sz) > budget
570        };
571        if needs_evict {
572            let target: usize = budget
573                .saturating_mul(3)
574                .saturating_div(4)
575                .saturating_sub(entry_sz);
576            self.evict_lru_to_target(target);
577        }
578        let code: u32 = key.get_codepoint() as u32;
579        let Self {
580            glyph_index,
581            entries,
582            entry_last_used,
583            entry_fence_ids,
584            active_fence_id,
585            ascii_tables,
586            revision,
587            resident_bytes,
588            lru_clock,
589            cache_misses,
590            ..
591        } = self;
592        if entries.is_empty() {
593            entries.reserve(GLYPH_ENTRIES_INIT_CAP);
594            entry_last_used.reserve(GLYPH_ENTRIES_INIT_CAP);
595            entry_fence_ids.reserve(GLYPH_ENTRIES_INIT_CAP);
596        }
597        *cache_misses = cache_misses.wrapping_add(1);
598        *lru_clock = lru_clock.wrapping_add(1);
599        let slot: u32 = entries.len() as u32;
600        entries.push((key, glyph));
601        entry_last_used.push(*lru_clock);
602        entry_fence_ids.push(*active_fence_id);
603        *resident_bytes = resident_bytes.saturating_add(entry_sz);
604        Self::insert_index(glyph_index, entries.len(), packed_key, slot);
605        if code < 128 {
606            let mut updated: bool = false;
607            for table in ascii_tables.iter_mut() {
608                if table.style_sig == style_sig {
609                    table.slots[code as usize] = slot;
610                    updated = true;
611                    break;
612                }
613            }
614            if create_ascii_table && !updated {
615                let mut slots: [u32; 128] = [u32::MAX; 128];
616                slots[code as usize] = slot;
617                ascii_tables.push(AsciiGlyphStyleTable { style_sig, slots });
618            }
619        }
620        *revision = revision.wrapping_add(1);
621        slot
622    }
623
624    /// Returns the arena slot index for `key`, rasterizing through `rasterize_glyph` on a miss.
625    ///
626    /// # Arguments
627    ///
628    /// - `&Self` - Mutable glyph atlas reference.
629    /// - `GlyphKey` - Quantized glyph lookup key.
630    ///
631    /// # Returns
632    ///
633    /// - `u32` - Direct slot index into `entries`.
634    #[inline]
635    pub(crate) fn get_or_rasterize_slot(&mut self, key: GlyphKey) -> u32 {
636        let code: u32 = key.get_codepoint() as u32;
637        let style_sig: u32 = Self::pack_style_sig(
638            key.get_size_tenths(),
639            key.get_bold(),
640            key.get_monospace(),
641            key.get_italic(),
642        );
643        let packed_key: u64 = Self::pack_glyph_key(key);
644        {
645            let Self {
646                glyph_index,
647                entry_last_used,
648                entry_fence_ids,
649                active_fence_id,
650                ascii_tables,
651                lru_clock,
652                cache_hits,
653                ..
654            } = self;
655            if code < 128 {
656                for table in ascii_tables.iter() {
657                    if table.style_sig == style_sig {
658                        let cached: u32 = table.slots[code as usize];
659                        if cached != u32::MAX {
660                            *cache_hits = cache_hits.wrapping_add(1);
661                            *lru_clock = lru_clock.wrapping_add(1);
662                            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
663                                *tick = *lru_clock;
664                            }
665                            if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
666                                *fence = (*fence).max(*active_fence_id);
667                            }
668                            return cached;
669                        }
670                        break;
671                    }
672                }
673            }
674            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
675                *cache_hits = cache_hits.wrapping_add(1);
676                *lru_clock = lru_clock.wrapping_add(1);
677                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
678                    *tick = *lru_clock;
679                }
680                if let Some(fence) = entry_fence_ids.get_mut(slot as usize) {
681                    *fence = (*fence).max(*active_fence_id);
682                }
683                if code < 128 {
684                    for table in ascii_tables.iter_mut() {
685                        if table.style_sig == style_sig {
686                            table.slots[code as usize] = slot;
687                            break;
688                        }
689                    }
690                }
691                return slot;
692            }
693        }
694        let glyph: RasterizedGlyph = rasterize_glyph(key);
695        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true)
696    }
697
698    /// Returns the arena slot index for `key`, rasterizing through `provider` on a miss.
699    ///
700    /// # Arguments
701    ///
702    /// - `&Self` - Mutable glyph atlas reference.
703    /// - `GlyphKey` - Quantized glyph lookup key.
704    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
705    ///
706    /// # Returns
707    ///
708    /// - `u32` - Direct slot index into `entries`.
709    #[inline]
710    pub(crate) fn get_or_rasterize_slot_with(
711        &mut self,
712        key: GlyphKey,
713        provider: &dyn SystemFontProvider,
714    ) -> u32 {
715        let code: u32 = key.get_codepoint() as u32;
716        let style_sig: u32 = Self::pack_style_sig(
717            key.get_size_tenths(),
718            key.get_bold(),
719            key.get_monospace(),
720            key.get_italic(),
721        );
722        let packed_key: u64 = Self::pack_glyph_key(key);
723        {
724            let Self {
725                glyph_index,
726                entry_last_used,
727                entry_fence_ids,
728                active_fence_id,
729                ascii_tables,
730                lru_clock,
731                cache_hits,
732                ..
733            } = self;
734            if code < 128 && !ascii_tables.is_empty() {
735                for table in ascii_tables.iter() {
736                    if table.style_sig == style_sig {
737                        let cached: u32 = table.slots[code as usize];
738                        if cached != u32::MAX {
739                            *cache_hits = cache_hits.wrapping_add(1);
740                            *lru_clock = lru_clock.wrapping_add(1);
741                            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
742                                *tick = *lru_clock;
743                            }
744                            if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
745                                *fence = (*fence).max(*active_fence_id);
746                            }
747                            return cached;
748                        }
749                        break;
750                    }
751                }
752            }
753            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
754                *cache_hits = cache_hits.wrapping_add(1);
755                *lru_clock = lru_clock.wrapping_add(1);
756                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
757                    *tick = *lru_clock;
758                }
759                if let Some(fence) = entry_fence_ids.get_mut(slot as usize) {
760                    *fence = (*fence).max(*active_fence_id);
761                }
762                return slot;
763            }
764        }
765        let glyph: RasterizedGlyph = provider
766            .rasterize(key)
767            .unwrap_or_else(|| rasterize_glyph(key));
768        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, false)
769    }
770
771    /// Returns a read-only reference to the `RasterizedGlyph` at flat arena index `slot`.
772    ///
773    /// # Arguments
774    ///
775    /// - `&Self` - Glyph atlas reference.
776    /// - `u32` - Valid slot index into `entries`.
777    ///
778    /// # Returns
779    ///
780    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
781    #[inline(always)]
782    #[must_use]
783    pub(crate) fn glyph_by_slot(&self, slot: u32) -> &RasterizedGlyph {
784        let Self { entries, .. } = self;
785        &entries[slot as usize].1
786    }
787
788    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing and inserting it on a miss.
789    ///
790    /// # Arguments
791    ///
792    /// - `&Self` - Mutable reference to the glyph atlas.
793    /// - `GlyphKey` - Quantized glyph lookup key.
794    ///
795    /// # Returns
796    ///
797    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
798    #[inline]
799    pub fn get_or_rasterize(&mut self, key: GlyphKey) -> &RasterizedGlyph {
800        let slot: u32 = self.get_or_rasterize_slot(key);
801        self.glyph_by_slot(slot)
802    }
803
804    /// Returns the total number of cached glyph entries.
805    ///
806    /// # Arguments
807    ///
808    /// - `&Self` - Glyph atlas reference.
809    ///
810    /// # Returns
811    ///
812    /// - `usize` - Number of cached glyphs.
813    #[must_use]
814    pub fn len(&self) -> usize {
815        self.get_entries().len()
816    }
817
818    /// Returns true when the atlas contains no cached glyphs.
819    ///
820    /// # Arguments
821    ///
822    /// - `&Self` - Glyph atlas reference.
823    ///
824    /// # Returns
825    ///
826    /// - `bool` - True if empty.
827    #[must_use]
828    pub fn is_empty(&self) -> bool {
829        self.get_entries().is_empty()
830    }
831
832    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing through `provider` on a miss.
833    ///
834    /// # Arguments
835    ///
836    /// - `&Self` - Mutable reference to the glyph atlas.
837    /// - `GlyphKey` - Quantized glyph lookup key.
838    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
839    ///
840    /// # Returns
841    ///
842    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
843    #[inline]
844    pub fn get_or_rasterize_with(
845        &mut self,
846        key: GlyphKey,
847        provider: &dyn SystemFontProvider,
848    ) -> &RasterizedGlyph {
849        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
850        self.glyph_by_slot(slot)
851    }
852
853    /// Blits one glyph's 8-bit coverage bitmap into a white-RGB RGBA8 atlas slice at `(rx, ry)`.
854    ///
855    /// # Arguments
856    ///
857    /// - `&RasterizedGlyph` - Source coverage bitmap.
858    /// - `&mut [u8]` - Destination RGBA8 atlas pixel buffer.
859    /// - `usize` - Atlas width in pixels.
860    /// - `u32` - Destination X pixel offset.
861    /// - `u32` - Destination Y pixel offset.
862    #[inline]
863    fn blit_glyph_to_rgba(
864        glyph: &RasterizedGlyph,
865        pixels: &mut [u8],
866        atlas_w: usize,
867        rx: u32,
868        ry: u32,
869    ) {
870        let gw: usize = glyph.get_width() as usize;
871        let gh: usize = glyph.get_height() as usize;
872        let cov: &[u8] = glyph.get_coverage().as_slice();
873        let row_stride: usize = atlas_w * 4;
874        let mut src_off: usize = 0;
875        let mut dst_off: usize = ((ry as usize) * atlas_w + (rx as usize)) * 4;
876        for _ in 0..gh {
877            let src_row: &[u8] = &cov[src_off..src_off + gw];
878            let dst_row: &mut [u8] = &mut pixels[dst_off..dst_off + gw * 4];
879            let (src_quads, src_rem): (&[[u8; 4]], &[u8]) = src_row.as_chunks::<4>();
880            let (dst_quads, dst_rem): (&mut [[u8; 16]], &mut [u8]) = dst_row.as_chunks_mut::<16>();
881            for (a4, dst16) in src_quads.iter().zip(dst_quads.iter_mut()) {
882                *dst16 = [
883                    255, 255, 255, a4[0], 255, 255, 255, a4[1], 255, 255, 255, a4[2], 255, 255,
884                    255, a4[3],
885                ];
886            }
887            for (alpha, dst4) in src_rem
888                .iter()
889                .copied()
890                .zip(dst_rem.as_chunks_mut::<4>().0.iter_mut())
891            {
892                *dst4 = [255, 255, 255, alpha];
893            }
894            src_off += gw;
895            dst_off += row_stride;
896        }
897    }
898
899    /// Shelf-packs all cached glyphs into a single GPU-uploadable RGBA8 texture atlas.
900    ///
901    /// # Arguments
902    ///
903    /// - `&Self` - Glyph atlas reference.
904    ///
905    /// # Returns
906    ///
907    /// - `PackedGlyphAtlas` - Packed RGBA8 texture, per-glyph UV rects, and revision tag.
908    #[must_use]
909    pub fn pack_rgba_atlas(&self) -> PackedGlyphAtlas {
910        let entries: &[(GlyphKey, RasterizedGlyph)] = self.get_entries().as_slice();
911        let glyph_count: usize = entries.len();
912        let mut total_row_w: u32 = 1;
913        let mut max_glyph_w: u32 = 0;
914        for (_, glyph) in entries.iter() {
915            let gw: u32 = glyph.get_width();
916            total_row_w = total_row_w.saturating_add(gw.saturating_add(1));
917            if gw > max_glyph_w {
918                max_glyph_w = gw;
919            }
920        }
921        let min_needed_w: u32 = max_glyph_w.saturating_add(2).max(ATLAS_MIN_DIM);
922        let atlas_w: u32 = if total_row_w <= ATLAS_DEFAULT_WIDTH {
923            total_row_w
924                .max(ATLAS_MIN_DIM)
925                .next_power_of_two()
926                .min(ATLAS_DEFAULT_WIDTH)
927        } else {
928            ATLAS_DEFAULT_WIDTH.max(min_needed_w.next_power_of_two())
929        };
930        let mut cursor_x: u32 = 1;
931        let mut cursor_y: u32 = 1;
932        let mut shelf_h: u32 = 0;
933        let mut regions: HashMap<GlyphKey, (u32, u32, u32, u32)> =
934            HashMap::with_capacity(glyph_count);
935        let use_stack: bool = glyph_count <= ATLAS_STACK_PLACEMENTS;
936        let mut stack_placements: [(usize, u32, u32); ATLAS_STACK_PLACEMENTS] =
937            [(0, 0, 0); ATLAS_STACK_PLACEMENTS];
938        let mut heap_placements: Vec<(usize, u32, u32)> = if use_stack {
939            Vec::new()
940        } else {
941            Vec::with_capacity(glyph_count)
942        };
943        for (idx, (key, glyph)) in entries.iter().enumerate() {
944            let gw: u32 = glyph.get_width();
945            let gh: u32 = glyph.get_height();
946            if cursor_x + gw + 1 > atlas_w {
947                cursor_x = 1;
948                cursor_y += shelf_h + 1;
949                shelf_h = 0;
950            }
951            let _: Option<(u32, u32, u32, u32)> =
952                regions.insert(*key, (cursor_x, cursor_y, gw, gh));
953            if use_stack {
954                stack_placements[idx] = (idx, cursor_x, cursor_y);
955            } else {
956                heap_placements.push((idx, cursor_x, cursor_y));
957            }
958            cursor_x += gw + 1;
959            shelf_h = shelf_h.max(gh);
960        }
961        let atlas_h: u32 = (cursor_y + shelf_h + 1).max(ATLAS_MIN_DIM);
962        let atlas_w_usize: usize = atlas_w as usize;
963        let mut pixels: Vec<u8> = vec![0; atlas_w_usize * (atlas_h as usize) * 4];
964        let placements: &[(usize, u32, u32)] = if use_stack {
965            &stack_placements[..glyph_count]
966        } else {
967            heap_placements.as_slice()
968        };
969        for &(entry_idx, rx, ry) in placements.iter() {
970            Self::blit_glyph_to_rgba(&entries[entry_idx].1, &mut pixels, atlas_w_usize, rx, ry);
971        }
972        PackedGlyphAtlas::new(atlas_w, atlas_h, pixels, regions, self.get_revision())
973    }
974
975    /// Clears all cached glyphs and increments the atlas revision.
976    ///
977    /// # Arguments
978    ///
979    /// - `&Self` - Mutable reference to the glyph atlas.
980    pub fn clear(&mut self) {
981        self.clear_with_fence_deferral();
982    }
983}