damascene-core 0.6.0

Damascene — backend-agnostic UI library core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
//! MTSDF glyph atlas — outline glyphs only.
//!
//! One MTSDF per `(font, glyph)`, sized at a fixed base em and reused
//! at every logical render size. Pages are RGBA8: RGB carries the
//! standard 3-channel MSDF, A carries a true single-channel SDF. The
//! shader uses A as a fallback wherever median(R,G,B) disagrees with
//! it, eliminating the false-outside artifacts that MSDF produces near
//! sharp corners. A backend mirrors pages onto a GPU texture and
//! samples them through the `stock::text_msdf` shader.
//!
//! Color-emoji glyphs flow through the separate
//! [`crate::text::atlas::GlyphAtlas`] (size-keyed RGBA bitmaps). The
//! recorder routes each glyph to whichever atlas matches the source
//! face — outline fonts here, color fonts there.

// Lock in full per-item documentation for this module (issue #73).
#![warn(missing_docs)]

use std::collections::HashMap;

use cosmic_text::fontdb;
use ttf_parser::Face;

use crate::text::msdf::{MsdfGlyph, build_glyph_msdf, glyph_advance};
use crate::text::msdf_snapshot::{
    SnapshotError, SnapshotGlyph, SnapshotHeader, SnapshotSection, decode_snapshot, encode_snapshot,
};

/// Default base em size (atlas pixels). 48 covers UI sizes 10–64 with
/// good fidelity at the cost of ~9 KB per glyph (48×48×4). Smaller
/// values (32) lose noticeable sharpness at body sizes (12–14 px) on
/// 1× displays; larger values (64) only marginally improve quality.
pub const DEFAULT_BASE_EM: u32 = 48;
/// Default MSDF spread radius in atlas pixels. 6 px at 48 base-em gives
/// clean AA with margin for thin strokes; the absolute value scales
/// with base_em (we keep ~12.5% of base).
pub const DEFAULT_SPREAD: f64 = 6.0;

/// Atlas page side. 1024 holds ~600 typical 32-em-px MSDFs without
/// growing.
const PAGE_SIZE: u32 = 1024;

/// Soft cap on resident pages (8 × 1024² RGBA ≈ 32 MB, roughly 4–5K
/// distinct glyphs — comfortably more than a screenful of CJK). At the
/// cap, making room recycles the least-recently-used page in place
/// instead of growing — unless every page was referenced this frame,
/// in which case the atlas grows past the budget (instances already
/// recorded this frame point at their pages' UVs).
const PAGE_BUDGET: usize = 8;

/// Inter-glyph padding (atlas pixels) so neighbour MSDF gradients don't
/// bleed under bilinear filtering.
const GLYPH_PADDING: u32 = 2;

/// Bytes per atlas pixel — RGBA8 (RGB = MSDF distance channels, A=255).
pub const MSDF_BYTES_PER_PIXEL: u32 = 4;

/// Atlas key — outline glyphs are size-independent but
/// weight-dependent: a variable face produces different outlines per
/// `wght` instance, so each rasterized weight gets its own slot.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct MsdfGlyphKey {
    /// fontdb face the glyph belongs to (the shaping atlas's
    /// `FontSystem` IDs).
    pub font: fontdb::ID,
    /// Glyph index within the face (not a codepoint).
    pub glyph_id: u16,
    /// `wght` variation value applied when rasterizing, or `0` for the
    /// face's default instance (static faces, or faces without a
    /// `wght` axis). Normalize through
    /// [`crate::text::msdf::apply_weight_variation`] (per-face
    /// classification is cached by
    /// `crate::text::atlas::GlyphAtlas::msdf_raster_weight`) so static
    /// faces never fragment into per-weight duplicates.
    pub weight: u16,
}

/// Axis-aligned pixel rect inside an MSDF atlas page (y-down, top-left
/// origin). Units are atlas texels.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct MsdfRect {
    /// Left edge in atlas px.
    pub x: u32,
    /// Top edge in atlas px.
    pub y: u32,
    /// Width in atlas px.
    pub w: u32,
    /// Height in atlas px.
    pub h: u32,
}

impl MsdfRect {
    /// One past the right edge: `x + w`.
    pub fn right(&self) -> u32 {
        self.x + self.w
    }
    /// One past the bottom edge: `y + h`.
    pub fn bottom(&self) -> u32 {
        self.y + self.h
    }
}

/// Where a cached MSDF glyph lives, plus the metrics the recorder needs
/// to place its quad.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct MsdfSlot {
    /// Index into [`MsdfAtlas::pages`] of the page holding the MTSDF.
    pub page: u32,
    /// Pixel rect inside the page where the MTSDF bitmap sits.
    pub rect: MsdfRect,
    /// Pen-relative X of the bitmap top-left, in base-em px (includes
    /// the SDF spread).
    pub bearing_x: f32,
    /// Baseline-relative Y of the bitmap top edge, in base-em px,
    /// y-down (includes spread; typically negative).
    pub bearing_y: f32,
    /// Horizontal advance width in base-em px.
    pub advance: f32,
    /// MSDF spread in base-em px — needed to derive distance from
    /// sampled byte values in the shader.
    pub spread: f32,
}

