Skip to main content

sui_render_wgpu/
surface.rs

1#[cfg(target_os = "windows")]
2#[allow(unsafe_code)]
3#[path = "surface/windows.rs"]
4mod windows_surface;
5
6use crate::WgpuRenderer;
7use crate::diagnostics::RendererFrameStats;
8use crate::output::ColorManagementMode;
9use crate::output::DisplayCapabilities;
10use crate::output::OutputStrategy;
11use crate::output::output_transform_requires_intermediate;
12use crate::output::select_output_strategy;
13use std::sync::Arc;
14use sui_core::Error;
15use sui_core::Result;
16use sui_core::Size;
17use sui_core::WindowId;
18use sui_scene::SceneFrame;
19use web_time::Instant;
20use winit::window::Window;
21
22impl WgpuRenderer {
23    /// Begin device setup using this native surface before the first CPU layout.
24    /// Call `register_window` afterwards to finish configuration. Preparation is
25    /// optional, idempotent, and cancelled when the window/renderer is removed.
26    pub fn prepare_window(&mut self, window_id: WindowId, window: Arc<Window>) -> Result<()> {
27        #[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
28        if self.shared.is_none() && !self.prepared_surfaces.contains_key(&window_id) {
29            let surface = Arc::new(
30                self.instance
31                    .create_surface(Arc::clone(&window))
32                    .map_err(|error| {
33                        Error::new(format!("failed to create wgpu surface: {error}"))
34                    })?,
35            );
36            self.start_device_preparation(Some(window_id), Some(surface.clone()));
37            self.prepared_surfaces
38                .insert(window_id, PreparedSurface { window, surface });
39        }
40        #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
41        let _ = (window_id, window);
42        Ok(())
43    }
44
45    pub fn register_window(&mut self, window_id: WindowId, window: Arc<Window>) -> Result<()> {
46        let physical_size = window.inner_size();
47        let size = normalize_surface_size(physical_size.width, physical_size.height);
48        let state = match self.prepared_surfaces.remove(&window_id) {
49            Some(prepared) if Arc::ptr_eq(&prepared.window, &window) => {
50                self.configure_new_surface(window, prepared.surface, size)?
51            }
52            _ => self.create_surface_state(window, size)?,
53        };
54
55        self.surfaces.insert(window_id, state);
56        self.offscreen_targets.remove(&window_id);
57        self.intermediate_targets.remove(&window_id);
58        Ok(())
59    }
60
61    pub(crate) fn render_surface(
62        &mut self,
63        frame: &SceneFrame,
64        size: (u32, u32),
65    ) -> Result<RendererFrameStats> {
66        self.ensure_shared(None)?;
67        self.resize_surface(frame.window_id, size)?;
68
69        let prepared = self.prepare_scene_submission(frame)?;
70
71        let Some((frame_texture, suboptimal, surface_acquire_time_us)) =
72            self.acquire_surface_texture(frame.window_id, size)?
73        else {
74            return Ok(RendererFrameStats::default());
75        };
76
77        let (format, strategy, tone_mapping, sdr_content_brightness_nits, display_sdr_white_nits) = {
78            let surface = self.surfaces.get(&frame.window_id).ok_or_else(|| {
79                Error::new(format!(
80                    "missing surface for window {}",
81                    frame.window_id.get()
82                ))
83            })?;
84            (
85                surface.config.format,
86                surface.output_strategy,
87                surface.color_management.tone_mapping,
88                surface.color_management.sdr_content_brightness_nits,
89                surface.display_capabilities.sdr_white_nits,
90            )
91        };
92        let view = frame_texture
93            .texture
94            .create_view(&wgpu::TextureViewDescriptor::default());
95
96        let mut frame_stats = if output_transform_requires_intermediate(strategy) {
97            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
98            let intermediate_format = self
99                .intermediate_targets
100                .get(&frame.window_id)
101                .map(|target| target.format)
102                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
103            let mut encoder = self.frame_encoder();
104            let mut frame_stats = self.encode_prepared_scene(
105                prepared,
106                intermediate_format,
107                &intermediate_view,
108                &mut encoder,
109            )?;
110            self.encode_output_transform_pass(
111                frame.window_id,
112                &intermediate_view,
113                &view,
114                format,
115                strategy,
116                tone_mapping,
117                sdr_content_brightness_nits,
118                display_sdr_white_nits,
119                &mut frame_stats,
120                &mut encoder,
121            )?;
122            self.submit_frame_encoder(encoder, &mut frame_stats);
123            frame_stats
124        } else {
125            self.submit_prepared_scene(prepared, format, &view)?
126        };
127        frame_stats.surface_acquire_time_us = surface_acquire_time_us;
128        let surface_present_started = self.runtime_diagnostics_enabled.then(Instant::now);
129        self.shared
130            .as_ref()
131            .expect("renderer shared state initialized")
132            .queue
133            .present(frame_texture);
134        frame_stats.surface_present_time_us = surface_present_started
135            .map(|started| started.elapsed().as_micros() as u64)
136            .unwrap_or(0);
137
138        if suboptimal {
139            self.configure_surface(frame.window_id, size)?;
140        }
141
142        Ok(frame_stats)
143    }
144
145    pub(crate) fn acquire_surface_texture(
146        &mut self,
147        window_id: WindowId,
148        size: (u32, u32),
149    ) -> Result<Option<(wgpu::SurfaceTexture, bool, u64)>> {
150        let surface_acquire_started = self.runtime_diagnostics_enabled.then(Instant::now);
151        let (frame_texture, suboptimal) = loop {
152            let result = {
153                let surface = self.surfaces.get(&window_id).ok_or_else(|| {
154                    Error::new(format!("missing surface for window {}", window_id.get()))
155                })?;
156                surface.surface.get_current_texture()
157            };
158
159            match result {
160                wgpu::CurrentSurfaceTexture::Success(texture) => break (texture, false),
161                wgpu::CurrentSurfaceTexture::Suboptimal(texture) => break (texture, true),
162                wgpu::CurrentSurfaceTexture::Outdated => {
163                    self.configure_surface(window_id, size)?;
164                }
165                wgpu::CurrentSurfaceTexture::Lost => {
166                    self.recreate_surface(window_id, size)?;
167                }
168                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
169                    return Ok(None);
170                }
171                wgpu::CurrentSurfaceTexture::Validation => {
172                    return Err(Error::new(
173                        "wgpu surface acquisition triggered a validation error",
174                    ));
175                }
176            }
177        };
178        let surface_acquire_time_us = surface_acquire_started
179            .map(|started| started.elapsed().as_micros() as u64)
180            .unwrap_or(0);
181
182        Ok(Some((frame_texture, suboptimal, surface_acquire_time_us)))
183    }
184
185    pub(crate) fn resize_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
186        let surface = self
187            .surfaces
188            .get(&window_id)
189            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
190
191        if surface.config.width == size.0 && surface.config.height == size.1 {
192            return Ok(());
193        }
194
195        self.configure_surface(window_id, size)
196    }
197
198    pub(crate) fn configure_existing_surface(&mut self, window_id: WindowId) -> Result<()> {
199        let size = {
200            let surface = self.surfaces.get(&window_id).ok_or_else(|| {
201                Error::new(format!("missing surface for window {}", window_id.get()))
202            })?;
203            (surface.config.width.max(1), surface.config.height.max(1))
204        };
205        self.configure_surface(window_id, size)
206    }
207
208    pub(crate) fn configure_surface(
209        &mut self,
210        window_id: WindowId,
211        size: (u32, u32),
212    ) -> Result<()> {
213        let shared = self
214            .shared
215            .as_ref()
216            .expect("renderer shared state initialized");
217        let surface = self
218            .surfaces
219            .get_mut(&window_id)
220            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
221
222        let available_surface_formats = surface.surface.get_capabilities(&shared.adapter).formats;
223        let (config, output_strategy) = configure_surface(
224            &surface.surface,
225            &shared.adapter,
226            &shared.device,
227            size,
228            self.vsync_enabled,
229            surface.display_capabilities.clone(),
230            surface.color_management,
231        )?;
232        surface.config = config;
233        surface.output_strategy = output_strategy;
234        surface.available_surface_formats = available_surface_formats;
235        Ok(())
236    }
237
238    pub(crate) fn recreate_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
239        let window = self
240            .surfaces
241            .get(&window_id)
242            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?
243            .window
244            .clone();
245        let state = self.create_surface_state(window, size)?;
246        self.surfaces.insert(window_id, state);
247        Ok(())
248    }
249
250    pub(crate) fn create_surface_state(
251        &mut self,
252        window: Arc<Window>,
253        size: (u32, u32),
254    ) -> Result<SurfaceState> {
255        let surface = self
256            .instance
257            .create_surface(Arc::clone(&window))
258            .map_err(|error| Error::new(format!("failed to create wgpu surface: {error}")))?;
259        self.configure_new_surface(window, Arc::new(surface), size)
260    }
261
262    fn configure_new_surface(
263        &mut self,
264        window: Arc<Window>,
265        surface: Arc<wgpu::Surface<'static>>,
266        size: (u32, u32),
267    ) -> Result<SurfaceState> {
268        self.ensure_shared(Some(&surface))?;
269
270        let shared = self
271            .shared
272            .as_ref()
273            .expect("renderer shared state initialized");
274        let default_capabilities = DisplayCapabilities::default();
275        let default_color_management = ColorManagementMode::default();
276        let available_surface_formats = surface.get_capabilities(&shared.adapter).formats;
277        let (config, output_strategy) = configure_surface(
278            &surface,
279            &shared.adapter,
280            &shared.device,
281            size,
282            self.vsync_enabled,
283            default_capabilities.clone(),
284            default_color_management,
285        )?;
286
287        Ok(SurfaceState {
288            window,
289            surface,
290            config,
291            display_capabilities: default_capabilities,
292            color_management: default_color_management,
293            output_strategy,
294            available_surface_formats,
295        })
296    }
297}
298
299pub(crate) fn normalize_framebuffer_size(size: Size) -> Option<(u32, u32)> {
300    if size.is_empty() {
301        None
302    } else {
303        Some(normalize_surface_size(
304            size.width.round() as u32,
305            size.height.round() as u32,
306        ))
307    }
308}
309
310pub(crate) fn normalize_surface_size(width: u32, height: u32) -> (u32, u32) {
311    (width.max(1), height.max(1))
312}
313
314pub(crate) fn configure_surface_for_strategy(
315    surface: &wgpu::Surface<'static>,
316    adapter: &wgpu::Adapter,
317    device: &wgpu::Device,
318    size: (u32, u32),
319    vsync_enabled: bool,
320    strategy: OutputStrategy,
321) -> Result<wgpu::SurfaceConfiguration> {
322    let mut config = surface
323        .get_default_config(adapter, size.0, size.1)
324        .ok_or_else(|| Error::new("wgpu adapter does not support presenting to this surface"))?;
325    config.format = strategy.surface_format();
326    config.present_mode = if vsync_enabled {
327        wgpu::PresentMode::AutoVsync
328    } else {
329        wgpu::PresentMode::AutoNoVsync
330    };
331    let capabilities = surface.get_capabilities(adapter);
332    if capabilities
333        .alpha_modes
334        .contains(&wgpu::CompositeAlphaMode::Opaque)
335    {
336        config.alpha_mode = wgpu::CompositeAlphaMode::Opaque;
337    }
338    surface.configure(device, &config);
339    configure_native_hdr_surface_color_space(surface, strategy)?;
340    Ok(config)
341}
342
343pub(crate) fn configure_native_hdr_surface_color_space(
344    surface: &wgpu::Surface<'static>,
345    strategy: OutputStrategy,
346) -> Result<()> {
347    if !matches!(strategy, OutputStrategy::HdrNativeSurface { .. }) {
348        return Ok(());
349    }
350
351    #[cfg(target_os = "windows")]
352    {
353        windows_surface::set_native_hdr_surface_color_space(surface)
354            .map_err(|error| Error::new(format!("failed to configure native HDR surface: {error}")))
355    }
356
357    #[cfg(not(target_os = "windows"))]
358    {
359        let _ = surface;
360        Ok(())
361    }
362}
363
364pub(crate) fn configure_surface(
365    surface: &wgpu::Surface<'static>,
366    adapter: &wgpu::Adapter,
367    device: &wgpu::Device,
368    size: (u32, u32),
369    vsync_enabled: bool,
370    display_capabilities: DisplayCapabilities,
371    color_management: ColorManagementMode,
372) -> Result<(wgpu::SurfaceConfiguration, OutputStrategy)> {
373    let surface_capabilities = surface.get_capabilities(adapter);
374    let strategy = select_output_strategy(
375        &surface_capabilities.formats,
376        display_capabilities,
377        color_management,
378    );
379    let config =
380        configure_surface_for_strategy(surface, adapter, device, size, vsync_enabled, strategy)?;
381    Ok((config, strategy))
382}
383
384pub(crate) struct PreparedSurface {
385    window: Arc<Window>,
386    surface: Arc<wgpu::Surface<'static>>,
387}
388
389pub(crate) struct SurfaceState {
390    pub(crate) window: Arc<Window>,
391    pub(crate) surface: Arc<wgpu::Surface<'static>>,
392    pub(crate) config: wgpu::SurfaceConfiguration,
393    pub(crate) display_capabilities: DisplayCapabilities,
394    pub(crate) color_management: ColorManagementMode,
395    pub(crate) output_strategy: OutputStrategy,
396    pub(crate) available_surface_formats: Vec<wgpu::TextureFormat>,
397}