skia-rs-gpu 0.2.7

GPU backends for skia-rs
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
//! Atlas management for GPU rendering.
//!
//! This module provides texture atlas management for efficiently batching
//! small paths, glyphs, and other small elements into larger textures.

use skia_rs_core::{Point, Rect, Scalar};
use std::collections::HashMap;

/// Unique identifier for an atlas entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AtlasEntryId(u64);

impl AtlasEntryId {
    /// Create a new entry ID.
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// Get the raw ID value.
    pub fn raw(&self) -> u64 {
        self.0
    }
}

/// A region within an atlas.
#[derive(Debug, Clone, Copy)]
pub struct AtlasRegion {
    /// X position in atlas.
    pub x: u32,
    /// Y position in atlas.
    pub y: u32,
    /// Width of region.
    pub width: u32,
    /// Height of region.
    pub height: u32,
    /// Atlas layer (for array textures).
    pub layer: u32,
}

impl AtlasRegion {
    /// Get UV coordinates for this region within an atlas of given size.
    pub fn uv_rect(&self, atlas_width: u32, atlas_height: u32) -> [f32; 4] {
        [
            self.x as f32 / atlas_width as f32,
            self.y as f32 / atlas_height as f32,
            (self.x + self.width) as f32 / atlas_width as f32,
            (self.y + self.height) as f32 / atlas_height as f32,
        ]
    }

    /// Convert to a rect.
    pub fn to_rect(&self) -> Rect {
        Rect::from_xywh(
            self.x as f32,
            self.y as f32,
            self.width as f32,
            self.height as f32,
        )
    }
}

/// Atlas configuration.
#[derive(Debug, Clone)]
pub struct AtlasConfig {
    /// Atlas width in pixels.
    pub width: u32,
    /// Atlas height in pixels.
    pub height: u32,
    /// Maximum number of layers (for array textures).
    pub max_layers: u32,
    /// Padding between entries.
    pub padding: u32,
    /// Allow resizing when full.
    pub allow_resize: bool,
}

impl Default for AtlasConfig {
    fn default() -> Self {
        Self {
            width: 2048,
            height: 2048,
            max_layers: 4,
            padding: 1,
            allow_resize: true,
        }
    }
}

/// Atlas allocation result.
#[derive(Debug)]
pub enum AtlasAllocResult {
    /// Successfully allocated.
    Success(AtlasRegion),
    /// Atlas is full, need to flush and reset.
    Full,
    /// Request too large for atlas.
    TooLarge,
}

/// A single atlas layer using shelf-based allocation.
#[derive(Debug)]
struct AtlasLayer {
    /// Current shelf Y position.
    current_y: u32,
    /// Current shelf height.
    current_shelf_height: u32,
    /// Current X position in shelf.
    current_x: u32,
    /// Layer dimensions.
    width: u32,
    height: u32,
}

impl AtlasLayer {
    fn new(width: u32, height: u32) -> Self {
        Self {
            current_y: 0,
            current_shelf_height: 0,
            current_x: 0,
            width,
            height,
        }
    }

    fn allocate(&mut self, width: u32, height: u32, padding: u32) -> Option<(u32, u32)> {
        let padded_width = width + padding * 2;
        let padded_height = height + padding * 2;

        // Check if it fits in current shelf
        if self.current_x + padded_width <= self.width
            && self.current_y + padded_height.max(self.current_shelf_height) <= self.height
        {
            let x = self.current_x + padding;
            let y = self.current_y + padding;

            self.current_x += padded_width;
            self.current_shelf_height = self.current_shelf_height.max(padded_height);

            return Some((x, y));
        }

        // Try next shelf
        if self.current_y + self.current_shelf_height + padded_height <= self.height {
            self.current_y += self.current_shelf_height;
            self.current_x = 0;
            self.current_shelf_height = padded_height;

            if self.current_x + padded_width <= self.width {
                let x = self.current_x + padding;
                let y = self.current_y + padding;

                self.current_x += padded_width;

                return Some((x, y));
            }
        }

        None
    }

    fn reset(&mut self) {
        self.current_y = 0;
        self.current_shelf_height = 0;
        self.current_x = 0;
    }
}

