Skip to main content

euv_core/render/graph/
impl.rs

1use super::*;
2
3/// Default persistent incremental R8 GPU glyph atlas initialized at `1024x512`.
4impl Default for IncrementalGpuGlyphAtlas {
5    /// Creates an empty persistent R8 GPU glyph atlas with zero eagerly packed glyphs.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Initialized incremental GPU glyph atlas.
10    fn default() -> Self {
11        let width: u32 = GPU_GLYPH_ATLAS_INITIAL_WIDTH;
12        let height: u32 = GPU_GLYPH_ATLAS_INITIAL_HEIGHT;
13        Self {
14            width,
15            height,
16            pixels: vec![0u8; (width as usize).saturating_mul(height as usize)],
17            cursor_x: GPU_GLYPH_ATLAS_PAD_PX,
18            cursor_y: GPU_GLYPH_ATLAS_PAD_PX,
19            shelf_height: 0,
20            placements: HashMap::new(),
21            pending_dirty_rects: Vec::new(),
22            submission_dirty_rects: Vec::new(),
23            synced_revision: 0,
24            synced_entry_count: 0,
25            needs_full_upload: false,
26            submission_needs_full_upload: true,
27            total_uploaded_bytes: 0,
28        }
29    }
30}
31
32/// Incremental glyph shelf packing, UV lookup, and GPU sub-rectangle upload for `IncrementalGpuGlyphAtlas`.
33impl IncrementalGpuGlyphAtlas {
34    /// Looks up the cached GPU UV placement for `key` if already packed.
35    ///
36    /// # Arguments
37    ///
38    /// - `GlyphKey` - Rasterized glyph lookup key.
39    ///
40    /// # Returns
41    ///
42    /// - `Option<GpuGlyphPlacement>` - Placement coordinates and normalized UV rect when present.
43    #[must_use]
44    pub fn placement(&self, key: GlyphKey) -> Option<GpuGlyphPlacement> {
45        self.get_placements().get(&key).copied()
46    }
47
48    /// Packs a single rasterized glyph into the persistent R8 shelf and queues its dirty sub-rect for GPU upload.
49    ///
50    /// # Arguments
51    ///
52    /// - `GlyphKey` - Unique glyph cache key.
53    /// - `&RasterizedGlyph` - Rasterized alpha coverage bitmap.
54    ///
55    /// # Returns
56    ///
57    /// - `GpuGlyphPlacement` - Resolved atlas placement and normalized UV rectangle.
58    pub fn insert_or_get(&mut self, key: GlyphKey, glyph: &RasterizedGlyph) -> GpuGlyphPlacement {
59        if let Some(existing) = self.get_placements().get(&key).copied() {
60            return existing;
61        }
62        let glyph_w: u32 = glyph.get_width();
63        let glyph_h: u32 = glyph.get_height();
64        if glyph_w == 0 || glyph_h == 0 {
65            let empty: GpuGlyphPlacement = GpuGlyphPlacement::new(0, 0, 0, 0, [0, 0, 0, 0]);
66            let _: Option<GpuGlyphPlacement> = self.get_mut_placements().insert(key, empty);
67            return empty;
68        }
69        if self
70            .get_cursor_x()
71            .saturating_add(glyph_w)
72            .saturating_add(GPU_GLYPH_ATLAS_PAD_PX)
73            > self.get_width()
74        {
75            self.set_cursor_x(GPU_GLYPH_ATLAS_PAD_PX);
76            let next_y: u32 = self
77                .get_cursor_y()
78                .saturating_add(self.get_shelf_height())
79                .saturating_add(GPU_GLYPH_ATLAS_PAD_PX);
80            self.set_cursor_y(next_y);
81            self.set_shelf_height(0);
82        }
83        if self
84            .get_cursor_y()
85            .saturating_add(glyph_h)
86            .saturating_add(GPU_GLYPH_ATLAS_PAD_PX)
87            > self.get_height()
88        {
89            let next_h: u32 = (self.get_height().saturating_mul(2)).min(GPU_GLYPH_ATLAS_MAX_DIM);
90            if next_h > self.get_height() {
91                self.grow_height(next_h);
92            } else {
93                self.reset_shelves();
94            }
95        }
96        let dst_x: u32 = self.get_cursor_x();
97        let dst_y: u32 = self.get_cursor_y();
98        let atlas_w: u32 = self.get_width();
99        let atlas_h: u32 = self.get_height();
100        let coverage: &[u8] = glyph.get_coverage().as_slice();
101        let pixel_count: usize = (glyph_w as usize).saturating_mul(glyph_h as usize);
102        let is_color: bool = pixel_count > 0 && coverage.len() >= pixel_count.saturating_mul(4);
103        {
104            let pixels: &mut Vec<u8> = self.get_mut_pixels();
105            for row_idx in 0..glyph_h {
106                let dst_row: usize = ((dst_y + row_idx) as usize).saturating_mul(atlas_w as usize);
107                for col_idx in 0..glyph_w {
108                    let cov: u8 = if is_color {
109                        let src_idx: usize =
110                            ((row_idx as usize) * (glyph_w as usize) + (col_idx as usize)) * 4 + 3;
111                        coverage.get(src_idx).copied().unwrap_or(0)
112                    } else {
113                        let src_idx: usize =
114                            (row_idx as usize) * (glyph_w as usize) + (col_idx as usize);
115                        coverage.get(src_idx).copied().unwrap_or(0)
116                    };
117                    let dst_idx: usize = dst_row + ((dst_x + col_idx) as usize);
118                    if let Some(slot) = pixels.get_mut(dst_idx) {
119                        *slot = cov;
120                    }
121                }
122            }
123        }
124        let uv_rect: [u16; 4] =
125            encode_glyph_atlas_uv(dst_x, dst_y, glyph_w, glyph_h, atlas_w, atlas_h);
126        let placement: GpuGlyphPlacement =
127            GpuGlyphPlacement::new(dst_x, dst_y, glyph_w, glyph_h, uv_rect);
128        let _: Option<GpuGlyphPlacement> = self.get_mut_placements().insert(key, placement);
129        self.set_cursor_x(
130            dst_x
131                .saturating_add(glyph_w)
132                .saturating_add(GPU_GLYPH_ATLAS_PAD_PX),
133        );
134        self.set_shelf_height(self.get_shelf_height().max(glyph_h));
135        let dirty: PixelDirtyRect = PixelDirtyRect::new(dst_x, dst_y, glyph_w, glyph_h);
136        self.get_mut_pending_dirty_rects().push(dirty);
137        self.get_mut_submission_dirty_rects().push(dirty);
138        placement
139    }
140
141    /// Synchronizes all newly rasterized entries from `atlas` into this persistent incremental GPU atlas.
142    ///
143    /// # Arguments
144    ///
145    /// - `&GlyphAtlas` - Source CPU glyph cache.
146    ///
147    /// # Returns
148    ///
149    /// - `usize` - Number of newly packed glyphs added during this sync.
150    pub fn sync_from_glyph_atlas(&mut self, atlas: &GlyphAtlas) -> usize {
151        let rev: u64 = atlas.get_revision();
152        let entry_count: usize = atlas.len();
153        if rev == self.get_synced_revision() && entry_count == self.get_synced_entry_count() {
154            return 0;
155        }
156        if entry_count < self.get_synced_entry_count() {
157            self.reset_shelves();
158        }
159        let mut added: usize = 0;
160        for (key, glyph) in atlas.get_entries().iter() {
161            if !self.get_placements().contains_key(key) {
162                let _: GpuGlyphPlacement = self.insert_or_get(*key, glyph);
163                added += 1;
164            }
165        }
166        self.set_synced_revision(rev);
167        self.set_synced_entry_count(entry_count);
168        added
169    }
170
171    /// Drains all queued dirty glyph sub-rectangles pending GPU texture upload.
172    ///
173    /// # Returns
174    ///
175    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles accumulated since the last flush.
176    pub fn take_dirty_rects(&mut self) -> Vec<PixelDirtyRect> {
177        if self.get_needs_full_upload() {
178            self.set_needs_full_upload(false);
179            self.get_mut_pending_dirty_rects().clear();
180            return vec![PixelDirtyRect::new(
181                0,
182                0,
183                self.get_width(),
184                self.get_height(),
185            )];
186        }
187        take(self.get_mut_pending_dirty_rects())
188    }
189
190    /// Drains queued dirty glyph sub-rectangles strictly for direct-GPU platform swapchain submissions, unaffected by driver-local flushes.
191    ///
192    /// # Returns
193    ///
194    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles (or full atlas rect on initial/resized sync) pending swapchain upload.
195    pub fn take_submission_dirty_rects(&mut self) -> Vec<PixelDirtyRect> {
196        if self.get_submission_needs_full_upload() {
197            if self.get_placements().is_empty() {
198                return Vec::new();
199            }
200            self.set_submission_needs_full_upload(false);
201            self.get_mut_submission_dirty_rects().clear();
202            return vec![PixelDirtyRect::new(
203                0,
204                0,
205                self.get_width(),
206                self.get_height(),
207            )];
208        }
209        take(self.get_mut_submission_dirty_rects())
210    }
211
212    /// Uploads all pending dirty R8 sub-rectangles into `driver`'s resident GPU glyph texture slot 0.
213    ///
214    /// # Arguments
215    ///
216    /// - `&mut NativeGpuDriver` - Target hardware GPU driver.
217    ///
218    /// # Returns
219    ///
220    /// - `usize` - Total R8 texel bytes uploaded to the GPU texture during this flush.
221    pub fn flush_to_driver(&mut self, driver: &mut NativeGpuDriver) -> usize {
222        let dirty_rects: Vec<PixelDirtyRect> = self.take_dirty_rects();
223        if dirty_rects.is_empty() {
224            return 0;
225        }
226        let atlas_w: u32 = self.get_width();
227        let atlas_h: u32 = self.get_height();
228        let row_stride: usize = atlas_w as usize;
229        let mut uploaded_bytes: usize = 0;
230        let pixels_slice: &[u8] = self.get_pixels().as_slice();
231        for rect in dirty_rects.iter() {
232            let Some(clamped) = rect.clamp_to(atlas_w, atlas_h) else {
233                continue;
234            };
235            let start_offset: usize = (clamped.get_y() as usize)
236                .saturating_mul(row_stride)
237                .saturating_add(clamped.get_x() as usize);
238            if start_offset >= pixels_slice.len() {
239                continue;
240            }
241            let _: bool = driver.upload_texture_dirty_rect(
242                GpuAtlasPixelFormat::R8Unorm,
243                0,
244                (atlas_w, atlas_h),
245                (
246                    clamped.get_x(),
247                    clamped.get_y(),
248                    clamped.get_width(),
249                    clamped.get_height(),
250                ),
251                &pixels_slice[start_offset..],
252                row_stride,
253            );
254            uploaded_bytes = uploaded_bytes.saturating_add(clamped.area_pixels());
255        }
256        self.set_total_uploaded_bytes(
257            self.get_total_uploaded_bytes()
258                .saturating_add(uploaded_bytes as u64),
259        );
260        uploaded_bytes
261    }
262
263    /// Grows backing atlas height while preserving existing pixel rows and re-normalizing cached UVs.
264    ///
265    /// # Arguments
266    ///
267    /// - `u32` - New atlas height in texels.
268    fn grow_height(&mut self, next_height: u32) {
269        let atlas_w: u32 = self.get_width();
270        let next_len: usize = (atlas_w as usize).saturating_mul(next_height as usize);
271        self.get_mut_pixels().resize(next_len, 0);
272        self.set_height(next_height);
273        self.set_needs_full_upload(true);
274        self.set_submission_needs_full_upload(true);
275        for placement in self.get_mut_placements().values_mut() {
276            let uv: [u16; 4] = encode_glyph_atlas_uv(
277                placement.get_x(),
278                placement.get_y(),
279                placement.get_width(),
280                placement.get_height(),
281                atlas_w,
282                next_height,
283            );
284            placement.set_uv_rect(uv);
285        }
286    }
287
288    /// Clears all shelf placements and pixels, marking the atlas for a clean full upload.
289    fn reset_shelves(&mut self) {
290        self.get_mut_placements().clear();
291        self.get_mut_pixels().fill(0);
292        self.set_cursor_x(GPU_GLYPH_ATLAS_PAD_PX);
293        self.set_cursor_y(GPU_GLYPH_ATLAS_PAD_PX);
294        self.set_shelf_height(0);
295        self.get_mut_pending_dirty_rects().clear();
296        self.get_mut_submission_dirty_rects().clear();
297        self.set_needs_full_upload(true);
298        self.set_submission_needs_full_upload(true);
299    }
300}
301
302/// Default persistent incremental RGBA8 GPU image atlas initialized at `1024x512`.
303impl Default for IncrementalGpuImageAtlas {
304    /// Creates an empty persistent RGBA8 GPU image atlas ready for shelf packing.
305    ///
306    /// # Returns
307    ///
308    /// - `Self` - Initialized incremental GPU image atlas.
309    fn default() -> Self {
310        let width: u32 = GPU_IMAGE_ATLAS_INITIAL_WIDTH;
311        let height: u32 = GPU_IMAGE_ATLAS_INITIAL_HEIGHT;
312        let byte_len: usize = (width as usize)
313            .saturating_mul(height as usize)
314            .saturating_mul(4);
315        Self {
316            width,
317            height,
318            pixels: vec![0u8; byte_len],
319            cursor_x: GPU_IMAGE_ATLAS_PAD_PX,
320            cursor_y: GPU_IMAGE_ATLAS_PAD_PX,
321            shelf_height: 0,
322            placements: HashMap::new(),
323            submission_dirty_rects: Vec::new(),
324            submission_needs_full_upload: true,
325            revision: 0,
326        }
327    }
328}
329
330/// Incremental shelf packing, edge-clamped gutter blitting, and dirty-rect upload tracking for `IncrementalGpuImageAtlas`.
331impl IncrementalGpuImageAtlas {
332    /// Recycles atlas shelves at frame start when dynamic occupancy approaches capacity so mid-frame UV invalidations never occur.
333    pub fn begin_frame(&mut self) {
334        let height_limit: u32 = (self.get_height().saturating_mul(3)) / 4;
335        if self.get_cursor_y() >= height_limit
336            && self.get_height() >= GPU_IMAGE_ATLAS_MAX_DIM
337            && self.get_placements().len() > 8
338        {
339            self.reset_shelves();
340        }
341    }
342
343    /// Packs an RGBA8 image into the persistent shelf atlas (or reuses its cached placement by content hash) with a `1px` edge-clamped gutter.
344    ///
345    /// # Arguments
346    ///
347    /// - `u32` - Source image width in pixels.
348    /// - `u32` - Source image height in pixels.
349    /// - `&[u8]` - Tightly packed RGBA8 pixel slice (`width * height * 4`).
350    ///
351    /// # Returns
352    ///
353    /// - `Option<GpuImagePlacement>` - Resolved atlas placement and normalized UV rectangle, or `None` for empty buffers.
354    pub fn insert_or_get(
355        &mut self,
356        src_w: u32,
357        src_h: u32,
358        rgba_pixels: &[u8],
359    ) -> Option<GpuImagePlacement> {
360        let required: usize = (src_w as usize)
361            .saturating_mul(src_h as usize)
362            .saturating_mul(4);
363        if src_w == 0 || src_h == 0 || rgba_pixels.len() < required {
364            return None;
365        }
366        let key: u64 = hash_rgba8_image_content(src_w, src_h, &rgba_pixels[..required]);
367        if let Some(existing) = self.get_placements().get(&key).copied() {
368            return Some(existing);
369        }
370        let pad: u32 = GPU_IMAGE_ATLAS_PAD_PX;
371        let max_slot_dim: u32 = GPU_IMAGE_ATLAS_MAX_DIM.saturating_sub(pad.saturating_mul(2));
372        let (pack_w, pack_h): (u32, u32) = if src_w <= max_slot_dim && src_h <= max_slot_dim {
373            (src_w, src_h)
374        } else {
375            let scale_x: f32 = (max_slot_dim as f32) / (src_w as f32);
376            let scale_y: f32 = (max_slot_dim as f32) / (src_h as f32);
377            let fit: f32 = scale_x.min(scale_y);
378            (
379                ((src_w as f32) * fit).floor().max(1.0) as u32,
380                ((src_h as f32) * fit).floor().max(1.0) as u32,
381            )
382        };
383        let need_w: u32 = pack_w.saturating_add(pad.saturating_mul(2));
384        if need_w > self.get_width() {
385            let next_w: u32 = need_w.next_power_of_two().min(GPU_IMAGE_ATLAS_MAX_DIM);
386            self.grow_dimensions(next_w, self.get_height());
387        }
388        if self
389            .get_cursor_x()
390            .saturating_add(pack_w)
391            .saturating_add(pad)
392            > self.get_width()
393        {
394            self.set_cursor_x(pad);
395            let next_y: u32 = self
396                .get_cursor_y()
397                .saturating_add(self.get_shelf_height())
398                .saturating_add(pad.saturating_mul(2));
399            self.set_cursor_y(next_y);
400            self.set_shelf_height(0);
401        }
402        if self
403            .get_cursor_y()
404            .saturating_add(pack_h)
405            .saturating_add(pad)
406            > self.get_height()
407        {
408            let target_h: u32 = self
409                .get_cursor_y()
410                .saturating_add(pack_h)
411                .saturating_add(pad.saturating_mul(2))
412                .next_power_of_two()
413                .min(GPU_IMAGE_ATLAS_MAX_DIM);
414            if target_h > self.get_height() {
415                self.grow_dimensions(self.get_width(), target_h);
416            } else {
417                self.reset_shelves();
418                if pack_h.saturating_add(pad.saturating_mul(2)) > self.get_height() {
419                    let exact_h: u32 = pack_h
420                        .saturating_add(pad.saturating_mul(2))
421                        .next_power_of_two()
422                        .min(GPU_IMAGE_ATLAS_MAX_DIM);
423                    self.grow_dimensions(self.get_width(), exact_h);
424                }
425            }
426        }
427        let dst_x: u32 = self.get_cursor_x();
428        let dst_y: u32 = self.get_cursor_y();
429        let atlas_w: u32 = self.get_width();
430        let atlas_h: u32 = self.get_height();
431        {
432            let pixels: &mut Vec<u8> = self.get_mut_pixels();
433            let atlas_stride: usize = (atlas_w as usize).saturating_mul(4);
434            let src_stride: usize = (src_w as usize).saturating_mul(4);
435            if pack_w == src_w && pack_h == src_h {
436                for row_idx in 0..pack_h {
437                    let src_off: usize = (row_idx as usize).saturating_mul(src_stride);
438                    let dst_off: usize = ((dst_y + row_idx) as usize)
439                        .saturating_mul(atlas_stride)
440                        .saturating_add((dst_x as usize).saturating_mul(4));
441                    let row_bytes: usize = (pack_w as usize).saturating_mul(4);
442                    if src_off + row_bytes <= rgba_pixels.len()
443                        && dst_off + row_bytes <= pixels.len()
444                    {
445                        pixels[dst_off..(dst_off + row_bytes)]
446                            .copy_from_slice(&rgba_pixels[src_off..(src_off + row_bytes)]);
447                    }
448                }
449            } else {
450                for row_idx in 0..pack_h {
451                    let sy: u32 = (((row_idx as u64) * u64::from(src_h)) / u64::from(pack_h))
452                        .min(u64::from(src_h.saturating_sub(1)))
453                        as u32;
454                    let dst_row_off: usize =
455                        ((dst_y + row_idx) as usize).saturating_mul(atlas_stride);
456                    let src_row_off: usize = (sy as usize).saturating_mul(src_stride);
457                    for col_idx in 0..pack_w {
458                        let sx: u32 = (((col_idx as u64) * u64::from(src_w)) / u64::from(pack_w))
459                            .min(u64::from(src_w.saturating_sub(1)))
460                            as u32;
461                        let s_off: usize = src_row_off + (sx as usize) * 4;
462                        let d_off: usize = dst_row_off + ((dst_x + col_idx) as usize) * 4;
463                        if s_off + 4 <= rgba_pixels.len() && d_off + 4 <= pixels.len() {
464                            pixels[d_off..(d_off + 4)]
465                                .copy_from_slice(&rgba_pixels[s_off..(s_off + 4)]);
466                        }
467                    }
468                }
469            }
470            let left_gutter: bool = dst_x > 0;
471            let right_gutter: bool = dst_x.saturating_add(pack_w) < atlas_w;
472            for row_idx in 0..pack_h {
473                let row_base: usize = ((dst_y + row_idx) as usize).saturating_mul(atlas_stride);
474                if left_gutter {
475                    let src_px: usize = row_base + (dst_x as usize) * 4;
476                    let dst_px: usize = row_base + ((dst_x - 1) as usize) * 4;
477                    if src_px + 4 <= pixels.len() {
478                        let edge: [u8; 4] = [
479                            pixels[src_px],
480                            pixels[src_px + 1],
481                            pixels[src_px + 2],
482                            pixels[src_px + 3],
483                        ];
484                        pixels[dst_px..(dst_px + 4)].copy_from_slice(&edge);
485                    }
486                }
487                if right_gutter {
488                    let src_px: usize = row_base + ((dst_x + pack_w - 1) as usize) * 4;
489                    let dst_px: usize = row_base + ((dst_x + pack_w) as usize) * 4;
490                    if dst_px + 4 <= pixels.len() {
491                        let edge: [u8; 4] = [
492                            pixels[src_px],
493                            pixels[src_px + 1],
494                            pixels[src_px + 2],
495                            pixels[src_px + 3],
496                        ];
497                        pixels[dst_px..(dst_px + 4)].copy_from_slice(&edge);
498                    }
499                }
500            }
501            let copy_x0: u32 = dst_x.saturating_sub(1);
502            let copy_x1: u32 = dst_x.saturating_add(pack_w).saturating_add(1).min(atlas_w);
503            let span_bytes: usize = ((copy_x1.saturating_sub(copy_x0)) as usize).saturating_mul(4);
504            if dst_y > 0 && span_bytes > 0 {
505                let src_row: usize =
506                    (dst_y as usize).saturating_mul(atlas_stride) + (copy_x0 as usize) * 4;
507                let dst_row: usize =
508                    ((dst_y - 1) as usize).saturating_mul(atlas_stride) + (copy_x0 as usize) * 4;
509                if src_row + span_bytes <= pixels.len() {
510                    pixels.copy_within(src_row..(src_row + span_bytes), dst_row);
511                }
512            }
513            if dst_y.saturating_add(pack_h) < atlas_h && span_bytes > 0 {
514                let src_row: usize = ((dst_y + pack_h - 1) as usize).saturating_mul(atlas_stride)
515                    + (copy_x0 as usize) * 4;
516                let dst_row: usize = ((dst_y + pack_h) as usize).saturating_mul(atlas_stride)
517                    + (copy_x0 as usize) * 4;
518                if dst_row + span_bytes <= pixels.len() {
519                    pixels.copy_within(src_row..(src_row + span_bytes), dst_row);
520                }
521            }
522        }
523        let uv_rect: [u16; 4] =
524            encode_glyph_atlas_uv(dst_x, dst_y, pack_w, pack_h, atlas_w, atlas_h);
525        let placement: GpuImagePlacement =
526            GpuImagePlacement::new(dst_x, dst_y, pack_w, pack_h, uv_rect);
527        let _: Option<GpuImagePlacement> = self.get_mut_placements().insert(key, placement);
528        self.set_cursor_x(
529            dst_x
530                .saturating_add(pack_w)
531                .saturating_add(pad.saturating_mul(2)),
532        );
533        self.set_shelf_height(self.get_shelf_height().max(pack_h));
534        let dirty_x: u32 = dst_x.saturating_sub(1);
535        let dirty_y: u32 = dst_y.saturating_sub(1);
536        let dirty_w: u32 = dst_x
537            .saturating_add(pack_w)
538            .saturating_add(1)
539            .min(atlas_w)
540            .saturating_sub(dirty_x);
541        let dirty_h: u32 = dst_y
542            .saturating_add(pack_h)
543            .saturating_add(1)
544            .min(atlas_h)
545            .saturating_sub(dirty_y);
546        self.get_mut_submission_dirty_rects()
547            .push(PixelDirtyRect::new(dirty_x, dirty_y, dirty_w, dirty_h));
548        self.set_revision(self.get_revision().wrapping_add(1));
549        Some(placement)
550    }
551
552    /// Computes normalized sub-rectangle UV coordinates inside `placement` for a cropped `SpriteRegion`.
553    ///
554    /// # Arguments
555    ///
556    /// - `GpuImagePlacement` - Packed sheet placement inside this atlas.
557    /// - `u32` - Original sprite sheet width in pixels.
558    /// - `u32` - Original sprite sheet height in pixels.
559    /// - `Rect` - Cropped source sub-rectangle in sprite-sheet pixels.
560    ///
561    /// # Returns
562    ///
563    /// - `[u16; 4]` - Quantized normalized UV rectangle `[u0, v0, u1, v1]` in `[0..=65535]`.
564    #[must_use]
565    pub fn sub_uv_rect(
566        &self,
567        placement: GpuImagePlacement,
568        sheet_w: u32,
569        sheet_h: u32,
570        src_rect: Rect,
571    ) -> [u16; 4] {
572        let sx_scale: f32 = (placement.get_width() as f32) / (sheet_w.max(1) as f32);
573        let sy_scale: f32 = (placement.get_height() as f32) / (sheet_h.max(1) as f32);
574        let rx: f32 = (placement.get_x() as f32) + src_rect.get_x().max(0.0) * sx_scale;
575        let ry: f32 = (placement.get_y() as f32) + src_rect.get_y().max(0.0) * sy_scale;
576        let rw: f32 = (src_rect.get_width().max(1.0) * sx_scale).min(placement.get_width() as f32);
577        let rh: f32 =
578            (src_rect.get_height().max(1.0) * sy_scale).min(placement.get_height() as f32);
579        let inv_w: f32 = 1.0 / (self.get_width().max(1) as f32);
580        let inv_h: f32 = 1.0 / (self.get_height().max(1) as f32);
581        [
582            (rx * inv_w * 65535.0).round().clamp(0.0, 65535.0) as u16,
583            (ry * inv_h * 65535.0).round().clamp(0.0, 65535.0) as u16,
584            ((rx + rw) * inv_w * 65535.0).round().clamp(0.0, 65535.0) as u16,
585            ((ry + rh) * inv_h * 65535.0).round().clamp(0.0, 65535.0) as u16,
586        ]
587    }
588
589    /// Drains queued dirty RGBA8 sub-rectangles strictly for direct-GPU platform swapchain submissions.
590    ///
591    /// # Returns
592    ///
593    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles (or full atlas rect on initial/resized sync) pending swapchain upload.
594    pub fn take_submission_dirty_rects(&mut self) -> Vec<PixelDirtyRect> {
595        if self.get_submission_needs_full_upload() {
596            if self.get_placements().is_empty() {
597                return Vec::new();
598            }
599            self.set_submission_needs_full_upload(false);
600            self.get_mut_submission_dirty_rects().clear();
601            return vec![PixelDirtyRect::new(
602                0,
603                0,
604                self.get_width(),
605                self.get_height(),
606            )];
607        }
608        take(self.get_mut_submission_dirty_rects())
609    }
610
611    /// Grows backing RGBA8 atlas dimensions while preserving existing rows and re-normalizing cached UVs.
612    ///
613    /// # Arguments
614    ///
615    /// - `u32` - New atlas width in texels.
616    /// - `u32` - New atlas height in texels.
617    fn grow_dimensions(&mut self, next_width: u32, next_height: u32) {
618        let old_w: u32 = self.get_width();
619        let old_h: u32 = self.get_height();
620        let next_len: usize = (next_width as usize)
621            .saturating_mul(next_height as usize)
622            .saturating_mul(4);
623        let mut next_pixels: Vec<u8> = vec![0u8; next_len];
624        let old_stride: usize = (old_w as usize).saturating_mul(4);
625        let new_stride: usize = (next_width as usize).saturating_mul(4);
626        let copy_rows: u32 = old_h.min(next_height);
627        let copy_bytes: usize = old_stride.min(new_stride);
628        {
629            let old_pixels: &[u8] = self.get_pixels().as_slice();
630            for row_idx in 0..copy_rows {
631                let s_off: usize = (row_idx as usize).saturating_mul(old_stride);
632                let d_off: usize = (row_idx as usize).saturating_mul(new_stride);
633                if s_off + copy_bytes <= old_pixels.len() && d_off + copy_bytes <= next_pixels.len()
634                {
635                    next_pixels[d_off..(d_off + copy_bytes)]
636                        .copy_from_slice(&old_pixels[s_off..(s_off + copy_bytes)]);
637                }
638            }
639        }
640        self.set_width(next_width);
641        self.set_height(next_height);
642        self.set_pixels(next_pixels);
643        self.set_submission_needs_full_upload(true);
644        for placement in self.get_mut_placements().values_mut() {
645            let uv: [u16; 4] = encode_glyph_atlas_uv(
646                placement.get_x(),
647                placement.get_y(),
648                placement.get_width(),
649                placement.get_height(),
650                next_width,
651                next_height,
652            );
653            placement.set_uv_rect(uv);
654        }
655    }
656
657    /// Clears all packed image placements and pixels, scheduling a clean full RGBA8 upload.
658    fn reset_shelves(&mut self) {
659        self.get_mut_placements().clear();
660        self.get_mut_pixels().fill(0);
661        self.set_cursor_x(GPU_IMAGE_ATLAS_PAD_PX);
662        self.set_cursor_y(GPU_IMAGE_ATLAS_PAD_PX);
663        self.set_shelf_height(0);
664        self.get_mut_submission_dirty_rects().clear();
665        self.set_submission_needs_full_upload(true);
666        self.set_revision(self.get_revision().wrapping_add(1));
667    }
668}
669
670/// Default `RenderGraph` configured for `max_frames_in_flight = 2` pipelined CPU/GPU overlap.
671impl Default for RenderGraph {
672    /// Creates a `RenderGraph` with `2` frames in flight and empty dirty-span and glyph atlas caches.
673    ///
674    /// # Returns
675    ///
676    /// - `Self` - Initialized render-graph scheduler.
677    fn default() -> Self {
678        Self {
679            max_frames_in_flight: RENDER_GRAPH_DEFAULT_MAX_IN_FLIGHT,
680            dirty_coalescer: DirtySpanCoalescer::default(),
681            gpu_glyph_atlas: IncrementalGpuGlyphAtlas::default(),
682            last_plan: RenderGraphFramePlan::default(),
683            last_receipt: RenderGraphExecutionReceipt::default(),
684            executed_frames: 0,
685        }
686    }
687}
688
689/// Construction helpers for `RenderGraphFrameTarget`.
690impl RenderGraphFrameTarget {
691    /// Creates a frame target descriptor without an external offscreen texture.
692    ///
693    /// # Arguments
694    ///
695    /// - `u32` - Physical surface width in pixels.
696    /// - `u32` - Physical surface height in pixels.
697    /// - `Color` - Surface clear color.
698    ///
699    /// # Returns
700    ///
701    /// - `Self` - Configured frame target descriptor.
702    #[must_use]
703    pub fn new(width: u32, height: u32, clear_color: Color) -> Self {
704        Self {
705            width,
706            height,
707            clear_color,
708            external_texture_handle: 0,
709        }
710    }
711
712    /// Attaches an external GPU texture handle for Pass 2 compositing.
713    ///
714    /// # Arguments
715    ///
716    /// - `usize` - External GPU texture handle (`0` disables Pass 2).
717    ///
718    /// # Returns
719    ///
720    /// - `Self` - Updated frame target descriptor.
721    #[must_use]
722    pub fn with_external_texture(mut self, external_texture_handle: usize) -> Self {
723        self.set_external_texture_handle(external_texture_handle);
724        self
725    }
726}
727
728/// Pass planning, coalesced dirty upload, Dual-Kawase blur orchestration, and submission for `RenderGraph`.
729impl RenderGraph {
730    /// Builds an explicit pass execution plan for the current frame.
731    ///
732    /// # Arguments
733    ///
734    /// - `RenderGraphFrameTarget` - Target surface dimensions and optional external texture handle.
735    /// - `RenderGraphPlanCounts` - Active pass counts for Pass 0, Pass 1, and Pass 3.
736    ///
737    /// # Returns
738    ///
739    /// - `RenderGraphFramePlan` - Ordered render-graph pass schedule.
740    #[must_use]
741    pub fn plan_frame(
742        &self,
743        target: RenderGraphFrameTarget,
744        counts: RenderGraphPlanCounts,
745    ) -> RenderGraphFramePlan {
746        let mut passes: Vec<RenderGraphPassKind> = Vec::with_capacity(5);
747        if counts.get_has_compute_layout() {
748            passes.push(RenderGraphPassKind::ComputeLayout);
749        }
750        if counts.get_dirty_span_count() > 0 || counts.get_atlas_dirty_rect_count() > 0 {
751            passes.push(RenderGraphPassKind::BlitAndAtlasUpload);
752        }
753        if target.get_external_texture_handle() != 0 {
754            passes.push(RenderGraphPassKind::OffscreenExternalTarget);
755        }
756        if counts.get_blur_pass_count() > 0 {
757            passes.push(RenderGraphPassKind::DualKawaseBackdropBlur);
758        }
759        passes.push(RenderGraphPassKind::UberUiDirectAndIndirect);
760        RenderGraphFramePlan {
761            passes,
762            width: target.get_width(),
763            height: target.get_height(),
764            dirty_span_count: counts.get_dirty_span_count(),
765            atlas_dirty_rect_count: counts.get_atlas_dirty_rect_count(),
766            blur_pass_count: counts
767                .get_blur_pass_count()
768                .min(RENDER_GRAPH_MAX_BLUR_PASSES),
769            external_texture_handle: target.get_external_texture_handle(),
770        }
771    }
772
773    /// Executes Passes 0..4 against `driver`, updating real GPU timing, dirty-span savings, and completion fences.
774    ///
775    /// # Arguments
776    ///
777    /// - `&mut NativeGpuDriver` - Target hardware GPU driver.
778    /// - `RenderGraphFrameTarget` - Surface dimensions, clear color, and optional external texture handle.
779    /// - `&[GpuBatch]` - Coalesced 64-byte primitive batches for Pass 4.
780    /// - `&[GpuBackdropBlurPass]` - Dual-Kawase backdrop blur regions for Pass 3.
781    /// - `Option<(&mut GpuComputeLayoutEngine, &GpuComputeSceneInput)>` - Optional Pass 0 GPU compute layout workload.
782    ///
783    /// # Returns
784    ///
785    /// - `Result<RenderGraphExecutionReceipt, PlatformError>` - Detailed pass execution and timing receipt.
786    pub fn execute_frame(
787        &mut self,
788        driver: &mut NativeGpuDriver,
789        target: RenderGraphFrameTarget,
790        batches: &[GpuBatch],
791        blur_passes: &[GpuBackdropBlurPass],
792        compute_work: Option<(&mut GpuComputeLayoutEngine, &GpuComputeSceneInput)>,
793    ) -> Result<RenderGraphExecutionReceipt, PlatformError> {
794        let width: u32 = target.get_width();
795        let height: u32 = target.get_height();
796        let clear_color: Color = target.get_clear_color();
797        let external_texture_handle: usize = target.get_external_texture_handle();
798        let dirty_spans_count: usize = if batches.len() == 1 {
799            self.get_mut_dirty_coalescer()
800                .diff_and_coalesce(batches[0].get_primitives().as_slice())
801                .len()
802        } else {
803            let mut flat_prims: Vec<GpuPrimitiveInstance> = Vec::new();
804            for batch in batches.iter() {
805                flat_prims.extend_from_slice(batch.get_primitives().as_slice());
806            }
807            self.get_mut_dirty_coalescer()
808                .diff_and_coalesce(flat_prims.as_slice())
809                .len()
810        };
811        let dirty_upload_bytes: usize = self.get_dirty_coalescer().get_last_dirty_bytes();
812        let full_upload_bytes: usize = self.get_dirty_coalescer().get_last_full_bytes();
813        let pending_atlas_rects: usize = self.get_gpu_glyph_atlas().get_pending_dirty_rects().len()
814            + usize::from(self.get_gpu_glyph_atlas().get_needs_full_upload());
815        let plan_counts: RenderGraphPlanCounts = RenderGraphPlanCounts::new(
816            compute_work.is_some(),
817            dirty_spans_count,
818            pending_atlas_rects,
819            blur_passes.len(),
820        );
821        let plan: RenderGraphFramePlan = self.plan_frame(target, plan_counts);
822        let observed_completed: u64 = completed_gpu_fence();
823        let mut gpu_compute_ns: u64 = last_gpu_compute_ns();
824        let mut draw_calls: usize = 0;
825        if let Some((compute_engine, compute_scene)) = compute_work {
826            let comp_res: GpuComputeDispatchResult = compute_engine.dispatch(compute_scene, false);
827            gpu_compute_ns = comp_res.get_gpu_compute_ns();
828            draw_calls = draw_calls.saturating_add(comp_res.get_draw_calls());
829        }
830        let atlas_upload_bytes: usize = self.get_mut_gpu_glyph_atlas().flush_to_driver(driver);
831        if external_texture_handle != 0 {
832            driver.set_external_texture(external_texture_handle);
833        }
834        let blur_executed: usize =
835            if !blur_passes.is_empty() && driver.supports_backdrop_blur_pass() {
836                driver.execute_dual_kawase_blur_passes(width, height, blur_passes)
837            } else {
838                0
839            };
840        let ui_draws: usize = driver.submit_batches(width, height, clear_color, batches)?;
841        draw_calls = draw_calls
842            .saturating_add(ui_draws)
843            .saturating_add(blur_executed.saturating_mul(2));
844        let submitted_fence_id: u64 = submitted_gpu_fence().max(driver.get_submitted_frames());
845        let gpu_render_ns: u64 = driver.get_last_gpu_exec_ns().max(last_gpu_render_ns());
846        let receipt: RenderGraphExecutionReceipt = RenderGraphExecutionReceipt {
847            executed_passes: plan.get_passes().clone(),
848            submitted_fence_id,
849            observed_completed_fence_id: observed_completed,
850            dirty_upload_bytes,
851            full_upload_bytes,
852            atlas_upload_bytes,
853            blur_passes_executed: blur_executed,
854            draw_calls,
855            gpu_compute_ns,
856            gpu_render_ns,
857        };
858        self.set_last_plan(plan);
859        self.set_last_receipt(receipt.clone());
860        self.set_executed_frames(self.get_executed_frames().wrapping_add(1));
861        Ok(receipt)
862    }
863}