Skip to main content

sim_engine/renderer/
initialization.rs

1//! Renderer initialization, surface sizing and host-facing diagnostics.
2
3use super::{
4    Arc, GpuTimingBatch, GpuTimingStatistics, INITIAL_VERTEX_CAPACITY, ImageRenderer,
5    LogicalScreenPosition, LogicalViewport, Mesh3dRenderer, PhysicalScreenPosition,
6    PipelineResources, RendererConfigurationError, RendererCoordinateError, RendererInitError,
7    RendererSurfacePresentMode, WgpuRenderer, WgpuRendererOptions, create_multisample_target,
8    create_pipeline, create_submitted_particle_unit_buffer, create_vertex_buffer, frame,
9    gpu_timing, invoke_pre_present_notify, logical_to_physical_screen, physical_to_logical_screen,
10    preferred_sample_count, select_surface_present_mode, validate_scale_factor,
11    validate_surface_dimensions,
12};
13
14impl WgpuRenderer {
15    /// Creates a renderer for a window or canvas surface target.
16    ///
17    /// `width` and `height` are physical surface pixels. Zero sizes are clamped
18    /// to one pixel because `wgpu` surfaces cannot be configured at zero size.
19    /// This convenience constructor assumes a display scale factor of `1.0`;
20    /// HiDPI hosts should use [`WgpuRenderer::new_with_options`].
21    pub async fn new(
22        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
23        width: u32,
24        height: u32,
25    ) -> Result<Self, RendererInitError> {
26        Self::new_with_options(
27            surface_target,
28            width,
29            height,
30            WgpuRendererOptions::default(),
31        )
32        .await
33    }
34
35    /// Creates a renderer with explicit options.
36    ///
37    /// Use this when measuring renderer throughput or when the host application
38    /// needs control over presentation behavior or display scale.
39    pub async fn new_with_options(
40        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
41        width: u32,
42        height: u32,
43        options: WgpuRendererOptions,
44    ) -> Result<Self, RendererInitError> {
45        let instance =
46            wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
47        let surface = instance
48            .create_surface(surface_target)
49            .map_err(RendererInitError::CreateSurface)?;
50        let adapter = instance
51            .request_adapter(&wgpu::RequestAdapterOptions {
52                power_preference: wgpu::PowerPreference::HighPerformance,
53                force_fallback_adapter: false,
54                compatible_surface: Some(&surface),
55                apply_limit_buckets: false,
56            })
57            .await
58            .map_err(RendererInitError::RequestAdapter)?;
59        let adapter_info = adapter.get_info();
60
61        let (device, queue) = adapter
62            .request_device(&wgpu::DeviceDescriptor {
63                label: Some("sim-engine device"),
64                required_features: gpu_timing::requested_features(
65                    adapter.features(),
66                    options.gpu_timing(),
67                ),
68                required_limits: wgpu::Limits::default(),
69                experimental_features: wgpu::ExperimentalFeatures::disabled(),
70                memory_hints: wgpu::MemoryHints::Performance,
71                trace: wgpu::Trace::Off,
72            })
73            .await
74            .map_err(RendererInitError::RequestDevice)?;
75
76        let width = width.max(1);
77        let height = height.max(1);
78        let dimension_limit = device.limits().max_texture_dimension_2d;
79        if width > dimension_limit || height > dimension_limit {
80            return Err(RendererInitError::SurfaceDimensionsTooLarge {
81                width,
82                height,
83                limit: dimension_limit,
84            });
85        }
86        let surface_capabilities = surface.get_capabilities(&adapter);
87        let mut config = surface
88            .get_default_config(&adapter, width, height)
89            .ok_or(RendererInitError::NoSurfaceConfig)?;
90        let surface_present_mode = select_surface_present_mode(
91            options.present_mode(),
92            &surface_capabilities.present_modes,
93        );
94        config.present_mode = surface_present_mode.to_wgpu();
95        surface.configure(&device, &config);
96
97        let sample_count = preferred_sample_count(&adapter, config.format);
98        let PipelineResources {
99            pipeline,
100            target_pipeline,
101            dynamic_pipeline,
102            particle_pipeline,
103            target_particle_pipeline,
104            heatmap_pipeline,
105            target_heatmap_pipeline,
106            composition_pipelines,
107            target_composition_pipelines,
108            camera_uniform_buffer,
109            camera_bind_group,
110            camera_bind_group_layout,
111            heatmap_uniform_buffer,
112            heatmap_bind_group_layout,
113        } = create_pipeline(&device, config.format, sample_count);
114        let vertex_buffer = Arc::new(create_vertex_buffer(&device, INITIAL_VERTEX_CAPACITY));
115        let particle_unit_buffer = create_submitted_particle_unit_buffer(&device, &queue);
116        let multisample_target = create_multisample_target(&device, &config, sample_count);
117        let image_renderer = ImageRenderer::new(&device, config.format, sample_count);
118        let screen_primitive_pipeline = super::screen_primitives::create_pipeline(
119            &device,
120            &camera_bind_group_layout,
121            config.format,
122            sample_count,
123        );
124        let target_screen_primitive_pipeline = super::screen_primitives::create_pipeline(
125            &device,
126            &camera_bind_group_layout,
127            config.format,
128            1,
129        );
130        let mesh3d_renderer = Mesh3dRenderer::new(&device, config.format);
131        let gpu_timing = gpu_timing::GpuTimingCollector::new(&device, &queue, options.gpu_timing());
132
133        Ok(Self {
134            renderer_identity: Arc::new(()),
135            _instance: instance,
136            surface,
137            _adapter: adapter,
138            adapter_info,
139            device,
140            queue,
141            config,
142            requested_present_mode: options.present_mode(),
143            surface_present_mode,
144            pre_present_notify: None,
145            scale_factor: options.scale_factor(),
146            pipeline,
147            target_pipeline,
148            dynamic_pipeline,
149            particle_pipeline,
150            target_particle_pipeline,
151            heatmap_pipeline,
152            target_heatmap_pipeline,
153            composition_pipelines,
154            target_composition_pipelines,
155            image_renderer,
156            screen_primitive_pipeline,
157            target_screen_primitive_pipeline,
158            mesh3d_renderer,
159            gpu_timing,
160            gpu_timing_requested: options.gpu_timing(),
161            camera_uniform_buffer,
162            camera_bind_group,
163            camera_bind_group_layout,
164            heatmap_uniform_buffer,
165            heatmap_bind_group_layout,
166            color_map_cache: None,
167            frame_cache: frame::FrameCache::default(),
168            vertex_buffer,
169            particle_unit_buffer,
170            vertex_capacity: INITIAL_VERTEX_CAPACITY,
171            multisample_target,
172            sample_count,
173            vertices: Vec::new(),
174            draw_batches: Vec::new(),
175            retired_devices: Vec::new(),
176            max_quarantined_devices: options.max_quarantined_devices(),
177        })
178    }
179
180    /// Returns the configured surface size in physical pixels.
181    pub fn size(&self) -> (u32, u32) {
182        (self.config.width, self.config.height)
183    }
184
185    /// Returns optional GPU-query availability, bounded resources and losses.
186    /// These diagnostics are independent of frame CPU timings and scene uploads.
187    pub fn gpu_timing_statistics(&self) -> GpuTimingStatistics {
188        self.gpu_timing.statistics()
189    }
190
191    /// Collects at most eight completed GPU pass intervals without waiting.
192    ///
193    /// Call regularly when timing is enabled; uncollected samples occupy the
194    /// fixed ring and eventually cause new samples to be dropped. Match sample
195    /// IDs to submitted reports when excluding warmup or unrelated work. A call
196    /// performs one nonblocking device poll and reports its CPU overhead. Device
197    /// recovery discards pending old-device samples and resets the counters.
198    pub fn collect_gpu_timings(&mut self) -> GpuTimingBatch {
199        self.gpu_timing.collect(&self.device)
200    }
201
202    /// Returns the render viewport size in logical screen pixels.
203    ///
204    /// Scene clipping, stroke widths, shadows, and camera zoom use this logical
205    /// coordinate space so their visual size remains stable across display DPI.
206    pub fn logical_size(&self) -> (f32, f32) {
207        let scale_factor = self.scale_factor as f32;
208        (
209            self.config.width as f32 / scale_factor,
210            self.config.height as f32 / scale_factor,
211        )
212    }
213
214    /// Returns the current camera viewport in logical screen pixels.
215    pub fn logical_viewport(&self) -> Result<LogicalViewport, crate::LogicalViewportError> {
216        let (width, height) = self.logical_size();
217        LogicalViewport::new(width, height)
218    }
219
220    /// Converts a physical surface position into logical screen pixels.
221    pub fn physical_to_logical_screen(
222        &self,
223        position: PhysicalScreenPosition,
224    ) -> Result<LogicalScreenPosition, RendererCoordinateError> {
225        physical_to_logical_screen(position, self.scale_factor as f32)
226    }
227
228    /// Converts a logical screen position into physical surface pixels.
229    pub fn logical_to_physical_screen(
230        &self,
231        position: LogicalScreenPosition,
232    ) -> Result<PhysicalScreenPosition, RendererCoordinateError> {
233        logical_to_physical_screen(position, self.scale_factor as f32)
234    }
235
236    /// Returns physical surface pixels per logical screen pixel.
237    pub fn scale_factor(&self) -> f64 {
238        self.scale_factor
239    }
240
241    /// Returns the concrete presentation mode selected for the active surface.
242    ///
243    /// `RendererPresentMode::NoVsync` prefers Immediate, then Mailbox, then
244    /// FIFO. This method reveals which supported fallback was configured. The
245    /// desktop compositor may still pace host redraw callbacks independently.
246    pub fn surface_present_mode(&self) -> RendererSurfacePresentMode {
247        self.surface_present_mode
248    }
249
250    /// Installs a host callback invoked immediately before synchronized
251    /// surface presentation.
252    ///
253    /// A winit host should capture its `Arc<Window>` and call
254    /// `Window::pre_present_notify` from this callback. The renderer invokes
255    /// it after command submission and immediately before `Queue::present`,
256    /// but only when the concrete surface mode is Mailbox, FIFO, or
257    /// FIFO-relaxed. Immediate presentation deliberately remains uncapped.
258    pub fn set_pre_present_notify(&mut self, notify: impl Fn() + Send + Sync + 'static) {
259        self.pre_present_notify = Some(Arc::new(notify));
260    }
261
262    /// Removes the synchronized-presentation callback, if one is installed.
263    pub fn clear_pre_present_notify(&mut self) {
264        self.pre_present_notify = None;
265    }
266
267    pub(super) fn notify_before_present(&self) {
268        invoke_pre_present_notify(
269            self.surface_present_mode,
270            self.pre_present_notify.as_deref(),
271        );
272    }
273
274    /// Returns the active graphics adapter's human-readable name.
275    pub fn adapter_name(&self) -> &str {
276        &self.adapter_info.name
277    }
278
279    /// Returns the active graphics API backend as a stable lowercase name.
280    pub fn adapter_backend(&self) -> &'static str {
281        self.adapter_info.backend.to_str()
282    }
283
284    /// Returns the PCI vendor identifier reported for the active adapter.
285    pub fn adapter_vendor_id(&self) -> u32 {
286        self.adapter_info.vendor
287    }
288
289    /// Returns the device identifier reported for the active adapter.
290    pub fn adapter_device_id(&self) -> u32 {
291        self.adapter_info.device
292    }
293
294    /// Returns the backend-reported PCI bus address for the active adapter.
295    ///
296    /// Vulkan adapters expose this as `domain:bus:device.function` when the
297    /// driver supports `VK_EXT_pci_bus_info`. An empty string means that the
298    /// backend cannot identify a physical adapter instance; release evidence
299    /// must not treat model identifiers alone as instance identity.
300    pub fn adapter_pci_bus_id(&self) -> &str {
301        &self.adapter_info.device_pci_bus_id
302    }
303
304    /// Returns the texture format selected for the active presentation surface.
305    pub fn surface_format(&self) -> wgpu::TextureFormat {
306        self.config.format
307    }
308
309    /// Returns the raster sample count selected for the active surface format.
310    pub fn surface_sample_count(&self) -> u32 {
311        self.sample_count
312    }
313
314    /// Returns the driver name reported by the active graphics adapter.
315    pub fn adapter_driver(&self) -> &str {
316        &self.adapter_info.driver
317    }
318
319    /// Returns the driver version or implementation detail reported by the adapter.
320    pub fn adapter_driver_info(&self) -> &str {
321        &self.adapter_info.driver_info
322    }
323
324    /// Returns previous logical devices retained for safe native-driver teardown.
325    pub fn quarantined_device_count(&self) -> usize {
326        self.retired_devices.len()
327    }
328
329    /// Returns the configured maximum previous-device quarantine size.
330    pub fn max_quarantined_device_count(&self) -> usize {
331        self.max_quarantined_devices
332    }
333
334    /// Returns successful recoveries available before the bounded quarantine is full.
335    pub fn remaining_device_recoveries(&self) -> usize {
336        self.max_quarantined_devices
337            .saturating_sub(self.retired_devices.len())
338    }
339
340    /// Blocks until all previously submitted GPU work has completed.
341    ///
342    /// This is intended for diagnostic throughput measurements, readback, and
343    /// controlled resource teardown. Calling it in an interactive frame loop
344    /// defeats normal CPU/GPU pipelining.
345    pub fn wait_for_gpu_idle(&self) -> Result<(), wgpu::PollError> {
346        self.device
347            .poll(wgpu::PollType::wait_indefinitely())
348            .map(|_| ())
349    }
350
351    /// Replaces display scale without changing physical surface dimensions.
352    ///
353    /// Invalid values return an error and leave the current scale unchanged.
354    pub fn set_scale_factor(
355        &mut self,
356        scale_factor: f64,
357    ) -> Result<(), RendererConfigurationError> {
358        validate_scale_factor(scale_factor)?;
359        self.scale_factor = scale_factor;
360        Ok(())
361    }
362
363    /// Reconfigures the surface after a host window resize.
364    ///
365    /// Zero width or height is ignored because minimized windows often report
366    /// zero size and `wgpu` cannot configure a zero-sized surface.
367    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RendererConfigurationError> {
368        if width == 0 || height == 0 {
369            return Ok(());
370        }
371        validate_surface_dimensions(width, height, self.device.limits().max_texture_dimension_2d)?;
372
373        self.config.width = width;
374        self.config.height = height;
375        self.surface.configure(&self.device, &self.config);
376        self.multisample_target =
377            create_multisample_target(&self.device, &self.config, self.sample_count);
378        Ok(())
379    }
380
381    /// Reconfigures physical surface size and logical-to-physical display scale.
382    ///
383    /// Invalid scale returns an error without changing either value. Zero
384    /// physical dimensions update the scale but leave the minimized surface
385    /// configuration unchanged.
386    pub fn resize_with_scale_factor(
387        &mut self,
388        width: u32,
389        height: u32,
390        scale_factor: f64,
391    ) -> Result<(), RendererConfigurationError> {
392        validate_scale_factor(scale_factor)?;
393        if width != 0 && height != 0 {
394            validate_surface_dimensions(
395                width,
396                height,
397                self.device.limits().max_texture_dimension_2d,
398            )?;
399        }
400        self.resize(width, height)?;
401        self.scale_factor = scale_factor;
402        Ok(())
403    }
404}