rustial-renderer-wgpu 1.0.0

Pure WGPU renderer for the rustial 2.5D map engine
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
// ---------------------------------------------------------------------------
//! # Tile atlas -- packs individual tile textures into shared GPU atlas pages
//!
//! Instead of binding a separate texture for every tile draw call, the atlas
//! packs decoded tile images into large shared textures (atlas pages).  All
//! tiles within the same page can be drawn with a single texture bind-group
//! swap, and their geometry can be merged into one vertex/index buffer for a
//! single batched draw call.
//!
//! ## Atlas layout
//!
//! Each page is a square RGBA8 texture of [`ATLAS_PAGE_SIZE`] x
//! [`ATLAS_PAGE_SIZE`] pixels (default 4096 x 4096), divided into a regular
//! grid of [`TILE_SIZE`] x [`TILE_SIZE`] slots (default 256 x 256).  This
//! yields [`SLOTS_PER_PAGE`] = 256 slots per page, which at moderate zoom
//! levels covers all visible tiles in a single page.
//!
//! ## UV remapping
//!
//! When a tile is placed into slot `(col, row)`, its original `[0, 1]` UVs
//! are remapped to the sub-rectangle within the atlas via
//! [`AtlasRegion::remap_uv`]:
//!
//! ```text
//! u' = (col + u) / slots_per_side
//! v' = (row + v) / slots_per_side
//! ```
//!
//! A half-texel inset is applied to avoid sampling across slot boundaries
//! when linear filtering is active.
//!
//! ## Eviction
//!
//! Slots are tracked per frame.  The caller marks every tile that is drawn
//! via [`TileAtlas::mark_used`], then calls [`TileAtlas::end_frame`] which
//! frees every slot that was *not* used.  Freed slots are recycled on the
//! next insertion.  Atlas pages themselves are never deallocated; only their
//! slots are reused.
//!
//! ## Tile size mismatch
//!
//! If a decoded tile image is smaller than [`TILE_SIZE`], it is copied into
//! the top-left corner of the slot and any extra texels are undefined (not
//! visible because UVs only span the copied region).  Images larger than
//! [`TILE_SIZE`] are clamped to [`TILE_SIZE`] in the `write_texture` call.
//!
//! ## Thread safety
//!
//! `TileAtlas` is **not** `Send`/`Sync` because it holds `wgpu::Texture`
//! handles, which in some backends are `!Send`.  This is fine -- the atlas
//! lives exclusively on the render thread alongside the `wgpu::Device`.
// ---------------------------------------------------------------------------

use rustial_engine::DecodedImage;
use rustial_engine::RasterMipChain;
use rustial_engine::TileId;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Edge length of each atlas page texture in pixels.
pub const ATLAS_PAGE_SIZE: u32 = 4096;

/// Edge length of a single tile in pixels.
pub const TILE_SIZE: u32 = 256;

/// Number of tile slots along one edge of an atlas page.
///
/// `ATLAS_PAGE_SIZE / TILE_SIZE` = 16 for the default 4096 / 256.
pub const SLOTS_PER_SIDE: u32 = ATLAS_PAGE_SIZE / TILE_SIZE;

/// Total number of tile slots in a single atlas page.
///
/// 16 x 16 = 256 for the defaults.
pub const SLOTS_PER_PAGE: u32 = SLOTS_PER_SIDE * SLOTS_PER_SIDE;

/// Half-texel size in atlas-UV space, used to inset UVs so that linear
/// filtering never samples across slot boundaries.
const HALF_TEXEL: f32 = 0.5 / ATLAS_PAGE_SIZE as f32;

/// Number of mip levels allocated for each atlas page.
#[inline]
fn atlas_page_mip_count() -> u32 {
    ATLAS_PAGE_SIZE.ilog2() + 1
}

// ---------------------------------------------------------------------------
// AtlasRegion -- where a tile lives inside the atlas
// ---------------------------------------------------------------------------

