Skip to main content

sim_logic/rendering/extraction/
screen_cache.rs

1//! Exact source proofs for reusing CPU screen scenes, never hashed guesses.
2use super::*;
3
4/// CPU screen extraction work, not tessellation, upload or GPU timing.
5///
6/// Each of the two atomic publication buffers retains its own proof. A warm
7/// unchanged frame compares current sources but does not recollect/sort them
8/// or reconstruct Engine scenes. Changed frames still validate all source
9/// limits; geometry and mixed sub-runs can reuse their independent proofs.
10#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
11pub struct ScreenExtractionUpdates {
12    /// Sources compared with the previous accepted input sequence of this buffer.
13    pub compared_sources: usize,
14    /// The entire screen snapshot was unchanged; no sorting/scene reconstruction.
15    pub reused_snapshot: bool,
16    /// The aggregate Engine screen scene was reused, even if labels/images changed.
17    pub reused_scene: bool,
18    /// Mixed geometry sub-runs whose exact records allowed CPU scene reuse.
19    pub reused_runs: usize,
20    /// Mixed geometry sub-runs reconstructed during this extraction.
21    pub rebuilt_runs: usize,
22    /// Metadata capacity of source proofs, scratch and sub-run comparison records.
23    /// Excludes shared fonts/paths/images and Engine scenes, which have separate
24    /// owners. This counts one publication buffer, not both buffers combined.
25    pub retained_key_bytes: usize,
26}
27
28impl ScreenSource {
29    fn is_geometry(&self) -> bool {
30        match self {
31            Self::Rectangle(_) | Self::Line(..) | Self::Circle(..) | Self::Polyline(..) => true,
32            Self::Image(_) => false,
33            #[cfg(feature = "headless-text")]
34            Self::Text(_) => false,
35        }
36    }
37}
38
39impl ScreenExtractionBuffer {
40    pub(crate) fn extract(
41        &mut self,
42        generation: WorldGeneration,
43        limits: RenderLimits,
44        sources: impl IntoIterator<Item = ScreenSource>,
45    ) -> Result<(), ExtractionError> {
46        self.updates = ScreenExtractionUpdates::default();
47        let same_scope =
48            limits.screen_scene_reuse() && self.cache_scope == Some((generation, limits));
49        let mut sources = sources.into_iter().fuse();
50        let mut matched = 0;
51        let mut first_changed = None;
52        if same_scope {
53            for previous in &self.source_keys {
54                match sources.next() {
55                    Some(current) => {
56                        self.updates.compared_sources += 1;
57                        if current == *previous {
58                            matched += 1;
59                        } else {
60                            first_changed = Some(current);
61                            break;
62                        }
63                    }
64                    None => break,
65                }
66            }
67            if matched == self.source_keys.len() {
68                first_changed = sources.next();
69                if first_changed.is_none() {
70                    self.updates.reused_snapshot = true;
71                    self.updates.reused_scene = true;
72                    self.updates.reused_runs = self.runs.len();
73                    self.update_key_bytes();
74                    return Ok(());
75                }
76            }
77        }
78        // A failed build must never bless a partial source sequence as reusable.
79        self.cache_scope = None;
80        let mut previous = std::mem::take(&mut self.source_keys);
81        self.source_keys = std::mem::take(&mut self.source_scratch);
82        self.source_keys.clear();
83        self.clear_sources();
84        if !same_scope {
85            // Invalidate proofs, but retain bounded ordinary scene capacity for
86            // the uncached comparison route and generation changes alike.
87            for run in &mut self.runs {
88                run.records.clear();
89            }
90        }
91        let result = (|| {
92            // Replay only the equal prefix. There is no allocation on the fully
93            // unchanged route or dependence on ECS tick age. Reordered source
94            // iteration safely misses this proof, even if painter order is equal.
95            self.collect_sources(
96                generation,
97                limits,
98                previous[..matched]
99                    .iter()
100                    .cloned()
101                    .chain(first_changed)
102                    .chain(sources),
103            )?;
104            let same_geometry = same_scope
105                && previous
106                    .iter()
107                    .filter(|key| key.is_geometry())
108                    .eq(self.source_keys.iter().filter(|key| key.is_geometry()));
109            if same_geometry {
110                self.updates.reused_scene = true;
111            } else {
112                self.scene.clear();
113                for index in 0..self.geometry_len() {
114                    if let Some(primitive) = self.geometry(index) {
115                        primitive
116                            .append(&mut self.scene)
117                            .map_err(ExtractionError::ScreenScene)?;
118                    }
119                }
120            }
121            self.compose(limits.screen_scene_budget())?;
122            Ok(())
123        })();
124        // Keep bounded metadata capacity, but release old shared payloads now.
125        previous.clear();
126        self.source_scratch = previous;
127        if result.is_ok() {
128            self.cache_scope = Some((generation, limits));
129        } else {
130            self.clear();
131        }
132        self.update_key_bytes();
133        result
134    }
135
136    pub(super) fn remember_source(&mut self, key: ScreenSource) -> Result<(), ExtractionError> {
137        // Called only after the existing per-kind/aggregate source admission.
138        self.source_keys
139            .try_reserve(1)
140            .map_err(|_| ExtractionError::AllocationFailed {
141                requested_bytes: size_of::<ScreenSource>(),
142            })?;
143        self.source_keys.push(key);
144        Ok(())
145    }
146
147    fn update_key_bytes(&mut self) {
148        self.updates.retained_key_bytes = self
149            .source_keys
150            .capacity()
151            .saturating_add(self.source_scratch.capacity())
152            .saturating_mul(size_of::<ScreenSource>())
153            .saturating_add(
154                self.runs
155                    .iter()
156                    .map(|run| {
157                        run.records
158                            .capacity()
159                            .saturating_mul(size_of::<ResolvedScreenPrimitive>())
160                    })
161                    .fold(0usize, usize::saturating_add),
162            );
163    }
164}
165
166#[cfg(test)]
167#[path = "screen_cache_tests.rs"]
168mod tests;