#[derive(Copy, Clone)]
struct Shelf {
    y_top: u32,
    height: u32,
    cursor: u32,
}

/// One CPU-side MSDF atlas page. Backends sample from a GPU texture
/// mirror they keep in sync via [`MsdfAtlas::take_dirty`].
pub struct MsdfAtlasPage {
    /// Page width in pixels.
    pub width: u32,
    /// Page height in pixels.
    pub height: u32,
    /// Row-major RGBA8.
    pub pixels: Vec<u8>,
    dirty: Option<MsdfRect>,
    shelves: Vec<Shelf>,
    /// Frame stamp of the last allocation or `touch`/`ensure` hit.
    /// Pages stamped before the current frame are recycling candidates
    /// once the atlas reaches [`PAGE_BUDGET`].
    last_used: u64,
}

impl MsdfAtlasPage {
    fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            pixels: vec![0; (width * height * MSDF_BYTES_PER_PIXEL) as usize],
            dirty: None,
            shelves: Vec::new(),
            last_used: 0,
        }
    }

    fn allocate(&mut self, w: u32, h: u32) -> Option<MsdfRect> {
        if w > self.width || h > self.height {
            return None;
        }
        // Best-fit on existing shelves (least leftover height).
        let mut best: Option<usize> = None;
        for (i, shelf) in self.shelves.iter().enumerate() {
            if shelf.cursor + w > self.width || shelf.height < h {
                continue;
            }
            let waste = shelf.height - h;
            if best
                .map(|b| waste < self.shelves[b].height - h)
                .unwrap_or(true)
            {
                best = Some(i);
            }
        }
        if let Some(i) = best {
            let shelf = &mut self.shelves[i];
            let rect = MsdfRect {
                x: shelf.cursor,
                y: shelf.y_top,
                w,
                h,
            };
            shelf.cursor += w + GLYPH_PADDING;
            return Some(rect);
        }
        let next_y = self
            .shelves
            .last()
            .map(|s| s.y_top + s.height + GLYPH_PADDING)
            .unwrap_or(0);
        if next_y + h > self.height {
            return None;
        }
        self.shelves.push(Shelf {
            y_top: next_y,
            height: h,
            cursor: w + GLYPH_PADDING,
        });
        Some(MsdfRect {
            x: 0,
            y: next_y,
            w,
            h,
        })
    }
}

/// MSDF glyph cache.
pub struct MsdfAtlas {
    pages: Vec<MsdfAtlasPage>,
    /// `Some(slot)` for a cached glyph, `None` when the glyph has no
    /// outline (whitespace, .notdef without contours) — recorded so the
    /// recorder still gets the advance width without re-trying every
    /// frame.
    map: HashMap<MsdfGlyphKey, MsdfEntry>,
    base_em: u32,
    spread: f64,
    /// Frame counter for page-LRU bookkeeping, bumped once per frame in
    /// [`Self::take_dirty`] (which every backend drains exactly once
    /// per frame in its flush).
    frame: u64,
    /// Resident-page soft cap; [`PAGE_BUDGET`] outside tests.
    page_budget: usize,
    /// How many of the most recent frame ticks count as "in use" for
    /// the page recycler — see [`Self::set_lru_protection_window`].
    lru_protection_window: u64,
    /// Run fdsm's MTSDF error-correction pass per glyph. Off by default:
    /// it costs ~22% of generation and the shader's alpha-SDF fallback
    /// already masks the artifacts it fixes for typical faces. See
    /// [`Self::set_error_correction`].
    error_correction: bool,
}

#[derive(Copy, Clone, Debug, PartialEq)]
enum MsdfEntry {
    /// Glyph has an outline and is packed into the atlas.
    Slot(MsdfSlot),
    /// Glyph has no outline; only the advance width is meaningful.
    Empty { advance: f32 },
}

impl Default for MsdfAtlas {
    fn default() -> Self {
        Self::new(DEFAULT_BASE_EM, DEFAULT_SPREAD)
    }
}

impl MsdfAtlas {
    /// Build an empty atlas. `base_em` is the em size (atlas px) every
    /// MTSDF is generated at; `spread` is the SDF radius in atlas px.
    /// Use [`DEFAULT_BASE_EM`] / [`DEFAULT_SPREAD`] (via
    /// `MsdfAtlas::default()`) unless tuning quality vs. memory.
    pub fn new(base_em: u32, spread: f64) -> Self {
        Self {
            pages: vec![MsdfAtlasPage::new(PAGE_SIZE, PAGE_SIZE)],
            map: HashMap::new(),
            base_em,
            spread,
            frame: 0,
            page_budget: PAGE_BUDGET,
            lru_protection_window: 1,
            error_correction: false,
        }
    }

