Skip to main content

sim_engine/renderer/screen_primitives/
mod.rs

1//! Compact retained analytic circles, capsules and rectangles in logical pixels.
2
3use super::{CameraUniform, PreparedDrawBatch, WgpuRenderer};
4use std::sync::{Arc, Mutex};
5
6type CachedProof = (Option<(CameraUniform, u32)>, bool);
7
8mod certificate;
9mod pipeline;
10mod quality;
11mod resources;
12mod types;
13mod validation;
14
15pub(super) use pipeline::create_pipeline;
16pub(super) use types::ScreenPrimitiveGpu;
17
18pub use types::{
19    ScreenPrimitive2d, ScreenPrimitiveBudget, ScreenPrimitiveError, ScreenPrimitiveUploadReport,
20};
21
22/// An ordered immutable draw snapshot of solid screen primitives.
23///
24/// Each circle or independent round line is one analytic quad, not a polygonal
25/// fan. Curves have no segmentation error. Coverage is evaluated per MSAA sample;
26/// a single-sample target has binary edge coverage. Rectangles are axis-aligned.
27/// Input order and clips are preserved, including normalized translucent colors.
28/// The batch owns CPU recovery data and cannot be cloned into mutable aliases.
29/// Camera transforms cannot be supplied: use fixed-screen frame composition.
30/// A conservative construction/fragment/transform precision envelope must fit
31/// within 0.25 physical pixels at the destination scale; otherwise drawing is
32/// rejected before submission. MSAA coverage remains sample-dependent.
33pub struct ScreenPrimitiveBatch2d {
34    pub(super) renderer_identity: Arc<()>,
35    pub(super) instance_buffer: wgpu::Buffer,
36    pub(super) instances: Vec<ScreenPrimitiveGpu>,
37    pub(super) draw_batches: Vec<PreparedDrawBatch>,
38    capacity: usize,
39    budget: ScreenPrimitiveBudget,
40    primitive_counts: crate::PrimitiveCommandCounts,
41    certificate: certificate::Certificate,
42    quality: quality::Quality,
43    proof_cache: Mutex<[CachedProof; 8]>,
44}
45
46impl ScreenPrimitiveBatch2d {
47    /// Number of retained primitives, without truncation or visibility quotas.
48    pub fn primitive_count(&self) -> usize {
49        self.instances.len()
50    }
51    /// Six shader-generated quad vertices are submitted per instance.
52    pub fn vertex_count(&self) -> usize {
53        self.instances.len().saturating_mul(6)
54    }
55    /// Owned instance and clip-span CPU capacities, excluding this fixed object.
56    pub fn retained_cpu_bytes(&self) -> usize {
57        self.instances
58            .capacity()
59            .saturating_mul(std::mem::size_of::<ScreenPrimitiveGpu>())
60            .saturating_add(
61                self.draw_batches
62                    .capacity()
63                    .saturating_mul(std::mem::size_of::<PreparedDrawBatch>()),
64            )
65    }
66    /// Actual retained GPU instance-buffer capacity, excluding driver overhead.
67    pub fn gpu_buffer_bytes(&self) -> usize {
68        self.capacity * std::mem::size_of::<ScreenPrimitiveGpu>()
69    }
70    /// Limits used for creation and every subsequent full update.
71    pub const fn budget(&self) -> ScreenPrimitiveBudget {
72        self.budget
73    }
74
75    pub(super) fn tessellation_stats(&self) -> super::TessellationStats {
76        super::TessellationStats {
77            command_count: self.primitive_count(),
78            rendered_command_count: self.primitive_count(),
79            command_counts: self.primitive_counts,
80            rendered_counts: self.primitive_counts,
81            vertex_count: self.vertex_count(),
82            draw_batch_count: self.draw_batches.len(),
83            ..Default::default()
84        }
85    }
86
87    pub(super) fn is_safe_for(&self, uniform: CameraUniform, scale_factor: f32) -> bool {
88        {
89            let cache = self
90                .proof_cache
91                .lock()
92                .unwrap_or_else(|error| error.into_inner());
93            if let Some((_, valid)) = cache.iter().find(|(key, _)| {
94                key.as_ref().is_some_and(|(key, scale)| {
95                    bytemuck::bytes_of(key) == bytemuck::bytes_of(&uniform)
96                        && *scale == scale_factor.to_bits()
97                })
98            }) {
99                return *valid;
100            }
101        }
102        let valid = self.quality.accepts(uniform, scale_factor)
103            && validation::instances_are_safe_accelerated(
104                &self.instances,
105                self.certificate,
106                uniform,
107            );
108        let mut cache = self
109            .proof_cache
110            .lock()
111            .unwrap_or_else(|error| error.into_inner());
112        cache.rotate_right(1);
113        cache[0] = (Some((uniform, scale_factor.to_bits())), valid);
114        valid
115    }
116}
117
118impl WgpuRenderer {
119    /// Uploads ordered analytic screen primitives under explicit residency/work limits.
120    /// No draw or presentation occurs. The input slice is snapshotted.
121    pub fn create_screen_primitive_batch(
122        &self,
123        primitives: &[ScreenPrimitive2d],
124        budget: ScreenPrimitiveBudget,
125    ) -> Result<ScreenPrimitiveBatch2d, ScreenPrimitiveError> {
126        resources::create(
127            &self.device,
128            &self.queue,
129            Arc::clone(&self.renderer_identity),
130            primitives,
131            budget,
132        )
133    }
134
135    /// Replaces the entire snapshot transactionally, reusing CPU/GPU capacity.
136    /// Rejected input or allocation failure leaves the previous snapshot intact.
137    /// Changed instance data invalidates all camera/viewport proofs. Clip-only
138    /// changes preserve numeric proofs because they cannot change shader positions. GPU queue order
139    /// protects prior submitted draws; no synchronous readback or wait is added.
140    pub fn update_screen_primitive_batch(
141        &self,
142        batch: &mut ScreenPrimitiveBatch2d,
143        primitives: &[ScreenPrimitive2d],
144    ) -> Result<ScreenPrimitiveUploadReport, ScreenPrimitiveError> {
145        if !Arc::ptr_eq(&self.renderer_identity, &batch.renderer_identity) {
146            return Err(ScreenPrimitiveError::RendererMismatch);
147        }
148        resources::update(&self.device, &self.queue, batch, primitives)
149    }
150
151    /// Recreates a device-local batch from its complete retained CPU snapshot.
152    /// The old batch remains valid for its old renderer and is not mutated.
153    pub fn restore_screen_primitive_batch(
154        &self,
155        source: &ScreenPrimitiveBatch2d,
156    ) -> Result<ScreenPrimitiveBatch2d, ScreenPrimitiveError> {
157        resources::restore(
158            &self.device,
159            &self.queue,
160            Arc::clone(&self.renderer_identity),
161            source,
162        )
163    }
164}
165
166#[cfg(test)]
167mod tests;
168#[cfg(test)]
169pub(super) use tests::verify_analytic_primitives;