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