    /// Enable or disable fdsm's MTSDF error-correction pass (default
    /// off). Leaving it off saves ~22% of per-glyph generation cost; the
    /// shader's alpha-channel SDF fallback already neutralizes the
    /// sign-disagreement artifacts it targets for the bundled sans/mono
    /// faces. Turn it on for unusual faces if you observe corner specks.
    /// Only affects glyphs rasterized after the call.
    pub fn set_error_correction(&mut self, on: bool) {
        self.error_correction = on;
    }

    /// Widen the recycler's "referenced this frame" guard to the last
    /// `n` frame ticks (default 1).
    ///
    /// The frame counter advances once per [`Self::take_dirty`], i.e.
    /// once per *backend flush*. When several `Runner`s share one
    /// atlas (see `damascene_wgpu::SharedText`), each runner's flush
    /// ticks the shared counter — so a page referenced by window A's
    /// recorded-but-not-yet-submitted instances would look one-tick
    /// stale during window B's prepare and could be recycled out from
    /// under A's frame. Setting the window to the number of attached
    /// runners protects every page referenced within the last
    /// whole-host frame, whatever the hosts's prepare/render
    /// interleaving. Clamped to at least 1.
    pub fn set_lru_protection_window(&mut self, n: u32) {
        self.lru_protection_window = u64::from(n.max(1));
    }

    /// Em size (atlas px) glyphs are generated at. Backends scale
    /// quads by `render_size / base_em`.
    pub fn base_em(&self) -> u32 {
        self.base_em
    }

    /// SDF spread radius in atlas px, as passed to [`Self::new`].
    pub fn spread(&self) -> f64 {
        self.spread
    }

    /// All resident pages, indexed by [`MsdfSlot::page`]. Backends
    /// mirror each page to a GPU texture.
    pub fn pages(&self) -> &[MsdfAtlasPage] {
        &self.pages
    }

    /// One page by index ([`MsdfSlot::page`]), or `None` if out of
    /// range.
    pub fn page(&self, index: u32) -> Option<&MsdfAtlasPage> {
        self.pages.get(index as usize)
    }

    /// Atlas slot for a cached glyph, if present and non-empty.
    pub fn slot(&self, key: MsdfGlyphKey) -> Option<MsdfSlot> {
        match self.map.get(&key)? {
            MsdfEntry::Slot(s) => Some(*s),
            MsdfEntry::Empty { .. } => None,
        }
    }

    /// [`Self::slot`], but also stamps the slot's page as used this
    /// frame so the LRU page recycler skips it. Backends call this on
    /// their per-glyph draw path; every glyph drawn each frame keeps
    /// its page warm.
    pub fn touch(&mut self, key: MsdfGlyphKey) -> Option<MsdfSlot> {
        let slot = self.slot(key)?;
        self.pages[slot.page as usize].last_used = self.frame;
        Some(slot)
    }

    /// Cached advance width for a glyph (works for both outline and
    /// whitespace entries).
    pub fn advance(&self, key: MsdfGlyphKey) -> Option<f32> {
        Some(match self.map.get(&key)? {
            MsdfEntry::Slot(s) => s.advance,
            MsdfEntry::Empty { advance } => *advance,
        })
    }

    /// Drain dirty rects since the last call (one per page that has new
    /// writes).
    ///
    /// Every backend drains dirty rects exactly once per frame in its
    /// flush, so this call doubles as the atlas's frame tick for
    /// page-LRU bookkeeping.
    pub fn take_dirty(&mut self) -> Vec<(usize, MsdfRect)> {
        self.frame += 1;
        let mut out = Vec::new();
        for (i, page) in self.pages.iter_mut().enumerate() {
            if let Some(rect) = page.dirty.take() {
                out.push((i, rect));
            }
        }
        out
    }

    /// Ensure the glyph is rasterized into the atlas; returns the slot
    /// (or `None` for empty/notdef glyphs).
    ///
    /// Contract: `face` must already carry the variation state
    /// `key.weight` describes — i.e. the caller ran
    /// [`crate::text::msdf::apply_weight_variation`] on it and used the
    /// returned value as `key.weight`. The atlas itself never touches
    /// variation coordinates.
    pub fn ensure(&mut self, key: MsdfGlyphKey, face: &Face<'_>) -> Option<MsdfSlot> {
        if let Some(entry) = self.map.get(&key) {
            return match entry {
                MsdfEntry::Slot(s) => {
                    let s = *s;
                    // Keep the page warm so the LRU recycler skips it.
                    self.pages[s.page as usize].last_used = self.frame;
                    Some(s)
                }
                MsdfEntry::Empty { .. } => None,
            };
        }
        match build_glyph_msdf(
            face,
            key.glyph_id,
            self.base_em,
            self.spread,
            self.error_correction,
        ) {
            Some(glyph) => {
                let slot = self.pack(glyph);
                self.map.insert(key, MsdfEntry::Slot(slot));
                Some(slot)
            }
            None => {
                let advance = glyph_advance(face, key.glyph_id, self.base_em);
                self.map.insert(key, MsdfEntry::Empty { advance });
                None
            }
        }
    }

