Skip to main content

euv_core/render/ring/
impl.rs

1use super::*;
2
3/// Default bounded GPU resource ring configured for 3 in-flight frames and 16 MiB scroll tile cache.
4impl Default for GpuResourceRing {
5    /// Creates a bounded GPU resource ring with default staging and tile budgets.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Initialized GPU resource ring.
10    fn default() -> Self {
11        Self::with_limits(
12            GPU_RING_DEFAULT_SLOTS,
13            GPU_RING_DEFAULT_MAX_TOTAL_BYTES,
14            GPU_TILE_CACHE_DEFAULT_BUDGET_BYTES,
15        )
16    }
17}
18
19/// Bounded staging ring acquisition, fence completion, persistent scroll tile caching, and deferred reclamation for `GpuResourceRing`.
20impl GpuResourceRing {
21    /// Creates a bounded GPU resource ring with explicit staging slot count, staging byte ceiling, and tile budget.
22    ///
23    /// # Arguments
24    ///
25    /// - `usize` - Maximum number of staging ring slots (`>= 1`).
26    /// - `usize` - Maximum aggregate staging bytes across all slots.
27    /// - `usize` - Maximum resident bytes for persistent scroll tile textures.
28    ///
29    /// # Returns
30    ///
31    /// - `Self` - Configured GPU resource ring.
32    #[must_use]
33    pub fn with_limits(max_slots: usize, max_total_bytes: usize, tile_budget_bytes: usize) -> Self {
34        let clamped_slots: usize = max_slots.max(1);
35        let clamped_staging: usize = max_total_bytes.max(4096);
36        let clamped_tiles: usize = tile_budget_bytes.max(GPU_TILE_CACHE_MIN_BUDGET_BYTES);
37        let mut slots: Vec<GpuStagingSlot> = Vec::with_capacity(clamped_slots);
38        for idx in 0..clamped_slots {
39            slots.push(GpuStagingSlot {
40                slot_index: idx,
41                handle: RenderResourceHandle::new(
42                    (idx as u64) + 1,
43                    1,
44                    RenderResourceKind::StagingSlot,
45                    0,
46                    0,
47                ),
48                capacity_bytes: 0,
49                used_bytes: 0,
50                fence_id: 0,
51                in_flight: false,
52                reuse_count: 0,
53            });
54        }
55        Self {
56            max_slots: clamped_slots,
57            max_total_bytes: clamped_staging,
58            slots,
59            next_fence_id: 1,
60            completed_fence_id: 0,
61            next_handle_id: (clamped_slots as u64) + 1,
62            cursor: 0,
63            total_allocations: 0,
64            total_reuses: 0,
65            dropped_prefetch_uploads: 0,
66            deferred_frame_uploads: 0,
67            tile_budget_bytes: clamped_tiles,
68            tile_resident_bytes: 0,
69            tile_clock: 0,
70            tile_hits: 0,
71            tile_misses: 0,
72            tile_evictions: 0,
73            tiles: Vec::new(),
74            pending_reclaim: Vec::new(),
75            pending_reclaim_bytes: 0,
76            reclaimed_count: 0,
77            pending_texture_uploads: Vec::new(),
78            total_texture_upload_bytes: 0,
79        }
80    }
81
82    /// Returns whether `fence_id` has retired relative to `completed_fence_id` with wrap-around safety.
83    ///
84    /// # Arguments
85    ///
86    /// - `u64` - Fence identifier guarding a GPU resource or staging slot.
87    /// - `u64` - Latest completed GPU fence identifier (`0` when no fence has completed yet).
88    ///
89    /// # Returns
90    ///
91    /// - `bool` - `true` when `fence_id` is retired and safe for CPU reuse.
92    #[must_use]
93    pub fn fence_is_completed(fence_id: u64, completed_fence_id: u64) -> bool {
94        if fence_id == 0 {
95            return true;
96        }
97        if completed_fence_id == 0 {
98            return false;
99        }
100        (completed_fence_id.wrapping_sub(fence_id) as i64) >= 0
101    }
102
103    /// Advances `fence_id` monotonically across the non-zero 64-bit fence space.
104    ///
105    /// # Arguments
106    ///
107    /// - `u64` - Current fence identifier.
108    ///
109    /// # Returns
110    ///
111    /// - `u64` - Next non-zero monotonic fence identifier.
112    #[must_use]
113    pub fn next_monotonic_fence(fence_id: u64) -> u64 {
114        let next: u64 = fence_id.wrapping_add(1);
115        if next == 0 { 1 } else { next }
116    }
117
118    /// Allocates the next monotonic `RenderResourceHandle` of `kind` and `byte_size`.
119    ///
120    /// # Arguments
121    ///
122    /// - `&Self` - Mutable GPU resource ring.
123    /// - `RenderResourceKind` - Resource category.
124    /// - `usize` - Resident byte size.
125    /// - `u64` - Associated GPU fence ID.
126    ///
127    /// # Returns
128    ///
129    /// - `RenderResourceHandle` - Fresh generation-1 handle.
130    fn alloc_handle(
131        &mut self,
132        kind: RenderResourceKind,
133        byte_size: usize,
134        fence_id: u64,
135    ) -> RenderResourceHandle {
136        let id: u64 = self.get_next_handle_id();
137        self.set_next_handle_id(id.wrapping_add(1).max(1));
138        RenderResourceHandle::new(id, 1, kind, byte_size, fence_id)
139    }
140
141    /// Acquires an idle or fence-completed staging slot for `required_bytes` without unbounded queue growth.
142    ///
143    /// # Arguments
144    ///
145    /// - `&Self` - Mutable GPU resource ring.
146    /// - `usize` - Upload payload size in bytes.
147    /// - `GpuUploadPriority` - Priority deciding whether a full ring drops prefetch or defers the frame.
148    ///
149    /// # Returns
150    ///
151    /// - `GpuRingAcquireResult` - Acquired slot and fence ID, or bounded backpressure status.
152    pub fn acquire_staging(
153        &mut self,
154        required_bytes: usize,
155        priority: GpuUploadPriority,
156    ) -> GpuRingAcquireResult {
157        let completed: u64 = self.get_completed_fence_id();
158        let slot_count: usize = self.get_slots().len();
159        let start: usize = self.get_cursor() % slot_count.max(1);
160        let mut chosen: Option<usize> = None;
161        for step in 0..slot_count {
162            let idx: usize = (start + step) % slot_count;
163            let slot: GpuStagingSlot = self.get_slots()[idx];
164            if !slot.get_in_flight() || Self::fence_is_completed(slot.get_fence_id(), completed) {
165                chosen = Some(idx);
166                break;
167            }
168        }
169        let Some(slot_idx) = chosen else {
170            return match priority {
171                GpuUploadPriority::OptionalPrefetch => {
172                    self.set_dropped_prefetch_uploads(
173                        self.get_dropped_prefetch_uploads().saturating_add(1),
174                    );
175                    GpuRingAcquireResult::DroppedPrefetchRingFull
176                }
177                GpuUploadPriority::RequiredFrame => {
178                    self.set_deferred_frame_uploads(
179                        self.get_deferred_frame_uploads().saturating_add(1),
180                    );
181                    GpuRingAcquireResult::DeferredFrameRingFull
182                }
183            };
184        };
185        let fence_id: u64 = self.get_next_fence_id();
186        self.set_next_fence_id(Self::next_monotonic_fence(fence_id));
187        let prev_slot: GpuStagingSlot = self.get_slots()[slot_idx];
188        let old_cap: usize = prev_slot.get_capacity_bytes();
189        let mut total_other_bytes: usize = 0;
190        for (idx, s) in self.get_slots().iter().enumerate() {
191            if idx != slot_idx {
192                total_other_bytes = total_other_bytes.saturating_add(s.get_capacity_bytes());
193            }
194        }
195        let needed_cap: usize = if required_bytes == 0 {
196            old_cap.max(4096)
197        } else {
198            required_bytes
199                .max(GPU_RING_DEFAULT_SLOT_BYTES.min(required_bytes.next_power_of_two()))
200                .next_power_of_two()
201        };
202        let mut reused: bool = old_cap >= required_bytes && old_cap > 0;
203        let new_cap: usize = if reused {
204            old_cap
205        } else {
206            let max_allowed: usize = self.get_max_total_bytes().saturating_sub(total_other_bytes);
207            if required_bytes > max_allowed && priority == GpuUploadPriority::OptionalPrefetch {
208                self.set_dropped_prefetch_uploads(
209                    self.get_dropped_prefetch_uploads().saturating_add(1),
210                );
211                return GpuRingAcquireResult::DroppedPrefetchRingFull;
212            }
213            if old_cap > 0 && !Self::fence_is_completed(prev_slot.get_fence_id(), completed) {
214                self.queue_deferred_reclaim(prev_slot.get_handle(), prev_slot.get_fence_id());
215            }
216            reused = false;
217            needed_cap.min(max_allowed.max(required_bytes))
218        };
219        let slot_ref: &mut GpuStagingSlot = &mut self.get_mut_slots()[slot_idx];
220        if !reused {
221            let next_gen: u32 = slot_ref
222                .get_handle()
223                .get_generation()
224                .wrapping_add(1)
225                .max(1);
226            let mut next_handle: RenderResourceHandle = slot_ref.get_handle();
227            next_handle.set_generation(next_gen);
228            next_handle.set_byte_size(new_cap);
229            next_handle.set_fence_id(fence_id);
230            slot_ref.set_handle(next_handle);
231            slot_ref.set_capacity_bytes(new_cap);
232        } else {
233            let mut next_handle: RenderResourceHandle = slot_ref.get_handle();
234            next_handle.set_fence_id(fence_id);
235            slot_ref.set_handle(next_handle);
236            slot_ref.set_reuse_count(slot_ref.get_reuse_count().saturating_add(1));
237        }
238        slot_ref.set_used_bytes(required_bytes);
239        slot_ref.set_fence_id(fence_id);
240        slot_ref.set_in_flight(true);
241        if reused {
242            self.set_total_reuses(self.get_total_reuses().saturating_add(1));
243        } else {
244            self.set_total_allocations(self.get_total_allocations().saturating_add(1));
245        }
246        self.set_cursor((slot_idx + 1) % slot_count.max(1));
247        GpuRingAcquireResult::Acquired {
248            slot_index: slot_idx,
249            fence_id,
250            reused,
251        }
252    }
253
254    /// Marks GPU fence `fence_id` complete, releasing finished staging slots and reclaiming deferred GPU resources.
255    ///
256    /// # Arguments
257    ///
258    /// - `&Self` - Mutable GPU resource ring.
259    /// - `u64` - Completed monotonic GPU fence identifier.
260    ///
261    /// # Returns
262    ///
263    /// - `usize` - Number of deferred GPU resources reclaimed by this fence completion.
264    pub fn complete_fence(&mut self, fence_id: u64) -> usize {
265        let prev_completed: u64 = self.get_completed_fence_id();
266        if fence_id != 0
267            && (prev_completed == 0 || (fence_id.wrapping_sub(prev_completed) as i64) > 0)
268        {
269            self.set_completed_fence_id(fence_id);
270        }
271        let completed: u64 = self.get_completed_fence_id();
272        for slot in self.get_mut_slots().iter_mut() {
273            if slot.get_in_flight() && Self::fence_is_completed(slot.get_fence_id(), completed) {
274                slot.set_in_flight(false);
275            }
276        }
277        let Self {
278            pending_reclaim,
279            pending_reclaim_bytes,
280            reclaimed_count,
281            ..
282        } = self;
283        let before: usize = pending_reclaim.len();
284        let mut reclaimed_bytes: usize = 0;
285        pending_reclaim.retain(|item: &DeferredGpuReclaim| {
286            if Self::fence_is_completed(item.get_retire_fence_id(), completed) {
287                reclaimed_bytes = reclaimed_bytes.saturating_add(item.get_byte_size());
288                false
289            } else {
290                true
291            }
292        });
293        let reclaimed_now: usize = before.saturating_sub(pending_reclaim.len());
294        *pending_reclaim_bytes = pending_reclaim_bytes.saturating_sub(reclaimed_bytes);
295        *reclaimed_count = reclaimed_count.saturating_add(reclaimed_now as u64);
296        reclaimed_now
297    }
298
299    /// Returns the number of staging slots currently in flight on the GPU.
300    ///
301    /// # Arguments
302    ///
303    /// - `&Self` - GPU resource ring reference.
304    ///
305    /// # Returns
306    ///
307    /// - `usize` - Count of in-flight staging slots.
308    #[must_use]
309    pub fn in_flight_slot_count(&self) -> usize {
310        let completed: u64 = self.get_completed_fence_id();
311        self.get_slots()
312            .iter()
313            .filter(|s: &&GpuStagingSlot| {
314                s.get_in_flight() && !Self::fence_is_completed(s.get_fence_id(), completed)
315            })
316            .count()
317    }
318
319    /// Returns total allocated bytes across all staging buffer slots.
320    ///
321    /// # Arguments
322    ///
323    /// - `&Self` - GPU resource ring reference.
324    ///
325    /// # Returns
326    ///
327    /// - `usize` - Aggregate staging buffer bytes.
328    #[must_use]
329    pub fn staging_allocated_bytes(&self) -> usize {
330        self.get_slots()
331            .iter()
332            .fold(0_usize, |acc: usize, s: &GpuStagingSlot| {
333                acc.saturating_add(s.get_capacity_bytes())
334            })
335    }
336
337    /// Queues an evicted GPU resource handle for fence-deferred reclamation.
338    ///
339    /// # Arguments
340    ///
341    /// - `&Self` - Mutable GPU resource ring.
342    /// - `RenderResourceHandle` - Evicted resource handle.
343    /// - `u64` - Fence ID that must complete before release.
344    fn queue_deferred_reclaim(&mut self, handle: RenderResourceHandle, retire_fence_id: u64) {
345        let bytes: usize = handle.get_byte_size();
346        if Self::fence_is_completed(retire_fence_id, self.get_completed_fence_id()) {
347            self.set_reclaimed_count(self.get_reclaimed_count().saturating_add(1));
348            return;
349        }
350        self.get_mut_pending_reclaim().push(DeferredGpuReclaim::new(
351            handle,
352            retire_fence_id,
353            bytes,
354        ));
355        self.set_pending_reclaim_bytes(self.get_pending_reclaim_bytes().saturating_add(bytes));
356    }
357
358    /// Marks all cached scroll tiles as non-visible before starting a new frame's visibility pass.
359    ///
360    /// # Arguments
361    ///
362    /// - `&Self` - Mutable GPU resource ring.
363    pub fn begin_tile_frame(&mut self) {
364        for tile in self.get_mut_tiles().iter_mut() {
365            tile.set_visible_this_frame(false);
366        }
367    }
368
369    /// Looks up or allocates a persistent scroll tile texture, touching LRU age and tagging `fence_id`.
370    ///
371    /// # Arguments
372    ///
373    /// - `&Self` - Mutable GPU resource ring.
374    /// - `GpuScrollTileKey` - Content/DPI/layer key for the tile.
375    /// - `u32` - Tile physical width in pixels.
376    /// - `u32` - Tile physical height in pixels.
377    /// - `u64` - Active frame GPU fence identifier.
378    /// - `bool` - Whether this tile is visible in the current viewport.
379    ///
380    /// # Returns
381    ///
382    /// - `(RenderResourceHandle, bool)` - Tile handle and `true` on cache hit (`false` on fresh miss).
383    pub fn acquire_scroll_tile(
384        &mut self,
385        key: GpuScrollTileKey,
386        width: u32,
387        height: u32,
388        fence_id: u64,
389        visible: bool,
390    ) -> (RenderResourceHandle, bool) {
391        let next_tick: u64 = self.get_tile_clock().wrapping_add(1);
392        self.set_tile_clock(next_tick);
393        let hit_idx: Option<usize> = self
394            .get_tiles()
395            .iter()
396            .position(|entry: &GpuScrollTileEntry| entry.get_key() == key);
397        if let Some(idx) = hit_idx {
398            let tile_ref: &mut GpuScrollTileEntry = &mut self.get_mut_tiles()[idx];
399            tile_ref.set_last_used_tick(next_tick);
400            tile_ref.set_last_fence_id(fence_id.max(tile_ref.get_last_fence_id()));
401            if visible {
402                tile_ref.set_visible_this_frame(true);
403            }
404            let handle: RenderResourceHandle = tile_ref.get_handle();
405            self.set_tile_hits(self.get_tile_hits().saturating_add(1));
406            return (handle, true);
407        }
408        let byte_size: usize = (width.max(1) as usize)
409            .saturating_mul(height.max(1) as usize)
410            .saturating_mul(4);
411        let handle: RenderResourceHandle =
412            self.alloc_handle(RenderResourceKind::TileLayer, byte_size, fence_id);
413        self.get_mut_tiles().push(GpuScrollTileEntry {
414            key,
415            handle,
416            width: width.max(1),
417            height: height.max(1),
418            byte_size,
419            last_used_tick: next_tick,
420            last_fence_id: fence_id,
421            visible_this_frame: visible,
422        });
423        self.set_tile_resident_bytes(self.get_tile_resident_bytes().saturating_add(byte_size));
424        self.set_tile_misses(self.get_tile_misses().saturating_add(1));
425        self.evict_cold_tiles_to_budget(self.get_tile_budget_bytes());
426        (handle, false)
427    }
428
429    /// Invalidates all cached scroll tiles belonging to a destroyed or invalidated layer node or old DPI scale.
430    ///
431    /// # Arguments
432    ///
433    /// - `&Self` - Mutable GPU resource ring.
434    /// - `Option<NodeId>` - Optional specific layer node to invalidate (`None` invalidates all non-matching DPI tiles).
435    /// - `Option<f32>` - Optional active DPI scale; tiles with a different scale are evicted cleanly.
436    ///
437    /// # Returns
438    ///
439    /// - `usize` - Number of invalidated tiles moved to fence-deferred reclamation.
440    pub fn invalidate_scroll_tiles(
441        &mut self,
442        layer_node: Option<NodeId>,
443        active_dpr: Option<f32>,
444    ) -> usize {
445        let target_dpr_bits: Option<u32> = active_dpr.map(|d: f32| d.max(0.5).to_bits());
446        let mut evicted: Vec<GpuScrollTileEntry> = Vec::new();
447        self.get_mut_tiles().retain(|entry: &GpuScrollTileEntry| {
448            let match_node: bool = layer_node.is_some_and(|nid: NodeId| {
449                entry.get_key().get_layer_node_index() == nid.get_index()
450                    && entry.get_key().get_layer_node_gen() == nid.get_generation()
451            });
452            let mismatch_dpr: bool =
453                target_dpr_bits.is_some_and(|bits: u32| entry.get_key().get_dpr_bits() != bits);
454            if match_node || mismatch_dpr {
455                evicted.push(*entry);
456                false
457            } else {
458                true
459            }
460        });
461        let count: usize = evicted.len();
462        for item in evicted.into_iter() {
463            self.set_tile_resident_bytes(
464                self.get_tile_resident_bytes()
465                    .saturating_sub(item.get_byte_size()),
466            );
467            self.set_tile_evictions(self.get_tile_evictions().saturating_add(1));
468            self.queue_deferred_reclaim(item.get_handle(), item.get_last_fence_id());
469        }
470        count
471    }
472
473    /// Trims invisible cold scroll tiles down to `target_bytes`, never evicting currently visible tiles.
474    ///
475    /// # Arguments
476    ///
477    /// - `&Self` - Mutable GPU resource ring.
478    /// - `usize` - Target resident VRAM ceiling in bytes.
479    ///
480    /// # Returns
481    ///
482    /// - `usize` - Number of cold tiles evicted.
483    pub fn evict_cold_tiles_to_budget(&mut self, target_bytes: usize) -> usize {
484        if self.get_tile_resident_bytes() <= target_bytes || self.get_tiles().is_empty() {
485            return 0;
486        }
487        let mut cold_indices: Vec<(u64, usize)> = Vec::new();
488        for (idx, tile) in self.get_tiles().iter().enumerate() {
489            if !tile.get_visible_this_frame() {
490                cold_indices.push((tile.get_last_used_tick(), idx));
491            }
492        }
493        cold_indices.sort_unstable_by_key(|pair: &(u64, usize)| pair.0);
494        let mut drop_flags: Vec<bool> = vec![false; self.get_tiles().len()];
495        let mut rem_bytes: usize = self.get_tile_resident_bytes();
496        let mut dropped_count: usize = 0;
497        for (_, idx) in cold_indices.into_iter() {
498            if rem_bytes <= target_bytes {
499                break;
500            }
501            drop_flags[idx] = true;
502            rem_bytes = rem_bytes.saturating_sub(self.get_tiles()[idx].get_byte_size());
503            dropped_count += 1;
504        }
505        if dropped_count == 0 {
506            return 0;
507        }
508        let mut evicted: Vec<GpuScrollTileEntry> = Vec::with_capacity(dropped_count);
509        let mut write_idx: usize = 0;
510        for (read_idx, &dropped) in drop_flags.iter().enumerate() {
511            if dropped {
512                evicted.push(self.get_tiles()[read_idx]);
513            } else {
514                if write_idx != read_idx {
515                    self.get_mut_tiles().swap(write_idx, read_idx);
516                }
517                write_idx += 1;
518            }
519        }
520        self.get_mut_tiles().truncate(write_idx);
521        for item in evicted.into_iter() {
522            self.set_tile_resident_bytes(
523                self.get_tile_resident_bytes()
524                    .saturating_sub(item.get_byte_size()),
525            );
526            self.set_tile_evictions(self.get_tile_evictions().saturating_add(1));
527            self.queue_deferred_reclaim(item.get_handle(), item.get_last_fence_id());
528        }
529        dropped_count
530    }
531
532    /// Shrinks the persistent tile cache budget under memory pressure and evicts invisible cold tiles immediately.
533    ///
534    /// # Arguments
535    ///
536    /// - `&Self` - Mutable GPU resource ring.
537    /// - `f32` - Retained budget fraction in `(0.0..=1.0]`.
538    ///
539    /// # Returns
540    ///
541    /// - `usize` - Number of cold tiles evicted.
542    pub fn apply_retention_ratio(&mut self, retain_ratio: f32) -> usize {
543        let clamped: f32 = retain_ratio.clamp(0.1, 1.0);
544        let target: usize = ((GPU_TILE_CACHE_DEFAULT_BUDGET_BYTES as f32) * clamped)
545            .round()
546            .max(GPU_TILE_CACHE_MIN_BUDGET_BYTES as f32) as usize;
547        self.set_tile_budget_bytes(target);
548        self.evict_cold_tiles_to_budget(target)
549    }
550
551    /// Returns total live GPU bytes combining staging slots, resident scroll tiles, and pending fence-deferred bytes.
552    ///
553    /// # Arguments
554    ///
555    /// - `&Self` - GPU resource ring reference.
556    ///
557    /// # Returns
558    ///
559    /// - `usize` - Total live GPU allocation bytes.
560    #[must_use]
561    pub fn total_live_gpu_bytes(&self) -> usize {
562        self.staging_allocated_bytes()
563            .saturating_add(self.get_tile_resident_bytes())
564            .saturating_add(self.get_pending_reclaim_bytes())
565    }
566
567    /// Queues a dirty-rectangle R8 or RGBA8 atlas/image sub-region upload for the active frame.
568    ///
569    /// # Arguments
570    ///
571    /// - `GpuTextureUploadRect` - Dirty sub-region upload descriptor.
572    pub fn queue_texture_dirty_rect(&mut self, upload: GpuTextureUploadRect) {
573        if upload.get_width() == 0 || upload.get_height() == 0 {
574            return;
575        }
576        let bpp: u64 = match upload.get_format() {
577            GpuAtlasPixelFormat::R8Unorm => 1,
578            GpuAtlasPixelFormat::Rgba8Unorm => 4,
579        };
580        let bytes: u64 = (upload.get_width() as u64)
581            .saturating_mul(upload.get_height() as u64)
582            .saturating_mul(bpp);
583        self.set_total_texture_upload_bytes(
584            self.get_total_texture_upload_bytes().saturating_add(bytes),
585        );
586        self.get_mut_pending_texture_uploads().push(upload);
587    }
588
589    /// Drains all queued dirty-rectangle R8/RGBA8 texture uploads for GPU command encoding.
590    ///
591    /// # Returns
592    ///
593    /// - `Vec<GpuTextureUploadRect>` - Pending dirty-rectangle sub-region uploads.
594    #[must_use]
595    pub fn drain_texture_uploads(&mut self) -> Vec<GpuTextureUploadRect> {
596        take(self.get_mut_pending_texture_uploads())
597    }
598}