Skip to main content

sim_logic/platform/desktop/
geometry.rs

1//! Exact-value retained screen runs. Engine alone builds and validates geometry.
2
3use std::{
4    error::Error,
5    fmt,
6    mem::size_of,
7    time::{Duration, Instant},
8};
9
10use sim_engine::{
11    FrameComposer, FrameComposerError, FramePassOptions, PreparedSceneError, PreparedScreenScene,
12    ScreenPrimitive2d, ScreenPrimitiveBatch2d, ScreenPrimitiveBudget, ScreenPrimitiveError,
13    WgpuRenderer,
14};
15
16use crate::{ExtractedFrame, ResolvedScreenPrimitive, ScreenDraw, identity::WorldGeneration};
17
18/// Desktop geometry route. Both retained routes preserve mixed painter order.
19#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
20pub enum DesktopScreenMode {
21    /// Engine analytic primitives where supported; prepared triangles otherwise.
22    /// Compact primitives have Engine's explicit subpixel precision envelope.
23    Compact,
24    /// Retain ordinary tessellation, including its polygonal circle appearance.
25    #[default]
26    Prepared,
27    /// Legacy streaming route, useful for paired measurements on the same source.
28    Streaming,
29}
30
31/// Resource preparation outside Engine's surface-frame metrics. Not GPU timing.
32/// In Compact mode, run counters count ordered sub-runs (at most 256 records).
33#[derive(Debug, Default, Clone, Copy)]
34pub struct DesktopScreenUpdates {
35    /// Runs reused by exact source/value comparison without tessellation or upload.
36    pub reused_runs: usize,
37    /// Newly prepared ordinary runs.
38    pub prepared_runs: usize,
39    /// Created compact runs.
40    pub compact_runs: usize,
41    /// Compact runs updated without changing their kind.
42    pub updated_runs: usize,
43    /// Actual geometry uploads during successful preparation, excluding uniforms.
44    pub uploaded_bytes: usize,
45    /// Current retained Engine recovery storage plus comparison-record capacity.
46    /// Excludes fixed object metadata, temporary conversion, driver and in-flight memory.
47    /// Shared source path points/styles belong to the CPU visual/snapshot, not this count.
48    pub retained_cpu_bytes: usize,
49    /// CPU wall time for comparison, construction and queueing resource updates.
50    pub cpu_time: Duration,
51}
52
53/// A retained screen resource could not be prepared; no partial frame is drawn.
54#[derive(Debug)]
55pub enum DesktopScreenError {
56    /// Engine rejected reconstruction of one ordered CPU sub-run.
57    Scene(sim_engine::SceneError),
58    /// Ordinary Engine preparation failed.
59    Prepared(PreparedSceneError),
60    /// Compact Engine preparation failed.
61    Compact(ScreenPrimitiveError),
62    /// Bounded comparison/cache metadata allocation failed.
63    Allocation {
64        /// Requested additional bytes.
65        requested_bytes: usize,
66    },
67    /// The private draw plan does not match its published snapshot.
68    InvalidDrawPlan,
69}
70
71impl fmt::Display for DesktopScreenError {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            Self::Scene(error) => write!(f, "screen sub-run: {error}"),
75            Self::Prepared(error) => write!(f, "retained screen geometry: {error}"),
76            Self::Compact(error) => write!(f, "compact screen geometry: {error}"),
77            Self::Allocation { requested_bytes } => {
78                write!(f, "screen cache could not reserve {requested_bytes} bytes")
79            }
80            Self::InvalidDrawPlan => f.write_str("screen cache and draw plan disagree"),
81        }
82    }
83}
84impl Error for DesktopScreenError {
85    fn source(&self) -> Option<&(dyn Error + 'static)> {
86        match self {
87            Self::Scene(error) => Some(error),
88            Self::Prepared(error) => Some(error),
89            Self::Compact(error) => Some(error),
90            _ => None,
91        }
92    }
93}
94
95enum Resource {
96    Empty,
97    Prepared(PreparedScreenScene),
98    Compact(ScreenPrimitiveBatch2d),
99}
100
101struct Entry {
102    records: Vec<ResolvedScreenPrimitive>,
103    resource: Resource,
104}
105
106#[derive(Default)]
107struct Run {
108    parts: Vec<Entry>,
109}
110
111/// One entry per *current* geometry run, never per historic entity or revision.
112/// Admission is bounded by the aggregate ScreenScene budget and RenderLimits.
113/// Replacement may retain old and new resource storage simultaneously. A failed
114/// preparation does not present, but successful earlier updates are not rolled back.
115#[derive(Default)]
116pub(super) struct DesktopGeometry {
117    generation: Option<WorldGeneration>,
118    entries: Vec<Run>,
119    scratch: Vec<ResolvedScreenPrimitive>,
120    pub(super) updates: DesktopScreenUpdates,
121}
122
123impl DesktopGeometry {
124    pub(super) fn clear(&mut self) {
125        self.entries.clear();
126        self.scratch.clear();
127        self.generation = None;
128    }
129    pub(super) fn has_runs(&self) -> bool {
130        !self.entries.is_empty()
131    }
132
133    pub(super) fn prepare(
134        &mut self,
135        renderer: &WgpuRenderer,
136        snapshot: &ExtractedFrame,
137        mode: DesktopScreenMode,
138    ) -> Result<(), DesktopScreenError> {
139        let started = Instant::now();
140        self.updates = DesktopScreenUpdates::default();
141        if mode == DesktopScreenMode::Streaming {
142            self.clear();
143            return Ok(());
144        }
145        if self.generation != Some(snapshot.world_generation()) {
146            self.clear();
147            self.generation = Some(snapshot.world_generation());
148        }
149        let count = snapshot
150            .screen_draws()
151            .iter()
152            .filter(|draw| {
153                matches!(
154                    draw,
155                    ScreenDraw::Rectangles { .. } | ScreenDraw::Primitives { .. }
156                )
157            })
158            .count();
159        self.entries.truncate(count);
160        self.entries
161            .try_reserve_exact(count.saturating_sub(self.entries.len()))
162            .map_err(|_| DesktopScreenError::Allocation {
163                requested_bytes: count.saturating_mul(size_of::<Run>()),
164            })?;
165        self.entries.resize_with(count, Run::default);
166        for draw in snapshot.screen_draws() {
167            let run = match *draw {
168                ScreenDraw::Rectangles { run } | ScreenDraw::Primitives { run } => run,
169                _ => continue,
170            };
171            let mut records = snapshot
172                .screen_primitive_run_records(run)
173                .ok_or(DesktopScreenError::InvalidDrawPlan)?
174                .peekable();
175            let scene = snapshot
176                .screen_rectangle_run(run)
177                .ok_or(DesktopScreenError::InvalidDrawPlan)?;
178            let parts = &mut self
179                .entries
180                .get_mut(run)
181                .ok_or(DesktopScreenError::InvalidDrawPlan)?
182                .parts;
183            let mut index = 0;
184            while let Some(first) = records.peek() {
185                let compact = mode == DesktopScreenMode::Compact && compact_candidate(first);
186                self.scratch.clear();
187                while records.peek().is_some_and(|record| {
188                    mode != DesktopScreenMode::Compact
189                        || (self.scratch.len() < 256 && compact_candidate(record) == compact)
190                }) {
191                    self.scratch
192                        .try_reserve(1)
193                        .map_err(|_| DesktopScreenError::Allocation {
194                            requested_bytes: size_of::<ResolvedScreenPrimitive>(),
195                        })?;
196                    self.scratch
197                        .push(records.next().ok_or(DesktopScreenError::InvalidDrawPlan)?);
198                }
199                prepare_part(
200                    renderer,
201                    parts,
202                    index,
203                    &self.scratch,
204                    scene,
205                    compact,
206                    &mut self.updates,
207                )?;
208                index += 1;
209            }
210            parts.truncate(index);
211        }
212        // Scratch must not retain shared path snapshots from a retired run.
213        self.scratch.clear();
214        self.updates.retained_cpu_bytes = self
215            .entries
216            .iter()
217            .flat_map(|run| &run.parts)
218            .map(|entry| {
219                let bytes = match &entry.resource {
220                    Resource::Empty => 0,
221                    Resource::Prepared(value) => value.recovery_memory_bytes(),
222                    Resource::Compact(value) => value.retained_cpu_bytes(),
223                };
224                bytes.saturating_add(
225                    entry
226                        .records
227                        .capacity()
228                        .saturating_mul(size_of::<ResolvedScreenPrimitive>()),
229                )
230            })
231            .fold(
232                self.scratch
233                    .capacity()
234                    .saturating_mul(size_of::<ResolvedScreenPrimitive>()),
235                usize::saturating_add,
236            );
237        self.updates.cpu_time = started.elapsed();
238        Ok(())
239    }
240
241    pub(super) fn draw<'a>(
242        &'a self,
243        frame: &mut FrameComposer<'a>,
244        run: usize,
245        options: FramePassOptions,
246    ) -> Result<(), FrameComposerError> {
247        // Preparation checks run indices from this same immutable snapshot.
248        for entry in &self.entries[run].parts {
249            match &entry.resource {
250                Resource::Empty => (),
251                Resource::Prepared(value) => frame.draw_prepared_screen_scene(value, options)?,
252                Resource::Compact(value) => frame.draw_screen_primitive_batch(value, options)?,
253            }
254        }
255        Ok(())
256    }
257}
258
259fn compact_candidate(record: &ResolvedScreenPrimitive) -> bool {
260    match record {
261        ResolvedScreenPrimitive::Rectangle(value) => {
262            value.visual().corner_radius() == 0.0 && value.visual().stroke().is_none()
263        }
264        ResolvedScreenPrimitive::Line { .. } => true,
265        ResolvedScreenPrimitive::Circle { visual, .. } => visual.stroke().is_none(),
266        ResolvedScreenPrimitive::Polyline { .. } => false,
267    }
268}
269
270fn prepare_part(
271    renderer: &WgpuRenderer,
272    parts: &mut Vec<Entry>,
273    index: usize,
274    records: &[ResolvedScreenPrimitive],
275    source: &sim_engine::ScreenScene,
276    compact: bool,
277    updates: &mut DesktopScreenUpdates,
278) -> Result<(), DesktopScreenError> {
279    if parts.get(index).is_some_and(|old| old.records == records) {
280        updates.reused_runs += 1;
281        return Ok(());
282    }
283    parts
284        .try_reserve_exact(index.saturating_add(1).saturating_sub(parts.len()))
285        .map_err(|_| DesktopScreenError::Allocation {
286            requested_bytes: size_of::<Entry>(),
287        })?;
288    let mut scene = sim_engine::ScreenScene::with_budget(
289        sim_engine::Color::TRANSPARENT,
290        source.budget().ok_or(DesktopScreenError::InvalidDrawPlan)?,
291    )
292    .map_err(DesktopScreenError::Scene)?;
293    for record in records {
294        record
295            .append(&mut scene)
296            .map_err(DesktopScreenError::Scene)?;
297    }
298    // Allocate comparison records fallibly before changing the retained resource.
299    let mut captured = Vec::new();
300    captured
301        .try_reserve_exact(records.len())
302        .map_err(|_| DesktopScreenError::Allocation {
303            requested_bytes: records
304                .len()
305                .saturating_mul(size_of::<ResolvedScreenPrimitive>()),
306        })?;
307    for record in records {
308        captured.push(record.clone());
309    }
310    let compact = if compact {
311        match ScreenPrimitive2d::from_screen_scene(&scene) {
312            Ok(values) => Some(values),
313            // These only reject the optional compact representation.
314            // The already validated ordinary scene remains authoritative.
315            Err(
316                ScreenPrimitiveError::UnsupportedCommand { .. }
317                | ScreenPrimitiveError::PrecisionLimit
318                | ScreenPrimitiveError::InvalidGeometry,
319            ) => None,
320            Err(error) => return Err(DesktopScreenError::Compact(error)),
321        }
322    } else {
323        None
324    };
325    let resource = if scene.statistics().accepted_commands() == 0 {
326        Resource::Empty
327    } else if let Some(values) = compact {
328        if let Some(Entry {
329            records,
330            resource: Resource::Compact(batch),
331        }) = parts.get_mut(index)
332        {
333            // A growing run receives a new bound below. Fitting changes use
334            // Engine's capacity-aware update and exact recovery snapshot.
335            if values.len() <= batch.budget().max_primitives() {
336                let report = renderer
337                    .update_screen_primitive_batch(batch, &values)
338                    .map_err(DesktopScreenError::Compact)?;
339                updates.uploaded_bytes = updates
340                    .uploaded_bytes
341                    .saturating_add(report.uploaded_bytes());
342                updates.updated_runs += 1;
343                *records = captured;
344                return Ok(());
345            }
346        }
347        // Engine's compact per-item storage is smaller than the scene's
348        // admitted tessellation. Use that same finite upload ceiling;
349        // metadata has a separate finite, count-derived allowance.
350        let bytes = scene.statistics().estimated_upload_bytes().max(256);
351        let budget =
352            ScreenPrimitiveBudget::new(values.len(), bytes.saturating_mul(2), bytes, bytes);
353        let batch = renderer
354            .create_screen_primitive_batch(&values, budget)
355            .map_err(DesktopScreenError::Compact)?;
356        updates.uploaded_bytes = updates
357            .uploaded_bytes
358            .saturating_add(batch.gpu_buffer_bytes());
359        updates.compact_runs += 1;
360        Resource::Compact(batch)
361    } else {
362        let prepared = renderer
363            .prepare_screen_scene(&scene)
364            .map_err(DesktopScreenError::Prepared)?;
365        updates.uploaded_bytes = updates
366            .uploaded_bytes
367            .saturating_add(prepared.tessellation_stats().upload_bytes());
368        updates.prepared_runs += 1;
369        Resource::Prepared(prepared)
370    };
371    let entry = Entry {
372        records: captured,
373        resource,
374    };
375    if index < parts.len() {
376        parts[index] = entry;
377    } else if index == parts.len() {
378        parts.push(entry);
379    } else {
380        return Err(DesktopScreenError::InvalidDrawPlan);
381    }
382    Ok(())
383}
384
385#[cfg(all(test, target_os = "linux"))]
386#[path = "geometry/tests.rs"]
387mod tests;