    /// Ensure every key is resident, rasterizing the misses as a batch.
    ///
    /// All keys share the one `face`, so they must agree on
    /// [`MsdfGlyphKey::weight`] and `face` must already carry that
    /// variation state (see [`Self::ensure`]) — warm one weight per
    /// call.
    ///
    /// MTSDF generation for each glyph is independent and dominates cold
    /// start, so with the `parallel-raster` feature the misses are
    /// rasterized across rayon's global pool; without it they run
    /// serially. Either way, packing into atlas pages stays on the
    /// calling thread (it mutates shared page state and is cheap — a
    /// memcpy per glyph). Already-resident keys are skipped, so this is
    /// safe to call every warmup without re-doing work.
    ///
    /// Use the per-glyph [`Self::ensure`] / [`Self::slot`] afterward to
    /// read back individual slots; this call only guarantees residency.
    pub fn ensure_many(&mut self, keys: &[MsdfGlyphKey], face: &Face<'_>) {
        // Unique, not-yet-resident keys. Dedup so a repeated key isn't
        // rasterized (and packed) twice within one batch.
        let mut seen = std::collections::HashSet::new();
        let misses: Vec<MsdfGlyphKey> = keys
            .iter()
            .copied()
            .filter(|k| !self.map.contains_key(k) && seen.insert(*k))
            .collect();
        if misses.is_empty() {
            return;
        }

        let (base_em, spread, correct) = (self.base_em, self.spread, self.error_correction);
        let build = |k: &MsdfGlyphKey| {
            (
                *k,
                build_glyph_msdf(face, k.glyph_id, base_em, spread, correct),
            )
        };

        #[cfg(feature = "parallel-raster")]
        let built: Vec<(MsdfGlyphKey, Option<MsdfGlyph>)> = {
            use rayon::prelude::*;
            misses.par_iter().map(build).collect()
        };
        #[cfg(not(feature = "parallel-raster"))]
        let built: Vec<(MsdfGlyphKey, Option<MsdfGlyph>)> = misses.iter().map(build).collect();

        for (key, glyph) in built {
            match glyph {
                Some(glyph) => {
                    let slot = self.pack(glyph);
                    self.map.insert(key, MsdfEntry::Slot(slot));
                }
                None => {
                    let advance = glyph_advance(face, key.glyph_id, self.base_em);
                    self.map.insert(key, MsdfEntry::Empty { advance });
                }
            }
        }
    }

    /// Bake parameters this atlas generates with — the staleness guard a
    /// snapshot is validated against on import.
    fn snapshot_header(&self) -> SnapshotHeader {
        SnapshotHeader {
            base_em: self.base_em,
            spread: self.spread,
            error_correction: self.error_correction,
        }
    }

    /// Serialize every resident glyph into a portable snapshot blob (see
    /// [`crate::text::msdf_snapshot`]). `token_of` maps each glyph's
    /// runtime `fontdb::ID` to a stable cross-process token (e.g. a hash
    /// of the font bytes); glyphs whose font maps to `None` are omitted.
    /// Reload with [`Self::import_snapshot`].
    pub fn export_snapshot(&self, token_of: impl Fn(fontdb::ID) -> Option<u64>) -> Vec<u8> {
        let mut by_token: HashMap<u64, Vec<(u16, u16, SnapshotGlyph)>> = HashMap::new();
        for (key, entry) in &self.map {
            let Some(token) = token_of(key.font) else {
                continue;
            };
            let g = match entry {
                MsdfEntry::Slot(s) => SnapshotGlyph::Outline(self.read_slot_glyph(s)),
                MsdfEntry::Empty { advance } => SnapshotGlyph::Empty { advance: *advance },
            };
            by_token
                .entry(token)
                .or_default()
                .push((key.glyph_id, key.weight, g));
        }
        let sections: Vec<SnapshotSection> = by_token.into_iter().collect();
        encode_snapshot(self.snapshot_header(), &sections)
    }