/// Describes where a tile's pixels are stored inside the atlas.
///
/// Returned by [`TileAtlas::insert`] and [`TileAtlas::get`].  The region
/// is used by the batch builder ([`crate::gpu::batch`]) to remap each
/// tile quad's UVs from `[0, 1]` into the correct atlas sub-rectangle.
#[derive(Debug, Clone, Copy)]
pub struct AtlasRegion {
    /// Index of the atlas page (into [`TileAtlas::pages`]).
    pub page: usize,
    /// Column of the slot within the page (0-based, max [`SLOTS_PER_SIDE`]-1).
    pub col: u32,
    /// Row of the slot within the page (0-based, max [`SLOTS_PER_SIDE`]-1).
    pub row: u32,
}

impl AtlasRegion {
    /// Remap a tile-local UV `[0, 1]` to an atlas-global UV.
    ///
    /// Applies a half-texel inset so that bilinear sampling at slot edges
    /// never bleeds into the neighbouring slot.
    ///
    /// # Mapping
    ///
    /// ```text
    /// u' = (col + u) / slots_per_side   (+ half-texel inset)
    /// v' = (row + v) / slots_per_side   (+ half-texel inset)
    /// ```
    #[inline]
    pub fn remap_uv(&self, u: f32, v: f32) -> [f32; 2] {
        let inv = 1.0 / SLOTS_PER_SIDE as f32;
        let base_u = (self.col as f32 + u) * inv;
        let base_v = (self.row as f32 + v) * inv;
        // Inset: push 0.0 inward by +HALF_TEXEL, push 1.0 inward by -HALF_TEXEL.
        let inset_u = base_u + HALF_TEXEL * (1.0 - 2.0 * u);
        let inset_v = base_v + HALF_TEXEL * (1.0 - 2.0 * v);
        [inset_u, inset_v]
    }
}

// ---------------------------------------------------------------------------
// PendingUpload -- deferred tile texture upload
// ---------------------------------------------------------------------------

/// A single tile texture upload that has been enqueued but not yet written
/// to the GPU.
///
/// Instead of issuing `queue.write_texture` immediately during
/// [`TileAtlas::insert`], the atlas records a `PendingUpload` and defers
/// the actual GPU write until [`TileAtlas::flush_uploads`] is called.
/// This lets the renderer batch all per-frame texture writes into a
/// single submission window, reducing driver overhead and matching
/// MapLibre's incremental atlas streaming model.
struct PendingUpload {
    /// Atlas page index that owns the destination slot.
    page_idx: usize,
    /// Slot column within the atlas page.
    col: u32,
    /// Slot row within the atlas page.
    row: u32,
    /// Pre-computed mip chain data ready for GPU upload.
    mip_chain: RasterMipChain,
}

// ---------------------------------------------------------------------------
// AtlasPage -- one GPU texture with a grid of tile slots
// ---------------------------------------------------------------------------

/// A single atlas page: one large GPU texture with a free-list of tile slots.
///
/// Each page is [`ATLAS_PAGE_SIZE`] x [`ATLAS_PAGE_SIZE`] pixels of
/// `Rgba8UnormSrgb`, containing up to [`SLOTS_PER_PAGE`] tile slots arranged
/// in a [`SLOTS_PER_SIDE`] x [`SLOTS_PER_SIDE`] grid.
pub(crate) struct AtlasPage {
    /// The GPU texture (ATLAS_PAGE_SIZE x ATLAS_PAGE_SIZE, Rgba8UnormSrgb).
    pub texture: wgpu::Texture,
    /// A view over the full atlas texture, bound in draw calls.
    pub view: wgpu::TextureView,
    /// Per-slot occupancy: `true` = occupied by a tile, `false` = free.
    ///
    /// Indexed as `row * SLOTS_PER_SIDE + col`.
    pub(crate) occupied: Vec<bool>,
    /// Per-slot "used this frame" flag, set by [`AtlasPage::mark_used`],
    /// reset by [`AtlasPage::evict_unused`].
    used_this_frame: Vec<bool>,
}

