Skip to main content

emblema_text/
atlas.rs

1//! Packing rasterized glyph coverage into one texture.
2//!
3//! # What this does and does not do
4//!
5//! It takes coverage bitmaps and answers where in a texture each one sits. It
6//! does not rasterize them: turning an outline into coverage needs a font
7//! parser, and font parsing is out of scope here — bring `swash` or
8//! `ttf-parser` and hand the result over. That boundary is what lets the atlas
9//! be tested with no font anywhere in the tree, against bitmaps whose contents
10//! are known exactly.
11//!
12//! # Shelf packing
13//!
14//! Glyphs are packed into horizontal shelves: a new glyph goes on the first
15//! shelf tall enough for it with room to its right, and starts a new shelf
16//! otherwise. That wastes the space above short glyphs on a tall shelf, which
17//! a skyline or a max-rects packer would recover.
18//!
19//! It is the right trade for glyphs specifically. A run of text is a stream of
20//! boxes of very similar height, so shelves fill densely in practice, and the
21//! packer runs once per glyph per size rather than per frame. A packer with
22//! better worst-case density would cost more per insertion and more to read for
23//! a gain that the input's own shape mostly removes.
24//!
25//! # Making room
26//!
27//! Shelves cannot free a glyph in place: a hole in the middle of one is not
28//! reusable by anything but a glyph of the same height, and tracking holes is
29//! most of what makes a general packer expensive. So room is made by compacting
30//! — keeping the glyphs this frame has asked for, discarding the rest, and
31//! repacking from scratch.
32//!
33//! That is a heavier operation than freeing one entry and a much simpler one to
34//! be sure of, and its cost is bounded by how often it can happen: it runs only
35//! when an insertion would otherwise fail, and it cannot run twice in a frame
36//! without the second one failing outright, because everything left after the
37//! first is something this frame needs. Text that genuinely needs more than an
38//! atlas holds is a case for a second page, not for a cleverer packer.
39
40use std::collections::HashMap;
41
42/// Where a glyph sits in the atlas, in texels.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub struct AtlasRect {
45    pub x: u32,
46    pub y: u32,
47    pub width: u32,
48    pub height: u32,
49}
50
51impl AtlasRect {
52    /// The rectangle in texture coordinates, from zero to one.
53    ///
54    /// Returned as `[left, top, right, bottom]`, with V running downward to
55    /// match the row order the texture was uploaded in.
56    pub fn uv(&self, atlas: u32) -> [f32; 4] {
57        let scale = 1.0 / atlas as f32;
58        [
59            self.x as f32 * scale,
60            self.y as f32 * scale,
61            (self.x + self.width) as f32 * scale,
62            (self.y + self.height) as f32 * scale,
63        ]
64    }
65}
66
67/// What identifies a glyph in the atlas.
68///
69/// A font identifier alongside the glyph index, because glyph indices are
70/// per font and two fonts will disagree about what index seven means. Size is
71/// in whole pixels: a cache keyed by a float would miss on values that differ
72/// only in their last bit, and rasterizing at a rounded size is what a caller
73/// is doing anyway.
74///
75/// `subpixel` is the fractional position the coverage was rasterized at, as
76/// the caller buckets it: the same glyph a quarter of a pixel along is
77/// different coverage, and Impeller keys its atlas the same way, by a quarter
78/// across and a quarter down. The atlas only tells buckets apart; what one
79/// means, and placing the glyph to match, is the caller's. Zero for a glyph
80/// rasterized on a whole pixel.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
82pub struct GlyphKey {
83    pub font: u64,
84    pub glyph: u16,
85    pub size: u16,
86    pub subpixel: u8,
87}
88
89impl GlyphKey {
90    /// A glyph rasterized on a whole pixel.
91    pub fn new(font: u64, glyph: u16, size: u16) -> Self {
92        Self {
93            font,
94            glyph,
95            size,
96            subpixel: 0,
97        }
98    }
99
100    /// The same glyph at subpixel bucket `subpixel`.
101    pub fn at_subpixel(self, subpixel: u8) -> Self {
102        Self { subpixel, ..self }
103    }
104}
105
106/// A rasterized glyph, as a caller supplies it.
107#[derive(Debug, Clone, PartialEq)]
108pub struct Coverage {
109    pub width: u32,
110    pub height: u32,
111    /// One byte per texel, row-major from the top, tightly packed.
112    pub texels: Vec<u8>,
113}
114
115impl Coverage {
116    /// Whether the dimensions and the buffer agree.
117    pub fn is_consistent(&self) -> bool {
118        self.texels.len() as u64 == self.width as u64 * self.height as u64
119    }
120}
121
122/// Why a glyph could not be added.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum AtlasError {
125    /// The coverage's dimensions and its buffer disagree.
126    Inconsistent,
127    /// The glyph does not fit, even in an empty atlas.
128    TooLarge,
129    /// The atlas is full.
130    ///
131    /// Distinct from `TooLarge` because the remedies differ: this one is fixed
132    /// by evicting or by growing, and that one never is.
133    Full,
134}
135
136impl std::fmt::Display for AtlasError {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        match self {
139            Self::Inconsistent => write!(f, "coverage dimensions do not match its buffer"),
140            Self::TooLarge => write!(f, "glyph is larger than the atlas"),
141            Self::Full => write!(f, "atlas is full"),
142        }
143    }
144}
145
146impl std::error::Error for AtlasError {}
147
148/// One shelf: a horizontal band, filled left to right.
149#[derive(Debug, Clone, Copy)]
150struct Shelf {
151    top: u32,
152    height: u32,
153    /// Where the next glyph on this shelf would start.
154    used: u32,
155}
156
157/// A square atlas of glyph coverage, and where each glyph landed.
158///
159/// Holds the texels itself rather than a device texture, so that packing can be
160/// exercised and reasoned about without a GPU. Whoever owns the device uploads
161/// [`Atlas::texels`] when [`Atlas::is_dirty`] says something changed.
162#[derive(Debug)]
163pub struct Atlas {
164    size: u32,
165    texels: Vec<u8>,
166    shelves: Vec<Shelf>,
167    placed: HashMap<GlyphKey, Placed>,
168    frame: u64,
169    dirty: bool,
170    compactions: u64,
171    /// The largest this may grow to.
172    ///
173    /// A caller's to choose, because the ceiling that matters is the device's
174    /// maximum texture size and the atlas has no way to ask.
175    limit: u32,
176    growths: u64,
177}
178
179/// Where a glyph is, and when it was last asked for.
180#[derive(Debug, Clone, Copy)]
181struct Placed {
182    rect: AtlasRect,
183    /// The frame this glyph was most recently inserted in.
184    ///
185    /// Insertion rather than lookup, because insertion is what a caller does
186    /// for every glyph of every run each frame — that is the usage the atlas is
187    /// built around — and marking on lookup would need a unique borrow at the
188    /// point where a run is being recorded from a shared one.
189    used: u64,
190}
191
192/// `len` zeroed texels, every page of them written.
193///
194/// Not `vec![0; len]`, which asks the allocator for zeroed memory and gets
195/// pages the system has only promised: they become the process's as they are
196/// first written, so an atlas's footprint crept up glyph by glyph as text
197/// landed on fresh rows, until it was full. The atlas is uploaded whole, so
198/// the memory is in use from the first upload; what the lazy pages did was
199/// hide that, and a soak reads the creep as a leak. Measured in fl-engine at
200/// 2048 texels a side: 4.1 MB over the first seventy app lifecycles, then
201/// flat. Written once here, the footprint is the atlas's size from the start
202/// and stays there.
203///
204/// `with_capacity` and `resize` rather than a zeroed allocation followed by a
205/// fill: an optimizer may drop a fill of memory it knows to be zero, and a
206/// write it keeps is the point.
207fn resident_zeroed(len: usize) -> Vec<u8> {
208    let texels = vec![0; len];
209    texels
210}
211
212/// Blank texels around each glyph.
213///
214/// One texel is enough and less is not. A linear filter samples a two-by-two
215/// neighborhood, so a glyph flush against its neighbor bleeds that neighbor's
216/// coverage into its own edge under any magnification. The padding is cleared
217/// rather than merely skipped, since the space may hold an evicted glyph.
218const PADDING: u32 = 1;
219
220impl Atlas {
221    /// An empty atlas of `size` by `size` texels.
222    pub fn new(size: u32) -> Self {
223        // Four thousand and ninety-six is the smallest maximum texture size
224        // this project's supported devices are required to offer, so it is the
225        // largest an atlas can grow to without asking. A caller that knows the
226        // device says so.
227        Self::with_limit(size, 4096)
228    }
229
230    /// An atlas that may grow up to `limit` texels on a side.
231    ///
232    /// A limit below the starting size means it never grows, which is a
233    /// reasonable thing to ask for and not an error.
234    pub fn with_limit(size: u32, limit: u32) -> Self {
235        Self {
236            size,
237            texels: resident_zeroed((size as usize) * (size as usize)),
238            shelves: Vec::new(),
239            placed: HashMap::new(),
240            frame: 0,
241            dirty: false,
242            compactions: 0,
243            limit,
244            growths: 0,
245        }
246    }
247
248    pub fn size(&self) -> u32 {
249        self.size
250    }
251
252    /// One byte of coverage per texel, row-major from the top.
253    pub fn texels(&self) -> &[u8] {
254        &self.texels
255    }
256
257    /// Whether anything has been added since [`Atlas::mark_clean`].
258    ///
259    /// The upload is the caller's to make, because only they know which device
260    /// the texture lives on and when in the frame it is safe to write.
261    pub fn is_dirty(&self) -> bool {
262        self.dirty
263    }
264
265    pub fn mark_clean(&mut self) {
266        self.dirty = false;
267    }
268
269    pub fn len(&self) -> usize {
270        self.placed.len()
271    }
272
273    pub fn is_empty(&self) -> bool {
274        self.placed.is_empty()
275    }
276
277    /// Where a glyph sits, if it is present.
278    pub fn get(&self, key: GlyphKey) -> Option<AtlasRect> {
279        self.placed.get(&key).map(|placed| placed.rect)
280    }
281
282    /// Begin a new frame, after which glyphs not inserted again are evictable.
283    ///
284    /// Nothing happens here but a counter moving. A caller that never calls it
285    /// keeps every glyph forever, which is correct rather than a leak: without
286    /// frame boundaries nothing is stale, and an atlas that filled would be
287    /// genuinely out of room.
288    pub fn begin_frame(&mut self) {
289        self.frame += 1;
290    }
291
292    /// How many times room has been made by repacking.
293    ///
294    /// Worth reporting because it is the number that says the atlas is too
295    /// small for the text going through it: a compaction or two as a working
296    /// set settles is ordinary, and one per frame means every frame is
297    /// repacking everything.
298    pub fn compactions(&self) -> u64 {
299        self.compactions
300    }
301
302    /// How many times the atlas has doubled.
303    ///
304    /// Every growth reallocates and repacks everything, so a count that keeps
305    /// climbing says the atlas started far too small. It settles once the
306    /// working set fits.
307    pub fn growths(&self) -> u64 {
308        self.growths
309    }
310
311    /// The largest this may grow to.
312    pub fn limit(&self) -> u32 {
313        self.limit
314    }
315
316    /// Add a glyph, or return where it already is.
317    ///
318    /// Idempotent, so a caller can insert every glyph of every run each frame
319    /// and pay only for the ones that are new. That is the usage this is for:
320    /// deciding what is already present is exactly what an atlas is.
321    pub fn insert(&mut self, key: GlyphKey, coverage: &Coverage) -> Result<AtlasRect, AtlasError> {
322        if let Some(placed) = self.placed.get_mut(&key) {
323            // Refreshed rather than merely found: a glyph asked for again this
324            // frame is one this frame needs, and that is what keeps it from
325            // being the one compaction discards.
326            placed.used = self.frame;
327            return Ok(placed.rect);
328        }
329        if !coverage.is_consistent() {
330            return Err(AtlasError::Inconsistent);
331        }
332        // A glyph with no area still has a position, which is what lets a space
333        // travel through a run like any other glyph rather than being a case
334        // every caller has to remember to skip.
335        if coverage.width == 0 || coverage.height == 0 {
336            let rect = AtlasRect {
337                x: 0,
338                y: 0,
339                width: 0,
340                height: 0,
341            };
342            self.placed.insert(
343                key,
344                Placed {
345                    rect,
346                    used: self.frame,
347                },
348            );
349            return Ok(rect);
350        }
351
352        let rect = match self.allocate(coverage.width, coverage.height) {
353            Ok(rect) => rect,
354            // Only fullness is worth retrying. A glyph larger than the atlas
355            // does not fit an empty one either, and compacting to discover that
356            // would throw away everything for nothing.
357            // Compaction first, then growth. Discarding what nothing has
358            // asked for is far cheaper than doubling, and an atlas that grew
359            // before compacting would keep the memory it had stopped needing.
360            Err(AtlasError::Full) => {
361                if !self.compact() && !self.grow() {
362                    return Err(AtlasError::Full);
363                }
364                self.allocate(coverage.width, coverage.height)?
365            }
366            Err(e) => return Err(e),
367        };
368        for row in 0..coverage.height {
369            let from = (row * coverage.width) as usize;
370            let to = ((rect.y + row) * self.size + rect.x) as usize;
371            self.texels[to..to + coverage.width as usize]
372                .copy_from_slice(&coverage.texels[from..from + coverage.width as usize]);
373        }
374        self.placed.insert(
375            key,
376            Placed {
377                rect,
378                used: self.frame,
379            },
380        );
381        self.dirty = true;
382        Ok(rect)
383    }
384
385    /// Discard glyphs this frame has not asked for, and repack the rest.
386    ///
387    /// Returns whether anything was freed. False means every glyph present is
388    /// one this frame needs, so there is nothing to give up and the atlas is
389    /// genuinely too small for the text going through it.
390    fn compact(&mut self) -> bool {
391        let survivors: Vec<(GlyphKey, Placed)> = self
392            .placed
393            .iter()
394            .filter(|(_, placed)| placed.used == self.frame)
395            .map(|(key, placed)| (*key, *placed))
396            .collect();
397        if survivors.len() == self.placed.len() {
398            return false;
399        }
400
401        // Copied out before anything is cleared, since the atlas's own texels
402        // are the only place a glyph's coverage still exists — the bitmaps a
403        // caller supplied were borrowed and are long gone.
404        let mut coverage: Vec<(GlyphKey, Coverage)> = survivors
405            .iter()
406            .map(|(key, placed)| (*key, self.extract(placed.rect)))
407            .collect();
408        repacking_order(&mut coverage);
409
410        self.texels.fill(0);
411        self.shelves.clear();
412        self.placed.clear();
413        self.compactions += 1;
414        self.dirty = true;
415
416        for (key, coverage) in coverage {
417            // Everything here fitted a moment ago and is being packed into an
418            // atlas holding a subset of what it held then, so this cannot fail.
419            // If it somehow does, dropping the glyph is better than refusing
420            // the insertion that triggered the compaction: the caller will
421            // offer it again next frame.
422            let _ = self.insert(key, &coverage);
423        }
424        true
425    }
426
427    /// Double the atlas and repack everything into it.
428    ///
429    /// Returns whether it grew. False means it is already at its limit, which
430    /// is the point at which being full is genuinely full.
431    ///
432    /// Everything is kept, not only what this frame asked for: growing is what
433    /// happens when nothing was stale, so there is nothing to discard, and a
434    /// glyph dropped here would be re-rasterized by the caller for no reason.
435    fn grow(&mut self) -> bool {
436        if self.size >= self.limit {
437            return false;
438        }
439        let grown = (self.size.saturating_mul(2)).min(self.limit);
440        if grown <= self.size {
441            return false;
442        }
443
444        // Read back before the texels are replaced: the atlas is the only place
445        // a glyph's coverage still exists, the bitmaps a caller supplied having
446        // been borrowed.
447        let mut kept: Vec<(GlyphKey, Coverage)> = self
448            .placed
449            .iter()
450            .map(|(key, placed)| (*key, self.extract(placed.rect)))
451            .collect();
452        repacking_order(&mut kept);
453
454        self.size = grown;
455        self.texels = resident_zeroed((grown as usize) * (grown as usize));
456        self.shelves.clear();
457        self.placed.clear();
458        self.growths += 1;
459        self.dirty = true;
460
461        for (key, coverage) in kept {
462            // Everything fitted the smaller atlas, so it fits this one.
463            let _ = self.insert(key, &coverage);
464        }
465        true
466    }
467
468    /// Read a glyph's coverage back out of the atlas.
469    fn extract(&self, rect: AtlasRect) -> Coverage {
470        let mut texels = Vec::with_capacity((rect.width * rect.height) as usize);
471        for row in 0..rect.height {
472            let from = ((rect.y + row) * self.size + rect.x) as usize;
473            texels.extend_from_slice(&self.texels[from..from + rect.width as usize]);
474        }
475        Coverage {
476            width: rect.width,
477            height: rect.height,
478            texels,
479        }
480    }
481
482    /// Find room for a glyph and reserve it.
483    fn allocate(&mut self, width: u32, height: u32) -> Result<AtlasRect, AtlasError> {
484        let padded_width = width + PADDING;
485        let padded_height = height + PADDING;
486        if padded_width > self.size || padded_height > self.size {
487            return Err(AtlasError::TooLarge);
488        }
489
490        // The first shelf tall enough with room to the right. Shelves are not
491        // sorted by height, so this is a scan; a run of text produces shelves
492        // of similar height and few of them, which is why that is not worth
493        // indexing.
494        for shelf in &mut self.shelves {
495            if shelf.height >= padded_height && self.size - shelf.used >= padded_width {
496                let rect = AtlasRect {
497                    x: shelf.used,
498                    y: shelf.top,
499                    width,
500                    height,
501                };
502                shelf.used += padded_width;
503                return Ok(rect);
504            }
505        }
506
507        let top = self
508            .shelves
509            .last()
510            .map_or(0, |shelf| shelf.top + shelf.height);
511        if top + padded_height > self.size {
512            return Err(AtlasError::Full);
513        }
514        self.shelves.push(Shelf {
515            top,
516            height: padded_height,
517            used: padded_width,
518        });
519        Ok(AtlasRect {
520            x: 0,
521            y: top,
522            width,
523            height,
524        })
525    }
526}
527
528/// The order glyphs are packed in when the atlas is rebuilt.
529///
530/// Tallest first, which is what shelf packing wants: a shelf is as tall as the
531/// tallest glyph on it, so a short glyph landing first opens a shelf that a
532/// tall one cannot use and every tall glyph after it opens another. Width and
533/// then the key break ties, the key because two glyphs of the same size have to
534/// land in the same order every run.
535///
536/// Determinism is the reason this exists at all, not the packing. Both rebuilds
537/// took their order from a `HashMap`, whose iteration order Rust seeds per
538/// process -- so the same text through the same atlas produced a different
539/// layout each run, and, worse, a different *number of compactions*: measured
540/// over four runs of one fixed sequence, three compacted once and one did not
541/// compact at all. Anything asserting on those counters was a coin flip, and
542/// the comment claiming a repack "cannot fail" rested on packing a subset in an
543/// order nothing guaranteed.
544fn repacking_order(glyphs: &mut [(GlyphKey, Coverage)]) {
545    glyphs.sort_by(|(left_key, left), (right_key, right)| {
546        right
547            .height
548            .cmp(&left.height)
549            .then(right.width.cmp(&left.width))
550            .then(left_key.cmp(right_key))
551    });
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    fn solid(width: u32, height: u32, value: u8) -> Coverage {
559        Coverage {
560            width,
561            height,
562            texels: vec![value; (width * height) as usize],
563        }
564    }
565
566    fn key(glyph: u16) -> GlyphKey {
567        GlyphKey::new(1, glyph, 16)
568    }
569
570    #[test]
571    fn a_compaction_lays_its_survivors_out_tallest_first() {
572        // The observable consequence of packing a rebuild in a defined order,
573        // and the reason there is one. Shelves are opened top-down, so if the
574        // tallest survivor is placed first it takes the first shelf, and every
575        // survivor after it sits on that shelf or a later one -- which makes
576        // "sorted by height descending" and "sorted by row" the same ordering.
577        //
578        // What this stands in for is a property that cannot be asserted from
579        // inside a single run. Both rebuilds took their order from a `HashMap`,
580        // seeded per process, so the same text packed differently every run;
581        // measured over five runs of one sequence, the atlas held thirty-six
582        // glyphs three times and thirty-five twice, a glyph lost to the hasher.
583        // That loss is a probabilistic consequence and a test for it would
584        // catch the fault only sometimes, which is worse than not testing it.
585        // This asks the deterministic thing that causes it instead.
586        let mut atlas = Atlas::with_limit(64, 64);
587        let sizes: Vec<(u32, u32)> = (0..40u32)
588            .map(|i| (3 + (i * 7) % 11, 3 + (i * 5) % 13))
589            .collect();
590        for (i, (w, h)) in sizes.iter().enumerate() {
591            let _ = atlas.insert(key(i as u16), &solid(*w, *h, 200));
592        }
593        atlas.begin_frame();
594        let mut survivors = Vec::new();
595        for i in (0..40usize).step_by(2) {
596            let (w, h) = sizes[i];
597            if atlas.insert(key(i as u16), &solid(w, h, 200)).is_ok() {
598                survivors.push((i as u16, h));
599            }
600        }
601        // One more, which needs the room the stale glyphs are holding.
602        let _ = atlas.insert(key(90), &solid(6, 9, 200));
603        assert_eq!(
604            atlas.compactions(),
605            1,
606            "nothing compacted, so this proves nothing"
607        );
608
609        // The tallest survivor is placed first into an empty atlas, so it
610        // opens the first shelf and sits at its top. Nothing stronger holds:
611        // shelves are scanned for the first that fits, so a shorter glyph
612        // placed later can land on an earlier shelf, and rows do go backward.
613        survivors.sort_by(|(left_key, left), (right_key, right)| {
614            right.cmp(left).then(left_key.cmp(right_key))
615        });
616        let (tallest, height) = survivors[0];
617        let rect = atlas
618            .get(key(tallest))
619            .expect("the tallest survivor should have been kept");
620        assert_eq!(
621            rect.y, 0,
622            "glyph {tallest}, the tallest survivor at {height}, landed at row \
623             {} rather than opening the first shelf -- so the rebuild placed \
624             something else before it",
625            rect.y
626        );
627    }
628
629    #[test]
630    fn a_rebuild_packs_the_tallest_glyphs_first() {
631        // A shelf is as tall as the tallest glyph on it, so a short glyph
632        // landing first opens a shelf a tall one cannot use, and every tall
633        // glyph after it opens another. Sorting by height is what makes a
634        // rebuild pack at least as well as the atlas it is rebuilding.
635        let mut glyphs = vec![
636            (key(1), solid(4, 4, 1)),
637            (key(2), solid(4, 20, 2)),
638            (key(3), solid(9, 12, 3)),
639            (key(4), solid(2, 20, 4)),
640        ];
641        repacking_order(&mut glyphs);
642        let heights: Vec<u32> = glyphs.iter().map(|(_, c)| c.height).collect();
643        assert_eq!(heights, vec![20, 20, 12, 4], "tallest first");
644        // Ties broken by width and then by the key, so two glyphs of a size
645        // land in the same order every run rather than in whichever order they
646        // arrived.
647        assert_eq!(
648            (glyphs[0].1.width, glyphs[1].1.width),
649            (4, 2),
650            "a tie in height is broken by width"
651        );
652    }
653
654    #[test]
655    fn an_inserted_glyph_can_be_found_again() {
656        let mut atlas = Atlas::new(64);
657        let rect = atlas.insert(key(1), &solid(8, 10, 200)).expect("insert");
658        assert_eq!(atlas.get(key(1)), Some(rect));
659        assert_eq!(rect.width, 8);
660        assert_eq!(rect.height, 10);
661        assert_eq!(atlas.len(), 1);
662    }
663
664    #[test]
665    fn inserting_the_same_glyph_twice_returns_the_same_place() {
666        // The usage this exists for: a caller inserts every glyph of every run
667        // each frame and pays only for the new ones. A second insertion that
668        // allocated again would fill the atlas in proportion to frames drawn
669        // rather than to distinct glyphs.
670        let mut atlas = Atlas::new(64);
671        let first = atlas.insert(key(1), &solid(8, 10, 200)).expect("first");
672        let second = atlas.insert(key(1), &solid(8, 10, 200)).expect("second");
673        assert_eq!(first, second);
674        assert_eq!(atlas.len(), 1);
675    }
676
677    #[test]
678    fn glyphs_differing_only_in_font_or_size_are_distinct() {
679        // Glyph indices are per font, and a glyph rasterized at one size, or a
680        // quarter of a pixel along, is not the same picture as at another. A
681        // key that ignored any of them would serve one glyph's coverage for
682        // another's.
683        let mut atlas = Atlas::new(64);
684        let a = atlas.insert(key(1), &solid(8, 8, 255)).expect("a");
685        let b = atlas
686            .insert(GlyphKey { font: 2, ..key(1) }, &solid(8, 8, 255))
687            .expect("b");
688        let c = atlas
689            .insert(GlyphKey { size: 32, ..key(1) }, &solid(8, 8, 255))
690            .expect("c");
691        let d = atlas
692            .insert(key(1).at_subpixel(2), &solid(8, 8, 255))
693            .expect("d");
694        assert_ne!(a, b);
695        assert_ne!(a, c);
696        assert_ne!(b, c);
697        assert_ne!(a, d);
698        assert_eq!(atlas.len(), 4);
699        assert_eq!(key(1).at_subpixel(0), key(1));
700        assert_eq!(GlyphKey::new(1, 1, 16), key(1));
701    }
702
703    #[test]
704    fn coverage_lands_where_the_rectangle_says() {
705        let mut atlas = Atlas::new(16);
706        // A bitmap with a distinct value per texel, so a transposed or
707        // off-by-one copy produces a different atlas rather than the same one.
708        let coverage = Coverage {
709            width: 3,
710            height: 2,
711            texels: vec![10, 20, 30, 40, 50, 60],
712        };
713        let rect = atlas.insert(key(1), &coverage).expect("insert");
714        for row in 0..coverage.height {
715            for column in 0..coverage.width {
716                let at = ((rect.y + row) * atlas.size() + rect.x + column) as usize;
717                assert_eq!(
718                    atlas.texels()[at],
719                    coverage.texels[(row * coverage.width + column) as usize],
720                    "texel ({column}, {row}) landed wrong"
721                );
722            }
723        }
724    }
725
726    #[test]
727    fn glyphs_do_not_touch_each_other() {
728        // A linear filter samples a neighborhood, so a glyph flush against its
729        // neighbor bleeds that neighbor's coverage into its own edge. This
730        // asserts the gap rather than the filtering, since the filtering is the
731        // device's business.
732        let mut atlas = Atlas::new(64);
733        let a = atlas.insert(key(1), &solid(8, 8, 255)).expect("a");
734        let b = atlas.insert(key(2), &solid(8, 8, 255)).expect("b");
735        assert!(
736            b.x >= a.x + a.width + PADDING || b.y >= a.y + a.height + PADDING,
737            "{a:?} and {b:?} are adjacent"
738        );
739    }
740
741    #[test]
742    fn a_second_shelf_starts_below_the_first() {
743        let mut atlas = Atlas::new(32);
744        // Three glyphs eleven wide with padding do not fit across thirty-two.
745        let first = atlas.insert(key(1), &solid(11, 6, 255)).expect("first");
746        let second = atlas.insert(key(2), &solid(11, 6, 255)).expect("second");
747        let third = atlas.insert(key(3), &solid(11, 6, 255)).expect("third");
748        assert_eq!(first.y, second.y, "the first two share a shelf");
749        assert!(third.y > first.y, "the third started a new shelf");
750        assert_eq!(third.x, 0, "a new shelf starts at the left edge");
751    }
752
753    #[test]
754    fn a_short_glyph_reuses_a_taller_shelf() {
755        // The trade shelf packing makes: the space above a short glyph on a
756        // tall shelf is lost, and in exchange placement is a scan of a few
757        // entries. A run of text is boxes of similar height, which is what
758        // keeps that loss small.
759        let mut atlas = Atlas::new(64);
760        let tall = atlas.insert(key(1), &solid(8, 20, 255)).expect("tall");
761        let short = atlas.insert(key(2), &solid(8, 4, 255)).expect("short");
762        assert_eq!(tall.y, short.y, "the short glyph opened a new shelf");
763    }
764
765    #[test]
766    fn a_glyph_larger_than_the_atlas_is_reported_as_such() {
767        // Distinct from being full, because the remedies differ: growing or
768        // evicting fixes one and never fixes the other.
769        let mut atlas = Atlas::new(16);
770        assert_eq!(
771            atlas.insert(key(1), &solid(16, 16, 255)),
772            Err(AtlasError::TooLarge),
773            "a glyph needing padding beyond the edge should not fit"
774        );
775        assert_eq!(
776            atlas.insert(key(2), &solid(64, 4, 255)),
777            Err(AtlasError::TooLarge)
778        );
779    }
780
781    #[test]
782    fn a_full_atlas_says_so_rather_than_overwriting() {
783        let mut atlas = fixed(16);
784        let mut inserted = 0;
785        for glyph in 0..64u16 {
786            match atlas.insert(key(glyph), &solid(6, 6, 255)) {
787                Ok(_) => inserted += 1,
788                Err(e) => {
789                    assert_eq!(e, AtlasError::Full);
790                    break;
791                }
792            }
793        }
794        assert!(inserted > 0, "nothing fit at all");
795        assert!(inserted < 64, "everything fit, so fullness went untested");
796
797        // And every glyph that did fit is still where it was put: running out
798        // of room must not disturb what is already there.
799        let mut seen = std::collections::HashSet::new();
800        for glyph in 0..inserted as u16 {
801            let rect = atlas.get(key(glyph)).expect("still present");
802            assert!(seen.insert((rect.x, rect.y)), "two glyphs share a place");
803        }
804    }
805
806    #[test]
807    fn a_glyph_with_no_area_is_placed_rather_than_refused() {
808        // A space has a position in a run like any other glyph, and making
809        // every caller remember to skip it is how one of them forgets.
810        let mut atlas = Atlas::new(16);
811        let rect = atlas.insert(key(1), &solid(0, 0, 0)).expect("insert");
812        assert_eq!(rect.width, 0);
813        assert!(!atlas.is_dirty(), "an empty glyph changed no texels");
814    }
815
816    #[test]
817    fn inconsistent_coverage_is_refused() {
818        let mut atlas = Atlas::new(16);
819        let bad = Coverage {
820            width: 4,
821            height: 4,
822            texels: vec![0; 3],
823        };
824        assert_eq!(atlas.insert(key(1), &bad), Err(AtlasError::Inconsistent));
825    }
826
827    #[test]
828    fn the_dirty_flag_tracks_whether_an_upload_is_owed() {
829        let mut atlas = Atlas::new(32);
830        assert!(!atlas.is_dirty(), "an empty atlas owes no upload");
831        atlas.insert(key(1), &solid(4, 4, 255)).expect("insert");
832        assert!(atlas.is_dirty());
833        atlas.mark_clean();
834        assert!(!atlas.is_dirty());
835        // A repeat insertion changes no texels, so it owes nothing either.
836        atlas.insert(key(1), &solid(4, 4, 255)).expect("again");
837        assert!(
838            !atlas.is_dirty(),
839            "a glyph already present dirtied the atlas"
840        );
841    }
842
843    /// An atlas that cannot grow, for the behaviors that only appear at the
844    /// limit: compaction, and being genuinely full.
845    fn fixed(size: u32) -> Atlas {
846        Atlas::with_limit(size, size)
847    }
848
849    /// Insert glyphs until the atlas grows, returning how many went in.
850    ///
851    /// The counterpart of `fill` for an atlas that can grow, where "until it
852    /// refuses" never arrives until the limit.
853    fn fill_until_growth(atlas: &mut Atlas, from: u16) -> u16 {
854        let mut glyph = from;
855        while atlas.growths() == 0 {
856            atlas
857                .insert(key(glyph), &solid(6, 6, 255))
858                .unwrap_or_else(|e| panic!("insert {glyph}: {e}"));
859            glyph += 1;
860            assert!(glyph < from + 200, "the atlas never grew");
861        }
862        glyph - from
863    }
864
865    /// Fill an atlas until it refuses, returning how many glyphs fitted.
866    fn fill(atlas: &mut Atlas, from: u16) -> u16 {
867        let mut glyph = from;
868        while atlas.insert(key(glyph), &solid(6, 6, 255)).is_ok() {
869            glyph += 1;
870            assert!(glyph < from + 200, "the atlas never filled");
871        }
872        glyph - from
873    }
874
875    #[test]
876    fn a_full_atlas_makes_room_for_what_the_new_frame_needs() {
877        let mut atlas = fixed(32);
878        let fitted = fill(&mut atlas, 0);
879        assert!(
880            fitted > 2,
881            "only {fitted} glyphs fitted; too few to evict from"
882        );
883
884        // A new frame, and nothing from the old one asked for again. Everything
885        // present is now stale, so an insertion that would have failed makes
886        // room instead.
887        atlas.begin_frame();
888        let rect = atlas
889            .insert(key(500), &solid(6, 6, 255))
890            .expect("a stale atlas should make room");
891        assert_eq!(rect.width, 6);
892        assert_eq!(atlas.compactions(), 1);
893        assert_eq!(atlas.len(), 1, "the stale glyphs were not discarded");
894    }
895
896    #[test]
897    fn compaction_keeps_the_glyphs_this_frame_asked_for() {
898        let mut atlas = fixed(32);
899        let fitted = fill(&mut atlas, 0);
900
901        // A new frame that asks for two of the old glyphs before filling up.
902        // Those two are what this frame needs; the rest are not.
903        atlas.begin_frame();
904        let kept: Vec<u16> = vec![0, 1];
905        for glyph in &kept {
906            atlas
907                .insert(key(*glyph), &solid(6, 6, 255))
908                .expect("refresh");
909        }
910        atlas
911            .insert(key(500), &solid(6, 6, 255))
912            .expect("should make room");
913
914        assert_eq!(atlas.compactions(), 1);
915        for glyph in &kept {
916            assert!(
917                atlas.get(key(*glyph)).is_some(),
918                "glyph {glyph} was asked for this frame and discarded anyway"
919            );
920        }
921        assert!(
922            atlas.get(key(fitted - 1)).is_none(),
923            "a glyph nothing asked for survived"
924        );
925    }
926
927    #[test]
928    fn a_glyph_kept_through_compaction_keeps_its_coverage() {
929        // The coverage a caller supplied was borrowed and is long gone, so
930        // repacking has to read it back out of the atlas. Getting that wrong
931        // gives a glyph that is present, addressable, and blank.
932        let mut atlas = fixed(32);
933        let distinct = Coverage {
934            width: 3,
935            height: 2,
936            texels: vec![11, 22, 33, 44, 55, 66],
937        };
938        atlas.insert(key(0), &distinct).expect("insert");
939        fill(&mut atlas, 1);
940
941        atlas.begin_frame();
942        atlas.insert(key(0), &distinct).expect("refresh");
943        atlas
944            .insert(key(500), &solid(6, 6, 255))
945            .expect("should make room");
946
947        let rect = atlas.get(key(0)).expect("survived");
948        let mut got = Vec::new();
949        for row in 0..rect.height {
950            let from = ((rect.y + row) * atlas.size() + rect.x) as usize;
951            got.extend_from_slice(&atlas.texels()[from..from + rect.width as usize]);
952        }
953        assert_eq!(got, distinct.texels, "coverage was lost in repacking");
954    }
955
956    #[test]
957    fn an_atlas_full_of_glyphs_this_frame_needs_reports_full() {
958        // Compaction can free only what nothing has asked for, so an atlas
959        // whose every glyph is in use this frame is genuinely out of room.
960        // Saying so is the honest answer; the remedy is a second page, and
961        // pretending otherwise would evict a glyph about to be drawn.
962        let mut atlas = fixed(32);
963        let fitted = fill(&mut atlas, 0);
964        atlas.begin_frame();
965        for glyph in 0..fitted {
966            atlas
967                .insert(key(glyph), &solid(6, 6, 255))
968                .expect("refresh");
969        }
970        assert_eq!(
971            atlas.insert(key(500), &solid(6, 6, 255)),
972            Err(AtlasError::Full)
973        );
974        assert_eq!(
975            atlas.compactions(),
976            0,
977            "it repacked without freeing anything"
978        );
979    }
980
981    #[test]
982    fn a_glyph_too_large_is_not_worth_compacting_for() {
983        // Nothing an empty atlas cannot hold is made to fit by emptying it, and
984        // compacting to find that out throws away every glyph for nothing.
985        let mut atlas = fixed(32);
986        fill(&mut atlas, 0);
987        let before = atlas.len();
988        atlas.begin_frame();
989        assert_eq!(
990            atlas.insert(key(500), &solid(64, 64, 255)),
991            Err(AtlasError::TooLarge)
992        );
993        assert_eq!(atlas.compactions(), 0);
994        assert_eq!(atlas.len(), before, "the atlas was emptied for nothing");
995    }
996
997    #[test]
998    fn an_atlas_that_is_never_told_about_frames_keeps_everything() {
999        // Without frame boundaries nothing is stale, so a full atlas is
1000        // genuinely full. That is correct rather than a leak: a caller that
1001        // never says a frame ended has never said any glyph stopped mattering.
1002        let mut atlas = fixed(32);
1003        let fitted = fill(&mut atlas, 0);
1004        assert_eq!(
1005            atlas.insert(key(500), &solid(6, 6, 255)),
1006            Err(AtlasError::Full)
1007        );
1008        assert_eq!(atlas.len(), fitted as usize);
1009        assert_eq!(atlas.compactions(), 0);
1010    }
1011
1012    #[test]
1013    fn an_atlas_with_nothing_stale_grows_rather_than_refusing() {
1014        // Everything present was asked for this frame, so compaction has
1015        // nothing to free. Growing is what keeps a run of any length one draw;
1016        // a second page would make it two, which is the property the vertex
1017        // format exists to provide.
1018        // No frame boundary, so nothing is ever stale and compaction can free
1019        // nothing. Growing is the only way forward, which is the ordering this
1020        // pins as well as the growth.
1021        let mut atlas = Atlas::with_limit(32, 128);
1022        let inserted = fill_until_growth(&mut atlas, 0);
1023        assert!(inserted > 2, "only {inserted} glyphs went in");
1024
1025        assert_eq!(atlas.size(), 64, "it did not double");
1026        assert_eq!(atlas.growths(), 1);
1027        assert_eq!(atlas.compactions(), 0, "it discarded something it needed");
1028        assert_eq!(atlas.len(), inserted as usize, "a glyph was lost");
1029    }
1030
1031    #[test]
1032    fn growth_keeps_every_glyph_and_its_coverage() {
1033        // Growing happens because nothing was stale, so nothing may be dropped
1034        // — and the coverage has to be read back out of the atlas, the bitmaps
1035        // a caller supplied having been borrowed and long gone.
1036        let mut atlas = Atlas::with_limit(32, 128);
1037        let distinct = Coverage {
1038            width: 3,
1039            height: 2,
1040            texels: vec![11, 22, 33, 44, 55, 66],
1041        };
1042        atlas.insert(key(0), &distinct).expect("insert");
1043        fill_until_growth(&mut atlas, 1);
1044        assert_eq!(atlas.growths(), 1);
1045
1046        let rect = atlas.get(key(0)).expect("survived");
1047        let mut got = Vec::new();
1048        for row in 0..rect.height {
1049            let from = ((rect.y + row) * atlas.size() + rect.x) as usize;
1050            got.extend_from_slice(&atlas.texels()[from..from + rect.width as usize]);
1051        }
1052        assert_eq!(got, distinct.texels, "coverage was lost in growing");
1053    }
1054
1055    #[test]
1056    fn growth_stops_at_the_limit_and_says_so() {
1057        // The limit is the device's maximum texture size, which the atlas has
1058        // no way to ask about. Past it there is nowhere to go, and reporting
1059        // full is the honest answer rather than allocating what cannot be
1060        // uploaded.
1061        let mut atlas = Atlas::with_limit(16, 32);
1062        let mut glyph = 0u16;
1063        loop {
1064            match atlas.insert(key(glyph), &solid(6, 6, 255)) {
1065                Ok(_) => glyph += 1,
1066                Err(e) => {
1067                    assert_eq!(e, AtlasError::Full);
1068                    break;
1069                }
1070            }
1071            assert!(glyph < 200, "it never filled");
1072        }
1073        assert_eq!(atlas.size(), 32, "it did not grow to its limit");
1074        assert!(atlas.growths() >= 1);
1075        // And it stays usable at the limit: a glyph already present is still
1076        // found, rather than the atlas being poisoned by having filled.
1077        assert!(atlas.get(key(0)).is_some());
1078    }
1079
1080    #[test]
1081    fn a_limit_no_larger_than_the_atlas_means_it_never_grows() {
1082        // A caller who knows the size they want says so this way, and it is a
1083        // reasonable thing to ask for rather than a contradiction to reject.
1084        let mut atlas = Atlas::with_limit(16, 16);
1085        fill(&mut atlas, 0);
1086        assert_eq!(
1087            atlas.insert(key(500), &solid(6, 6, 255)),
1088            Err(AtlasError::Full)
1089        );
1090        assert_eq!(atlas.size(), 16);
1091        assert_eq!(atlas.growths(), 0);
1092    }
1093
1094    #[test]
1095    fn texture_coordinates_span_the_rectangle() {
1096        let rect = AtlasRect {
1097            x: 16,
1098            y: 32,
1099            width: 8,
1100            height: 4,
1101        };
1102        let [left, top, right, bottom] = rect.uv(64);
1103        assert!((left - 0.25).abs() < 1e-6);
1104        assert!((top - 0.5).abs() < 1e-6);
1105        assert!((right - 0.375).abs() < 1e-6);
1106        assert!((bottom - 0.5625).abs() < 1e-6);
1107        // V runs downward, matching the row order the texels are stored in.
1108        assert!(bottom > top);
1109    }
1110}