    /// Populate the atlas from a snapshot blob, packing its glyphs into
    /// pages without regenerating any MTSDF. `id_of` maps each section's
    /// token back to a runtime `fontdb::ID`; sections whose token maps to
    /// `None` (font not loaded here) are skipped. Already-resident keys
    /// are left untouched. Returns the number of outline glyphs packed,
    /// or a [`SnapshotError`] if the blob is unreadable or its bake
    /// parameters don't match this atlas (caller then generates live).
    pub fn import_snapshot(
        &mut self,
        bytes: &[u8],
        id_of: impl Fn(u64) -> Option<fontdb::ID>,
    ) -> Result<usize, SnapshotError> {
        let sections = decode_snapshot(bytes, self.snapshot_header())?;
        let mut packed = 0;
        for (token, glyphs) in sections {
            let Some(font) = id_of(token) else {
                continue;
            };
            for (glyph_id, weight, g) in glyphs {
                let key = MsdfGlyphKey {
                    font,
                    glyph_id,
                    weight,
                };
                if self.map.contains_key(&key) {
                    continue;
                }
                match g {
                    SnapshotGlyph::Outline(glyph) => {
                        let slot = self.pack(glyph);
                        self.map.insert(key, MsdfEntry::Slot(slot));
                        packed += 1;
                    }
                    SnapshotGlyph::Empty { advance } => {
                        self.map.insert(key, MsdfEntry::Empty { advance });
                    }
                }
            }
        }
        Ok(packed)
    }

    /// Copy a packed glyph's MTSDF back out of its page into a standalone
    /// [`MsdfGlyph`] (used by [`Self::export_snapshot`]).
    fn read_slot_glyph(&self, s: &MsdfSlot) -> MsdfGlyph {
        let page = &self.pages[s.page as usize];
        let rgba = copy_rgba_out(&page.pixels, page.width, &s.rect);
        MsdfGlyph {
            rgba,
            width: s.rect.w,
            height: s.rect.h,
            bearing_x: s.bearing_x,
            bearing_y: s.bearing_y,
            advance: s.advance,
            spread: s.spread,
        }
    }

    fn pack(&mut self, glyph: MsdfGlyph) -> MsdfSlot {
        let MsdfGlyph {
            rgba,
            width,
            height,
            bearing_x,
            bearing_y,
            advance,
            spread,
        } = glyph;
        let (page_idx, rect) = self.allocate(width, height);
        let page = &mut self.pages[page_idx];
        copy_rgba_into_rgba(&mut page.pixels, page.width, &rect, &rgba);
        merge_dirty(&mut page.dirty, rect);
        MsdfSlot {
            page: page_idx as u32,
            rect,
            bearing_x,
            bearing_y,
            advance,
            spread,
        }
    }

    fn allocate(&mut self, w: u32, h: u32) -> (usize, MsdfRect) {
        for (i, page) in self.pages.iter_mut().enumerate() {
            if let Some(rect) = page.allocate(w, h) {
                page.last_used = self.frame;
                return (i, rect);
            }
        }
        // At the page budget, recycle the least-recently-used page that
        // fits the glyph and wasn't referenced this frame (instances
        // recorded this frame point at its UVs). Evicted glyphs that
        // are still on screen re-rasterize on next frame's draw path.
        if self.pages.len() >= self.page_budget
            && let Some(i) = self
                .pages
                .iter()
                .enumerate()
                .filter(|(_, p)| {
                    p.last_used + self.lru_protection_window <= self.frame
                        && p.width >= w
                        && p.height >= h
                })
                .min_by_key(|(_, p)| p.last_used)
                .map(|(i, _)| i)
        {
            self.recycle_page(i);
            let page = &mut self.pages[i];
            let rect = page.allocate(w, h).expect("recycled page fits the glyph");
            page.last_used = self.frame;
            return (i, rect);
        }
        // Grow: past the budget this is the soft-cap escape hatch for
        // frames whose live glyph set genuinely exceeds the budget.
        let new_w = PAGE_SIZE.max(w.next_power_of_two());
        let new_h = PAGE_SIZE.max(h.next_power_of_two());
        let mut page = MsdfAtlasPage::new(new_w, new_h);
        page.last_used = self.frame;
        let rect = page
            .allocate(w, h)
            .expect("freshly-sized page must fit a glyph");
        self.pages.push(page);
        (self.pages.len() - 1, rect)
    }

    /// Reset a page for reuse: forget its glyphs, zero its pixels, and
    /// mark the whole page dirty so backends re-upload their mirror.
    /// The page keeps its index and dimensions, so backend GPU page
    /// arrays stay valid with no API involvement. `Empty` entries
    /// (whitespace advances) occupy no atlas space and are kept.
    fn recycle_page(&mut self, index: usize) {
        let page_idx = index as u32;
        self.map
            .retain(|_, e| !matches!(e, MsdfEntry::Slot(s) if s.page == page_idx));
        let page = &mut self.pages[index];
        page.pixels.fill(0);
        page.shelves.clear();
        page.dirty = Some(MsdfRect {
            x: 0,
            y: 0,
            w: page.width,
            h: page.height,
        });
    }

    #[cfg(test)]
    fn set_page_budget_for_tests(&mut self, budget: usize) {
        self.page_budget = budget;
    }
}