impl AtlasPage {
    /// Count the number of occupied slots.
    fn occupied_count_inner(&self) -> u32 {
        self.occupied.iter().filter(|&&o| o).count() as u32
    }
}

impl AtlasPage {
    // NOTE: `occupied_count_inner` lives in the impl block above (before
    // the main impl block) so it is available outside `#[cfg(test)]`.

    /// Allocate a new atlas page on the GPU.
    ///
    /// This creates a single `ATLAS_PAGE_SIZE x ATLAS_PAGE_SIZE` texture
    /// allocation.  On a typical GPU this is 4096 x 4096 x 4 = 64 MiB of
    /// VRAM per page.  Most map sessions need only 1-2 pages.
    fn new(device: &wgpu::Device) -> Self {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("tile_atlas_page"),
            size: wgpu::Extent3d {
                width: ATLAS_PAGE_SIZE,
                height: ATLAS_PAGE_SIZE,
                depth_or_array_layers: 1,
            },
            mip_level_count: atlas_page_mip_count(),
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let n = SLOTS_PER_PAGE as usize;
        Self {
            texture,
            view,
            occupied: vec![false; n],
            used_this_frame: vec![false; n],
        }
    }

    /// Find a free slot and mark it occupied.  Returns `(col, row)` or
    /// `None` if every slot is taken.
    ///
    /// Performs a linear scan -- O(SLOTS_PER_PAGE) in the worst case (256).
    /// This is negligible compared to the GPU texture write that follows.
    fn alloc_slot(&mut self) -> Option<(u32, u32)> {
        for (i, occ) in self.occupied.iter_mut().enumerate() {
            if !*occ {
                *occ = true;
                let col = (i as u32) % SLOTS_PER_SIDE;
                let row = (i as u32) / SLOTS_PER_SIDE;
                return Some((col, row));
            }
        }
        None
    }

    /// Mark a slot as drawn this frame (prevents eviction).
    fn mark_used(&mut self, col: u32, row: u32) {
        let idx = (row * SLOTS_PER_SIDE + col) as usize;
        if idx < self.used_this_frame.len() {
            self.used_this_frame[idx] = true;
        }
    }

    /// Free a specific slot (e.g. from [`TileAtlas::remove`]).
    fn free_slot(&mut self, col: u32, row: u32) {
        let idx = (row * SLOTS_PER_SIDE + col) as usize;
        if idx < self.occupied.len() {
            self.occupied[idx] = false;
        }
    }

    /// Evict all slots that were *not* marked as used this frame.
    ///
    /// After eviction the `used_this_frame` flags are cleared for the next
    /// frame.  The caller ([`TileAtlas::end_frame`]) is responsible for
    /// removing the corresponding `regions` entries.
    fn evict_unused(&mut self) {
        for i in 0..self.occupied.len() {
            if self.occupied[i] && !self.used_this_frame[i] {
                self.occupied[i] = false;
            }
        }
        self.used_this_frame.iter_mut().for_each(|f| *f = false);
    }

    /// Number of occupied slots in this page (test-only convenience).
    #[allow(dead_code)]
    #[cfg(test)]
    fn occupied_count(&self) -> usize {
        self.occupied_count_inner() as usize
    }
}

// ---------------------------------------------------------------------------
// TileAtlas -- manages multiple atlas pages
// ---------------------------------------------------------------------------

