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    /// Compacts the glyph arena by evicting the coldest LRU entries until `resident_bytes <= target_bytes`.
127    ///
128    /// # Arguments
129    ///
130    /// - `&Self` - Mutable glyph atlas reference.
131    /// - `usize` - Target post-eviction resident byte ceiling.
132    fn evict_lru_to_target(&mut self, target_bytes: usize) {
133        let Self {
134            glyph_index,
135            entries,
136            entry_last_used,
137            ascii_tables,
138            revision,
139            resident_bytes,
140            evictions,
141            ..
142        } = self;
143        let count: usize = entries.len();
144        if count == 0 || *resident_bytes <= target_bytes {
145            return;
146        }
147        let mut order: Vec<usize> = (0..count).collect();
148        order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
149        let mut keep: Vec<bool> = vec![true; count];
150        let mut remaining_bytes: usize = *resident_bytes;
151        let mut evicted_count: usize = 0;
152        for idx in order.into_iter() {
153            if remaining_bytes <= target_bytes {
154                break;
155            }
156            let bytes: usize = Self::entry_bytes(&entries[idx].1);
157            remaining_bytes = remaining_bytes.saturating_sub(bytes);
158            keep[idx] = false;
159            evicted_count += 1;
160        }
161        if evicted_count == 0 {
162            return;
163        }
164        let mut write_idx: usize = 0;
165        let mut next_resident: usize = 0;
166        for (read_idx, &kept) in keep.iter().enumerate() {
167            if kept {
168                if write_idx != read_idx {
169                    entries.swap(write_idx, read_idx);
170                    if read_idx < entry_last_used.len() && write_idx < entry_last_used.len() {
171                        entry_last_used.swap(write_idx, read_idx);
172                    }
173                }
174                next_resident =
175                    next_resident.saturating_add(Self::entry_bytes(&entries[write_idx].1));
176                write_idx += 1;
177            }
178        }
179        entries.truncate(write_idx);
180        entry_last_used.truncate(write_idx);
181        *resident_bytes = next_resident;
182        *evictions = evictions.saturating_add(evicted_count as u64);
183        glyph_index.fill(GLYPH_INDEX_EMPTY);
184        for (slot_idx, (key, _)) in entries.iter().enumerate() {
185            let packed_key: u64 = Self::pack_glyph_key(*key);
186            Self::insert_index(glyph_index, slot_idx + 1, packed_key, slot_idx as u32);
187        }
188        for table in ascii_tables.iter_mut() {
189            table.slots.fill(u32::MAX);
190        }
191        *revision = revision.wrapping_add(1);
192    }
193
194    /// Probes the open-addressed `glyph_index` slice for `packed_key`.
195    ///
196    /// # Arguments
197    ///
198    /// - `&[u64]` - Power-of-two open-addressed index table.
199    /// - `u64` - Lossless 40-bit packed glyph key.
200    ///
201    /// # Returns
202    ///
203    /// - `Option<u32>` - Cached arena slot index when present.
204    #[inline(always)]
205    #[must_use]
206    fn lookup_index(glyph_index: &[u64], packed_key: u64) -> Option<u32> {
207        let cap: usize = glyph_index.len();
208        if cap == 0 {
209            return None;
210        }
211        let mask: usize = cap - 1;
212        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
213        loop {
214            let entry: u64 = glyph_index[idx];
215            if entry == GLYPH_INDEX_EMPTY {
216                return None;
217            }
218            if (entry & GLYPH_INDEX_KEY_MASK) == packed_key {
219                return Some((entry >> GLYPH_INDEX_SLOT_SHIFT) as u32);
220            }
221            idx = (idx + 1) & mask;
222        }
223    }
224
225    /// Inserts `(packed_key, slot)` into the open-addressed `glyph_index` table, doubling capacity at 75% load.
226    ///
227    /// # Arguments
228    ///
229    /// - `&mut Vec<u64>` - Open-addressed index table storage.
230    /// - `usize` - Current total entry count including the newly inserted glyph.
231    /// - `u64` - Lossless 40-bit packed glyph key.
232    /// - `u32` - Arena slot index into `entries`.
233    fn insert_index(glyph_index: &mut Vec<u64>, entry_count: usize, packed_key: u64, slot: u32) {
234        let cap: usize = glyph_index.len();
235        if cap == 0 {
236            glyph_index.resize(GLYPH_INDEX_INIT_CAP, GLYPH_INDEX_EMPTY);
237        } else if entry_count * 4 > cap * 3 {
238            let new_cap: usize = cap * 2;
239            let new_mask: usize = new_cap - 1;
240            let mut grown: Vec<u64> = vec![GLYPH_INDEX_EMPTY; new_cap];
241            for old_entry in glyph_index.iter().copied() {
242                if old_entry == GLYPH_INDEX_EMPTY {
243                    continue;
244                }
245                let old_key: u64 = old_entry & GLYPH_INDEX_KEY_MASK;
246                let mut idx: usize = Self::hash_packed_key(old_key) & new_mask;
247                while grown[idx] != GLYPH_INDEX_EMPTY {
248                    idx = (idx + 1) & new_mask;
249                }
250                grown[idx] = old_entry;
251            }
252            *glyph_index = grown;
253        }
254        let mask: usize = glyph_index.len() - 1;
255        let packed_entry: u64 = packed_key | ((slot as u64) << GLYPH_INDEX_SLOT_SHIFT);
256        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
257        loop {
258            let existing: u64 = glyph_index[idx];
259            if existing == GLYPH_INDEX_EMPTY || (existing & GLYPH_INDEX_KEY_MASK) == packed_key {
260                glyph_index[idx] = packed_entry;
261                return;
262            }
263            idx = (idx + 1) & mask;
264        }
265    }
266
267    /// Packs quantized glyph style attributes into a compact 32-bit signature for ASCII table matching.
268    ///
269    /// # Arguments
270    ///
271    /// - `u16` - Quantized physical font size in tenths of a pixel.
272    /// - `bool` - Bold flag.
273    /// - `bool` - Monospace family flag.
274    /// - `bool` - Italic flag.
275    ///
276    /// # Returns
277    ///
278    /// - `u32` - Packed style signature.
279    #[inline(always)]
280    #[must_use]
281    pub(crate) fn pack_style_sig(
282        size_tenths: u16,
283        bold: bool,
284        monospace: bool,
285        italic: bool,
286    ) -> u32 {
287        (size_tenths as u32)
288            | (u32::from(bold) << 16)
289            | (u32::from(monospace) << 17)
290            | (u32::from(italic) << 18)
291    }
292
293    /// Returns the index of the `[u32; 128]` ASCII slot table matching `(size_tenths, bold, monospace, italic)`, creating it if absent.
294    ///
295    /// # Arguments
296    ///
297    /// - `&Self` - Mutable glyph atlas reference.
298    /// - `u16` - Quantized physical font size in tenths of a pixel.
299    /// - `bool` - Bold flag.
300    /// - `bool` - Monospace family flag.
301    /// - `bool` - Italic flag.
302    ///
303    /// # Returns
304    ///
305    /// - `usize` - Index inside `ascii_tables` for zero-hash ASCII glyph resolution.
306    pub(crate) fn ascii_table_index(
307        &mut self,
308        size_tenths: u16,
309        bold: bool,
310        monospace: bool,
311        italic: bool,
312    ) -> usize {
313        let style_sig: u32 = Self::pack_style_sig(size_tenths, bold, monospace, italic);
314        let Self { ascii_tables, .. } = self;
315        for (idx, table) in ascii_tables.iter().enumerate() {
316            if table.style_sig == style_sig {
317                return idx;
318            }
319        }
320        let idx: usize = ascii_tables.len();
321        ascii_tables.push(AsciiGlyphStyleTable {
322            style_sig,
323            slots: [u32::MAX; 128],
324        });
325        idx
326    }
327
328    /// Resolves an ASCII byte directly through `ascii_tables[table_idx]` with zero hash probing on hits.
329    ///
330    /// # Arguments
331    ///
332    /// - `&Self` - Mutable glyph atlas reference.
333    /// - `usize` - Style table index returned by `ascii_table_index`.
334    /// - `u8` - ASCII codepoint byte in `0..128`.
335    /// - `(u16, bool, bool, bool)` - Quantized style metadata `(size_tenths, bold, monospace, italic)`.
336    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
337    ///
338    /// # Returns
339    ///
340    /// - `u32` - Direct slot index into `entries`.
341    #[inline(always)]
342    pub(crate) fn get_or_rasterize_ascii_slot_with(
343        &mut self,
344        table_idx: usize,
345        byte: u8,
346        key_meta: (u16, bool, bool, bool),
347        provider: &dyn SystemFontProvider,
348    ) -> u32 {
349        let Self {
350            ascii_tables,
351            entry_last_used,
352            lru_clock,
353            cache_hits,
354            ..
355        } = self;
356        let cached: u32 = ascii_tables[table_idx].slots[byte as usize];
357        if cached != u32::MAX {
358            *cache_hits = cache_hits.wrapping_add(1);
359            *lru_clock = lru_clock.wrapping_add(1);
360            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
361                *tick = *lru_clock;
362            }
363            return cached;
364        }
365        let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
366        let key: GlyphKey = GlyphKey {
367            codepoint: byte as char,
368            size_tenths,
369            bold,
370            monospace,
371            italic,
372        };
373        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
374        let Self { ascii_tables, .. } = self;
375        ascii_tables[table_idx].slots[byte as usize] = slot;
376        slot
377    }
378
379    /// Inserts a newly rasterized glyph into the arena, enforcing the bounded memory budget when unpinned.
380    ///
381    /// # Arguments
382    ///
383    /// - `&Self` - Mutable glyph atlas reference.
384    /// - `GlyphKey` - Quantized glyph lookup key.
385    /// - `u64` - Pre-packed 40-bit glyph key.
386    /// - `u32` - Pre-packed style signature for ASCII table updates.
387    /// - `RasterizedGlyph` - Newly rasterized coverage bitmap.
388    /// - `bool` - Whether a missing ASCII style table should be created automatically.
389    ///
390    /// # Returns
391    ///
392    /// - `u32` - Newly assigned arena slot index.
393    fn insert_rasterized_glyph(
394        &mut self,
395        key: GlyphKey,
396        packed_key: u64,
397        style_sig: u32,
398        glyph: RasterizedGlyph,
399        create_ascii_table: bool,
400    ) -> u32 {
401        let entry_sz: usize = Self::entry_bytes(&glyph);
402        let budget: usize = self.effective_budget_bytes();
403        let needs_evict: bool = {
404            let Self {
405                resident_bytes,
406                slots_pinned,
407                entries,
408                ..
409            } = self;
410            !*slots_pinned
411                && !entries.is_empty()
412                && resident_bytes.saturating_add(entry_sz) > budget
413        };
414        if needs_evict {
415            let target: usize = budget
416                .saturating_mul(3)
417                .saturating_div(4)
418                .saturating_sub(entry_sz);
419            self.evict_lru_to_target(target);
420        }
421        let code: u32 = key.get_codepoint() as u32;
422        let Self {
423            glyph_index,
424            entries,
425            entry_last_used,
426            ascii_tables,
427            revision,
428            resident_bytes,
429            lru_clock,
430            cache_misses,
431            ..
432        } = self;
433        if entries.is_empty() {
434            entries.reserve(GLYPH_ENTRIES_INIT_CAP);
435            entry_last_used.reserve(GLYPH_ENTRIES_INIT_CAP);
436        }
437        *cache_misses = cache_misses.wrapping_add(1);
438        *lru_clock = lru_clock.wrapping_add(1);
439        let slot: u32 = entries.len() as u32;
440        entries.push((key, glyph));
441        entry_last_used.push(*lru_clock);
442        *resident_bytes = resident_bytes.saturating_add(entry_sz);
443        Self::insert_index(glyph_index, entries.len(), packed_key, slot);
444        if code < 128 {
445            let mut updated: bool = false;
446            for table in ascii_tables.iter_mut() {
447                if table.style_sig == style_sig {
448                    table.slots[code as usize] = slot;
449                    updated = true;
450                    break;
451                }
452            }
453            if create_ascii_table && !updated {
454                let mut slots: [u32; 128] = [u32::MAX; 128];
455                slots[code as usize] = slot;
456                ascii_tables.push(AsciiGlyphStyleTable { style_sig, slots });
457            }
458        }
459        *revision = revision.wrapping_add(1);
460        slot
461    }
462
463    /// Returns the arena slot index for `key`, rasterizing through `rasterize_glyph` on a miss.
464    ///
465    /// # Arguments
466    ///
467    /// - `&Self` - Mutable glyph atlas reference.
468    /// - `GlyphKey` - Quantized glyph lookup key.
469    ///
470    /// # Returns
471    ///
472    /// - `u32` - Direct slot index into `entries`.
473    #[inline]
474    pub(crate) fn get_or_rasterize_slot(&mut self, key: GlyphKey) -> u32 {
475        let code: u32 = key.get_codepoint() as u32;
476        let style_sig: u32 = Self::pack_style_sig(
477            key.get_size_tenths(),
478            key.get_bold(),
479            key.get_monospace(),
480            key.get_italic(),
481        );
482        let packed_key: u64 = Self::pack_glyph_key(key);
483        {
484            let Self {
485                glyph_index,
486                entry_last_used,
487                ascii_tables,
488                lru_clock,
489                cache_hits,
490                ..
491            } = self;
492            if code < 128 {
493                for table in ascii_tables.iter() {
494                    if table.style_sig == style_sig {
495                        let cached: u32 = table.slots[code as usize];
496                        if cached != u32::MAX {
497                            *cache_hits = cache_hits.wrapping_add(1);
498                            *lru_clock = lru_clock.wrapping_add(1);
499                            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
500                                *tick = *lru_clock;
501                            }
502                            return cached;
503                        }
504                        break;
505                    }
506                }
507            }
508            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
509                *cache_hits = cache_hits.wrapping_add(1);
510                *lru_clock = lru_clock.wrapping_add(1);
511                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
512                    *tick = *lru_clock;
513                }
514                if code < 128 {
515                    for table in ascii_tables.iter_mut() {
516                        if table.style_sig == style_sig {
517                            table.slots[code as usize] = slot;
518                            break;
519                        }
520                    }
521                }
522                return slot;
523            }
524        }
525        let glyph: RasterizedGlyph = rasterize_glyph(key);
526        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true)
527    }
528
529    /// Returns the arena slot index for `key`, rasterizing through `provider` on a miss.
530    ///
531    /// # Arguments
532    ///
533    /// - `&Self` - Mutable glyph atlas reference.
534    /// - `GlyphKey` - Quantized glyph lookup key.
535    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
536    ///
537    /// # Returns
538    ///
539    /// - `u32` - Direct slot index into `entries`.
540    #[inline]
541    pub(crate) fn get_or_rasterize_slot_with(
542        &mut self,
543        key: GlyphKey,
544        provider: &dyn SystemFontProvider,
545    ) -> u32 {
546        let code: u32 = key.get_codepoint() as u32;
547        let style_sig: u32 = Self::pack_style_sig(
548            key.get_size_tenths(),
549            key.get_bold(),
550            key.get_monospace(),
551            key.get_italic(),
552        );
553        let packed_key: u64 = Self::pack_glyph_key(key);
554        {
555            let Self {
556                glyph_index,
557                entry_last_used,
558                ascii_tables,
559                lru_clock,
560                cache_hits,
561                ..
562            } = self;
563            if code < 128 && !ascii_tables.is_empty() {
564                for table in ascii_tables.iter() {
565                    if table.style_sig == style_sig {
566                        let cached: u32 = table.slots[code as usize];
567                        if cached != u32::MAX {
568                            *cache_hits = cache_hits.wrapping_add(1);
569                            *lru_clock = lru_clock.wrapping_add(1);
570                            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
571                                *tick = *lru_clock;
572                            }
573                            return cached;
574                        }
575                        break;
576                    }
577                }
578            }
579            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
580                *cache_hits = cache_hits.wrapping_add(1);
581                *lru_clock = lru_clock.wrapping_add(1);
582                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
583                    *tick = *lru_clock;
584                }
585                return slot;
586            }
587        }
588        let glyph: RasterizedGlyph = provider
589            .rasterize(key)
590            .unwrap_or_else(|| rasterize_glyph(key));
591        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, false)
592    }
593
594    /// Returns a read-only reference to the `RasterizedGlyph` at flat arena index `slot`.
595    ///
596    /// # Arguments
597    ///
598    /// - `&Self` - Glyph atlas reference.
599    /// - `u32` - Valid slot index into `entries`.
600    ///
601    /// # Returns
602    ///
603    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
604    #[inline(always)]
605    #[must_use]
606    pub(crate) fn glyph_by_slot(&self, slot: u32) -> &RasterizedGlyph {
607        let Self { entries, .. } = self;
608        &entries[slot as usize].1
609    }
610
611    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing and inserting it on a miss.
612    ///
613    /// # Arguments
614    ///
615    /// - `&Self` - Mutable reference to the glyph atlas.
616    /// - `GlyphKey` - Quantized glyph lookup key.
617    ///
618    /// # Returns
619    ///
620    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
621    #[inline]
622    pub fn get_or_rasterize(&mut self, key: GlyphKey) -> &RasterizedGlyph {
623        let slot: u32 = self.get_or_rasterize_slot(key);
624        self.glyph_by_slot(slot)
625    }
626
627    /// Returns the total number of cached glyph entries.
628    ///
629    /// # Arguments
630    ///
631    /// - `&Self` - Glyph atlas reference.
632    ///
633    /// # Returns
634    ///
635    /// - `usize` - Number of cached glyphs.
636    #[must_use]
637    pub fn len(&self) -> usize {
638        self.get_entries().len()
639    }
640
641    /// Returns true when the atlas contains no cached glyphs.
642    ///
643    /// # Arguments
644    ///
645    /// - `&Self` - Glyph atlas reference.
646    ///
647    /// # Returns
648    ///
649    /// - `bool` - True if empty.
650    #[must_use]
651    pub fn is_empty(&self) -> bool {
652        self.get_entries().is_empty()
653    }
654
655    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing through `provider` on a miss.
656    ///
657    /// # Arguments
658    ///
659    /// - `&Self` - Mutable reference to the glyph atlas.
660    /// - `GlyphKey` - Quantized glyph lookup key.
661    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
662    ///
663    /// # Returns
664    ///
665    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
666    #[inline]
667    pub fn get_or_rasterize_with(
668        &mut self,
669        key: GlyphKey,
670        provider: &dyn SystemFontProvider,
671    ) -> &RasterizedGlyph {
672        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
673        self.glyph_by_slot(slot)
674    }
675
676    /// Blits one glyph's 8-bit coverage bitmap into a white-RGB RGBA8 atlas slice at `(rx, ry)`.
677    ///
678    /// # Arguments
679    ///
680    /// - `&RasterizedGlyph` - Source coverage bitmap.
681    /// - `&mut [u8]` - Destination RGBA8 atlas pixel buffer.
682    /// - `usize` - Atlas width in pixels.
683    /// - `u32` - Destination X pixel offset.
684    /// - `u32` - Destination Y pixel offset.
685    #[inline]
686    fn blit_glyph_to_rgba(
687        glyph: &RasterizedGlyph,
688        pixels: &mut [u8],
689        atlas_w: usize,
690        rx: u32,
691        ry: u32,
692    ) {
693        let gw: usize = glyph.get_width() as usize;
694        let gh: usize = glyph.get_height() as usize;
695        let cov: &[u8] = glyph.get_coverage().as_slice();
696        let row_stride: usize = atlas_w * 4;
697        let mut src_off: usize = 0;
698        let mut dst_off: usize = ((ry as usize) * atlas_w + (rx as usize)) * 4;
699        for _ in 0..gh {
700            let src_row: &[u8] = &cov[src_off..src_off + gw];
701            let dst_row: &mut [u8] = &mut pixels[dst_off..dst_off + gw * 4];
702            let (src_quads, src_rem): (&[[u8; 4]], &[u8]) = src_row.as_chunks::<4>();
703            let (dst_quads, dst_rem): (&mut [[u8; 16]], &mut [u8]) = dst_row.as_chunks_mut::<16>();
704            for (a4, dst16) in src_quads.iter().zip(dst_quads.iter_mut()) {
705                *dst16 = [
706                    255, 255, 255, a4[0], 255, 255, 255, a4[1], 255, 255, 255, a4[2], 255, 255,
707                    255, a4[3],
708                ];
709            }
710            for (alpha, dst4) in src_rem
711                .iter()
712                .copied()
713                .zip(dst_rem.as_chunks_mut::<4>().0.iter_mut())
714            {
715                *dst4 = [255, 255, 255, alpha];
716            }
717            src_off += gw;
718            dst_off += row_stride;
719        }
720    }
721
722    /// Shelf-packs all cached glyphs into a single GPU-uploadable RGBA8 texture atlas.
723    ///
724    /// # Arguments
725    ///
726    /// - `&Self` - Glyph atlas reference.
727    ///
728    /// # Returns
729    ///
730    /// - `PackedGlyphAtlas` - Packed RGBA8 texture, per-glyph UV rects, and revision tag.
731    #[must_use]
732    pub fn pack_rgba_atlas(&self) -> PackedGlyphAtlas {
733        let entries: &[(GlyphKey, RasterizedGlyph)] = self.get_entries().as_slice();
734        let glyph_count: usize = entries.len();
735        let mut total_row_w: u32 = 1;
736        let mut max_glyph_w: u32 = 0;
737        for (_, glyph) in entries.iter() {
738            let gw: u32 = glyph.get_width();
739            total_row_w = total_row_w.saturating_add(gw.saturating_add(1));
740            if gw > max_glyph_w {
741                max_glyph_w = gw;
742            }
743        }
744        let min_needed_w: u32 = max_glyph_w.saturating_add(2).max(ATLAS_MIN_DIM);
745        let atlas_w: u32 = if total_row_w <= ATLAS_DEFAULT_WIDTH {
746            total_row_w
747                .max(ATLAS_MIN_DIM)
748                .next_power_of_two()
749                .min(ATLAS_DEFAULT_WIDTH)
750        } else {
751            ATLAS_DEFAULT_WIDTH.max(min_needed_w.next_power_of_two())
752        };
753        let mut cursor_x: u32 = 1;
754        let mut cursor_y: u32 = 1;
755        let mut shelf_h: u32 = 0;
756        let mut regions: HashMap<GlyphKey, (u32, u32, u32, u32)> =
757            HashMap::with_capacity(glyph_count);
758        let use_stack: bool = glyph_count <= ATLAS_STACK_PLACEMENTS;
759        let mut stack_placements: [(usize, u32, u32); ATLAS_STACK_PLACEMENTS] =
760            [(0, 0, 0); ATLAS_STACK_PLACEMENTS];
761        let mut heap_placements: Vec<(usize, u32, u32)> = if use_stack {
762            Vec::new()
763        } else {
764            Vec::with_capacity(glyph_count)
765        };
766        for (idx, (key, glyph)) in entries.iter().enumerate() {
767            let gw: u32 = glyph.get_width();
768            let gh: u32 = glyph.get_height();
769            if cursor_x + gw + 1 > atlas_w {
770                cursor_x = 1;
771                cursor_y += shelf_h + 1;
772                shelf_h = 0;
773            }
774            let _: Option<(u32, u32, u32, u32)> =
775                regions.insert(*key, (cursor_x, cursor_y, gw, gh));
776            if use_stack {
777                stack_placements[idx] = (idx, cursor_x, cursor_y);
778            } else {
779                heap_placements.push((idx, cursor_x, cursor_y));
780            }
781            cursor_x += gw + 1;
782            shelf_h = shelf_h.max(gh);
783        }
784        let atlas_h: u32 = (cursor_y + shelf_h + 1).max(ATLAS_MIN_DIM);
785        let atlas_w_usize: usize = atlas_w as usize;
786        let mut pixels: Vec<u8> = vec![0; atlas_w_usize * (atlas_h as usize) * 4];
787        let placements: &[(usize, u32, u32)] = if use_stack {
788            &stack_placements[..glyph_count]
789        } else {
790            heap_placements.as_slice()
791        };
792        for &(entry_idx, rx, ry) in placements.iter() {
793            Self::blit_glyph_to_rgba(&entries[entry_idx].1, &mut pixels, atlas_w_usize, rx, ry);
794        }
795        PackedGlyphAtlas::new(atlas_w, atlas_h, pixels, regions, self.get_revision())
796    }
797
798    /// Clears all cached glyphs and increments the atlas revision.
799    ///
800    /// # Arguments
801    ///
802    /// - `&Self` - Mutable reference to the glyph atlas.
803    pub fn clear(&mut self) {
804        let Self {
805            glyph_index,
806            entries,
807            entry_last_used,
808            ascii_tables,
809            revision,
810            resident_bytes,
811            ..
812        } = self;
813        glyph_index.fill(GLYPH_INDEX_EMPTY);
814        entries.clear();
815        entry_last_used.clear();
816        ascii_tables.clear();
817        *resident_bytes = 0;
818        *revision = revision.wrapping_add(1);
819    }
820}