fn copy_rgba_into_rgba(dst: &mut [u8], stride_pixels: u32, rect: &MsdfRect, src_rgba: &[u8]) {
    let dst_row_bytes = stride_pixels as usize * MSDF_BYTES_PER_PIXEL as usize;
    let src_row_bytes = rect.w as usize * 4;
    for row in 0..rect.h as usize {
        let dst_off = (rect.y as usize + row) * dst_row_bytes
            + rect.x as usize * MSDF_BYTES_PER_PIXEL as usize;
        let src_off = row * src_row_bytes;
        let row_bytes = rect.w as usize * 4;
        dst[dst_off..dst_off + row_bytes].copy_from_slice(&src_rgba[src_off..src_off + row_bytes]);
    }
}

/// Copy a `rect`-sized region out of a page's RGBA8 buffer into a tight
/// `w*h*4` Vec. Inverse of [`copy_rgba_into_rgba`].
fn copy_rgba_out(src: &[u8], stride_pixels: u32, rect: &MsdfRect) -> Vec<u8> {
    let src_row_bytes = stride_pixels as usize * MSDF_BYTES_PER_PIXEL as usize;
    let row_bytes = rect.w as usize * 4;
    let mut out = Vec::with_capacity(row_bytes * rect.h as usize);
    for row in 0..rect.h as usize {
        let off = (rect.y as usize + row) * src_row_bytes
            + rect.x as usize * MSDF_BYTES_PER_PIXEL as usize;
        out.extend_from_slice(&src[off..off + row_bytes]);
    }
    out
}

fn merge_dirty(dirty: &mut Option<MsdfRect>, rect: MsdfRect) {
    *dirty = Some(match *dirty {
        None => rect,
        Some(prev) => {
            let x = prev.x.min(rect.x);
            let y = prev.y.min(rect.y);
            let r = prev.right().max(rect.right());
            let b = prev.bottom().max(rect.bottom());
            MsdfRect {
                x,
                y,
                w: r - x,
                h: b - y,
            }
        }
    });
}

// The fixture face is Inter, so these tests only build when the `inter`
// font feature is on (it is in the default set).
#[cfg(all(test, feature = "inter"))]
mod tests {
    use super::*;