/// A texture atlas for batching small elements.
#[derive(Debug)]
pub struct TextureAtlas {
    /// Configuration.
    config: AtlasConfig,
    /// Atlas layers.
    layers: Vec<AtlasLayer>,
    /// Entry lookup by ID.
    entries: HashMap<AtlasEntryId, AtlasRegion>,
    /// IDs of entries that have been freed and are eligible for removal on
    /// the next `compact()`. Kept as a set for O(1) membership checks
    /// during compaction.
    freed: std::collections::HashSet<AtlasEntryId>,
    /// Next entry ID.
    next_id: u64,
    /// Generation counter (incremented on reset).
    generation: u64,
}

impl TextureAtlas {
    /// Create a new texture atlas.
    pub fn new(config: AtlasConfig) -> Self {
        let mut layers = Vec::with_capacity(config.max_layers as usize);
        layers.push(AtlasLayer::new(config.width, config.height));

        Self {
            config,
            layers,
            entries: HashMap::new(),
            freed: std::collections::HashSet::new(),
            next_id: 0,
            generation: 0,
        }
    }

    /// Get atlas configuration.
    pub fn config(&self) -> &AtlasConfig {
        &self.config
    }

    /// Get current generation.
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Get number of active layers.
    pub fn layer_count(&self) -> u32 {
        self.layers.len() as u32
    }

    /// Get number of entries.
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Look up an existing entry.
    pub fn lookup(&self, id: AtlasEntryId) -> Option<&AtlasRegion> {
        self.entries.get(&id)
    }

    /// Allocate a region in the atlas.
    pub fn allocate(&mut self, width: u32, height: u32) -> AtlasAllocResult {
        // Check if request is too large
        if width > self.config.width || height > self.config.height {
            return AtlasAllocResult::TooLarge;
        }

        // Try to allocate in existing layers
        for (layer_idx, layer) in self.layers.iter_mut().enumerate() {
            if let Some((x, y)) = layer.allocate(width, height, self.config.padding) {
                let id = AtlasEntryId::new(self.next_id);
                self.next_id += 1;

                let region = AtlasRegion {
                    x,
                    y,
                    width,
                    height,
                    layer: layer_idx as u32,
                };

                self.entries.insert(id, region);
                return AtlasAllocResult::Success(region);
            }
        }

        // Try to add a new layer
        if self.layers.len() < self.config.max_layers as usize {
            let mut new_layer = AtlasLayer::new(self.config.width, self.config.height);
            if let Some((x, y)) = new_layer.allocate(width, height, self.config.padding) {
                let layer_idx = self.layers.len();
                self.layers.push(new_layer);

                let id = AtlasEntryId::new(self.next_id);
                self.next_id += 1;

                let region = AtlasRegion {
                    x,
                    y,
                    width,
                    height,
                    layer: layer_idx as u32,
                };

                self.entries.insert(id, region);
                return AtlasAllocResult::Success(region);
            }
        }

        AtlasAllocResult::Full
    }

    /// Allocate and return the entry ID.
    pub fn allocate_with_id(
        &mut self,
        width: u32,
        height: u32,
    ) -> Option<(AtlasEntryId, AtlasRegion)> {
        match self.allocate(width, height) {
            AtlasAllocResult::Success(region) => {
                let id = AtlasEntryId::new(self.next_id - 1);
                Some((id, region))
            }
            _ => None,
        }
    }

    /// Reset the atlas, clearing all entries.
    pub fn reset(&mut self) {
        for layer in &mut self.layers {
            layer.reset();
        }
        self.entries.clear();
        self.freed.clear();
        self.generation += 1;
        // Keep only first layer
        self.layers.truncate(1);
    }

    /// Mark an entry as freed. The slot remains occupied until the next
    /// `compact()` call; this lets callers drop cached data they no longer
    /// need without immediately forcing a repack.
    pub fn free(&mut self, id: AtlasEntryId) -> bool {
        if self.entries.contains_key(&id) {
            self.freed.insert(id);
            true
        } else {
            false
        }
    }

    /// Number of entries currently marked as freed but not yet repacked.
    pub fn freed_count(&self) -> usize {
        self.freed.len()
    }

