1use super::*;
2
3impl GlyphAtlas {
5 #[inline(always)]
15 #[must_use]
16 pub(crate) fn pack_glyph_key(key: GlyphKey) -> u64 {
17 key.pack_u64()
18 }
19
20 #[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 #[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 #[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 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 #[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 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 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 #[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 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 #[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 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 #[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 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 #[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 #[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 #[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 #[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 #[must_use]
637 pub fn len(&self) -> usize {
638 self.get_entries().len()
639 }
640
641 #[must_use]
651 pub fn is_empty(&self) -> bool {
652 self.get_entries().is_empty()
653 }
654
655 #[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 #[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 #[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 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}