    fn test_face() -> ttf_parser::Face<'static> {
        ttf_parser::Face::parse(damascene_fonts::INTER_VARIABLE, 0).unwrap()
    }

    fn fake_font_id(seed: u32) -> fontdb::ID {
        let mut db = fontdb::Database::new();
        db.load_font_data(damascene_fonts::INTER_VARIABLE.to_vec());
        let id = db.faces().next().expect("test fontdb has Inter").id;
        let _ = seed;
        id
    }

    fn key(face: &Face<'_>, ch: char) -> MsdfGlyphKey {
        MsdfGlyphKey {
            font: fake_font_id(0),
            glyph_id: face.glyph_index(ch).unwrap().0,
            weight: 0,
        }
    }

    #[test]
    fn ensure_inserts_glyph_and_marks_dirty() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        let slot = atlas.ensure(key(&face, 'A'), &face).expect("slot");
        assert_eq!(slot.page, 0);
        assert!(slot.rect.w > 0 && slot.rect.h > 0);
        let dirty = atlas.take_dirty();
        assert_eq!(dirty.len(), 1);
        assert!(atlas.take_dirty().is_empty());
    }

    #[test]
    fn ensure_many_matches_per_glyph_ensure() {
        let face = test_face();
        // Mix of outline glyphs, a duplicate, and whitespace (no
        // outline) — ensure_many must handle all three like ensure.
        let chars = ['A', 'B', 'g', 'A', ' ', '@'];
        let keys: Vec<MsdfGlyphKey> = chars.iter().map(|&c| key(&face, c)).collect();

        let mut batched = MsdfAtlas::default();
        batched.ensure_many(&keys, &face);

        let mut serial = MsdfAtlas::default();
        for &k in &keys {
            serial.ensure(k, &face);
        }

        // Every distinct key resolves identically (outline → same-sized
        // slot, whitespace → None) under both paths.
        for &k in &keys {
            match (batched.slot(k), serial.slot(k)) {
                (Some(b), Some(s)) => {
                    assert_eq!((b.rect.w, b.rect.h), (s.rect.w, s.rect.h));
                    assert_eq!(b.advance, s.advance);
                }
                (None, None) => assert_eq!(batched.advance(k), serial.advance(k)),
                (b, s) => panic!("residency mismatch for {k:?}: {b:?} vs {s:?}"),
            }
        }
    }

    #[test]
    fn snapshot_round_trip_reproduces_residency() {
        let face = test_face();
        let font = fake_font_id(0);
        let chars = ['A', 'g', '@', ' '];

        // Source atlas: generate the glyphs the normal way.
        let mut src = MsdfAtlas::default();
        for &c in &chars {
            src.ensure(key(&face, c), &face);
        }
        // Token is a fixed stand-in for a stable font identity.
        let bytes = src.export_snapshot(|id| (id == font).then_some(42));

        // Destination atlas: import the snapshot, no live generation.
        let mut dst = MsdfAtlas::default();
        let packed = dst
            .import_snapshot(&bytes, |t| (t == 42).then_some(font))
            .expect("imports");
        assert_eq!(packed, 3, "A/g/@ are outlines; space is empty");

        for &c in &chars {
            let k = key(&face, c);
            match (src.slot(k), dst.slot(k)) {
                (Some(a), Some(b)) => {
                    assert_eq!((a.rect.w, a.rect.h), (b.rect.w, b.rect.h));
                    assert_eq!(
                        (a.bearing_x, a.bearing_y, a.advance, a.spread),
                        (b.bearing_x, b.bearing_y, b.advance, b.spread)
                    );
                    // Pixels survive the page→blob→page round trip intact.
                    let pa = copy_rgba_out(
                        &src.pages[a.page as usize].pixels,
                        src.pages[a.page as usize].width,
                        &a.rect,
                    );
                    let pb = copy_rgba_out(
                        &dst.pages[b.page as usize].pixels,
                        dst.pages[b.page as usize].width,
                        &b.rect,
                    );
                    assert_eq!(pa, pb, "MTSDF bytes differ after round trip for {c:?}");
                }
                (None, None) => assert_eq!(src.advance(k), dst.advance(k)),
                (a, b) => panic!("residency mismatch for {c:?}: {a:?} vs {b:?}"),
            }
        }
    }

    #[test]
    fn snapshot_import_rejects_param_mismatch() {
        let face = test_face();
        let font = fake_font_id(0);
        let mut src = MsdfAtlas::default(); // base_em 48
        src.ensure(key(&face, 'A'), &face);
        let bytes = src.export_snapshot(|_| Some(1));

        let mut dst = MsdfAtlas::new(32, 4.0); // different params
        assert!(
            dst.import_snapshot(&bytes, |_| Some(font)).is_err(),
            "a 48-em snapshot must not load into a 32-em atlas"
        );
        assert!(
            dst.slot(key(&face, 'A')).is_none(),
            "nothing imported on reject"
        );
    }

    #[test]
    fn ensure_many_skips_resident_keys() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        let a = key(&face, 'A');
        atlas.ensure(a, &face).expect("slot");
        atlas.take_dirty();
        // 'A' already resident; only 'B' is new work.
        atlas.ensure_many(&[a, key(&face, 'B')], &face);
        let dirty = atlas.take_dirty();
        assert_eq!(dirty.len(), 1, "only the new glyph should dirty a page");
    }

    #[test]
    fn ensure_is_idempotent() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        let s1 = atlas.ensure(key(&face, 'A'), &face).unwrap();
        atlas.take_dirty();
        let s2 = atlas.ensure(key(&face, 'A'), &face).unwrap();
        assert_eq!(s1, s2);
        assert!(atlas.take_dirty().is_empty());
    }

    #[test]
    fn whitespace_returns_none_but_caches_advance() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        let space_key = key(&face, ' ');
        assert!(atlas.ensure(space_key, &face).is_none());
        let advance = atlas.advance(space_key).expect("space advance cached");
        assert!(advance > 0.0);
    }

    #[test]
    fn distinct_weights_get_distinct_slots_and_bitmaps() {
        // Same glyph at two wght instances: the atlas must cache them
        // separately, and a heavier instance must actually produce
        // different MTSDF bytes (this is the regression guard for the
        // "every weight rasterized as Regular" bug).
        use crate::text::msdf::apply_weight_variation;
        let font = fake_font_id(0);
        let glyph_id = test_face().glyph_index('H').unwrap().0;
        let mut atlas = MsdfAtlas::default();

        let mut slots = Vec::new();
        for weight in [400u16, 700u16] {
            let mut face = test_face();
            let applied = apply_weight_variation(&mut face, weight);
            assert_eq!(applied, weight, "Inter Variable has a wght axis");
            let key = MsdfGlyphKey {
                font,
                glyph_id,
                weight: applied,
            };
            slots.push(atlas.ensure(key, &face).expect("slot"));
        }
        assert_ne!(slots[0].rect, slots[1].rect, "separate atlas slots");
        let px_of = |s: &MsdfSlot| {
            copy_rgba_out(
                &atlas.pages[s.page as usize].pixels,
                atlas.pages[s.page as usize].width,
                &s.rect,
            )
        };
        assert!(
            slots[0].rect.w != slots[1].rect.w || px_of(&slots[0]) != px_of(&slots[1]),
            "regular and bold instances must rasterize different outlines"
        );
    }

    #[test]
    fn static_weight_normalizes_to_default_bucket() {
        // A face without a wght axis must collapse every requested
        // weight to bucket 0 so static fonts don't duplicate rasters.
        // Inter *has* the axis, so simulate the static case via
        // weight 0 (the "already default" request) — the helper must
        // pass it through unchanged without touching the face.
        use crate::text::msdf::apply_weight_variation;
        let mut face = test_face();
        assert_eq!(apply_weight_variation(&mut face, 0), 0);
    }

    #[test]
    fn distinct_glyphs_get_distinct_slots() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        let a = atlas.ensure(key(&face, 'A'), &face).unwrap();
        let b = atlas.ensure(key(&face, 'B'), &face).unwrap();
        assert_ne!(a.rect, b.rect);
    }

    #[test]
    fn allocation_recycles_lru_page_at_budget() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        atlas.set_page_budget_for_tests(1);
        let key_a = key(&face, 'A');
        atlas.ensure(key_a, &face).expect("slot");

        // Page 0 was referenced this frame, so a full-page request must
        // grow past the budget rather than clear glyphs whose UVs may
        // already be recorded in this frame's instances.
        let (grown, _) = atlas.allocate(PAGE_SIZE, PAGE_SIZE);
        assert_eq!(grown, 1);
        assert_eq!(atlas.pages().len(), 2);
        assert!(atlas.slot(key_a).is_some());

        // Next frame both pages are stale; the same request recycles
        // the LRU page in place instead of growing further.
        atlas.take_dirty();
        let (recycled, rect) = atlas.allocate(PAGE_SIZE, PAGE_SIZE);
        assert_eq!(recycled, 0);
        assert_eq!(atlas.pages().len(), 2);
        assert_eq!((rect.x, rect.y), (0, 0));
        assert!(atlas.slot(key_a).is_none());
        let dirty = atlas.take_dirty();
        assert!(
            dirty
                .iter()
                .any(|(i, r)| *i == 0 && r.w == PAGE_SIZE && r.h == PAGE_SIZE),
            "expected a full-page dirty rect on page 0, got {dirty:?}"
        );
    }

    #[test]
    fn touch_protects_pages_from_recycling() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        atlas.set_page_budget_for_tests(1);
        let key_a = key(&face, 'A');
        atlas.ensure(key_a, &face).expect("slot");
        atlas.take_dirty();
        // 'A' is drawn again this frame: touch re-stamps its page, so
        // the full-page request must grow rather than recycle it out
        // from under the live glyph.
        assert!(atlas.touch(key_a).is_some());
        let (idx, _) = atlas.allocate(PAGE_SIZE, PAGE_SIZE);
        assert_eq!(idx, 1);
        assert!(atlas.slot(key_a).is_some());
    }

    #[test]
    fn lru_protection_window_spans_multiple_flush_ticks() {
        // Issue #94: with N runners sharing one atlas, the frame
        // counter ticks once per *runner flush*, so a page referenced
        // by runner A's in-flight frame is one tick stale by the time
        // runner B prepares. A protection window of N must keep it.
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        atlas.set_page_budget_for_tests(1);
        atlas.set_lru_protection_window(2);
        let key_a = key(&face, 'A');
        atlas.ensure(key_a, &face).expect("slot");

        // One flush tick (runner A's). Under the default window the
        // page would now be recyclable; with window 2 it must survive
        // runner B's allocation pressure.
        atlas.take_dirty();
        let (idx, _) = atlas.allocate(PAGE_SIZE, PAGE_SIZE);
        assert_eq!(idx, 1, "page must be protected for a second tick");
        assert!(atlas.slot(key_a).is_some());

        // Two ticks later the page is genuinely stale and recycles.
        atlas.take_dirty();
        atlas.take_dirty();
        let (idx, _) = atlas.allocate(PAGE_SIZE, PAGE_SIZE);
        assert!(idx <= 1, "stale page recycles in place");
        assert_eq!(atlas.pages().len(), 3 - 1, "no further growth");
    }

    #[test]
    fn recycling_preserves_empty_advance_entries() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        atlas.set_page_budget_for_tests(1);
        let space = key(&face, ' ');
        let key_a = key(&face, 'A');
        atlas.ensure(space, &face);
        atlas.ensure(key_a, &face).expect("slot");
        atlas.take_dirty();
        // Recycle page 0: the whitespace advance survives (it occupies
        // no atlas space), only the packed glyph is forgotten.
        let (idx, _) = atlas.allocate(PAGE_SIZE, PAGE_SIZE);
        assert_eq!(idx, 0);
        assert!(atlas.slot(key_a).is_none());
        assert!(atlas.advance(space).is_some());
    }

    #[test]
    fn shelf_packer_fits_a_typical_run_in_one_page() {
        let face = test_face();
        let mut atlas = MsdfAtlas::default();
        let font = fake_font_id(0);
        for ch in "The quick brown fox jumps over the lazy dog 0123456789".chars() {
            atlas.ensure(
                MsdfGlyphKey {
                    font,
                    glyph_id: face.glyph_index(ch).map(|g| g.0).unwrap_or(0),
                    weight: 0,
                },
                &face,
            );
        }
        assert_eq!(atlas.pages().len(), 1);
    }
}