    /// Result of a compaction pass.
    ///
    /// Callers get back the set of entries whose atlas region changed and
    /// therefore need their GPU texture data re-uploaded to the new slots.
    /// Entries whose region did not change are not included.
    ///
    /// `removed` lists entries that were freed and are no longer in the atlas.
    pub fn compact(&mut self) -> CompactResult {
        // Gather current entries into a sorted list (largest first gives
        // best shelf-pack behaviour for new placements). Drop any that
        // were previously marked as freed.
        let old_entries: Vec<(AtlasEntryId, AtlasRegion)> = self
            .entries
            .iter()
            .filter(|(id, _)| !self.freed.contains(id))
            .map(|(id, region)| (*id, *region))
            .collect();

        let removed: Vec<AtlasEntryId> = self.freed.iter().copied().collect();

        // Clear the layers — we're about to replay all surviving entries
        // into a fresh packing.
        for layer in &mut self.layers {
            layer.reset();
        }
        // Keep just one layer; we may grow it back during re-insertion.
        self.layers.truncate(1);
        self.entries.clear();
        self.freed.clear();
        self.generation += 1;

        // Sort by height descending for shelf-pack stability. Shelf-pack
        // works best when the tallest rectangles go down first so later
        // rectangles fit under existing shelves.
        let mut sorted = old_entries;
        sorted.sort_by(|a, b| b.1.height.cmp(&a.1.height).then(b.1.width.cmp(&a.1.width)));

        let mut remapped: Vec<(AtlasEntryId, AtlasRegion, AtlasRegion)> = Vec::new();

        for (id, old_region) in sorted {
            let mut placed = false;
            for (layer_idx, layer) in self.layers.iter_mut().enumerate() {
                if let Some((x, y)) = layer.allocate(old_region.width, old_region.height, self.config.padding) {
                    let new_region = AtlasRegion {
                        x,
                        y,
                        width: old_region.width,
                        height: old_region.height,
                        layer: layer_idx as u32,
                    };
                    self.entries.insert(id, new_region);
                    if (old_region.x, old_region.y, old_region.layer)
                        != (new_region.x, new_region.y, new_region.layer)
                    {
                        remapped.push((id, old_region, new_region));
                    }
                    placed = true;
                    break;
                }
            }

            if !placed && self.layers.len() < self.config.max_layers as usize {
                let mut new_layer = AtlasLayer::new(self.config.width, self.config.height);
                if let Some((x, y)) = new_layer.allocate(old_region.width, old_region.height, self.config.padding) {
                    let layer_idx = self.layers.len();
                    self.layers.push(new_layer);
                    let new_region = AtlasRegion {
                        x,
                        y,
                        width: old_region.width,
                        height: old_region.height,
                        layer: layer_idx as u32,
                    };
                    self.entries.insert(id, new_region);
                    if (old_region.x, old_region.y, old_region.layer)
                        != (new_region.x, new_region.y, new_region.layer)
                    {
                        remapped.push((id, old_region, new_region));
                    }
                    placed = true;
                }
            }

            if !placed {
                // Unable to re-pack — this only happens if the atlas has
                // pathological fragmentation across max_layers. Re-insert
                // at its original slot so the caller doesn't lose data.
                self.entries.insert(id, old_region);
            }
        }

        CompactResult { remapped, removed }
    }
}

/// Result of a `TextureAtlas::compact()` call.
#[derive(Debug, Clone, Default)]
pub struct CompactResult {
    /// Entries whose region moved during repacking. Each tuple is
    /// (id, old_region, new_region).
    pub remapped: Vec<(AtlasEntryId, AtlasRegion, AtlasRegion)>,
    /// Entries that were freed and dropped from the atlas.
    pub removed: Vec<AtlasEntryId>,
}

/// Atlas manager for multiple atlases by type.
#[derive(Debug)]
pub struct AtlasManager {
    /// Path atlas.
    path_atlas: TextureAtlas,
    /// Glyph atlas (alpha).
    glyph_atlas: TextureAtlas,
    /// Color atlas (RGBA).
    color_atlas: TextureAtlas,
}