/// Tile texture atlas -- packs individual tile images into shared GPU textures.
///
/// Manages one or more [`AtlasPage`]s and maintains a `TileId -> AtlasRegion`
/// lookup table.  New pages are lazily allocated when all existing pages are
/// full; pages are never deallocated (their slots are recycled instead).
///
/// # Lifecycle (called by [`WgpuMapRenderer`](crate::WgpuMapRenderer))
///
/// 1. **Insert**  -- [`insert`](Self::insert) enqueues a deferred upload.
/// 2. **Flush**   -- [`flush_uploads`](Self::flush_uploads) writes all
///    pending slot data to the GPU in one batched pass.
/// 3. **Mark**    -- [`mark_used`](Self::mark_used) for every tile drawn.
/// 4. **Evict**   -- [`end_frame`](Self::end_frame) once after submit;
///    optionally compacts the atlas when fragmentation is high.
///
/// # Deferred upload
///
/// Tile pixel data is *not* written to the GPU during [`insert`](Self::insert).
/// Instead, only the atlas slot is allocated and a [`PendingUpload`] is
/// enqueued.  The actual `queue.write_texture` calls happen during
/// [`flush_uploads`](Self::flush_uploads), which the renderer calls once
/// per frame before building batched geometry.  This ensures that only the
/// affected slot's pixel rectangle is uploaded (partial write), and all
/// uploads are grouped into a single submission window.
///
/// # VRAM budget
///
/// Each page consumes 4096 x 4096 x 4 = 64 MiB.  At moderate zoom levels a
/// single page (256 slots) is sufficient; at very high zoom with a large
/// viewport, 2-3 pages may be needed.
pub struct TileAtlas {
    /// Atlas pages.  New pages are appended when all existing pages are full.
    pub(crate) pages: Vec<AtlasPage>,
    /// Maps a `TileId` to its storage location inside the atlas.
    regions: HashMap<TileId, AtlasRegion>,
    /// Deferred upload queue -- filled by [`insert`], drained by
    /// [`flush_uploads`].
    pending_uploads: Vec<PendingUpload>,
    /// Rolling byte count of texture data written during the current frame
    /// (reset at the start of each [`flush_uploads`] call).
    bytes_uploaded_this_frame: u64,
}

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

impl TileAtlas {
    /// Create an empty tile atlas.  No GPU memory is allocated until the
    /// first [`insert`](Self::insert) call.
    pub fn new() -> Self {
        Self {
            pages: Vec::new(),
            regions: HashMap::new(),
            pending_uploads: Vec::new(),
            bytes_uploaded_this_frame: 0,
        }
    }

    // -- Queries ----------------------------------------------------------

    /// Look up where a tile is stored.  Returns `None` if the tile has not
    /// been uploaded.
    #[inline]
    pub fn get(&self, id: &TileId) -> Option<&AtlasRegion> {
        self.regions.get(id)
    }

    /// Check whether a tile is present in the atlas.
    #[inline]
    pub fn contains(&self, id: &TileId) -> bool {
        self.regions.contains_key(id)
    }

    /// Total number of tiles currently stored across all pages.
    #[inline]
    pub fn len(&self) -> usize {
        self.regions.len()
    }

