Skip to main content

kova_native_render/
atlas.rs

1//! Texture atlases for glyphs, images and rasterized vectors.
2//!
3//! Two atlases exist: a single channel coverage atlas (`Mono`, glyph masks,
4//! tintable icons) and a premultiplied RGBA atlas (`Color`, images, emoji).
5//! Each is a GPU texture array; when a layer fills up a new layer is added,
6//! so the whole UI can still be drawn with one bind group and one draw call.
7
8use etagere::{AllocId, BucketedAtlasAllocator, size2};
9use kova_native_core::ImageId;
10use kova_native_text::GlyphKey;
11use rustc_hash::FxHashMap;
12use std::borrow::Cow;
13
14/// Edge length of every atlas layer, in texels.
15pub const ATLAS_SIZE: u32 = 2048;
16/// Empty texels around every tile so bilinear filtering never bleeds.
17const PADDING: u32 = 1;
18
19/// What is stored in the atlas.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum AtlasKey {
22    Glyph(GlyphKey),
23    Image(ImageId),
24    /// A vector image rasterized at a specific device pixel size.
25    Vector {
26        id: ImageId,
27        width: u32,
28        height: u32,
29        mono: bool,
30    },
31    /// Application-supplied pixels (procedural masks, decoded frames...).
32    Custom(u64),
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub enum AtlasKind {
37    /// 8-bit coverage, tinted by the primitive color.
38    Mono,
39    /// Premultiplied RGBA.
40    Color,
41}
42
43impl AtlasKind {
44    fn bytes_per_pixel(self) -> u32 {
45        match self {
46            AtlasKind::Mono => 1,
47            AtlasKind::Color => 4,
48        }
49    }
50}
51
52/// Location of an image inside the atlas.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct AtlasTile {
55    pub kind: AtlasKind,
56    pub layer: u32,
57    pub x: u32,
58    pub y: u32,
59    pub width: u32,
60    pub height: u32,
61    /// Offset of the bitmap from its anchor point (e.g. glyph origin), copied
62    /// from [`AtlasImage::origin`].
63    pub origin: (i32, i32),
64}
65
66impl AtlasTile {
67    /// Normalized texture coordinates `[u0, v0, u1, v1]`.
68    pub fn uv(&self) -> [f32; 4] {
69        let s = ATLAS_SIZE as f32;
70        [
71            self.x as f32 / s,
72            self.y as f32 / s,
73            (self.x + self.width) as f32 / s,
74            (self.y + self.height) as f32 / s,
75        ]
76    }
77}
78
79/// Pixel data to insert into the atlas.
80pub struct AtlasImage<'a> {
81    pub kind: AtlasKind,
82    pub width: u32,
83    pub height: u32,
84    /// Tightly packed rows (`width * bytes_per_pixel` bytes each).
85    pub data: Cow<'a, [u8]>,
86    /// Offset of the bitmap's top-left corner from its anchor point (glyphs:
87    /// `(left, -top)` relative to the pen position on the baseline).
88    pub origin: (i32, i32),
89}
90
91pub(crate) struct Upload {
92    pub kind: AtlasKind,
93    pub layer: u32,
94    pub x: u32,
95    pub y: u32,
96    pub width: u32,
97    pub height: u32,
98    pub data: Vec<u8>,
99}
100
101#[derive(Default)]
102struct Layers {
103    allocators: Vec<BucketedAtlasAllocator>,
104}
105
106impl Layers {
107    fn allocate(&mut self, width: u32, height: u32) -> Option<(u32, AllocId, u32, u32)> {
108        let size = size2((width + 2 * PADDING) as i32, (height + 2 * PADDING) as i32);
109        for (layer, alloc) in self.allocators.iter_mut().enumerate() {
110            if let Some(a) = alloc.allocate(size) {
111                return Some((
112                    layer as u32,
113                    a.id,
114                    a.rectangle.min.x as u32,
115                    a.rectangle.min.y as u32,
116                ));
117            }
118        }
119        let mut alloc = BucketedAtlasAllocator::new(size2(ATLAS_SIZE as i32, ATLAS_SIZE as i32));
120        let a = alloc.allocate(size)?;
121        self.allocators.push(alloc);
122        Some((
123            (self.allocators.len() - 1) as u32,
124            a.id,
125            a.rectangle.min.x as u32,
126            a.rectangle.min.y as u32,
127        ))
128    }
129}
130
131/// CPU side of the atlases: allocation, key lookup and pending uploads.
132#[derive(Default)]
133pub struct Atlas {
134    tiles: FxHashMap<AtlasKey, Option<(AtlasTile, AllocId)>>,
135    mono: Layers,
136    color: Layers,
137    pending: Vec<Upload>,
138}
139
140impl Atlas {
141    pub fn new() -> Self {
142        Self::default()
143    }
144
145    /// Returns the tile for `key`, rasterizing it with `build` on first use.
146    /// `build` returning `None` (e.g. whitespace glyphs) is cached as well.
147    pub fn get_or_insert_with<'a>(
148        &mut self,
149        key: AtlasKey,
150        build: impl FnOnce() -> Option<AtlasImage<'a>>,
151    ) -> Option<AtlasTile> {
152        if let Some(entry) = self.tiles.get(&key) {
153            return entry.map(|(tile, _)| tile);
154        }
155        let entry = build().and_then(|image| self.insert(image));
156        self.tiles.insert(key, entry);
157        entry.map(|(tile, _)| tile)
158    }
159
160    fn insert(&mut self, image: AtlasImage<'_>) -> Option<(AtlasTile, AllocId)> {
161        if image.width == 0 || image.height == 0 {
162            return None;
163        }
164        if image.width + 2 * PADDING > ATLAS_SIZE || image.height + 2 * PADDING > ATLAS_SIZE {
165            log::warn!(
166                "kova-native atlas: {}x{} image exceeds atlas size {ATLAS_SIZE}",
167                image.width,
168                image.height
169            );
170            return None;
171        }
172        let expected = (image.width * image.height * image.kind.bytes_per_pixel()) as usize;
173        if image.data.len() < expected {
174            log::error!(
175                "kova-native atlas: image data too short ({} < {expected})",
176                image.data.len()
177            );
178            return None;
179        }
180        let layers = match image.kind {
181            AtlasKind::Mono => &mut self.mono,
182            AtlasKind::Color => &mut self.color,
183        };
184        let (layer, id, x, y) = layers.allocate(image.width, image.height)?;
185        let tile = AtlasTile {
186            kind: image.kind,
187            layer,
188            x: x + PADDING,
189            y: y + PADDING,
190            width: image.width,
191            height: image.height,
192            origin: image.origin,
193        };
194        self.pending.push(Upload {
195            kind: image.kind,
196            layer,
197            x: tile.x,
198            y: tile.y,
199            width: image.width,
200            height: image.height,
201            data: image.data[..expected].to_vec(),
202        });
203        Some((tile, id))
204    }
205
206    /// Frees the tile for `key` (e.g. when an image is dropped).
207    pub fn remove(&mut self, key: &AtlasKey) {
208        if let Some(Some((tile, id))) = self.tiles.remove(key) {
209            let layers = match tile.kind {
210                AtlasKind::Mono => &mut self.mono,
211                AtlasKind::Color => &mut self.color,
212            };
213            if let Some(alloc) = layers.allocators.get_mut(tile.layer as usize) {
214                alloc.deallocate(id);
215            }
216        }
217    }
218
219    pub fn contains(&self, key: &AtlasKey) -> bool {
220        self.tiles.contains_key(key)
221    }
222
223    pub fn layer_count(&self, kind: AtlasKind) -> u32 {
224        match kind {
225            AtlasKind::Mono => self.mono.allocators.len() as u32,
226            AtlasKind::Color => self.color.allocators.len() as u32,
227        }
228    }
229
230    pub fn tile_count(&self) -> usize {
231        self.tiles.len()
232    }
233
234    pub(crate) fn take_uploads(&mut self) -> Vec<Upload> {
235        std::mem::take(&mut self.pending)
236    }
237}
238
239/// GPU textures backing the atlas.
240pub(crate) struct AtlasTextures {
241    pub mono: GpuLayers,
242    pub color: GpuLayers,
243}
244
245pub(crate) struct GpuLayers {
246    pub texture: wgpu::Texture,
247    pub view: wgpu::TextureView,
248    pub layers: u32,
249    format: wgpu::TextureFormat,
250}
251
252impl GpuLayers {
253    fn new(device: &wgpu::Device, format: wgpu::TextureFormat, layers: u32, label: &str) -> Self {
254        let layers = layers.max(1);
255        let texture = device.create_texture(&wgpu::TextureDescriptor {
256            label: Some(label),
257            size: wgpu::Extent3d {
258                width: ATLAS_SIZE,
259                height: ATLAS_SIZE,
260                depth_or_array_layers: layers,
261            },
262            mip_level_count: 1,
263            sample_count: 1,
264            dimension: wgpu::TextureDimension::D2,
265            format,
266            usage: wgpu::TextureUsages::TEXTURE_BINDING
267                | wgpu::TextureUsages::COPY_DST
268                | wgpu::TextureUsages::COPY_SRC,
269            view_formats: &[],
270        });
271        let view = texture.create_view(&wgpu::TextureViewDescriptor {
272            label: Some(label),
273            dimension: Some(wgpu::TextureViewDimension::D2Array),
274            ..Default::default()
275        });
276        GpuLayers {
277            texture,
278            view,
279            layers,
280            format,
281        }
282    }
283
284    /// Grows the texture array to `needed` layers, preserving contents.
285    /// Returns `true` if the texture was recreated.
286    fn ensure(
287        &mut self,
288        device: &wgpu::Device,
289        queue: &wgpu::Queue,
290        needed: u32,
291        label: &str,
292    ) -> bool {
293        if needed <= self.layers {
294            return false;
295        }
296        let new_layers = needed.max(self.layers * 2);
297        let new = GpuLayers::new(device, self.format, new_layers, label);
298        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
299            label: Some("kova-native atlas grow"),
300        });
301        encoder.copy_texture_to_texture(
302            wgpu::TexelCopyTextureInfo {
303                texture: &self.texture,
304                mip_level: 0,
305                origin: wgpu::Origin3d::ZERO,
306                aspect: wgpu::TextureAspect::All,
307            },
308            wgpu::TexelCopyTextureInfo {
309                texture: &new.texture,
310                mip_level: 0,
311                origin: wgpu::Origin3d::ZERO,
312                aspect: wgpu::TextureAspect::All,
313            },
314            wgpu::Extent3d {
315                width: ATLAS_SIZE,
316                height: ATLAS_SIZE,
317                depth_or_array_layers: self.layers,
318            },
319        );
320        // Submit right away: queued texture writes issued afterwards are
321        // ordered after this copy and cannot be overwritten by it.
322        queue.submit(Some(encoder.finish()));
323        *self = new;
324        true
325    }
326}
327
328impl AtlasTextures {
329    pub fn new(device: &wgpu::Device) -> Self {
330        AtlasTextures {
331            mono: GpuLayers::new(
332                device,
333                wgpu::TextureFormat::R8Unorm,
334                1,
335                "kova-native mono atlas",
336            ),
337            color: GpuLayers::new(
338                device,
339                wgpu::TextureFormat::Rgba8Unorm,
340                1,
341                "kova-native color atlas",
342            ),
343        }
344    }
345
346    /// Uploads pending tiles. Returns `true` if textures were recreated (the
347    /// bind group must then be rebuilt).
348    pub fn sync(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, atlas: &mut Atlas) -> bool {
349        let mut recreated = self.mono.ensure(
350            device,
351            queue,
352            atlas.layer_count(AtlasKind::Mono),
353            "kova-native mono atlas",
354        );
355        recreated |= self.color.ensure(
356            device,
357            queue,
358            atlas.layer_count(AtlasKind::Color),
359            "kova-native color atlas",
360        );
361        for upload in atlas.take_uploads() {
362            let target = match upload.kind {
363                AtlasKind::Mono => &self.mono,
364                AtlasKind::Color => &self.color,
365            };
366            queue.write_texture(
367                wgpu::TexelCopyTextureInfo {
368                    texture: &target.texture,
369                    mip_level: 0,
370                    origin: wgpu::Origin3d {
371                        x: upload.x,
372                        y: upload.y,
373                        z: upload.layer,
374                    },
375                    aspect: wgpu::TextureAspect::All,
376                },
377                &upload.data,
378                wgpu::TexelCopyBufferLayout {
379                    offset: 0,
380                    bytes_per_row: Some(upload.width * upload.kind.bytes_per_pixel()),
381                    rows_per_image: Some(upload.height),
382                },
383                wgpu::Extent3d {
384                    width: upload.width,
385                    height: upload.height,
386                    depth_or_array_layers: 1,
387                },
388            );
389        }
390        recreated
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn allocation_and_caching() {
400        let mut atlas = Atlas::new();
401        let key = AtlasKey::Image(ImageId(1));
402        let mut builds = 0;
403        for _ in 0..3 {
404            let tile = atlas.get_or_insert_with(key, || {
405                builds += 1;
406                Some(AtlasImage {
407                    kind: AtlasKind::Color,
408                    width: 4,
409                    height: 2,
410                    data: Cow::Owned(vec![255; 32]),
411                    origin: (0, 0),
412                })
413            });
414            let tile = tile.unwrap();
415            assert_eq!((tile.width, tile.height), (4, 2));
416            assert!(tile.x >= PADDING && tile.y >= PADDING);
417        }
418        assert_eq!(builds, 1);
419        assert_eq!(atlas.take_uploads().len(), 1);
420
421        // Negative results are cached too.
422        let empty = AtlasKey::Image(ImageId(2));
423        assert!(atlas.get_or_insert_with(empty, || None).is_none());
424        assert!(atlas.contains(&empty));
425    }
426
427    #[test]
428    fn grows_new_layers_when_full() {
429        let mut atlas = Atlas::new();
430        let big = (ATLAS_SIZE - 2 * PADDING) as usize;
431        for i in 0..3 {
432            let tile = atlas
433                .get_or_insert_with(AtlasKey::Image(ImageId(100 + i)), || {
434                    Some(AtlasImage {
435                        kind: AtlasKind::Mono,
436                        width: big as u32,
437                        height: big as u32,
438                        data: Cow::Owned(vec![0; big * big]),
439                        origin: (0, 0),
440                    })
441                })
442                .unwrap();
443            assert_eq!(tile.layer, i as u32);
444        }
445        assert_eq!(atlas.layer_count(AtlasKind::Mono), 3);
446        atlas.remove(&AtlasKey::Image(ImageId(100)));
447        assert!(!atlas.contains(&AtlasKey::Image(ImageId(100))));
448    }
449}