impl AtlasManager {
    /// Create a new atlas manager with default configuration.
    pub fn new() -> Self {
        Self {
            path_atlas: TextureAtlas::new(AtlasConfig {
                width: 2048,
                height: 2048,
                max_layers: 4,
                padding: 2,
                allow_resize: true,
            }),
            glyph_atlas: TextureAtlas::new(AtlasConfig {
                width: 1024,
                height: 1024,
                max_layers: 2,
                padding: 1,
                allow_resize: true,
            }),
            color_atlas: TextureAtlas::new(AtlasConfig {
                width: 1024,
                height: 1024,
                max_layers: 2,
                padding: 1,
                allow_resize: true,
            }),
        }
    }

    /// Get path atlas.
    pub fn path_atlas(&self) -> &TextureAtlas {
        &self.path_atlas
    }

    /// Get mutable path atlas.
    pub fn path_atlas_mut(&mut self) -> &mut TextureAtlas {
        &mut self.path_atlas
    }

    /// Get glyph atlas.
    pub fn glyph_atlas(&self) -> &TextureAtlas {
        &self.glyph_atlas
    }

    /// Get mutable glyph atlas.
    pub fn glyph_atlas_mut(&mut self) -> &mut TextureAtlas {
        &mut self.glyph_atlas
    }

    /// Get color atlas.
    pub fn color_atlas(&self) -> &TextureAtlas {
        &self.color_atlas
    }

    /// Get mutable color atlas.
    pub fn color_atlas_mut(&mut self) -> &mut TextureAtlas {
        &mut self.color_atlas
    }

    /// Reset all atlases.
    pub fn reset_all(&mut self) {
        self.path_atlas.reset();
        self.glyph_atlas.reset();
        self.color_atlas.reset();
    }
}

impl Default for AtlasManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_atlas_region_uv() {
        let region = AtlasRegion {
            x: 100,
            y: 200,
            width: 50,
            height: 75,
            layer: 0,
        };