    /// Whether the atlas contains zero tiles.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.regions.is_empty()
    }

    /// Number of atlas pages currently allocated.
    #[inline]
    pub fn page_count(&self) -> usize {
        self.pages.len()
    }

    // -- Mutation ----------------------------------------------------------

    /// Enqueue a decoded tile image for deferred GPU upload.
    ///
    /// If the tile is already present this is a no-op and returns the
    /// existing region.  Otherwise a free slot is allocated (creating a new
    /// atlas page when necessary), the mip chain is pre-computed on the CPU,
    /// and a [`PendingUpload`] is enqueued.  The actual GPU write happens
    /// later when [`flush_uploads`](Self::flush_uploads) is called.
    ///
    /// # Arguments
    ///
    /// * `device` -- WGPU device, used only if a new atlas page must be created.
    /// * `id`     -- The tile identity.
    /// * `image`  -- Decoded RGBA8 tile imagery used to generate all mip levels.
    ///
    /// # Panics
    ///
    /// Panics (via `expect`) if a freshly created atlas page has no free
    /// slots, which cannot happen by construction.
    pub fn insert(
        &mut self,
        device: &wgpu::Device,
        id: TileId,
        image: &DecodedImage,
    ) -> AtlasRegion {
        // Early-out if the tile is already uploaded or enqueued.
        if let Some(region) = self.regions.get(&id) {
            return *region;
        }

        // Allocate an atlas slot (may create a new page).
        let (page_idx, col, row) = self.alloc_slot(device);

        // Build the full mip chain on the CPU (no GPU interaction yet).
        let mip_chain = image
            .build_mip_chain_rgba8()
            .expect("TileAtlas::insert requires valid RGBA8 tile imagery");

        // Enqueue the upload -- the actual write happens in flush_uploads.
        self.pending_uploads.push(PendingUpload {
            page_idx,
            col,
            row,
            mip_chain,
        });

        let region = AtlasRegion {
            page: page_idx,
            col,
            row,
        };
        self.regions.insert(id, region);
        region
    }

    /// Flush all pending tile uploads to the GPU.
    ///
    /// Each enqueued [`PendingUpload`] writes only the affected slot's pixel
    /// rectangle via `queue.write_texture` - the rest of the atlas page is
    /// left untouched.  This is the "partial texture write" path that
    /// replaces the previous full-page re-upload approach.
    ///
    /// Call once per frame, after all [`insert`](Self::insert) calls and
    /// before building batched geometry.
    ///
    /// Returns the number of tiles that were uploaded this frame.
    pub fn flush_uploads(&mut self, queue: &wgpu::Queue) -> usize {
        self.bytes_uploaded_this_frame = 0;
        let count = self.pending_uploads.len();

        for upload in self.pending_uploads.drain(..) {
            let page_texture = &self.pages[upload.page_idx].texture;

            for (level, mip) in upload.mip_chain.levels().iter().enumerate() {
                let mip_level = level as u32;
                // Slot pixel size at this mip level.
                let slot_size = (TILE_SIZE >> mip_level).max(1);
                let copy_w = mip.width.min(slot_size);
                let copy_h = mip.height.min(slot_size);

                // Write only the slot's sub-rectangle within the atlas page.
                queue.write_texture(
                    wgpu::TexelCopyTextureInfo {
                        texture: page_texture,
                        mip_level,
                        origin: wgpu::Origin3d {
                            x: upload.col * slot_size,
                            y: upload.row * slot_size,
                            z: 0,
                        },
                        aspect: wgpu::TextureAspect::All,
                    },
                    &mip.data,
                    wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(4 * mip.width),
                        rows_per_image: Some(mip.height),
                    },
                    wgpu::Extent3d {
                        width: copy_w,
                        height: copy_h,
                        depth_or_array_layers: 1,
                    },
                );

                // Track bytes uploaded for diagnostics.
                self.bytes_uploaded_this_frame += (copy_w as u64) * (copy_h as u64) * 4;
            }
        }

        count
    }

    /// Mark a tile as used this frame (prevents eviction at end-of-frame).
    ///
    /// Call this for every `TileId` that participates in the current frame's
    /// draw calls -- both imagery tiles and terrain tiles.
    pub fn mark_used(&mut self, id: &TileId) {
        if let Some(region) = self.regions.get(id) {
            if region.page < self.pages.len() {
                self.pages[region.page].mark_used(region.col, region.row);
            }
        }
    }

    /// End-of-frame housekeeping: evict unused slots and optionally compact.
    ///
    /// Call **once** after `queue.submit()`.  Tiles that were not
    /// [`mark_used`](Self::mark_used) this frame have their slots freed
    /// and their `regions` entries removed.
    ///
    /// When overall fragmentation exceeds 30% of allocated capacity, a
    /// compaction pass repacks all live tiles into the fewest contiguous
    /// slots and frees trailing empty pages.
    pub fn end_frame(&mut self) {
        // Evict slots that were not drawn this frame.
        for page in &mut self.pages {
            page.evict_unused();
        }

        // Remove lookup entries for slots that were freed.
        self.regions.retain(|_id, region| {
            let page = &self.pages[region.page];
            let idx = (region.row * SLOTS_PER_SIDE + region.col) as usize;
            page.occupied[idx]
        });

        // Compact when fragmentation is above the threshold.
        if self.fragmentation_ratio() > 0.30 {
            self.compact();
        }
    }

    /// Remove a specific tile from the atlas, freeing its slot immediately.
    pub fn remove(&mut self, id: &TileId) {
        if let Some(region) = self.regions.remove(id) {
            if region.page < self.pages.len() {
                self.pages[region.page].free_slot(region.col, region.row);
            }
        }
    }

    // -- Compaction -------------------------------------------------------

    /// Fraction of allocated capacity that is empty (fragmented).
    ///
    /// Returns `0.0` when there are no pages, and approaches `1.0` when
    /// most allocated slots are free.  Used by [`end_frame`](Self::end_frame)
    /// to decide whether compaction is worthwhile.
    pub fn fragmentation_ratio(&self) -> f32 {
        if self.pages.is_empty() {
            return 0.0;
        }
        let total_slots = self.pages.len() as f32 * SLOTS_PER_PAGE as f32;
        let occupied_slots = self.regions.len() as f32;
        1.0 - occupied_slots / total_slots
    }

    /// Repack live tiles into contiguous slots and free trailing empty pages.
    ///
    /// This operates *only* on the CPU-side metadata (slot occupancy and
    /// region lookup).  The pixel data already on the GPU is not moved;
    /// the next frame will naturally re-upload any tiles that need new
    /// slot assignments.  In practice, compaction simply clears the
    /// fragmentation so new inserts fill pages sequentially.
    ///
    /// Trailing pages with zero occupied slots are dropped, which frees
    /// the associated GPU texture allocation.
    fn compact(&mut self) {
        // Drop trailing pages that are completely empty.
        while let Some(last) = self.pages.last() {
            if last.occupied_count_inner() == 0 {
                self.pages.pop();
            } else {
                break;
            }
        }
    }

    // -- Diagnostics ------------------------------------------------------

    /// Snapshot of atlas health metrics for the current frame.
    ///
    /// The returned [`AtlasDiagnostics`] exposes page count, slot
    /// utilisation, bytes uploaded this frame, and the current
    /// fragmentation ratio - all useful for performance overlays and
    /// automated tests.
    pub fn diagnostics(&self) -> AtlasDiagnostics {
        let total_slots = self.pages.len() as u32 * SLOTS_PER_PAGE;
        let occupied_slots = self.regions.len() as u32;

        AtlasDiagnostics {
            page_count: self.pages.len() as u32,
            total_slots,
            occupied_slots,
            bytes_uploaded_this_frame: self.bytes_uploaded_this_frame,
            fragmentation_ratio: self.fragmentation_ratio(),
            pending_uploads: self.pending_uploads.len() as u32,
        }
    }

    // -- Internal ---------------------------------------------------------

    /// Find a free slot across all existing pages, or create a new page.
    ///
    /// Returns `(page_index, col, row)`.
    fn alloc_slot(&mut self, device: &wgpu::Device) -> (usize, u32, u32) {
        // Try existing pages first (prefer filling pages sequentially to
        // keep the working set compact).
        for (i, page) in self.pages.iter_mut().enumerate() {
            if let Some((col, row)) = page.alloc_slot() {
                return (i, col, row);
            }
        }
        // All pages full -- allocate a new one.
        let mut page = AtlasPage::new(device);
        let (col, row) = page.alloc_slot().expect("fresh page must have free slots");
        let idx = self.pages.len();
        self.pages.push(page);
        (idx, col, row)
    }
}

