wgpu_hal/vulkan/swapchain/native.rs
1//! Vulkan Surface and Swapchain implementation using native Vulkan surfaces.
2
3use alloc::{boxed::Box, sync::Arc, vec::Vec};
4use core::any::Any;
5
6use ash::{google, khr, vk};
7use wgpu_sync::{Mutex, MutexGuard};
8
9use crate::vulkan::{
10 conv, map_host_device_oom_and_lost_err,
11 semaphore_list::SemaphoreType,
12 swapchain::{
13 Surface, SurfaceTextureMetadata, Swapchain, SwapchainSubmissionSemaphoreGuard, WindowHandle,
14 },
15 DeviceShared, InstanceShared, PnextChain,
16};
17
18pub(crate) struct NativeSurface {
19 raw: vk::SurfaceKHR,
20 functor: khr::surface::Instance,
21 instance: Arc<InstanceShared>,
22 /// Built from the window's `HWND` (Windows only) to answer the display-HDR
23 /// query; `None` for non-Win32 surfaces.
24 #[cfg(windows)]
25 hdr_source: Option<crate::auxil::dxgi::hdr::DxgiHdrSource>,
26 /// A caller-provided `pNext` chain to attach to the [`vk::SwapchainCreateInfoKHR`]
27 /// of the next swapchain created for this surface.
28 ///
29 /// Set only through
30 /// [`Surface::set_next_swapchain_create_chain()`](crate::vulkan::Surface::set_next_swapchain_create_chain).
31 next_swapchain_create_chain: Mutex<Option<PnextChain>>,
32}
33
34impl NativeSurface {
35 pub fn from_vk_surface_khr(
36 instance: &crate::vulkan::Instance,
37 raw: vk::SurfaceKHR,
38 hwnd: Option<WindowHandle>,
39 ) -> Self {
40 #[cfg(not(windows))]
41 let _ = hwnd;
42 let functor = khr::surface::Instance::new(&instance.shared.entry, &instance.shared.raw);
43 Self {
44 raw,
45 functor,
46 instance: Arc::clone(&instance.shared),
47 #[cfg(windows)]
48 hdr_source: hwnd.map(|wh| crate::auxil::dxgi::hdr::DxgiHdrSource::new(wh.0)),
49 next_swapchain_create_chain: Mutex::new(None),
50 }
51 }
52
53 pub fn as_raw(&self) -> vk::SurfaceKHR {
54 self.raw
55 }
56
57 /// # Safety
58 ///
59 /// See [`Surface::set_next_swapchain_create_chain()`](crate::vulkan::Surface::set_next_swapchain_create_chain).
60 pub unsafe fn set_next_swapchain_create_chain(&self, chain: *mut core::ffi::c_void) {
61 *self.next_swapchain_create_chain.lock() = Some(PnextChain::new(chain));
62 }
63}
64
65impl Drop for NativeSurface {
66 fn drop(&mut self) {
67 unsafe {
68 self.functor.destroy_surface(self.raw, None);
69 }
70 }
71}
72
73impl Surface for NativeSurface {
74 fn surface_capabilities(
75 &self,
76 adapter: &crate::vulkan::Adapter,
77 ) -> Option<crate::SurfaceCapabilities> {
78 if !adapter.private_caps.can_present {
79 return None;
80 }
81 let queue_family_index = 0; //TODO
82 {
83 profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR");
84 match unsafe {
85 self.functor.get_physical_device_surface_support(
86 adapter.raw,
87 queue_family_index,
88 self.raw,
89 )
90 } {
91 Ok(true) => (),
92 Ok(false) => return None,
93 Err(e) => {
94 log::error!("get_physical_device_surface_support: {e}");
95 return None;
96 }
97 }
98 }
99
100 let caps = {
101 profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
102 match unsafe {
103 self.functor
104 .get_physical_device_surface_capabilities(adapter.raw, self.raw)
105 } {
106 Ok(caps) => caps,
107 Err(e) => {
108 log::error!("get_physical_device_surface_capabilities: {e}");
109 return None;
110 }
111 }
112 };
113
114 // If image count is 0, the support number of images is unlimited.
115 let max_image_count = if caps.max_image_count == 0 {
116 !0
117 } else {
118 caps.max_image_count
119 };
120
121 // `0xFFFFFFFF` indicates that the extent depends on the created swapchain.
122 let current_extent = if caps.current_extent.width != !0 && caps.current_extent.height != !0
123 {
124 Some(wgt::Extent3d {
125 width: caps.current_extent.width,
126 height: caps.current_extent.height,
127 depth_or_array_layers: 1,
128 })
129 } else {
130 None
131 };
132
133 let raw_present_modes = {
134 profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR");
135 match unsafe {
136 self.functor
137 .get_physical_device_surface_present_modes(adapter.raw, self.raw)
138 } {
139 Ok(present_modes) => present_modes,
140 Err(e) => {
141 log::error!("get_physical_device_surface_present_modes: {e}");
142 // Per definition of `SurfaceCapabilities`, there must be at least one present mode.
143 return None;
144 }
145 }
146 };
147
148 let raw_surface_formats = {
149 profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR");
150 match unsafe {
151 self.functor
152 .get_physical_device_surface_formats(adapter.raw, self.raw)
153 } {
154 Ok(formats) => formats,
155 Err(e) => {
156 log::error!("get_physical_device_surface_formats: {e}");
157 // Per definition of `SurfaceCapabilities`, there must be at least one present format.
158 return None;
159 }
160 }
161 };
162
163 // Group the driver's (format, color space) pairs into one entry per
164 // format, preserving the driver's format order.
165 let mut formats: Vec<wgt::SurfaceFormatCapabilities> = Vec::new();
166 for (format, color_space) in raw_surface_formats
167 .into_iter()
168 .filter_map(conv::map_vk_surface_formats)
169 {
170 let color_spaces = color_space.to_color_spaces().unwrap();
171 match formats.iter_mut().find(|fc| fc.format == format) {
172 Some(fc) => fc.color_spaces |= color_spaces,
173 None => formats.push(wgt::SurfaceFormatCapabilities {
174 format,
175 color_spaces,
176 }),
177 }
178 }
179 Some(crate::SurfaceCapabilities {
180 formats,
181 // TODO: Right now we're always truncating the swap chain
182 // (presumably - we're actually setting the min image count which isn't necessarily the swap chain size)
183 // Instead, we should use extensions when available to wait in present.
184 // See https://github.com/gfx-rs/wgpu/issues/2869
185 maximum_frame_latency: (caps.min_image_count - 1)..=(max_image_count - 1), // Note this can't underflow since both `min_image_count` is at least one and we already patched `max_image_count`.
186 current_extent,
187 usage: conv::map_vk_image_usage(caps.supported_usage_flags),
188 present_modes: raw_present_modes
189 .into_iter()
190 .flat_map(conv::map_vk_present_mode)
191 .collect(),
192 composite_alpha_modes: conv::map_vk_composite_alpha(caps.supported_composite_alpha),
193 })
194 }
195
196 unsafe fn create_swapchain(
197 &self,
198 device: &crate::vulkan::Device,
199 config: &crate::SurfaceConfiguration,
200 provided_old_swapchain: Option<Box<dyn Swapchain>>,
201 ) -> Result<Box<dyn Swapchain>, crate::SurfaceError> {
202 profiling::scope!("Device::create_swapchain");
203 let functor = khr::swapchain::Device::new(&self.instance.raw, &device.shared.raw);
204
205 let old_swapchain = provided_old_swapchain
206 .as_ref()
207 .map(|osc| osc.as_any().downcast_ref::<NativeSwapchain>().unwrap().raw)
208 .unwrap_or(vk::SwapchainKHR::null());
209
210 let color_space = conv::map_surface_color_space(config.color_space);
211
212 let original_format = device.shared.private_caps.map_texture_format(config.format);
213 let mut raw_flags = vk::SwapchainCreateFlagsKHR::empty();
214 let mut raw_view_formats: Vec<vk::Format> = vec![];
215 if !config.view_formats.is_empty() {
216 raw_flags |= vk::SwapchainCreateFlagsKHR::MUTABLE_FORMAT;
217 raw_view_formats = config
218 .view_formats
219 .iter()
220 .map(|f| device.shared.private_caps.map_texture_format(*f))
221 .collect();
222 raw_view_formats.push(original_format);
223 }
224
225 let mut info = vk::SwapchainCreateInfoKHR::default()
226 .flags(raw_flags)
227 .surface(self.raw)
228 .min_image_count(config.maximum_frame_latency + 1) // TODO: https://github.com/gfx-rs/wgpu/issues/2869
229 .image_format(original_format)
230 .image_color_space(color_space)
231 .image_extent(vk::Extent2D {
232 width: config.extent.width,
233 height: config.extent.height,
234 })
235 .image_array_layers(config.extent.depth_or_array_layers)
236 .image_usage(conv::map_texture_usage(config.usage))
237 .image_sharing_mode(vk::SharingMode::EXCLUSIVE)
238 .pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY)
239 .composite_alpha(conv::map_composite_alpha_mode(config.composite_alpha_mode))
240 .present_mode(conv::map_present_mode(config.present_mode))
241 .clipped(true)
242 .old_swapchain(old_swapchain);
243
244 let mut format_list_info = vk::ImageFormatListCreateInfo::default();
245 if !raw_view_formats.is_empty() {
246 format_list_info = format_list_info.view_formats(&raw_view_formats);
247 info = info.push_next(&mut format_list_info);
248 }
249
250 let create_chain = self.next_swapchain_create_chain.lock().take();
251 if let Some(chain) = create_chain {
252 // SAFETY: The contract on `Surface::set_next_swapchain_create_chain()` keeps
253 // the chain valid and unaliased until this swapchain creation returns.
254 info.p_next = unsafe { chain.splice_into(info.p_next) };
255 }
256
257 let result = {
258 profiling::scope!("vkCreateSwapchainKHR");
259 unsafe { functor.create_swapchain(&info, None) }
260 };
261
262 let raw = match result {
263 Ok(swapchain) => swapchain,
264 Err(error) => {
265 return Err(match error {
266 vk::Result::ERROR_SURFACE_LOST_KHR
267 | vk::Result::ERROR_INITIALIZATION_FAILED => crate::SurfaceError::Lost,
268 vk::Result::ERROR_NATIVE_WINDOW_IN_USE_KHR => {
269 crate::SurfaceError::Other("Native window is in use")
270 }
271 // We don't use VK_EXT_image_compression_control
272 // VK_ERROR_COMPRESSION_EXHAUSTED_EXT
273 other => map_host_device_oom_and_lost_err(other).into(),
274 });
275 }
276 };
277
278 let images = unsafe { functor.get_swapchain_images(raw) }
279 .map_err(crate::vulkan::map_host_device_oom_err)?;
280
281 // This fence is only used to throttle FIFO acquisition on Windows. It is very important to
282 // avoid bad frame pacing when the Vulkan driver is using a DXGI swapchain. See
283 // https://github.com/gfx-rs/wgpu/issues/8310 and
284 // https://github.com/gfx-rs/wgpu/issues/8354 for more details. In other present modes it
285 // only adds acquire latency, see https://github.com/gfx-rs/wgpu/issues/9559.
286 let fence = if cfg!(target_os = "windows")
287 && matches!(
288 config.present_mode,
289 wgt::PresentMode::Fifo | wgt::PresentMode::FifoRelaxed
290 ) {
291 let raw = unsafe {
292 device
293 .shared
294 .raw
295 .create_fence(&vk::FenceCreateInfo::default(), None)
296 .map_err(crate::vulkan::map_host_device_oom_err)?
297 };
298 Some(raw)
299 } else {
300 None
301 };
302
303 // NOTE: It's important that we define the same number of acquire/present semaphores
304 // as we will need to index into them with the image index.
305 let acquire_semaphores = (0..images.len())
306 .map(|i| {
307 SwapchainAcquireSemaphore::new(&device.shared, i)
308 .map(Mutex::new)
309 .map(Arc::new)
310 })
311 .collect::<Result<Vec<_>, _>>()?;
312
313 let present_semaphores = (0..images.len())
314 .map(|i| Arc::new(Mutex::new(SwapchainPresentSemaphores::new(i))))
315 .collect::<Vec<_>>();
316
317 Ok(Box::new(NativeSwapchain {
318 raw,
319 functor,
320 device: Arc::clone(&device.shared),
321 images,
322 fence,
323 config: config.clone(),
324 acquire_semaphores,
325 next_acquire_index: 0,
326 present_semaphores,
327 next_present_time: None,
328 next_present_chain: None,
329 }))
330 }
331
332 #[cfg(windows)]
333 fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> {
334 self.hdr_source.as_ref()?.display_hdr_info()
335 }
336
337 fn as_any(&self) -> &dyn Any {
338 self
339 }
340}
341
342pub(crate) struct NativeSwapchain {
343 raw: vk::SwapchainKHR,
344 functor: khr::swapchain::Device,
345 device: Arc<DeviceShared>,
346 images: Vec<vk::Image>,
347 /// Fence used to wait on the acquired image.
348 fence: Option<vk::Fence>,
349 config: crate::SurfaceConfiguration,
350
351 /// Semaphores used between image acquisition and the first submission
352 /// that uses that image. This is indexed using [`next_acquire_index`].
353 ///
354 /// Because we need to provide this to [`vkAcquireNextImageKHR`], we haven't
355 /// received the swapchain image index for the frame yet, so we cannot use
356 /// that to index it.
357 ///
358 /// Before we pass this to [`vkAcquireNextImageKHR`], we ensure that we wait on
359 /// the submission indicated by [`previously_used_submission_index`]. This ensures
360 /// the semaphore is no longer in use before we use it.
361 ///
362 /// [`next_acquire_index`]: NativeSwapchain::next_acquire_index
363 /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR
364 /// [`previously_used_submission_index`]: SwapchainAcquireSemaphore::previously_used_submission_index
365 acquire_semaphores: Vec<Arc<Mutex<SwapchainAcquireSemaphore>>>,
366 /// The index of the next acquire semaphore to use.
367 ///
368 /// This is incremented each time we acquire a new image, and wraps around
369 /// to 0 when it reaches the end of [`acquire_semaphores`].
370 ///
371 /// [`acquire_semaphores`]: NativeSwapchain::acquire_semaphores
372 next_acquire_index: usize,
373
374 /// Semaphore sets used between all submissions that write to an image and
375 /// the presentation of that image.
376 ///
377 /// This is indexed by the swapchain image index returned by
378 /// [`vkAcquireNextImageKHR`].
379 ///
380 /// We know it is safe to use these semaphores because use them
381 /// _after_ the acquire semaphore. Because the acquire semaphore
382 /// has been signaled, the previous presentation using that image
383 /// is known-finished, so this semaphore is no longer in use.
384 ///
385 /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR
386 present_semaphores: Vec<Arc<Mutex<SwapchainPresentSemaphores>>>,
387
388 /// The present timing information which will be set in the next call to [`present()`](crate::Queue::present()).
389 ///
390 /// # Safety
391 ///
392 /// This must only be set if the VK_GOOGLE_display_timing extension is enabled.
393 next_present_time: Option<vk::PresentTimeGOOGLE>,
394
395 /// A caller-provided `pNext` chain to attach to the [`vk::PresentInfoKHR`] of the next
396 /// call to [`present()`](crate::Queue::present()).
397 ///
398 /// Set only through
399 /// [`Surface::set_next_present_chain()`](crate::vulkan::Surface::set_next_present_chain).
400 next_present_chain: Option<PnextChain>,
401}
402
403impl Drop for NativeSwapchain {
404 fn drop(&mut self) {
405 unsafe {
406 self.functor.destroy_swapchain(self.raw, None);
407 }
408 }
409}
410
411/// Destroy the swapchain semaphores that are no longer referenced by a live
412/// surface texture. A still-referenced semaphore is skipped, as the texture
413/// may still submit work using it.
414///
415/// The vectors are drained.
416fn destroy_swapchain_semaphores(
417 acquire_semaphores: &mut Vec<Arc<Mutex<SwapchainAcquireSemaphore>>>,
418 present_semaphores: &mut Vec<Arc<Mutex<SwapchainPresentSemaphores>>>,
419 device: &crate::vulkan::Device,
420) {
421 for semaphore in acquire_semaphores.drain(..) {
422 if let Some(mutex_removed) = Arc::into_inner(semaphore) {
423 let semaphore_removed = mutex_removed.into_inner();
424 unsafe { semaphore_removed.destroy(&device.shared.raw) };
425 }
426 }
427
428 for semaphore in present_semaphores.drain(..) {
429 if let Some(mutex_removed) = Arc::into_inner(semaphore) {
430 let semaphore_removed = mutex_removed.into_inner();
431 unsafe { semaphore_removed.destroy(&device.shared.raw) };
432 }
433 }
434}
435
436impl Swapchain for NativeSwapchain {
437 unsafe fn release_resources(&mut self, device: &crate::vulkan::Device) {
438 profiling::scope!("Swapchain::release_resources");
439 {
440 profiling::scope!("vkDeviceWaitIdle");
441 // We need to also wait until all presentation work is done. Because there is no way to portably wait until
442 // the presentation work is done, we are forced to wait until the device is idle.
443 let _ = unsafe {
444 device
445 .shared
446 .raw
447 .device_wait_idle()
448 .map_err(map_host_device_oom_and_lost_err)
449 };
450 };
451
452 if let Some(fence) = self.fence {
453 unsafe { device.shared.raw.destroy_fence(fence, None) }
454 }
455
456 destroy_swapchain_semaphores(
457 &mut self.acquire_semaphores,
458 &mut self.present_semaphores,
459 device,
460 );
461 }
462
463 unsafe fn acquire(
464 &mut self,
465 timeout: Option<core::time::Duration>,
466 fence: &crate::vulkan::Fence,
467 ) -> Result<crate::AcquiredSurfaceTexture<crate::api::Vulkan>, crate::SurfaceError> {
468 let mut timeout_ns = match timeout {
469 Some(duration) => duration.as_nanos() as u64,
470 None => u64::MAX,
471 };
472
473 // AcquireNextImageKHR on Android (prior to Android 11) doesn't support timeouts
474 // and will also log verbose warnings if tying to use a timeout.
475 //
476 // Android 10 implementation for reference:
477 // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-10.0.0_r13/vulkan/libvulkan/swapchain.cpp#1426
478 // Android 11 implementation for reference:
479 // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-11.0.0_r45/vulkan/libvulkan/swapchain.cpp#1438
480 //
481 // Android 11 corresponds to an SDK_INT/ro.build.version.sdk of 30
482 if cfg!(target_os = "android") && self.device.instance.android_sdk_version < 30 {
483 timeout_ns = u64::MAX;
484 }
485
486 let acquire_semaphore_arc = self.get_acquire_semaphore();
487 // Nothing should be using this, so we don't block, but panic if we fail to lock.
488 let acquire_semaphore_guard = acquire_semaphore_arc
489 .try_lock()
490 .expect("Failed to lock a SwapchainSemaphores.");
491
492 // Wait for all commands writing to the previously acquired image to
493 // complete.
494 //
495 // Almost all the steps in the usual acquire-draw-present flow are
496 // asynchronous: they get something started on the presentation engine
497 // or the GPU, but on the CPU, control returns immediately. Without some
498 // sort of intervention, the CPU could crank out frames much faster than
499 // the presentation engine can display them.
500 //
501 // This is the intervention: if any submissions drew on this image, and
502 // thus waited for `locked_swapchain_semaphores.acquire`, wait for all
503 // of them to finish, thus ensuring that it's okay to pass `acquire` to
504 // `vkAcquireNextImageKHR` again.
505 let completed = self.device.wait_for_fence(
506 fence,
507 acquire_semaphore_guard.previously_used_submission_index,
508 timeout_ns,
509 )?;
510 if !completed {
511 return Err(crate::SurfaceError::Timeout);
512 }
513
514 let acquire_fence = self.fence.unwrap_or_else(vk::Fence::null);
515
516 // will block if no image is available
517 let (index, suboptimal) = match unsafe {
518 profiling::scope!("vkAcquireNextImageKHR");
519 self.functor.acquire_next_image(
520 self.raw,
521 timeout_ns,
522 acquire_semaphore_guard.acquire,
523 acquire_fence,
524 )
525 } {
526 // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android.
527 // See the comment in `Queue::present`.
528 #[cfg(target_os = "android")]
529 Ok((index, _)) => (index, false),
530 #[cfg(not(target_os = "android"))]
531 Ok(pair) => pair,
532 Err(error) => {
533 return match error {
534 vk::Result::TIMEOUT => Err(crate::SurfaceError::Timeout),
535 vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => {
536 Err(crate::SurfaceError::Outdated)
537 }
538 vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost),
539 // We don't use VK_EXT_full_screen_exclusive
540 // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT
541 other => Err(map_host_device_oom_and_lost_err(other).into()),
542 };
543 }
544 };
545
546 if let Some(fence) = self.fence {
547 unsafe {
548 // The `wait_all` argument must be `true` to avoid crash on some Android devices. See https://github.com/gfx-rs/wgpu/pull/8769
549 self.device
550 .raw
551 .wait_for_fences(&[fence], true, timeout_ns)
552 .map_err(map_host_device_oom_and_lost_err)?;
553
554 self.device
555 .raw
556 .reset_fences(&[fence])
557 .map_err(map_host_device_oom_and_lost_err)?;
558 }
559 }
560
561 drop(acquire_semaphore_guard);
562 // We only advance the surface semaphores if we successfully acquired an image, otherwise
563 // we should try to re-acquire using the same semaphores.
564 self.advance_acquire_semaphore();
565
566 let present_semaphore_arc = self.get_present_semaphores(index);
567
568 // special case for Intel Vulkan returning bizarre values (ugh)
569 if self.device.vendor_id == crate::auxil::db::intel::VENDOR && index > 0x100 {
570 return Err(crate::SurfaceError::Outdated);
571 }
572
573 let identity = self.device.texture_identity_factory.next();
574
575 let texture = crate::vulkan::SurfaceTexture {
576 index,
577 texture: crate::vulkan::Texture {
578 raw: self.images[index as usize],
579 drop_guard: None,
580 memory: crate::vulkan::TextureMemory::External,
581 format: self.config.format,
582 copy_size: crate::CopyExtent {
583 width: self.config.extent.width,
584 height: self.config.extent.height,
585 depth: 1,
586 },
587 identity,
588 },
589 metadata: Box::new(NativeSurfaceTextureMetadata {
590 acquire_semaphores: acquire_semaphore_arc,
591 present_semaphores: present_semaphore_arc,
592 }),
593 };
594 Ok(crate::AcquiredSurfaceTexture {
595 texture,
596 suboptimal,
597 })
598 }
599
600 unsafe fn discard_texture(
601 &mut self,
602 _texture: crate::vulkan::SurfaceTexture,
603 ) -> Result<(), crate::SurfaceError> {
604 // TODO: Current implementation no-ops
605 Ok(())
606 }
607
608 unsafe fn present(
609 &mut self,
610 queue: &crate::vulkan::Queue,
611 texture: crate::vulkan::SurfaceTexture,
612 damage_rects: &[wgt::Rect<u32>],
613 ) -> Result<(), crate::SurfaceError> {
614 let metadata = texture
615 .metadata
616 .as_any()
617 .downcast_ref::<NativeSurfaceTextureMetadata>()
618 .unwrap();
619 let mut acquire_semaphore = metadata.acquire_semaphores.lock();
620 let mut present_semaphores = metadata.present_semaphores.lock();
621
622 let wait_semaphores = present_semaphores.get_present_wait_semaphores();
623
624 // Reset the acquire and present semaphores internal state
625 // to be ready for the next frame.
626 //
627 // We do this before the actual call to present to ensure that
628 // even if this method errors and early outs, we have reset
629 // the state for next frame.
630 acquire_semaphore.end_semaphore_usage();
631 present_semaphores.end_semaphore_usage();
632
633 drop(acquire_semaphore);
634
635 let swapchains = [self.raw];
636 let image_indices = [texture.index];
637 let vk_info = vk::PresentInfoKHR::default()
638 .swapchains(&swapchains)
639 .image_indices(&image_indices)
640 .wait_semaphores(&wait_semaphores);
641
642 let mut display_timing;
643 let present_times;
644 let vk_info = if let Some(present_time) = self.next_present_time.take() {
645 debug_assert!(
646 self.device
647 .enabled_extensions
648 .contains(&google::display_timing::NAME),
649 "`next_present_time` should only be set if VK_GOOGLE_display_timing is enabled"
650 );
651 present_times = [present_time];
652 display_timing = vk::PresentTimesInfoGOOGLE::default().times(&present_times);
653 // SAFETY: We know that VK_GOOGLE_display_timing is present because of the safety contract on `next_present_time`.
654 vk_info.push_next(&mut display_timing)
655 } else {
656 vk_info
657 };
658
659 let rects: Vec<vk::RectLayerKHR>;
660 let present_region;
661 let mut present_regions;
662 let mut vk_info =
663 if self.device.private_caps.incremental_present && !damage_rects.is_empty() {
664 rects = conv::map_damage_rects(damage_rects);
665 present_region = vk::PresentRegionKHR::default().rectangles(&rects);
666 present_regions = vk::PresentRegionsKHR::default()
667 .regions(core::slice::from_ref(&present_region));
668 vk_info.push_next(&mut present_regions)
669 } else {
670 vk_info
671 };
672
673 if let Some(chain) = self.next_present_chain.take() {
674 // SAFETY: The contract on `Surface::set_next_present_chain()` keeps the chain
675 // valid and unaliased until this present completes.
676 vk_info.p_next = unsafe { chain.splice_into(vk_info.p_next) };
677 }
678
679 let suboptimal = {
680 profiling::scope!("vkQueuePresentKHR");
681 unsafe { self.functor.queue_present(queue.raw, &vk_info) }.map_err(|error| {
682 match error {
683 vk::Result::ERROR_OUT_OF_DATE_KHR => crate::SurfaceError::Outdated,
684 vk::Result::ERROR_SURFACE_LOST_KHR => crate::SurfaceError::Lost,
685 // We don't use VK_EXT_full_screen_exclusive
686 // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT
687 _ => map_host_device_oom_and_lost_err(error).into(),
688 }
689 })?
690 };
691 if suboptimal {
692 // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android.
693 // On Android 10+, libvulkan's `vkQueuePresentKHR` implementation returns `VK_SUBOPTIMAL_KHR` if not doing pre-rotation
694 // (i.e `VkSwapchainCreateInfoKHR::preTransform` not being equal to the current device orientation).
695 // This is always the case when the device orientation is anything other than the identity one, as we unconditionally use `VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR`.
696 #[cfg(not(target_os = "android"))]
697 log::debug!("Suboptimal present of frame {}", texture.index);
698 }
699 Ok(())
700 }
701
702 fn as_any(&self) -> &dyn Any {
703 self
704 }
705
706 fn as_any_mut(&mut self) -> &mut dyn Any {
707 self
708 }
709}
710
711impl NativeSwapchain {
712 pub(crate) fn as_raw(&self) -> vk::SwapchainKHR {
713 self.raw
714 }
715
716 pub fn set_next_present_time(&mut self, present_timing: vk::PresentTimeGOOGLE) {
717 if self
718 .device
719 .enabled_extensions
720 .contains(&google::display_timing::NAME)
721 {
722 self.next_present_time = Some(present_timing);
723 } else {
724 panic!(
725 "Tried to set display timing properties without the VK_GOOGLE_display_timing extension enabled."
726 );
727 }
728 }
729
730 /// # Safety
731 ///
732 /// See [`Surface::set_next_present_chain()`](crate::vulkan::Surface::set_next_present_chain).
733 pub unsafe fn set_next_present_chain(&mut self, chain: *mut core::ffi::c_void) {
734 self.next_present_chain = Some(PnextChain::new(chain));
735 }
736
737 /// Mark the current frame finished, advancing to the next acquire semaphore.
738 fn advance_acquire_semaphore(&mut self) {
739 let semaphore_count = self.acquire_semaphores.len();
740 self.next_acquire_index = (self.next_acquire_index + 1) % semaphore_count;
741 }
742
743 /// Get the next acquire semaphore that should be used with this swapchain.
744 fn get_acquire_semaphore(&self) -> Arc<Mutex<SwapchainAcquireSemaphore>> {
745 self.acquire_semaphores[self.next_acquire_index].clone()
746 }
747
748 /// Get the set of present semaphores that should be used with the given image index.
749 fn get_present_semaphores(&self, index: u32) -> Arc<Mutex<SwapchainPresentSemaphores>> {
750 self.present_semaphores[index as usize].clone()
751 }
752}
753
754/// Semaphore used to acquire a swapchain image.
755#[derive(Debug)]
756struct SwapchainAcquireSemaphore {
757 /// A semaphore that is signaled when this image is safe for us to modify.
758 ///
759 /// When [`vkAcquireNextImageKHR`] returns the index of the next swapchain
760 /// image that we should use, that image may actually still be in use by the
761 /// presentation engine, and is not yet safe to modify. However, that
762 /// function does accept a semaphore that it will signal when the image is
763 /// indeed safe to begin messing with.
764 ///
765 /// This semaphore is:
766 ///
767 /// - waited for by the first queue submission to operate on this image
768 /// since it was acquired, and
769 ///
770 /// - signaled by [`vkAcquireNextImageKHR`] when the acquired image is ready
771 /// for us to use.
772 ///
773 /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR
774 acquire: vk::Semaphore,
775
776 /// True if the next command submission operating on this image should wait
777 /// for [`acquire`].
778 ///
779 /// We must wait for `acquire` before drawing to this swapchain image, but
780 /// because `wgpu-hal` queue submissions are always strongly ordered, only
781 /// the first submission that works with a swapchain image actually needs to
782 /// wait. We set this flag when this image is acquired, and clear it the
783 /// first time it's passed to [`Queue::submit`] as a surface texture.
784 ///
785 /// Additionally, semaphores can only be waited on once, so we need to ensure
786 /// that we only actually pass this semaphore to the first submission that
787 /// uses that image.
788 ///
789 /// [`acquire`]: SwapchainAcquireSemaphore::acquire
790 /// [`Queue::submit`]: crate::Queue::submit
791 should_wait_for_acquire: bool,
792
793 /// The fence value of the last command submission that wrote to this image.
794 ///
795 /// The next time we try to acquire this image, we'll block until
796 /// this submission finishes, proving that [`acquire`] is ready to
797 /// pass to `vkAcquireNextImageKHR` again.
798 ///
799 /// [`acquire`]: SwapchainAcquireSemaphore::acquire
800 previously_used_submission_index: crate::FenceValue,
801}
802
803impl SwapchainAcquireSemaphore {
804 fn new(device: &DeviceShared, index: usize) -> Result<Self, crate::DeviceError> {
805 Ok(Self {
806 acquire: device
807 .new_binary_semaphore(&format!("SwapchainImageSemaphore: Index {index} acquire"))?,
808 should_wait_for_acquire: true,
809 previously_used_submission_index: 0,
810 })
811 }
812
813 /// Sets the fence value which the next acquire will wait for. This prevents
814 /// the semaphore from being used while the previous submission is still in flight.
815 fn set_used_fence_value(&mut self, value: crate::FenceValue) {
816 self.previously_used_submission_index = value;
817 }
818
819 /// Return the semaphore that commands drawing to this image should wait for, if any.
820 ///
821 /// This only returns `Some` once per acquisition; see
822 /// [`SwapchainAcquireSemaphore::should_wait_for_acquire`] for details.
823 fn get_acquire_wait_semaphore(&mut self) -> Option<vk::Semaphore> {
824 if self.should_wait_for_acquire {
825 self.should_wait_for_acquire = false;
826 Some(self.acquire)
827 } else {
828 None
829 }
830 }
831
832 /// Indicates the cpu-side usage of this semaphore has finished for the frame,
833 /// so reset internal state to be ready for the next frame.
834 fn end_semaphore_usage(&mut self) {
835 // Reset the acquire semaphore, so that the next time we acquire this
836 // image, we can wait for it again.
837 self.should_wait_for_acquire = true;
838 }
839
840 unsafe fn destroy(&self, device: &ash::Device) {
841 unsafe {
842 device.destroy_semaphore(self.acquire, None);
843 }
844 }
845}
846
847#[derive(Debug)]
848struct SwapchainPresentSemaphores {
849 /// A pool of semaphores for ordering presentation after drawing.
850 ///
851 /// The first [`present_index`] semaphores in this vector are:
852 ///
853 /// - all waited on by the call to [`vkQueuePresentKHR`] that presents this
854 /// image, and
855 ///
856 /// - each signaled by some [`vkQueueSubmit`] queue submission that draws to
857 /// this image, when the submission finishes execution.
858 ///
859 /// This vector accumulates one semaphore per submission that writes to this
860 /// image. This is awkward, but hard to avoid: [`vkQueuePresentKHR`]
861 /// requires a semaphore to order it with respect to drawing commands, and
862 /// we can't attach new completion semaphores to a command submission after
863 /// it's been submitted. This means that, at submission time, we must create
864 /// the semaphore we might need if the caller's next action is to enqueue a
865 /// presentation of this image.
866 ///
867 /// An alternative strategy would be for presentation to enqueue an empty
868 /// submit, ordered relative to other submits in the usual way, and
869 /// signaling a single presentation semaphore. But we suspect that submits
870 /// are usually expensive enough, and semaphores usually cheap enough, that
871 /// performance-sensitive users will avoid making many submits, so that the
872 /// cost of accumulated semaphores will usually be less than the cost of an
873 /// additional submit.
874 ///
875 /// Only the first [`present_index`] semaphores in the vector are actually
876 /// going to be signalled by submitted commands, and need to be waited for
877 /// by the next present call. Any semaphores beyond that index were created
878 /// for prior presents and are simply being retained for recycling.
879 ///
880 /// [`present_index`]: SwapchainPresentSemaphores::present_index
881 /// [`vkQueuePresentKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueuePresentKHR
882 /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit
883 present: Vec<vk::Semaphore>,
884
885 /// The number of semaphores in [`present`] to be signalled for this submission.
886 ///
887 /// [`present`]: SwapchainPresentSemaphores::present
888 present_index: usize,
889
890 /// Which image this semaphore set is used for.
891 frame_index: usize,
892}
893
894impl SwapchainPresentSemaphores {
895 pub fn new(frame_index: usize) -> Self {
896 Self {
897 present: Vec::new(),
898 present_index: 0,
899 frame_index,
900 }
901 }
902
903 /// Return the semaphore that the next submission that writes to this image should
904 /// signal when it's done.
905 ///
906 /// See [`SwapchainPresentSemaphores::present`] for details.
907 fn get_submit_signal_semaphore(
908 &mut self,
909 device: &DeviceShared,
910 ) -> Result<vk::Semaphore, crate::DeviceError> {
911 // Try to recycle a semaphore we created for a previous presentation.
912 let sem = match self.present.get(self.present_index) {
913 Some(sem) => *sem,
914 None => {
915 let sem = device.new_binary_semaphore(&format!(
916 "SwapchainImageSemaphore: Image {} present semaphore {}",
917 self.frame_index, self.present_index
918 ))?;
919 self.present.push(sem);
920 sem
921 }
922 };
923
924 self.present_index += 1;
925
926 Ok(sem)
927 }
928
929 /// Indicates the cpu-side usage of this semaphore has finished for the frame,
930 /// so reset internal state to be ready for the next frame.
931 fn end_semaphore_usage(&mut self) {
932 // Reset the index to 0, so that the next time we get a semaphore, we
933 // start from the beginning of the list.
934 self.present_index = 0;
935 }
936
937 /// Return the semaphores that a presentation of this image should wait on.
938 ///
939 /// Return a slice of semaphores that the call to [`vkQueueSubmit`] that
940 /// ends this image's acquisition should wait for. See
941 /// [`SwapchainPresentSemaphores::present`] for details.
942 ///
943 /// Reset `self` to be ready for the next acquisition cycle.
944 ///
945 /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit
946 fn get_present_wait_semaphores(&mut self) -> Vec<vk::Semaphore> {
947 self.present[0..self.present_index].to_vec()
948 }
949
950 unsafe fn destroy(&self, device: &ash::Device) {
951 unsafe {
952 for sem in &self.present {
953 device.destroy_semaphore(*sem, None);
954 }
955 }
956 }
957}
958
959#[derive(Debug)]
960struct NativeSurfaceTextureMetadata {
961 acquire_semaphores: Arc<Mutex<SwapchainAcquireSemaphore>>,
962 present_semaphores: Arc<Mutex<SwapchainPresentSemaphores>>,
963}
964
965impl SurfaceTextureMetadata for NativeSurfaceTextureMetadata {
966 fn get_semaphore_guard(&self) -> Box<dyn SwapchainSubmissionSemaphoreGuard + '_> {
967 Box::new(NativeSwapchainSubmissionSemaphoreGuard {
968 acquire_semaphore_guard: self
969 .acquire_semaphores
970 .try_lock()
971 .expect("Failed to lock surface acquire semaphore"),
972 present_semaphores_guard: self
973 .present_semaphores
974 .try_lock()
975 .expect("Failed to lock surface present semaphores"),
976 })
977 }
978
979 fn as_any(&self) -> &dyn Any {
980 self
981 }
982}
983
984struct NativeSwapchainSubmissionSemaphoreGuard<'a> {
985 acquire_semaphore_guard: MutexGuard<'a, SwapchainAcquireSemaphore>,
986 present_semaphores_guard: MutexGuard<'a, SwapchainPresentSemaphores>,
987}
988
989impl<'a> SwapchainSubmissionSemaphoreGuard for NativeSwapchainSubmissionSemaphoreGuard<'a> {
990 fn set_used_fence_value(&mut self, value: u64) {
991 self.acquire_semaphore_guard.set_used_fence_value(value);
992 }
993
994 fn get_acquire_wait_semaphore(&mut self) -> Option<SemaphoreType> {
995 self.acquire_semaphore_guard
996 .get_acquire_wait_semaphore()
997 .map(SemaphoreType::Binary)
998 }
999
1000 fn get_submit_signal_semaphore(
1001 &mut self,
1002 device: &DeviceShared,
1003 ) -> Result<SemaphoreType, crate::DeviceError> {
1004 self.present_semaphores_guard
1005 .get_submit_signal_semaphore(device)
1006 .map(SemaphoreType::Binary)
1007 }
1008}