Skip to main content

alpha2_render/
result_cache.rs

1//! Rendered node results kept across graph executions.
2//!
3//! A graph node's cache key names everything its pixels depend on: its
4//! operation, parameters, runtime, size, and its inputs' keys, down to its
5//! sources. That key is complete only when every source under the node has a
6//! key its host vouches for ([`crate::RenderGraph::add_source_with_key`]); a
7//! source added without one gets a key unique to its graph, so a node above it
8//! can never be found again. Only nodes a caller names as candidates
9//! ([`crate::RenderGraph::set_cache_intent`]) are stored, and only those with
10//! complete keys: a stored result is exactly the texture a live render would
11//! produce, never an approximation.
12//!
13//! What a key leaves out, the cache is cleared on: removing an effect (a new
14//! registration under its id and version could draw differently), uploading,
15//! replacing, or removing an effect resource, and changing quality controls.
16
17use std::collections::HashMap;
18
19use crate::RenderedTexture;
20use crate::graph::RenderCacheKey;
21
22/// Whether a node's result may be kept and reused.
23#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
24pub enum CacheIntent {
25    /// Keep it when its key is complete, evicting it like any other result.
26    #[default]
27    Auto,
28    /// Keep it when its key is complete, evicting it only after every
29    /// unpinned result.
30    Pin,
31    /// Never read or keep it, nor anything it is drawn from or drawn into:
32    /// for looking at a live render with certainty.
33    Bypass,
34}
35
36/// Whether a node's result can be cached, and if not, why.
37#[derive(Copy, Clone, Debug, Eq, PartialEq)]
38pub enum CacheEligibility {
39    /// Its key names everything it depends on.
40    Eligible,
41    /// A source under it has no stable key, so its key is unique to this
42    /// graph.
43    TransientSource,
44    /// It, something it is drawn from, or something it is drawn into asks
45    /// for [`CacheIntent::Bypass`].
46    Bypassed,
47}
48
49/// Why cached results were dropped all at once.
50#[derive(Copy, Clone, Debug, Eq, PartialEq)]
51pub enum CacheInvalidation {
52    /// An effect was registered or removed.
53    Effects,
54    /// An effect resource was uploaded, replaced, or removed.
55    EffectResources,
56    /// Filter or temporal sampling controls changed.
57    Quality,
58    /// The caller cleared it.
59    Explicit,
60    /// The browser reported a GPU error for earlier work, which may have
61    /// come from a kept result (see [`crate::Renderer::gpu_error_reports`]).
62    GpuError,
63}
64
65/// Result-cache counters since the renderer was created.
66#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
67pub struct ResultCacheStats {
68    /// Bytes results may occupy; zero disables the cache.
69    pub budget_bytes: u64,
70    /// Bytes the kept results occupy.
71    pub bytes: u64,
72    /// Results kept.
73    pub entries: u64,
74    /// Of those, pinned.
75    pub pinned: u64,
76    /// Candidate nodes found in the cache.
77    pub hits: u64,
78    /// Candidate nodes with complete keys that were not.
79    pub misses: u64,
80    /// Candidate nodes that could not be cached: a transient source or a
81    /// bypass under or over them.
82    pub ineligible: u64,
83    /// Results stored.
84    pub inserts: u64,
85    /// Results dropped to stay within the budget.
86    pub evictions: u64,
87    /// Nodes not encoded because a result above them was found.
88    pub skipped_nodes: u64,
89    /// Clears by reason: effects, effect resources, quality, explicit, and
90    /// a GPU error reported for earlier work.
91    pub invalidations: [u64; 5],
92}
93
94struct Entry {
95    texture: RenderedTexture,
96    bytes: u64,
97    pinned: bool,
98    last_used: u64,
99}
100
101/// Kept results by renderer-level key, bounded by bytes.
102#[derive(Default)]
103pub(crate) struct ResultCache {
104    entries: HashMap<u128, Entry>,
105    clock: u64,
106    stats: ResultCacheStats,
107}
108
109impl std::fmt::Debug for ResultCache {
110    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        formatter
112            .debug_struct("ResultCache")
113            .field("stats", &self.stats)
114            .finish_non_exhaustive()
115    }
116}
117
118impl ResultCache {
119    pub(crate) const fn enabled(&self) -> bool {
120        self.stats.budget_bytes > 0
121    }
122
123    pub(crate) const fn stats(&self) -> ResultCacheStats {
124        self.stats
125    }
126
127    pub(crate) fn set_budget(&mut self, budget_bytes: u64) {
128        self.stats.budget_bytes = budget_bytes;
129        self.evict_to(budget_bytes);
130    }
131
132    /// A kept result, marked as just used and pinned as the node that asks
133    /// for it now is: a cache intent is not part of the key, so a clip pinned
134    /// or unpinned after its picture was kept finds the same entry.
135    pub(crate) fn get(&mut self, key: RenderCacheKey, pinned: bool) -> Option<RenderedTexture> {
136        self.clock += 1;
137        let clock = self.clock;
138        let entry = self.entries.get_mut(&key.value())?;
139        entry.last_used = clock;
140        if entry.pinned != pinned {
141            entry.pinned = pinned;
142            if pinned {
143                self.stats.pinned += 1;
144            } else {
145                self.stats.pinned -= 1;
146            }
147        }
148        Some(entry.texture.clone())
149    }
150
151    /// Keeps `texture` under `key`, evicting least recently used results
152    /// (unpinned before pinned) to make room. A result larger than the whole
153    /// budget is not kept.
154    pub(crate) fn insert(&mut self, key: RenderCacheKey, texture: &RenderedTexture, pinned: bool) {
155        let bytes = texture_bytes(texture);
156        if bytes > self.stats.budget_bytes {
157            return;
158        }
159        self.remove(key.value());
160        self.evict_to(self.stats.budget_bytes - bytes);
161        self.clock += 1;
162        self.entries.insert(
163            key.value(),
164            Entry {
165                texture: texture.clone(),
166                bytes,
167                pinned,
168                last_used: self.clock,
169            },
170        );
171        self.stats.bytes += bytes;
172        self.stats.entries += 1;
173        self.stats.pinned += u64::from(pinned);
174        self.stats.inserts += 1;
175    }
176
177    pub(crate) fn clear(&mut self, reason: CacheInvalidation) {
178        if !self.entries.is_empty() {
179            self.stats.invalidations[reason as usize] += 1;
180        }
181        self.entries.clear();
182        self.stats.bytes = 0;
183        self.stats.entries = 0;
184        self.stats.pinned = 0;
185    }
186
187    pub(crate) fn record(&mut self, hits: u64, misses: u64, ineligible: u64, skipped: u64) {
188        self.stats.hits += hits;
189        self.stats.misses += misses;
190        self.stats.ineligible += ineligible;
191        self.stats.skipped_nodes += skipped;
192    }
193
194    fn evict_to(&mut self, bytes: u64) {
195        while self.stats.bytes > bytes {
196            let Some(victim) = self
197                .entries
198                .iter()
199                .min_by_key(|(_, entry)| (entry.pinned, entry.last_used))
200                .map(|(key, _)| *key)
201            else {
202                return;
203            };
204            self.remove(victim);
205            self.stats.evictions += 1;
206        }
207    }
208
209    fn remove(&mut self, key: u128) {
210        if let Some(entry) = self.entries.remove(&key) {
211            self.stats.bytes -= entry.bytes;
212            self.stats.entries -= 1;
213            self.stats.pinned -= u64::from(entry.pinned);
214        }
215    }
216}
217
218fn texture_bytes(texture: &RenderedTexture) -> u64 {
219    let texel = u64::from(texture.format.block_copy_size(None).unwrap_or(4));
220    u64::from(texture.size.width) * u64::from(texture.size.height) * texel
221}