        let uv = region.uv_rect(1000, 1000);
        assert_eq!(uv[0], 0.1);
        assert_eq!(uv[1], 0.2);
        assert_eq!(uv[2], 0.15);
        assert_eq!(uv[3], 0.275);
    }

    #[test]
    fn test_atlas_allocate() {
        let config = AtlasConfig {
            width: 256,
            height: 256,
            max_layers: 1,
            padding: 0,
            allow_resize: false,
        };

        let mut atlas = TextureAtlas::new(config);

        // First allocation should succeed
        match atlas.allocate(64, 64) {
            AtlasAllocResult::Success(region) => {
                assert_eq!(region.width, 64);
                assert_eq!(region.height, 64);
            }
            _ => panic!("Expected success"),
        }

        // Too large allocation should fail
        match atlas.allocate(512, 512) {
            AtlasAllocResult::TooLarge => {}
            _ => panic!("Expected TooLarge"),
        }
    }

    #[test]
    fn test_atlas_multiple_allocations() {
        let config = AtlasConfig {
            width: 256,
            height: 256,
            max_layers: 1,
            padding: 0,
            allow_resize: false,
        };

        let mut atlas = TextureAtlas::new(config);

        // Allocate multiple small regions
        for _ in 0..16 {
            match atlas.allocate(32, 32) {
                AtlasAllocResult::Success(_) => {}
                _ => panic!("Expected success"),
            }
        }

        assert_eq!(atlas.entry_count(), 16);
    }

    #[test]
    fn test_atlas_reset() {
        let mut atlas = TextureAtlas::new(AtlasConfig::default());

        atlas.allocate(100, 100);
        atlas.allocate(100, 100);
        assert_eq!(atlas.entry_count(), 2);

        let gen_before = atlas.generation();
        atlas.reset();
        assert_eq!(atlas.entry_count(), 0);
        assert_eq!(atlas.generation(), gen_before + 1);
    }

    #[test]
    fn test_atlas_manager() {
        let mut manager = AtlasManager::new();

        // Allocate in different atlases
        manager.path_atlas_mut().allocate(64, 64);
        manager.glyph_atlas_mut().allocate(32, 32);
        manager.color_atlas_mut().allocate(48, 48);

        assert_eq!(manager.path_atlas().entry_count(), 1);
        assert_eq!(manager.glyph_atlas().entry_count(), 1);
        assert_eq!(manager.color_atlas().entry_count(), 1);

        manager.reset_all();
        assert_eq!(manager.path_atlas().entry_count(), 0);
    }

    #[test]
    fn test_atlas_entry_id() {
        let id = AtlasEntryId::new(42);
        assert_eq!(id.raw(), 42);
    }

    #[test]
    fn test_atlas_lookup() {
        let mut atlas = TextureAtlas::new(AtlasConfig::default());

        if let Some((id, region)) = atlas.allocate_with_id(100, 100) {
            let looked_up = atlas.lookup(id);
            assert!(looked_up.is_some());
            assert_eq!(looked_up.unwrap().width, region.width);
        }
    }

    #[test]
    fn test_atlas_free_and_compact_removes_entries() {
        let mut atlas = TextureAtlas::new(AtlasConfig {
            width: 512,
            height: 512,
            max_layers: 1,
            padding: 0,
            allow_resize: false,
        });

        let mut ids = Vec::new();
        for _ in 0..4 {
            if let Some((id, _)) = atlas.allocate_with_id(64, 64) {
                ids.push(id);
            }
        }
        assert_eq!(atlas.entry_count(), 4);

        // Free two entries.
        assert!(atlas.free(ids[1]));
        assert!(atlas.free(ids[2]));
        assert_eq!(atlas.freed_count(), 2);

        let result = atlas.compact();
        assert_eq!(result.removed.len(), 2);
        assert_eq!(atlas.entry_count(), 2);
        assert_eq!(atlas.freed_count(), 0);

        // Surviving ids still resolve.
        assert!(atlas.lookup(ids[0]).is_some());
        assert!(atlas.lookup(ids[3]).is_some());
        // Removed ids are gone.
        assert!(atlas.lookup(ids[1]).is_none());
        assert!(atlas.lookup(ids[2]).is_none());
    }

    #[test]
    fn test_atlas_compact_reclaims_space() {
        // After compacting away freed entries we should be able to allocate
        // new rectangles that previously hit "Full".
        let mut atlas = TextureAtlas::new(AtlasConfig {
            width: 128,
            height: 128,
            max_layers: 1,
            padding: 0,
            allow_resize: false,
        });

        // Fill most of a 128-wide shelf with 60x60 rectangles.
        let a = atlas.allocate_with_id(60, 60).unwrap().0;
        let b = atlas.allocate_with_id(60, 60).unwrap().0;
        let c = atlas.allocate_with_id(60, 60).unwrap().0;
        assert_eq!(atlas.entry_count(), 3);

        // Trying to fit a 60x60 on top should still succeed once we have a
        // second shelf, but a 100x100 should not fit until we free & compact.
        match atlas.allocate(100, 100) {
            AtlasAllocResult::Full => {}
            other => panic!("expected Full, got {:?}", other),
        }

        // Free all three entries and compact.
        atlas.free(a);
        atlas.free(b);
        atlas.free(c);
        atlas.compact();

        // Now the 100x100 should fit.
        match atlas.allocate(100, 100) {
            AtlasAllocResult::Success(_) => {}
            other => panic!("expected Success, got {:?}", other),
        }
    }

    #[test]
    fn test_atlas_free_unknown_returns_false() {
        let mut atlas = TextureAtlas::new(AtlasConfig::default());
        assert!(!atlas.free(AtlasEntryId::new(9999)));
    }

    #[test]
    fn test_atlas_compact_without_frees_is_noop_ish() {
        let mut atlas = TextureAtlas::new(AtlasConfig {
            width: 256,
            height: 256,
            max_layers: 1,
            padding: 0,
            allow_resize: false,
        });

        let (id_a, _) = atlas.allocate_with_id(50, 50).unwrap();
        let (id_b, _) = atlas.allocate_with_id(50, 50).unwrap();

        let before_a = *atlas.lookup(id_a).unwrap();
        let before_b = *atlas.lookup(id_b).unwrap();

        let result = atlas.compact();
        assert!(result.removed.is_empty());

        // Both entries still resolve (possibly with the same regions,
        // possibly remapped).
        let after_a = *atlas.lookup(id_a).unwrap();
        let after_b = *atlas.lookup(id_b).unwrap();
        assert_eq!(before_a.width, after_a.width);
        assert_eq!(before_b.width, after_b.width);
    }
}