1use 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 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 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 pub fn size(&self) -> (u32, u32) {
182 (self.config.width, self.config.height)
183 }
184
185 pub fn gpu_timing_statistics(&self) -> GpuTimingStatistics {
188 self.gpu_timing.statistics()
189 }
190
191 pub fn collect_gpu_timings(&mut self) -> GpuTimingBatch {
199 self.gpu_timing.collect(&self.device)
200 }
201
202 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 pub fn logical_viewport(&self) -> Result<LogicalViewport, crate::LogicalViewportError> {
216 let (width, height) = self.logical_size();
217 LogicalViewport::new(width, height)
218 }
219
220 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 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 pub fn scale_factor(&self) -> f64 {
238 self.scale_factor
239 }
240
241 pub fn surface_present_mode(&self) -> RendererSurfacePresentMode {
247 self.surface_present_mode
248 }
249
250 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 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 pub fn adapter_name(&self) -> &str {
276 &self.adapter_info.name
277 }
278
279 pub fn adapter_backend(&self) -> &'static str {
281 self.adapter_info.backend.to_str()
282 }
283
284 pub fn adapter_vendor_id(&self) -> u32 {
286 self.adapter_info.vendor
287 }
288
289 pub fn adapter_device_id(&self) -> u32 {
291 self.adapter_info.device
292 }
293
294 pub fn adapter_pci_bus_id(&self) -> &str {
301 &self.adapter_info.device_pci_bus_id
302 }
303
304 pub fn surface_format(&self) -> wgpu::TextureFormat {
306 self.config.format
307 }
308
309 pub fn surface_sample_count(&self) -> u32 {
311 self.sample_count
312 }
313
314 pub fn adapter_driver(&self) -> &str {
316 &self.adapter_info.driver
317 }
318
319 pub fn adapter_driver_info(&self) -> &str {
321 &self.adapter_info.driver_info
322 }
323
324 pub fn quarantined_device_count(&self) -> usize {
326 self.retired_devices.len()
327 }
328
329 pub fn max_quarantined_device_count(&self) -> usize {
331 self.max_quarantined_devices
332 }
333
334 pub fn remaining_device_recoveries(&self) -> usize {
336 self.max_quarantined_devices
337 .saturating_sub(self.retired_devices.len())
338 }
339
340 pub fn wait_for_gpu_idle(&self) -> Result<(), wgpu::PollError> {
346 self.device
347 .poll(wgpu::PollType::wait_indefinitely())
348 .map(|_| ())
349 }
350
351 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 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 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}