// ---------------------------------------------------------------------------
// AtlasDiagnostics -- health metrics snapshot
// ---------------------------------------------------------------------------

/// Snapshot of atlas health metrics for one frame.
///
/// Returned by [`TileAtlas::diagnostics`].  All fields are cheap copies
/// suitable for logging, overlay display, or automated assertions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AtlasDiagnostics {
    /// Number of atlas pages currently allocated (each is 64 MiB).
    pub page_count: u32,
    /// Total slot capacity across all pages.
    pub total_slots: u32,
    /// Number of slots that are currently occupied by a tile.
    pub occupied_slots: u32,
    /// Total bytes written to the GPU during the last
    /// [`flush_uploads`](TileAtlas::flush_uploads) call.
    pub bytes_uploaded_this_frame: u64,
    /// Fragmentation ratio (0.0 = fully packed, 1.0 = all slots empty).
    pub fragmentation_ratio: f32,
    /// Number of uploads still queued (should be 0 after flush).
    pub pending_uploads: u32,
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- AtlasRegion UV remapping -----------------------------------------

    #[test]
    fn remap_uv_origin_slot() {
        let region = AtlasRegion { page: 0, col: 0, row: 0 };
        let [u, v] = region.remap_uv(0.0, 0.0);
        // At (0,0) with u=0, v=0 we expect a small positive inset.
        assert!(u > 0.0, "half-texel inset should push u above 0");
        assert!(v > 0.0, "half-texel inset should push v above 0");
        assert!(u < HALF_TEXEL * 2.0);
        assert!(v < HALF_TEXEL * 2.0);

        let [u, v] = region.remap_uv(1.0, 1.0);
        let slot_edge = 1.0 / SLOTS_PER_SIDE as f32;
        assert!(u < slot_edge, "half-texel inset should pull u below slot edge");
        assert!(v < slot_edge, "half-texel inset should pull v below slot edge");
    }

    #[test]
    fn remap_uv_midpoint_is_exact() {
        // At u=0.5, v=0.5 the inset term is zero, so the result should
        // equal the un-inset centre of the slot.
        let region = AtlasRegion { page: 0, col: 3, row: 5 };
        let [u, v] = region.remap_uv(0.5, 0.5);
        let inv = 1.0 / SLOTS_PER_SIDE as f32;
        let expected_u = (3.0 + 0.5) * inv;
        let expected_v = (5.0 + 0.5) * inv;
        assert!((u - expected_u).abs() < 1e-7);
        assert!((v - expected_v).abs() < 1e-7);
    }

    #[test]
    fn remap_uv_symmetry() {
        // The inset at u=0.0 and u=1.0 should be symmetric around the
        // slot centre.
        let region = AtlasRegion { page: 0, col: 7, row: 7 };
        let [u0, _] = region.remap_uv(0.0, 0.5);
        let [u1, _] = region.remap_uv(1.0, 0.5);
        let centre = (u0 + u1) / 2.0;
        let inv = 1.0 / SLOTS_PER_SIDE as f32;
        let expected_centre = (7.0 + 0.5) * inv;
        assert!((centre - expected_centre).abs() < 1e-7);
    }

    // -- Slot arithmetic --------------------------------------------------

    #[test]
    fn slots_per_page_correct() {
        assert_eq!(SLOTS_PER_SIDE, 16);
        assert_eq!(SLOTS_PER_PAGE, 256);
    }

    #[test]
    fn half_texel_magnitude() {
        // With a 4096-texel page the half-texel inset should be ~0.000122.
        assert!((HALF_TEXEL - 0.5 / 4096.0).abs() < 1e-8);
    }

    // -- Fragmentation ratio ----------------------------------------------

    #[test]
    fn fragmentation_empty_atlas() {
        // No pages means 0% fragmentation (nothing to compact).
        let atlas = TileAtlas::new();
        assert_eq!(atlas.fragmentation_ratio(), 0.0);
    }

    // -- AtlasDiagnostics -------------------------------------------------

    #[test]
    fn diagnostics_empty_atlas() {
        let atlas = TileAtlas::new();
        let diag = atlas.diagnostics();
        assert_eq!(diag.page_count, 0);
        assert_eq!(diag.total_slots, 0);
        assert_eq!(diag.occupied_slots, 0);
        assert_eq!(diag.bytes_uploaded_this_frame, 0);
        assert_eq!(diag.fragmentation_ratio, 0.0);
        assert_eq!(diag.pending_uploads, 0);
    }

    #[test]
    fn diagnostics_default_eq() {
        // Two fresh atlases should produce identical diagnostics.
        let a = TileAtlas::new().diagnostics();
        let b = TileAtlas::default().diagnostics();
        assert_eq!(a, b);
    }
}