wgpu_hal/vulkan/
instance.rs

1use alloc::{borrow::ToOwned as _, boxed::Box, ffi::CString, string::String, sync::Arc, vec::Vec};
2use core::{
3    ffi::{c_void, CStr},
4    marker::PhantomData,
5    mem::ManuallyDrop,
6    slice,
7    str::FromStr,
8};
9use std::thread;
10
11use arrayvec::ArrayVec;
12use ash::{ext, khr, vk};
13use parking_lot::RwLock;
14
15unsafe extern "system" fn debug_utils_messenger_callback(
16    message_severity: vk::DebugUtilsMessageSeverityFlagsEXT,
17    message_type: vk::DebugUtilsMessageTypeFlagsEXT,
18    callback_data_ptr: *const vk::DebugUtilsMessengerCallbackDataEXT,
19    user_data: *mut c_void,
20) -> vk::Bool32 {
21    use alloc::borrow::Cow;
22
23    if thread::panicking() {
24        return vk::FALSE;
25    }
26
27    let cd = unsafe { &*callback_data_ptr };
28    let user_data = unsafe { &*user_data.cast::<super::DebugUtilsMessengerUserData>() };
29
30    const VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912: i32 = 0x56146426;
31    if cd.message_id_number == VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912 {
32        // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/5671
33        // Versions 1.3.240 through 1.3.250 return a spurious error here if
34        // the debug range start and end appear in different command buffers.
35        if let Some(layer_properties) = user_data.validation_layer_properties.as_ref() {
36            if layer_properties.layer_description.as_ref() == c"Khronos Validation Layer"
37                && layer_properties.layer_spec_version >= vk::make_api_version(0, 1, 3, 240)
38                && layer_properties.layer_spec_version <= vk::make_api_version(0, 1, 3, 250)
39            {
40                return vk::FALSE;
41            }
42        }
43    }
44
45    // Silence Vulkan Validation error "VUID-VkSwapchainCreateInfoKHR-pNext-07781"
46    // This happens when a surface is configured with a size outside the allowed extent.
47    // It's a false positive due to the inherent racy-ness of surface resizing.
48    const VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781: i32 = 0x4c8929c1;
49    if cd.message_id_number == VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781 {
50        return vk::FALSE;
51    }
52
53    // Silence Vulkan Validation error "VUID-VkRenderPassBeginInfo-framebuffer-04627"
54    // if the OBS layer is enabled. This is a bug in the OBS layer. As the OBS layer
55    // does not have a version number they increment, there is no way to qualify the
56    // suppression of the error to a specific version of the OBS layer.
57    //
58    // See https://github.com/obsproject/obs-studio/issues/9353
59    const VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627: i32 = 0x45125641;
60    if cd.message_id_number == VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627
61        && user_data.has_obs_layer
62    {
63        return vk::FALSE;
64    }
65
66    // Silence Vulkan Validation error "VUID-vkCmdCopyImageToBuffer-pRegions-00184".
67    // While we aren't sure yet, we suspect this is probably a VVL issue.
68    // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/9276
69    const VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184: i32 = 0x45ef177c;
70    if cd.message_id_number == VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184 {
71        return vk::FALSE;
72    }
73
74    // Silence Vulkan Validation error "VUID-StandaloneSpirv-None-10684".
75    //
76    // This is a bug. To prevent massive noise in the tests, lets suppress it for now.
77    // https://github.com/gfx-rs/wgpu/issues/7696
78    const VUID_STANDALONESPIRV_NONE_10684: i32 = 0xb210f7c2_u32 as i32;
79    if cd.message_id_number == VUID_STANDALONESPIRV_NONE_10684 {
80        return vk::FALSE;
81    }
82
83    let level = match message_severity {
84        // We intentionally suppress info messages down to debug
85        // so that users are not innundated with info messages from the runtime.
86        vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => log::Level::Trace,
87        vk::DebugUtilsMessageSeverityFlagsEXT::INFO => log::Level::Debug,
88        vk::DebugUtilsMessageSeverityFlagsEXT::WARNING => log::Level::Warn,
89        vk::DebugUtilsMessageSeverityFlagsEXT::ERROR => log::Level::Error,
90        _ => log::Level::Warn,
91    };
92
93    let message_id_name =
94        unsafe { cd.message_id_name_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy);
95    let message = unsafe { cd.message_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy);
96
97    let _ = std::panic::catch_unwind(|| {
98        log::log!(
99            level,
100            "{:?} [{} (0x{:x})]\n\t{}",
101            message_type,
102            message_id_name,
103            cd.message_id_number,
104            message,
105        );
106    });
107
108    if cd.queue_label_count != 0 {
109        let labels =
110            unsafe { slice::from_raw_parts(cd.p_queue_labels, cd.queue_label_count as usize) };
111        let names = labels
112            .iter()
113            .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy))
114            .collect::<Vec<_>>();
115
116        let _ = std::panic::catch_unwind(|| {
117            log::log!(level, "\tqueues: {}", names.join(", "));
118        });
119    }
120
121    if cd.cmd_buf_label_count != 0 {
122        let labels =
123            unsafe { slice::from_raw_parts(cd.p_cmd_buf_labels, cd.cmd_buf_label_count as usize) };
124        let names = labels
125            .iter()
126            .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy))
127            .collect::<Vec<_>>();
128
129        let _ = std::panic::catch_unwind(|| {
130            log::log!(level, "\tcommand buffers: {}", names.join(", "));
131        });
132    }
133
134    if cd.object_count != 0 {
135        let labels = unsafe { slice::from_raw_parts(cd.p_objects, cd.object_count as usize) };
136        //TODO: use color fields of `vk::DebugUtilsLabelExt`?
137        let names = labels
138            .iter()
139            .map(|obj_info| {
140                let name = unsafe { obj_info.object_name_as_c_str() }
141                    .map_or(Cow::Borrowed("?"), CStr::to_string_lossy);
142
143                format!(
144                    "(type: {:?}, hndl: 0x{:x}, name: {})",
145                    obj_info.object_type, obj_info.object_handle, name
146                )
147            })
148            .collect::<Vec<_>>();
149        let _ = std::panic::catch_unwind(|| {
150            log::log!(level, "\tobjects: {}", names.join(", "));
151        });
152    }
153
154    #[cfg(feature = "validation_canary")]
155    if cfg!(debug_assertions) && level == log::Level::Error {
156        use alloc::string::ToString as _;
157
158        // Set canary and continue
159        crate::VALIDATION_CANARY.add(message.to_string());
160    }
161
162    vk::FALSE
163}
164
165impl super::DebugUtilsCreateInfo {
166    fn to_vk_create_info(&self) -> vk::DebugUtilsMessengerCreateInfoEXT<'_> {
167        let user_data_ptr: *const super::DebugUtilsMessengerUserData = &*self.callback_data;
168        vk::DebugUtilsMessengerCreateInfoEXT::default()
169            .message_severity(self.severity)
170            .message_type(self.message_type)
171            .user_data(user_data_ptr as *mut _)
172            .pfn_user_callback(Some(debug_utils_messenger_callback))
173    }
174}
175
176impl super::InstanceShared {
177    pub fn entry(&self) -> &ash::Entry {
178        &self.entry
179    }
180
181    pub fn raw_instance(&self) -> &ash::Instance {
182        &self.raw
183    }
184
185    pub fn instance_api_version(&self) -> u32 {
186        self.instance_api_version
187    }
188
189    pub fn extensions(&self) -> &[&'static CStr] {
190        &self.extensions[..]
191    }
192}
193
194impl super::Instance {
195    pub fn shared_instance(&self) -> &super::InstanceShared {
196        &self.shared
197    }
198
199    fn enumerate_instance_extension_properties(
200        entry: &ash::Entry,
201        layer_name: Option<&CStr>,
202    ) -> Result<Vec<vk::ExtensionProperties>, crate::InstanceError> {
203        let instance_extensions = {
204            profiling::scope!("vkEnumerateInstanceExtensionProperties");
205            unsafe { entry.enumerate_instance_extension_properties(layer_name) }
206        };
207        instance_extensions.map_err(|e| {
208            crate::InstanceError::with_source(
209                String::from("enumerate_instance_extension_properties() failed"),
210                e,
211            )
212        })
213    }
214
215    /// Return the instance extension names wgpu would like to enable.
216    ///
217    /// Return a vector of the names of instance extensions actually available
218    /// on `entry` that wgpu would like to enable.
219    ///
220    /// The `instance_api_version` argument should be the instance's Vulkan API
221    /// version, as obtained from `vkEnumerateInstanceVersion`. This is the same
222    /// space of values as the `VK_API_VERSION` constants.
223    ///
224    /// Note that wgpu can function without many of these extensions (for
225    /// example, `VK_KHR_wayland_surface` is certainly not going to be available
226    /// everywhere), but if one of these extensions is available at all, wgpu
227    /// assumes that it has been enabled.
228    pub fn desired_extensions(
229        entry: &ash::Entry,
230        _instance_api_version: u32,
231        flags: wgt::InstanceFlags,
232    ) -> Result<Vec<&'static CStr>, crate::InstanceError> {
233        let instance_extensions = Self::enumerate_instance_extension_properties(entry, None)?;
234
235        // Check our extensions against the available extensions
236        let mut extensions: Vec<&'static CStr> = Vec::new();
237
238        // VK_KHR_surface
239        extensions.push(khr::surface::NAME);
240
241        // Platform-specific WSI extensions
242        if cfg!(all(
243            unix,
244            not(target_os = "android"),
245            not(target_os = "macos")
246        )) {
247            // VK_KHR_xlib_surface
248            extensions.push(khr::xlib_surface::NAME);
249            // VK_KHR_xcb_surface
250            extensions.push(khr::xcb_surface::NAME);
251            // VK_KHR_wayland_surface
252            extensions.push(khr::wayland_surface::NAME);
253        }
254        if cfg!(target_os = "android") {
255            // VK_KHR_android_surface
256            extensions.push(khr::android_surface::NAME);
257        }
258        if cfg!(target_os = "windows") {
259            // VK_KHR_win32_surface
260            extensions.push(khr::win32_surface::NAME);
261        }
262        if cfg!(target_os = "macos") {
263            // VK_EXT_metal_surface
264            extensions.push(ext::metal_surface::NAME);
265            extensions.push(khr::portability_enumeration::NAME);
266        }
267        if cfg!(all(
268            unix,
269            not(target_vendor = "apple"),
270            not(target_family = "wasm")
271        )) {
272            // VK_EXT_acquire_drm_display -> VK_EXT_direct_mode_display -> VK_KHR_display
273            extensions.push(ext::acquire_drm_display::NAME);
274            extensions.push(ext::direct_mode_display::NAME);
275            extensions.push(khr::display::NAME);
276            extensions.push(khr::get_physical_device_properties2::NAME);
277            extensions.push(khr::get_display_properties2::NAME);
278        }
279
280        if flags.contains(wgt::InstanceFlags::DEBUG) {
281            // VK_EXT_debug_utils
282            extensions.push(ext::debug_utils::NAME);
283        }
284
285        // VK_EXT_swapchain_colorspace
286        // Provides wide color gamut
287        extensions.push(ext::swapchain_colorspace::NAME);
288
289        // VK_KHR_get_physical_device_properties2
290        // Even though the extension was promoted to Vulkan 1.1, we still require the extension
291        // so that we don't have to conditionally use the functions provided by the 1.1 instance
292        extensions.push(khr::get_physical_device_properties2::NAME);
293
294        // Only keep available extensions.
295        extensions.retain(|&ext| {
296            if instance_extensions
297                .iter()
298                .any(|inst_ext| inst_ext.extension_name_as_c_str() == Ok(ext))
299            {
300                true
301            } else {
302                log::debug!("Unable to find extension: {}", ext.to_string_lossy());
303                false
304            }
305        });
306        Ok(extensions)
307    }
308
309    /// # Safety
310    ///
311    /// - `raw_instance` must be created from `entry`
312    /// - `raw_instance` must be created respecting `instance_api_version`, `extensions` and `flags`
313    /// - `extensions` must be a superset of `desired_extensions()` and must be created from the
314    ///   same entry, `instance_api_version`` and flags.
315    /// - `android_sdk_version` is ignored and can be `0` for all platforms besides Android
316    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_instance`. If
317    ///   `drop_callback` is [`Some`], `raw_instance` must be valid until the callback is called.
318    ///
319    /// If `debug_utils_user_data` is `Some`, then the validation layer is
320    /// available, so create a [`vk::DebugUtilsMessengerEXT`].
321    #[allow(clippy::too_many_arguments)]
322    pub unsafe fn from_raw(
323        entry: ash::Entry,
324        raw_instance: ash::Instance,
325        instance_api_version: u32,
326        android_sdk_version: u32,
327        debug_utils_create_info: Option<super::DebugUtilsCreateInfo>,
328        extensions: Vec<&'static CStr>,
329        flags: wgt::InstanceFlags,
330        memory_budget_thresholds: wgt::MemoryBudgetThresholds,
331        has_nv_optimus: bool,
332        drop_callback: Option<crate::DropCallback>,
333    ) -> Result<Self, crate::InstanceError> {
334        log::debug!("Instance version: 0x{instance_api_version:x}");
335
336        let debug_utils = if let Some(debug_utils_create_info) = debug_utils_create_info {
337            if extensions.contains(&ext::debug_utils::NAME) {
338                log::debug!("Enabling debug utils");
339
340                let extension = ext::debug_utils::Instance::new(&entry, &raw_instance);
341                let vk_info = debug_utils_create_info.to_vk_create_info();
342                let messenger =
343                    unsafe { extension.create_debug_utils_messenger(&vk_info, None) }.unwrap();
344
345                Some(super::DebugUtils {
346                    extension,
347                    messenger,
348                    callback_data: debug_utils_create_info.callback_data,
349                })
350            } else {
351                log::debug!("Debug utils not enabled: extension not listed");
352                None
353            }
354        } else {
355            log::debug!(
356                "Debug utils not enabled: \
357                        debug_utils_user_data not passed to Instance::from_raw"
358            );
359            None
360        };
361
362        let get_physical_device_properties =
363            if extensions.contains(&khr::get_physical_device_properties2::NAME) {
364                log::debug!("Enabling device properties2");
365                Some(khr::get_physical_device_properties2::Instance::new(
366                    &entry,
367                    &raw_instance,
368                ))
369            } else {
370                None
371            };
372
373        let drop_guard = crate::DropGuard::from_option(drop_callback);
374
375        Ok(Self {
376            shared: Arc::new(super::InstanceShared {
377                raw: raw_instance,
378                extensions,
379                drop_guard,
380                flags,
381                memory_budget_thresholds,
382                debug_utils,
383                get_physical_device_properties,
384                entry,
385                has_nv_optimus,
386                instance_api_version,
387                android_sdk_version,
388            }),
389        })
390    }
391
392    fn create_surface_from_xlib(
393        &self,
394        dpy: *mut vk::Display,
395        window: vk::Window,
396    ) -> Result<super::Surface, crate::InstanceError> {
397        if !self.shared.extensions.contains(&khr::xlib_surface::NAME) {
398            return Err(crate::InstanceError::new(String::from(
399                "Vulkan driver does not support VK_KHR_xlib_surface",
400            )));
401        }
402
403        let surface = {
404            let xlib_loader =
405                khr::xlib_surface::Instance::new(&self.shared.entry, &self.shared.raw);
406            let info = vk::XlibSurfaceCreateInfoKHR::default()
407                .flags(vk::XlibSurfaceCreateFlagsKHR::empty())
408                .window(window)
409                .dpy(dpy);
410
411            unsafe { xlib_loader.create_xlib_surface(&info, None) }
412                .expect("XlibSurface::create_xlib_surface() failed")
413        };
414
415        Ok(self.create_surface_from_vk_surface_khr(surface))
416    }
417
418    fn create_surface_from_xcb(
419        &self,
420        connection: *mut vk::xcb_connection_t,
421        window: vk::xcb_window_t,
422    ) -> Result<super::Surface, crate::InstanceError> {
423        if !self.shared.extensions.contains(&khr::xcb_surface::NAME) {
424            return Err(crate::InstanceError::new(String::from(
425                "Vulkan driver does not support VK_KHR_xcb_surface",
426            )));
427        }
428
429        let surface = {
430            let xcb_loader = khr::xcb_surface::Instance::new(&self.shared.entry, &self.shared.raw);
431            let info = vk::XcbSurfaceCreateInfoKHR::default()
432                .flags(vk::XcbSurfaceCreateFlagsKHR::empty())
433                .window(window)
434                .connection(connection);
435
436            unsafe { xcb_loader.create_xcb_surface(&info, None) }
437                .expect("XcbSurface::create_xcb_surface() failed")
438        };
439
440        Ok(self.create_surface_from_vk_surface_khr(surface))
441    }
442
443    fn create_surface_from_wayland(
444        &self,
445        display: *mut vk::wl_display,
446        surface: *mut vk::wl_surface,
447    ) -> Result<super::Surface, crate::InstanceError> {
448        if !self.shared.extensions.contains(&khr::wayland_surface::NAME) {
449            return Err(crate::InstanceError::new(String::from(
450                "Vulkan driver does not support VK_KHR_wayland_surface",
451            )));
452        }
453
454        let surface = {
455            let w_loader =
456                khr::wayland_surface::Instance::new(&self.shared.entry, &self.shared.raw);
457            let info = vk::WaylandSurfaceCreateInfoKHR::default()
458                .flags(vk::WaylandSurfaceCreateFlagsKHR::empty())
459                .display(display)
460                .surface(surface);
461
462            unsafe { w_loader.create_wayland_surface(&info, None) }.expect("WaylandSurface failed")
463        };
464
465        Ok(self.create_surface_from_vk_surface_khr(surface))
466    }
467
468    fn create_surface_android(
469        &self,
470        window: *mut vk::ANativeWindow,
471    ) -> Result<super::Surface, crate::InstanceError> {
472        if !self.shared.extensions.contains(&khr::android_surface::NAME) {
473            return Err(crate::InstanceError::new(String::from(
474                "Vulkan driver does not support VK_KHR_android_surface",
475            )));
476        }
477
478        let surface = {
479            let a_loader =
480                khr::android_surface::Instance::new(&self.shared.entry, &self.shared.raw);
481            let info = vk::AndroidSurfaceCreateInfoKHR::default()
482                .flags(vk::AndroidSurfaceCreateFlagsKHR::empty())
483                .window(window);
484
485            unsafe { a_loader.create_android_surface(&info, None) }.expect("AndroidSurface failed")
486        };
487
488        Ok(self.create_surface_from_vk_surface_khr(surface))
489    }
490
491    fn create_surface_from_hwnd(
492        &self,
493        hinstance: vk::HINSTANCE,
494        hwnd: vk::HWND,
495    ) -> Result<super::Surface, crate::InstanceError> {
496        if !self.shared.extensions.contains(&khr::win32_surface::NAME) {
497            return Err(crate::InstanceError::new(String::from(
498                "Vulkan driver does not support VK_KHR_win32_surface",
499            )));
500        }
501
502        let surface = {
503            let info = vk::Win32SurfaceCreateInfoKHR::default()
504                .flags(vk::Win32SurfaceCreateFlagsKHR::empty())
505                .hinstance(hinstance)
506                .hwnd(hwnd);
507            let win32_loader =
508                khr::win32_surface::Instance::new(&self.shared.entry, &self.shared.raw);
509            unsafe {
510                win32_loader
511                    .create_win32_surface(&info, None)
512                    .expect("Unable to create Win32 surface")
513            }
514        };
515
516        Ok(self.create_surface_from_vk_surface_khr(surface))
517    }
518
519    #[cfg(target_vendor = "apple")]
520    fn create_surface_from_layer(
521        &self,
522        layer: raw_window_metal::Layer,
523    ) -> Result<super::Surface, crate::InstanceError> {
524        if !self.shared.extensions.contains(&ext::metal_surface::NAME) {
525            return Err(crate::InstanceError::new(String::from(
526                "Vulkan driver does not support VK_EXT_metal_surface",
527            )));
528        }
529
530        // NOTE: The layer is retained by Vulkan's `vkCreateMetalSurfaceEXT`,
531        // so no need to retain it beyond the scope of this function.
532        let surface = {
533            let metal_loader =
534                ext::metal_surface::Instance::new(&self.shared.entry, &self.shared.raw);
535            let vk_info = vk::MetalSurfaceCreateInfoEXT::default()
536                .flags(vk::MetalSurfaceCreateFlagsEXT::empty())
537                .layer(layer.as_ptr().as_ptr());
538
539            unsafe { metal_loader.create_metal_surface(&vk_info, None).unwrap() }
540        };
541
542        Ok(self.create_surface_from_vk_surface_khr(surface))
543    }
544
545    pub(super) fn create_surface_from_vk_surface_khr(
546        &self,
547        surface: vk::SurfaceKHR,
548    ) -> super::Surface {
549        let native_surface =
550            crate::vulkan::swapchain::NativeSurface::from_vk_surface_khr(self, surface);
551
552        super::Surface {
553            inner: ManuallyDrop::new(Box::new(native_surface)),
554            swapchain: RwLock::new(None),
555        }
556    }
557
558    /// `Instance::init` but with a callback.
559    /// If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, otherwise
560    /// it will be overwritten
561    ///
562    /// # Safety:
563    /// Same as `init` but additionally
564    /// - Callback must not remove features.
565    /// - Callback must not change anything to what the instance does not support.
566    pub unsafe fn init_with_callback(
567        desc: &crate::InstanceDescriptor<'_>,
568        callback: Option<Box<super::CreateInstanceCallback>>,
569    ) -> Result<Self, crate::InstanceError> {
570        profiling::scope!("Init Vulkan Backend");
571
572        let entry = unsafe {
573            profiling::scope!("Load vk library");
574            ash::Entry::load()
575        }
576        .map_err(|err| {
577            crate::InstanceError::with_source(String::from("missing Vulkan entry points"), err)
578        })?;
579        let version = {
580            profiling::scope!("vkEnumerateInstanceVersion");
581            unsafe { entry.try_enumerate_instance_version() }
582        };
583        let instance_api_version = match version {
584            // Vulkan 1.1+
585            Ok(Some(version)) => version,
586            Ok(None) => vk::API_VERSION_1_0,
587            Err(err) => {
588                return Err(crate::InstanceError::with_source(
589                    String::from("try_enumerate_instance_version() failed"),
590                    err,
591                ));
592            }
593        };
594
595        let app_name = CString::new(desc.name).unwrap();
596        let app_info = vk::ApplicationInfo::default()
597            .application_name(app_name.as_c_str())
598            .application_version(1)
599            .engine_name(c"wgpu-hal")
600            .engine_version(2)
601            .api_version(
602                // Vulkan 1.0 doesn't like anything but 1.0 passed in here...
603                if instance_api_version < vk::API_VERSION_1_1 {
604                    vk::API_VERSION_1_0
605                } else {
606                    // This is the max Vulkan API version supported by `wgpu-hal`.
607                    //
608                    // If we want to increment this, there are some things that must be done first:
609                    //  - Audit the behavioral differences between the previous and new API versions.
610                    //  - Audit all extensions used by this backend:
611                    //    - If any were promoted in the new API version and the behavior has changed, we must handle the new behavior in addition to the old behavior.
612                    //    - If any were obsoleted in the new API version, we must implement a fallback for the new API version
613                    //    - If any are non-KHR-vendored, we must ensure the new behavior is still correct (since backwards-compatibility is not guaranteed).
614                    vk::API_VERSION_1_3
615                },
616            );
617
618        let mut extensions = Self::desired_extensions(&entry, instance_api_version, desc.flags)?;
619        let mut create_info = vk::InstanceCreateInfo::default();
620
621        if let Some(callback) = callback {
622            callback(super::CreateInstanceCallbackArgs {
623                extensions: &mut extensions,
624                create_info: &mut create_info,
625                entry: &entry,
626                _phantom: PhantomData,
627            });
628        }
629
630        let instance_layers = {
631            profiling::scope!("vkEnumerateInstanceLayerProperties");
632            unsafe { entry.enumerate_instance_layer_properties() }
633        };
634        let instance_layers = instance_layers.map_err(|e| {
635            log::debug!("enumerate_instance_layer_properties: {e:?}");
636            crate::InstanceError::with_source(
637                String::from("enumerate_instance_layer_properties() failed"),
638                e,
639            )
640        })?;
641
642        fn find_layer<'layers>(
643            instance_layers: &'layers [vk::LayerProperties],
644            name: &CStr,
645        ) -> Option<&'layers vk::LayerProperties> {
646            instance_layers
647                .iter()
648                .find(|inst_layer| inst_layer.layer_name_as_c_str() == Ok(name))
649        }
650
651        let validation_layer_name = c"VK_LAYER_KHRONOS_validation";
652        let validation_layer_properties = find_layer(&instance_layers, validation_layer_name);
653
654        // Determine if VK_EXT_validation_features is available, so we can enable
655        // GPU assisted validation and synchronization validation.
656        let validation_features_are_enabled = if validation_layer_properties.is_some() {
657            // Get the all the instance extension properties.
658            let exts =
659                Self::enumerate_instance_extension_properties(&entry, Some(validation_layer_name))?;
660            // Convert all the names of the extensions into an iterator of CStrs.
661            let mut ext_names = exts
662                .iter()
663                .filter_map(|ext| ext.extension_name_as_c_str().ok());
664            // Find the validation features extension.
665            ext_names.any(|ext_name| ext_name == ext::validation_features::NAME)
666        } else {
667            false
668        };
669
670        let should_enable_gpu_based_validation = desc
671            .flags
672            .intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION)
673            && validation_features_are_enabled;
674
675        let has_nv_optimus = find_layer(&instance_layers, c"VK_LAYER_NV_optimus").is_some();
676
677        let has_obs_layer = find_layer(&instance_layers, c"VK_LAYER_OBS_HOOK").is_some();
678
679        let mut layers: Vec<&'static CStr> = Vec::new();
680
681        let has_debug_extension = extensions.contains(&ext::debug_utils::NAME);
682        let mut debug_user_data = has_debug_extension.then(|| {
683            // Put the callback data on the heap, to ensure it will never be
684            // moved.
685            Box::new(super::DebugUtilsMessengerUserData {
686                validation_layer_properties: None,
687                has_obs_layer,
688            })
689        });
690
691        // Request validation layer if asked.
692        if desc.flags.intersects(wgt::InstanceFlags::VALIDATION)
693            || should_enable_gpu_based_validation
694        {
695            if let Some(layer_properties) = validation_layer_properties {
696                layers.push(validation_layer_name);
697
698                if let Some(debug_user_data) = debug_user_data.as_mut() {
699                    debug_user_data.validation_layer_properties =
700                        Some(super::ValidationLayerProperties {
701                            layer_description: layer_properties
702                                .description_as_c_str()
703                                .unwrap()
704                                .to_owned(),
705                            layer_spec_version: layer_properties.spec_version,
706                        });
707                }
708            } else {
709                log::debug!(
710                    "InstanceFlags::VALIDATION requested, but unable to find layer: {}",
711                    validation_layer_name.to_string_lossy()
712                );
713            }
714        }
715        let mut debug_utils = if let Some(callback_data) = debug_user_data {
716            // having ERROR unconditionally because Vk doesn't like empty flags
717            let mut severity = vk::DebugUtilsMessageSeverityFlagsEXT::ERROR;
718            if log::max_level() >= log::LevelFilter::Debug {
719                severity |= vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE;
720            }
721            if log::max_level() >= log::LevelFilter::Info {
722                severity |= vk::DebugUtilsMessageSeverityFlagsEXT::INFO;
723            }
724            if log::max_level() >= log::LevelFilter::Warn {
725                severity |= vk::DebugUtilsMessageSeverityFlagsEXT::WARNING;
726            }
727
728            let message_type = vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
729                | vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION
730                | vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE;
731
732            let create_info = super::DebugUtilsCreateInfo {
733                severity,
734                message_type,
735                callback_data,
736            };
737
738            Some(create_info)
739        } else {
740            None
741        };
742
743        #[cfg(target_os = "android")]
744        let android_sdk_version = {
745            let properties = android_system_properties::AndroidSystemProperties::new();
746            // See: https://developer.android.com/reference/android/os/Build.VERSION_CODES
747            if let Some(val) = properties.get("ro.build.version.sdk") {
748                match val.parse::<u32>() {
749                    Ok(sdk_ver) => sdk_ver,
750                    Err(err) => {
751                        log::error!(
752                            concat!(
753                                "Couldn't parse Android's ",
754                                "ro.build.version.sdk system property ({}): {}",
755                            ),
756                            val,
757                            err,
758                        );
759                        0
760                    }
761                }
762            } else {
763                log::error!("Couldn't read Android's ro.build.version.sdk system property");
764                0
765            }
766        };
767        #[cfg(not(target_os = "android"))]
768        let android_sdk_version = 0;
769
770        let mut flags = vk::InstanceCreateFlags::empty();
771
772        // Avoid VUID-VkInstanceCreateInfo-flags-06559: Only ask the instance to
773        // enumerate incomplete Vulkan implementations (which we need on Mac) if
774        // we managed to find the extension that provides the flag.
775        if extensions.contains(&khr::portability_enumeration::NAME) {
776            flags |= vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR;
777        }
778        let vk_instance = {
779            let str_pointers = layers
780                .iter()
781                .chain(extensions.iter())
782                .map(|&s: &&'static _| {
783                    // Safe because `layers` and `extensions` entries have static lifetime.
784                    s.as_ptr()
785                })
786                .collect::<Vec<_>>();
787
788            create_info = create_info
789                .flags(flags)
790                .application_info(&app_info)
791                .enabled_layer_names(&str_pointers[..layers.len()])
792                .enabled_extension_names(&str_pointers[layers.len()..]);
793
794            let mut debug_utils_create_info = debug_utils
795                .as_mut()
796                .map(|create_info| create_info.to_vk_create_info());
797            if let Some(debug_utils_create_info) = debug_utils_create_info.as_mut() {
798                create_info = create_info.push_next(debug_utils_create_info);
799            }
800
801            // Enable explicit validation features if available
802            let mut validation_features;
803            let mut validation_feature_list: ArrayVec<_, 3>;
804            if validation_features_are_enabled {
805                validation_feature_list = ArrayVec::new();
806
807                // Always enable synchronization validation
808                validation_feature_list
809                    .push(vk::ValidationFeatureEnableEXT::SYNCHRONIZATION_VALIDATION);
810
811                // Only enable GPU assisted validation if requested.
812                if should_enable_gpu_based_validation {
813                    validation_feature_list.push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED);
814                    validation_feature_list
815                        .push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED_RESERVE_BINDING_SLOT);
816                }
817
818                validation_features = vk::ValidationFeaturesEXT::default()
819                    .enabled_validation_features(&validation_feature_list);
820                create_info = create_info.push_next(&mut validation_features);
821            }
822
823            unsafe {
824                profiling::scope!("vkCreateInstance");
825                entry.create_instance(&create_info, None)
826            }
827            .map_err(|e| {
828                crate::InstanceError::with_source(
829                    String::from("Entry::create_instance() failed"),
830                    e,
831                )
832            })?
833        };
834
835        unsafe {
836            Self::from_raw(
837                entry,
838                vk_instance,
839                instance_api_version,
840                android_sdk_version,
841                debug_utils,
842                extensions,
843                desc.flags,
844                desc.memory_budget_thresholds,
845                has_nv_optimus,
846                None,
847            )
848        }
849    }
850}
851
852impl Drop for super::InstanceShared {
853    fn drop(&mut self) {
854        unsafe {
855            // Keep du alive since destroy_instance may also log
856            let _du = self.debug_utils.take().inspect(|du| {
857                du.extension
858                    .destroy_debug_utils_messenger(du.messenger, None);
859            });
860            if self.drop_guard.is_none() {
861                self.raw.destroy_instance(None);
862            }
863        }
864    }
865}
866
867impl crate::Instance for super::Instance {
868    type A = super::Api;
869
870    unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
871        unsafe { Self::init_with_callback(desc, None) }
872    }
873
874    unsafe fn create_surface(
875        &self,
876        display_handle: raw_window_handle::RawDisplayHandle,
877        window_handle: raw_window_handle::RawWindowHandle,
878    ) -> Result<super::Surface, crate::InstanceError> {
879        use raw_window_handle::{RawDisplayHandle as Rdh, RawWindowHandle as Rwh};
880
881        // TODO: Replace with ash-window, which also lazy-loads the extension based on handle type
882
883        match (window_handle, display_handle) {
884            (Rwh::Wayland(handle), Rdh::Wayland(display)) => {
885                self.create_surface_from_wayland(display.display.as_ptr(), handle.surface.as_ptr())
886            }
887            (Rwh::Xlib(handle), Rdh::Xlib(display)) => {
888                let display = display.display.expect("Display pointer is not set.");
889                self.create_surface_from_xlib(display.as_ptr(), handle.window)
890            }
891            (Rwh::Xcb(handle), Rdh::Xcb(display)) => {
892                let connection = display.connection.expect("Pointer to X-Server is not set.");
893                self.create_surface_from_xcb(connection.as_ptr(), handle.window.get())
894            }
895            (Rwh::AndroidNdk(handle), _) => {
896                self.create_surface_android(handle.a_native_window.as_ptr())
897            }
898            (Rwh::Win32(handle), _) => {
899                let hinstance = handle.hinstance.ok_or_else(|| {
900                    crate::InstanceError::new(String::from(
901                        "Vulkan requires raw-window-handle's Win32::hinstance to be set",
902                    ))
903                })?;
904                self.create_surface_from_hwnd(hinstance.get(), handle.hwnd.get())
905            }
906            #[cfg(target_vendor = "apple")]
907            (Rwh::AppKit(handle), _)
908                if self.shared.extensions.contains(&ext::metal_surface::NAME) =>
909            {
910                let layer = unsafe { raw_window_metal::Layer::from_ns_view(handle.ns_view) };
911                self.create_surface_from_layer(layer)
912            }
913            #[cfg(target_vendor = "apple")]
914            (Rwh::UiKit(handle), _)
915                if self.shared.extensions.contains(&ext::metal_surface::NAME) =>
916            {
917                let layer = unsafe { raw_window_metal::Layer::from_ui_view(handle.ui_view) };
918                self.create_surface_from_layer(layer)
919            }
920            (_, _) => Err(crate::InstanceError::new(format!(
921                "window handle {window_handle:?} is not a Vulkan-compatible handle"
922            ))),
923        }
924    }
925
926    unsafe fn enumerate_adapters(
927        &self,
928        _surface_hint: Option<&super::Surface>,
929    ) -> Vec<crate::ExposedAdapter<super::Api>> {
930        use crate::auxil::db;
931
932        let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } {
933            Ok(devices) => devices,
934            Err(err) => {
935                log::error!("enumerate_adapters: {err}");
936                Vec::new()
937            }
938        };
939
940        let mut exposed_adapters = raw_devices
941            .into_iter()
942            .flat_map(|device| self.expose_adapter(device))
943            .collect::<Vec<_>>();
944
945        // Detect if it's an Intel + NVidia configuration with Optimus
946        let has_nvidia_dgpu = exposed_adapters.iter().any(|exposed| {
947            exposed.info.device_type == wgt::DeviceType::DiscreteGpu
948                && exposed.info.vendor == db::nvidia::VENDOR
949        });
950        if cfg!(target_os = "linux") && has_nvidia_dgpu && self.shared.has_nv_optimus {
951            for exposed in exposed_adapters.iter_mut() {
952                if exposed.info.device_type == wgt::DeviceType::IntegratedGpu
953                    && exposed.info.vendor == db::intel::VENDOR
954                {
955                    // Check if mesa driver and version less than 21.2
956                    if let Some(version) = exposed.info.driver_info.split_once("Mesa ").map(|s| {
957                        let mut components = s.1.split('.');
958                        let major = components.next().and_then(|s| u8::from_str(s).ok());
959                        let minor = components.next().and_then(|s| u8::from_str(s).ok());
960                        if let (Some(major), Some(minor)) = (major, minor) {
961                            (major, minor)
962                        } else {
963                            (0, 0)
964                        }
965                    }) {
966                        if version < (21, 2) {
967                            // See https://gitlab.freedesktop.org/mesa/mesa/-/issues/4688
968                            log::debug!(
969                                concat!(
970                                    "Disabling presentation on '{}' (id {:?}) ",
971                                    "due to NV Optimus and Intel Mesa < v21.2"
972                                ),
973                                exposed.info.name,
974                                exposed.adapter.raw
975                            );
976                            exposed.adapter.private_caps.can_present = false;
977                        }
978                    }
979                }
980            }
981        }
982
983        exposed_adapters
984    }
985}
986
987impl Drop for super::Surface {
988    fn drop(&mut self) {
989        unsafe { ManuallyDrop::take(&mut self.inner).delete_surface() };
990    }
991}
992
993impl crate::Surface for super::Surface {
994    type A = super::Api;
995
996    unsafe fn configure(
997        &self,
998        device: &super::Device,
999        config: &crate::SurfaceConfiguration,
1000    ) -> Result<(), crate::SurfaceError> {
1001        // SAFETY: `configure`'s contract guarantees there are no resources derived from the swapchain in use.
1002        let mut swap_chain = self.swapchain.write();
1003
1004        let mut old = swap_chain.take();
1005        if let Some(ref mut old) = old {
1006            unsafe { old.release_resources(device) };
1007        }
1008
1009        let swapchain = unsafe { self.inner.create_swapchain(device, config, old)? };
1010        *swap_chain = Some(swapchain);
1011
1012        Ok(())
1013    }
1014
1015    unsafe fn unconfigure(&self, device: &super::Device) {
1016        if let Some(mut sc) = self.swapchain.write().take() {
1017            // SAFETY: `unconfigure`'s contract guarantees there are no resources derived from the swapchain in use.
1018            unsafe { sc.release_resources(device) };
1019            unsafe { sc.delete_swapchain() };
1020        }
1021    }
1022
1023    unsafe fn acquire_texture(
1024        &self,
1025        timeout: Option<core::time::Duration>,
1026        fence: &super::Fence,
1027    ) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
1028        let mut swapchain = self.swapchain.write();
1029        let swapchain = swapchain.as_mut().unwrap();
1030
1031        unsafe { swapchain.acquire(timeout, fence) }
1032    }
1033
1034    unsafe fn discard_texture(&self, texture: super::SurfaceTexture) {
1035        unsafe {
1036            self.swapchain
1037                .write()
1038                .as_mut()
1039                .unwrap()
1040                .discard_texture(texture)
1041                .unwrap()
1042        };
1043    }
1044}