Skip to main content

ferroui_render3d/
output_cache.rs

1//! The output of the CPU reference kept for the next frame (`docs/porting/media3d.md`, section
2//! 3.7, step 1): a viewport whose snapshot, size, scale and options are unchanged draws the image
3//! it drew before, without rasterizing again.
4//!
5//! A backend keeps one cache on its render thread, with the form of the image it draws (a Skia
6//! image, a Vello image), so that the image is also uploaded to a GPU once rather than every frame.
7
8use crate::cpu::{CpuRasterizer, CpuRenderOptions, Scene3DImage};
9use ferroui_base::rendering::scene3d::Scene3DSnapshot;
10use ferroui_base::PixelSize;
11use std::sync::{Arc, Weak};
12
13/// What an output was made for.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15struct OutputKey {
16    generations: (u64, u64, u64),
17    size: (i32, i32),
18    scale_bits: u64,
19    options: CpuRenderOptions,
20}
21
22struct OutputEntry<T> {
23    /// The snapshot the output was made of. A snapshot is immutable, and a viewport hands out
24    /// the same one while nothing changes, so the allocation names the scene; the weak handle
25    /// keeps the allocation (not the scene) alive, so its address is not reused while the entry
26    /// lives.
27    scene: Weak<Scene3DSnapshot>,
28    key: OutputKey,
29    value: T,
30    last_used: u64,
31}
32
33/// The outputs of the scenes a backend drew recently, with the rasterizer that makes them.
34pub struct Scene3DOutputCache<T> {
35    rasterizer: CpuRasterizer,
36    entries: Vec<OutputEntry<T>>,
37    capacity: usize,
38    clock: u64,
39}
40
41impl<T: Clone> Default for Scene3DOutputCache<T> {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl<T: Clone> Scene3DOutputCache<T> {
48    /// The number of outputs a cache keeps by default: the viewports of a window or two.
49    pub const DEFAULT_CAPACITY: usize = 8;
50
51    /// An empty cache of [`DEFAULT_CAPACITY`](Self::DEFAULT_CAPACITY) outputs.
52    pub fn new() -> Self {
53        Self::with_capacity(Self::DEFAULT_CAPACITY)
54    }
55
56    /// An empty cache of `capacity` outputs (at least one).
57    pub fn with_capacity(capacity: usize) -> Self {
58        Scene3DOutputCache { rasterizer: CpuRasterizer::new(), entries: Vec::new(), capacity: capacity.max(1), clock: 0 }
59    }
60
61    /// The output of `scene` at `size` pixels, `scale` and `options`: the kept one when the
62    /// snapshot, its generations, the size, the scale and the options are those it was made for;
63    /// otherwise the scene is rasterized and `make` turns the image into the backend's form
64    /// (`None` when it cannot, which keeps nothing). A new output of a scene replaces the older
65    /// one of the same scene, and the least recently used output makes room for a new one.
66    pub fn get_or_render(
67        &mut self,
68        scene: &Arc<Scene3DSnapshot>,
69        size: PixelSize,
70        scale: f64,
71        options: CpuRenderOptions,
72        make: impl FnOnce(Scene3DImage) -> Option<T>,
73    ) -> Option<T> {
74        self.clock += 1;
75        let key = OutputKey {
76            generations: scene.generations(),
77            size: (size.width, size.height),
78            scale_bits: scale.to_bits(),
79            options,
80        };
81        // Outputs of snapshots nobody holds any more are dropped.
82        self.entries.retain(|entry| entry.scene.strong_count() > 0);
83        let same_scene = |entry: &OutputEntry<T>| std::ptr::eq(entry.scene.as_ptr(), Arc::as_ptr(scene));
84        if let Some(entry) = self.entries.iter_mut().find(|entry| same_scene(entry) && entry.key == key) {
85            entry.last_used = self.clock;
86            return Some(entry.value.clone());
87        }
88        let image = self.rasterizer.render(scene, size, scale, options);
89        let value = make(image)?;
90        self.entries.retain(|entry| !same_scene(entry));
91        if self.entries.len() >= self.capacity {
92            if let Some(oldest) =
93                self.entries.iter().enumerate().min_by_key(|(_, entry)| entry.last_used).map(|(index, _)| index)
94            {
95                self.entries.swap_remove(oldest);
96            }
97        }
98        self.entries.push(OutputEntry { scene: Arc::downgrade(scene), key, value: value.clone(), last_used: self.clock });
99        Some(value)
100    }
101
102    /// The number of outputs kept.
103    pub fn len(&self) -> usize {
104        self.entries.len()
105    }
106
107    /// Whether no output is kept.
108    pub fn is_empty(&self) -> bool {
109        self.entries.is_empty()
110    }
111
112    /// Drops every output (a lost device, a new context).
113    pub fn clear(&mut self) {
114        self.entries.clear();
115    }
116}
117
118#[cfg(test)]
119#[path = "output_cache_tests.rs"]
120mod tests;