wgpu_hal/vulkan/
adapter.rs

1use alloc::{borrow::ToOwned as _, boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec};
2use core::{ffi::CStr, marker::PhantomData};
3
4use ash::{ext, google, khr, vk};
5use wgpu_sync::Mutex;
6
7use crate::{vulkan::semaphore_list::SemaphoreList, AllocationSizes};
8
9use super::semaphore_list::SemaphoreListMode;
10
11fn depth_stencil_required_flags() -> vk::FormatFeatureFlags {
12    vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT
13}
14
15const INDEXING_FEATURES: wgt::Features = wgt::Features::TEXTURE_BINDING_ARRAY
16    .union(wgt::Features::BUFFER_BINDING_ARRAY)
17    .union(wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY)
18    .union(wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING)
19    .union(wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING)
20    .union(wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS)
21    .union(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
22#[expect(rustdoc::private_intra_doc_links)]
23/// Features supported by a [`vk::PhysicalDevice`] and its extensions.
24///
25/// This is used in two phases:
26///
27/// - When enumerating adapters, this represents the features offered by the
28///   adapter. [`Instance::expose_adapter`] calls `vkGetPhysicalDeviceFeatures2`
29///   (or `vkGetPhysicalDeviceFeatures` if that is not available) to collect
30///   this information about the `VkPhysicalDevice` represented by the
31///   `wgpu_hal::ExposedAdapter`.
32///
33/// - When opening a device, this represents the features we would like to
34///   enable. At `wgpu_hal::Device` construction time,
35///   [`PhysicalDeviceFeatures::from_extensions_and_requested_features`]
36///   constructs an value of this type indicating which Vulkan features to
37///   enable, based on the `wgpu_types::Features` requested.
38///
39/// [`Instance::expose_adapter`]: super::Instance::expose_adapter
40#[derive(Debug, Default)]
41pub struct PhysicalDeviceFeatures {
42    /// Basic Vulkan 1.0 features.
43    core: vk::PhysicalDeviceFeatures,
44
45    /// Features provided by `VK_EXT_descriptor_indexing`, promoted to Vulkan 1.2.
46    pub(super) descriptor_indexing:
47        Option<vk::PhysicalDeviceDescriptorIndexingFeaturesEXT<'static>>,
48
49    /// Features provided by `VK_KHR_timeline_semaphore`, promoted to Vulkan 1.2
50    timeline_semaphore: Option<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR<'static>>,
51
52    /// Features provided by `VK_EXT_image_robustness`, promoted to Vulkan 1.3
53    image_robustness: Option<vk::PhysicalDeviceImageRobustnessFeaturesEXT<'static>>,
54
55    /// Features provided by `VK_EXT_robustness2`.
56    robustness2: Option<vk::PhysicalDeviceRobustness2FeaturesEXT<'static>>,
57
58    /// Features provided by `VK_KHR_multiview`, promoted to Vulkan 1.1.
59    multiview: Option<vk::PhysicalDeviceMultiviewFeaturesKHR<'static>>,
60
61    /// Features provided by `VK_KHR_sampler_ycbcr_conversion`, promoted to Vulkan 1.1.
62    sampler_ycbcr_conversion: Option<vk::PhysicalDeviceSamplerYcbcrConversionFeatures<'static>>,
63
64    /// Features provided by `VK_EXT_texture_compression_astc_hdr`, promoted to Vulkan 1.3.
65    astc_hdr: Option<vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT<'static>>,
66
67    /// Features provided by `VK_KHR_shader_float16_int8`, promoted to Vulkan 1.2
68    shader_float16_int8: Option<vk::PhysicalDeviceShaderFloat16Int8Features<'static>>,
69
70    /// Features provided by `VK_KHR_16bit_storage`, promoted to Vulkan 1.1
71    _16bit_storage: Option<vk::PhysicalDevice16BitStorageFeatures<'static>>,
72
73    /// Features provided by `VK_KHR_acceleration_structure`.
74    acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructureFeaturesKHR<'static>>,
75
76    /// Features provided by `VK_KHR_buffer_device_address`, promoted to Vulkan 1.2.
77    ///
78    /// We only use this feature for
79    /// [`Features::EXPERIMENTAL_RAY_QUERY`], which requires
80    /// `VK_KHR_acceleration_structure`, which depends on
81    /// `VK_KHR_buffer_device_address`, so [`Instance::expose_adapter`] only
82    /// bothers to check if `VK_KHR_acceleration_structure` is available,
83    /// leaving this `None`.
84    ///
85    /// However, we do populate this when creating a device if
86    /// [`Features::EXPERIMENTAL_RAY_QUERY`] is requested.
87    ///
88    /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
89    /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
90    buffer_device_address: Option<vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR<'static>>,
91
92    /// Features provided by `VK_KHR_ray_query`,
93    ///
94    /// Vulkan requires that the feature be present if the `VK_KHR_ray_query`
95    /// extension is present, so [`Instance::expose_adapter`] doesn't bother retrieving
96    /// this from `vkGetPhysicalDeviceFeatures2`.
97    ///
98    /// However, we do populate this when creating a device if ray tracing is requested.
99    ///
100    /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
101    ray_query: Option<vk::PhysicalDeviceRayQueryFeaturesKHR<'static>>,
102
103    /// Features provided by `VK_KHR_ray_tracing_pipeline`.
104    ray_tracing_pipeline: Option<vk::PhysicalDeviceRayTracingPipelineFeaturesKHR<'static>>,
105
106    /// Features provided by `VK_KHR_zero_initialize_workgroup_memory`, promoted
107    /// to Vulkan 1.3.
108    zero_initialize_workgroup_memory:
109        Option<vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures<'static>>,
110    position_fetch: Option<vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR<'static>>,
111
112    /// Features provided by `VK_KHR_shader_atomic_int64`, promoted to Vulkan 1.2.
113    shader_atomic_int64: Option<vk::PhysicalDeviceShaderAtomicInt64Features<'static>>,
114
115    /// Features provided by `VK_EXT_shader_image_atomic_int64`
116    shader_image_atomic_int64: Option<vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT<'static>>,
117
118    /// Features provided by `VK_EXT_shader_atomic_float`.
119    shader_atomic_float: Option<vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT<'static>>,
120
121    /// Features provided by `VK_EXT_subgroup_size_control`, promoted to Vulkan 1.3.
122    subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlFeatures<'static>>,
123
124    /// Features provided by `VK_KHR_maintenance4`, promoted to Vulkan 1.3.
125    maintenance4: Option<vk::PhysicalDeviceMaintenance4FeaturesKHR<'static>>,
126
127    /// Features proved by `VK_EXT_mesh_shader`
128    mesh_shader: Option<vk::PhysicalDeviceMeshShaderFeaturesEXT<'static>>,
129
130    /// Features provided by `VK_KHR_shader_integer_dot_product`, promoted to Vulkan 1.3.
131    shader_integer_dot_product:
132        Option<vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR<'static>>,
133
134    /// Features provided by `VK_KHR_fragment_shader_barycentric`
135    shader_barycentrics: Option<vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR<'static>>,
136
137    /// Features provided by `VK_KHR_portability_subset`.
138    ///
139    /// Strictly speaking this tells us what features we *don't* have compared to core.
140    portability_subset: Option<vk::PhysicalDevicePortabilitySubsetFeaturesKHR<'static>>,
141
142    /// Features provided by `VK_KHR_cooperative_matrix`
143    cooperative_matrix: Option<vk::PhysicalDeviceCooperativeMatrixFeaturesKHR<'static>>,
144
145    /// Features provided by `VK_KHR_vulkan_memory_model`, promoted to Vulkan 1.2
146    vulkan_memory_model: Option<vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR<'static>>,
147
148    shader_draw_parameters: Option<vk::PhysicalDeviceShaderDrawParametersFeatures<'static>>,
149}
150
151impl PhysicalDeviceFeatures {
152    pub fn get_core(&self) -> vk::PhysicalDeviceFeatures {
153        self.core
154    }
155
156    /// Add the members of `self` into `info.enabled_features` and its `p_next` chain.
157    pub fn add_to_device_create<'a>(
158        &'a mut self,
159        mut info: vk::DeviceCreateInfo<'a>,
160    ) -> vk::DeviceCreateInfo<'a> {
161        info = info.enabled_features(&self.core);
162        if let Some(ref mut feature) = self.descriptor_indexing {
163            info = info.push_next(feature);
164        }
165        if let Some(ref mut feature) = self.timeline_semaphore {
166            info = info.push_next(feature);
167        }
168        if let Some(ref mut feature) = self.image_robustness {
169            info = info.push_next(feature);
170        }
171        if let Some(ref mut feature) = self.robustness2 {
172            info = info.push_next(feature);
173        }
174        if let Some(ref mut feature) = self.multiview {
175            info = info.push_next(feature);
176        }
177        if let Some(ref mut feature) = self.astc_hdr {
178            info = info.push_next(feature);
179        }
180        if let Some(ref mut feature) = self.shader_float16_int8 {
181            info = info.push_next(feature);
182        }
183        if let Some(ref mut feature) = self._16bit_storage {
184            info = info.push_next(feature);
185        }
186        if let Some(ref mut feature) = self.zero_initialize_workgroup_memory {
187            info = info.push_next(feature);
188        }
189        if let Some(ref mut feature) = self.acceleration_structure {
190            info = info.push_next(feature);
191        }
192        if let Some(ref mut feature) = self.buffer_device_address {
193            info = info.push_next(feature);
194        }
195        if let Some(ref mut feature) = self.ray_query {
196            info = info.push_next(feature);
197        }
198        if let Some(ref mut feature) = self.ray_tracing_pipeline {
199            info = info.push_next(feature);
200        }
201        if let Some(ref mut feature) = self.shader_atomic_int64 {
202            info = info.push_next(feature);
203        }
204        if let Some(ref mut feature) = self.position_fetch {
205            info = info.push_next(feature);
206        }
207        if let Some(ref mut feature) = self.shader_image_atomic_int64 {
208            info = info.push_next(feature);
209        }
210        if let Some(ref mut feature) = self.shader_atomic_float {
211            info = info.push_next(feature);
212        }
213        if let Some(ref mut feature) = self.subgroup_size_control {
214            info = info.push_next(feature);
215        }
216        if let Some(ref mut feature) = self.maintenance4 {
217            info = info.push_next(feature);
218        }
219        if let Some(ref mut feature) = self.mesh_shader {
220            info = info.push_next(feature);
221        }
222        if let Some(ref mut feature) = self.shader_integer_dot_product {
223            info = info.push_next(feature);
224        }
225        if let Some(ref mut feature) = self.shader_barycentrics {
226            info = info.push_next(feature);
227        }
228        if let Some(ref mut feature) = self.portability_subset {
229            info = info.push_next(feature);
230        }
231        if let Some(ref mut feature) = self.cooperative_matrix {
232            info = info.push_next(feature);
233        }
234        if let Some(ref mut feature) = self.vulkan_memory_model {
235            info = info.push_next(feature);
236        }
237        if let Some(ref mut feature) = self.shader_draw_parameters {
238            info = info.push_next(feature);
239        }
240        info
241    }
242
243    fn supports_storage_input_output_16(&self) -> bool {
244        self._16bit_storage
245            .as_ref()
246            .map(|features| features.storage_input_output16 != 0)
247            .unwrap_or(false)
248    }
249
250    /// Create a `PhysicalDeviceFeatures` that can be used to create a logical
251    /// device.
252    ///
253    /// Return a `PhysicalDeviceFeatures` value capturing all the Vulkan
254    /// features needed for the given [`Features`], [`DownlevelFlags`], and
255    /// [`PrivateCapabilities`]. You can use the returned value's
256    /// [`add_to_device_create`] method to configure a
257    /// [`vk::DeviceCreateInfo`] to build a logical device providing those
258    /// features.
259    ///
260    /// To ensure that the returned value is able to select all the Vulkan
261    /// features needed to express `requested_features`, `downlevel_flags`, and
262    /// `private_caps`:
263    ///
264    /// - The given `enabled_extensions` set must include all the extensions
265    ///   selected by [`Adapter::required_device_extensions`] when passed
266    ///   `features`.
267    ///
268    /// - The given `device_api_version` must be the Vulkan API version of the
269    ///   physical device we will use to create the logical device.
270    ///
271    /// [`Features`]: wgt::Features
272    /// [`DownlevelFlags`]: wgt::DownlevelFlags
273    /// [`PrivateCapabilities`]: super::PrivateCapabilities
274    /// [`add_to_device_create`]: PhysicalDeviceFeatures::add_to_device_create
275    /// [`Adapter::required_device_extensions`]: super::Adapter::required_device_extensions
276    fn from_extensions_and_requested_features(
277        phd_capabilities: &PhysicalDeviceProperties,
278        phd_features: &PhysicalDeviceFeatures,
279        enabled_extensions: &[&'static CStr],
280        requested_features: wgt::Features,
281        downlevel_flags: wgt::DownlevelFlags,
282        private_caps: &super::PrivateCapabilities,
283    ) -> Self {
284        let device_api_version = phd_capabilities.device_api_version;
285        let needs_bindless = requested_features.intersects(
286            wgt::Features::TEXTURE_BINDING_ARRAY
287                | wgt::Features::BUFFER_BINDING_ARRAY
288                | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY
289                | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
290                | wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
291        );
292        let needs_partially_bound =
293            requested_features.intersects(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
294
295        Self {
296            // vk::PhysicalDeviceFeatures is a struct composed of Bool32's while
297            // Features is a bitfield so we need to map everything manually
298            core: vk::PhysicalDeviceFeatures::default()
299                .robust_buffer_access(private_caps.robust_buffer_access)
300                .independent_blend(downlevel_flags.contains(wgt::DownlevelFlags::INDEPENDENT_BLEND))
301                .sample_rate_shading(
302                    downlevel_flags.contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING),
303                )
304                .image_cube_array(
305                    downlevel_flags.contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES),
306                )
307                .draw_indirect_first_instance(
308                    requested_features.contains(wgt::Features::INDIRECT_FIRST_INSTANCE),
309                )
310                //.dual_src_blend(requested_features.contains(wgt::Features::DUAL_SRC_BLENDING))
311                .multi_draw_indirect(phd_features.core.multi_draw_indirect != 0)
312                .fill_mode_non_solid(requested_features.intersects(
313                    wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT,
314                ))
315                //.depth_bounds(requested_features.contains(wgt::Features::DEPTH_BOUNDS))
316                //.alpha_to_one(requested_features.contains(wgt::Features::ALPHA_TO_ONE))
317                //.multi_viewport(requested_features.contains(wgt::Features::MULTI_VIEWPORTS))
318                .sampler_anisotropy(
319                    downlevel_flags.contains(wgt::DownlevelFlags::ANISOTROPIC_FILTERING),
320                )
321                .texture_compression_etc2(
322                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ETC2),
323                )
324                .texture_compression_astc_ldr(
325                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC),
326                )
327                .texture_compression_bc(
328                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC),
329                    // BC provides formats for Sliced 3D
330                )
331                //.occlusion_query_precise(requested_features.contains(wgt::Features::PRECISE_OCCLUSION_QUERY))
332                .pipeline_statistics_query(
333                    requested_features.contains(wgt::Features::PIPELINE_STATISTICS_QUERY),
334                )
335                .vertex_pipeline_stores_and_atomics(
336                    requested_features.contains(wgt::Features::VERTEX_WRITABLE_STORAGE),
337                )
338                .fragment_stores_and_atomics(
339                    downlevel_flags.contains(wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE),
340                )
341                //.shader_image_gather_extended(
342                //.shader_storage_image_extended_formats(
343                .shader_uniform_buffer_array_dynamic_indexing(
344                    requested_features.contains(wgt::Features::BUFFER_BINDING_ARRAY),
345                )
346                .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
347                    wgt::Features::BUFFER_BINDING_ARRAY
348                        | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
349                ))
350                .shader_sampled_image_array_dynamic_indexing(
351                    requested_features.contains(wgt::Features::TEXTURE_BINDING_ARRAY),
352                )
353                .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
354                    wgt::Features::TEXTURE_BINDING_ARRAY
355                        | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
356                ))
357                //.shader_storage_image_array_dynamic_indexing(
358                .shader_clip_distance(requested_features.contains(wgt::Features::CLIP_DISTANCES))
359                //.shader_cull_distance(requested_features.contains(wgt::Features::SHADER_CULL_DISTANCE))
360                .shader_float64(requested_features.contains(wgt::Features::SHADER_F64))
361                .shader_int64(requested_features.contains(wgt::Features::SHADER_INT64))
362                .shader_int16(requested_features.contains(wgt::Features::SHADER_I16))
363                //.shader_resource_residency(requested_features.contains(wgt::Features::SHADER_RESOURCE_RESIDENCY))
364                .geometry_shader(requested_features.contains(wgt::Features::PRIMITIVE_INDEX))
365                .depth_clamp(requested_features.contains(wgt::Features::DEPTH_CLIP_CONTROL))
366                .dual_src_blend(requested_features.contains(wgt::Features::DUAL_SOURCE_BLENDING)),
367            descriptor_indexing: if requested_features.intersects(INDEXING_FEATURES) {
368                Some(
369                    vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default()
370                        .shader_sampled_image_array_non_uniform_indexing(needs_bindless)
371                        .shader_storage_image_array_non_uniform_indexing(needs_bindless)
372                        .shader_storage_buffer_array_non_uniform_indexing(needs_bindless)
373                        .descriptor_binding_sampled_image_update_after_bind(needs_bindless)
374                        .descriptor_binding_storage_image_update_after_bind(needs_bindless)
375                        .descriptor_binding_storage_buffer_update_after_bind(needs_bindless)
376                        .descriptor_binding_partially_bound(needs_partially_bound),
377                )
378            } else {
379                None
380            },
381            timeline_semaphore: if device_api_version >= vk::API_VERSION_1_2
382                || enabled_extensions.contains(&khr::timeline_semaphore::NAME)
383            {
384                Some(
385                    vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default()
386                        .timeline_semaphore(private_caps.timeline_semaphores),
387                )
388            } else {
389                None
390            },
391            image_robustness: if device_api_version >= vk::API_VERSION_1_3
392                || enabled_extensions.contains(&ext::image_robustness::NAME)
393            {
394                Some(
395                    vk::PhysicalDeviceImageRobustnessFeaturesEXT::default()
396                        .robust_image_access(private_caps.robust_image_access),
397                )
398            } else {
399                None
400            },
401            robustness2: if enabled_extensions.contains(&ext::robustness2::NAME) {
402                Some(
403                    vk::PhysicalDeviceRobustness2FeaturesEXT::default()
404                        .robust_buffer_access2(private_caps.robust_buffer_access2)
405                        .robust_image_access2(private_caps.robust_image_access2),
406                )
407            } else {
408                None
409            },
410            multiview: if device_api_version >= vk::API_VERSION_1_1
411                || enabled_extensions.contains(&khr::multiview::NAME)
412            {
413                Some(
414                    vk::PhysicalDeviceMultiviewFeatures::default()
415                        .multiview(requested_features.contains(wgt::Features::MULTIVIEW)),
416                )
417            } else {
418                None
419            },
420            sampler_ycbcr_conversion: if device_api_version >= vk::API_VERSION_1_1
421                || enabled_extensions.contains(&khr::sampler_ycbcr_conversion::NAME)
422            {
423                Some(
424                    vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default(), // .sampler_ycbcr_conversion(requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12))
425                )
426            } else {
427                None
428            },
429            astc_hdr: if enabled_extensions.contains(&ext::texture_compression_astc_hdr::NAME) {
430                Some(
431                    vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default()
432                        .texture_compression_astc_hdr(true),
433                )
434            } else {
435                None
436            },
437            shader_float16_int8: match requested_features.contains(wgt::Features::SHADER_F16) {
438                shader_float16 if shader_float16 || private_caps.shader_int8 => Some(
439                    vk::PhysicalDeviceShaderFloat16Int8Features::default()
440                        .shader_float16(shader_float16)
441                        .shader_int8(private_caps.shader_int8),
442                ),
443                _ => None,
444            },
445            _16bit_storage: if requested_features
446                .intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16)
447            {
448                Some(
449                    vk::PhysicalDevice16BitStorageFeatures::default()
450                        .storage_buffer16_bit_access(true)
451                        .storage_input_output16(phd_features.supports_storage_input_output_16())
452                        .uniform_and_storage_buffer16_bit_access(true),
453                )
454            } else {
455                None
456            },
457            acceleration_structure: if enabled_extensions
458                .contains(&khr::acceleration_structure::NAME)
459            {
460                Some(
461                    vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default()
462                        .acceleration_structure(true)
463                        .descriptor_binding_acceleration_structure_update_after_bind(
464                            requested_features
465                                .contains(wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY),
466                        ),
467                )
468            } else {
469                None
470            },
471            buffer_device_address: if enabled_extensions.contains(&khr::buffer_device_address::NAME)
472            {
473                Some(
474                    vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR::default()
475                        .buffer_device_address(true),
476                )
477            } else {
478                None
479            },
480            ray_query: if enabled_extensions.contains(&khr::ray_query::NAME) {
481                Some(vk::PhysicalDeviceRayQueryFeaturesKHR::default().ray_query(true))
482            } else {
483                None
484            },
485            ray_tracing_pipeline: if enabled_extensions.contains(&khr::ray_tracing_pipeline::NAME) {
486                Some(
487                    vk::PhysicalDeviceRayTracingPipelineFeaturesKHR::default()
488                        .ray_tracing_pipeline(true),
489                )
490            } else {
491                None
492            },
493            zero_initialize_workgroup_memory: if device_api_version >= vk::API_VERSION_1_3
494                || enabled_extensions.contains(&khr::zero_initialize_workgroup_memory::NAME)
495            {
496                Some(
497                    vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default()
498                        .shader_zero_initialize_workgroup_memory(
499                            private_caps.zero_initialize_workgroup_memory,
500                        ),
501                )
502            } else {
503                None
504            },
505            shader_atomic_int64: if device_api_version >= vk::API_VERSION_1_2
506                || enabled_extensions.contains(&khr::shader_atomic_int64::NAME)
507            {
508                let needed = requested_features.intersects(
509                    wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
510                        | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
511                );
512                Some(
513                    vk::PhysicalDeviceShaderAtomicInt64Features::default()
514                        .shader_buffer_int64_atomics(needed)
515                        .shader_shared_int64_atomics(needed),
516                )
517            } else {
518                None
519            },
520            shader_image_atomic_int64: if enabled_extensions
521                .contains(&ext::shader_image_atomic_int64::NAME)
522            {
523                let needed = requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC);
524                Some(
525                    vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default()
526                        .shader_image_int64_atomics(needed),
527                )
528            } else {
529                None
530            },
531            shader_atomic_float: if enabled_extensions.contains(&ext::shader_atomic_float::NAME) {
532                let needed = requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC);
533                Some(
534                    vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default()
535                        .shader_buffer_float32_atomics(needed)
536                        .shader_buffer_float32_atomic_add(needed),
537                )
538            } else {
539                None
540            },
541            subgroup_size_control: if device_api_version >= vk::API_VERSION_1_3
542                || enabled_extensions.contains(&ext::subgroup_size_control::NAME)
543            {
544                Some(
545                    vk::PhysicalDeviceSubgroupSizeControlFeatures::default()
546                        .subgroup_size_control(true),
547                )
548            } else {
549                None
550            },
551            position_fetch: if enabled_extensions.contains(&khr::ray_tracing_position_fetch::NAME) {
552                Some(
553                    vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default()
554                        .ray_tracing_position_fetch(true),
555                )
556            } else {
557                None
558            },
559            mesh_shader: if enabled_extensions.contains(&ext::mesh_shader::NAME) {
560                let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
561                let multiview_needed =
562                    requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW);
563                Some(
564                    vk::PhysicalDeviceMeshShaderFeaturesEXT::default()
565                        .mesh_shader(needed)
566                        .task_shader(needed)
567                        .multiview_mesh_shader(multiview_needed),
568                )
569            } else {
570                None
571            },
572            maintenance4: if device_api_version >= vk::API_VERSION_1_3
573                || enabled_extensions.contains(&khr::maintenance4::NAME)
574            {
575                let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
576                Some(vk::PhysicalDeviceMaintenance4Features::default().maintenance4(needed))
577            } else {
578                None
579            },
580            shader_integer_dot_product: if device_api_version >= vk::API_VERSION_1_3
581                || enabled_extensions.contains(&khr::shader_integer_dot_product::NAME)
582            {
583                Some(
584                    vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR::default()
585                        .shader_integer_dot_product(private_caps.shader_integer_dot_product),
586                )
587            } else {
588                None
589            },
590            shader_barycentrics: if enabled_extensions
591                .contains(&khr::fragment_shader_barycentric::NAME)
592            {
593                let needed = requested_features.intersects(
594                    wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX,
595                );
596                Some(
597                    vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default()
598                        .fragment_shader_barycentric(needed),
599                )
600            } else {
601                None
602            },
603            portability_subset: if enabled_extensions.contains(&khr::portability_subset::NAME) {
604                let image_view_format_swizzle_needed =
605                    requested_features.intersects(wgt::Features::TEXTURE_COMPONENT_SWIZZLE);
606                let multisample_array_needed =
607                    requested_features.intersects(wgt::Features::MULTISAMPLE_ARRAY);
608
609                Some(
610                    vk::PhysicalDevicePortabilitySubsetFeaturesKHR::default()
611                        .image_view_format_swizzle(image_view_format_swizzle_needed)
612                        .multisample_array_image(multisample_array_needed),
613                )
614            } else {
615                None
616            },
617            cooperative_matrix: if enabled_extensions.contains(&khr::cooperative_matrix::NAME) {
618                let needed =
619                    requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX);
620                Some(
621                    vk::PhysicalDeviceCooperativeMatrixFeaturesKHR::default()
622                        .cooperative_matrix(needed),
623                )
624            } else {
625                None
626            },
627            vulkan_memory_model: if device_api_version >= vk::API_VERSION_1_2
628                || enabled_extensions.contains(&khr::vulkan_memory_model::NAME)
629            {
630                let needed =
631                    requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX);
632                Some(
633                    vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR::default()
634                        .vulkan_memory_model(needed)
635                        // The SPIR-V backend emits storage atomics with `Device`
636                        // memory scope, so whenever the Vulkan memory model is
637                        // enabled we must also enable device scope, otherwise the
638                        // validation layers report
639                        // `VUID-RuntimeSpirv-vulkanMemoryModel-06265`.
640                        .vulkan_memory_model_device_scope(needed),
641                )
642            } else {
643                None
644            },
645            shader_draw_parameters: if device_api_version >= vk::API_VERSION_1_1 {
646                let needed = requested_features.contains(wgt::Features::SHADER_DRAW_INDEX);
647                Some(
648                    vk::PhysicalDeviceShaderDrawParametersFeatures::default()
649                        .shader_draw_parameters(needed),
650                )
651            } else {
652                None
653            },
654        }
655    }
656
657    /// Compute the wgpu [`Features`] and [`DownlevelFlags`] supported by a physical device.
658    ///
659    /// Given `self`, together with the instance and physical device it was
660    /// built from, and a `caps` also built from those, determine which wgpu
661    /// features and downlevel flags the device can support.
662    ///
663    /// [`Features`]: wgt::Features
664    /// [`DownlevelFlags`]: wgt::DownlevelFlags
665    fn to_wgpu(
666        &self,
667        instance: &ash::Instance,
668        phd: vk::PhysicalDevice,
669        caps: &PhysicalDeviceProperties,
670        queue_props: &vk::QueueFamilyProperties,
671    ) -> (wgt::Features, wgt::DownlevelFlags) {
672        use wgt::{DownlevelFlags as Df, Features as F};
673        let mut features = F::empty()
674            | F::MAPPABLE_PRIMARY_BUFFERS
675            | F::IMMEDIATES
676            | F::ADDRESS_MODE_CLAMP_TO_BORDER
677            | F::ADDRESS_MODE_CLAMP_TO_ZERO
678            | F::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
679            | F::CLEAR_TEXTURE
680            | F::PIPELINE_CACHE
681            | F::SHADER_EARLY_DEPTH_TEST
682            | F::TEXTURE_ATOMIC
683            | F::PASSTHROUGH_SHADERS
684            | F::MEMORY_DECORATION_COHERENT
685            | F::MEMORY_DECORATION_VOLATILE;
686
687        let mut dl_flags = Df::COMPUTE_SHADERS
688            | Df::BASE_VERTEX
689            | Df::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES
690            | Df::COMPARISON_SAMPLERS
691            | Df::VERTEX_STORAGE
692            | Df::FRAGMENT_STORAGE
693            | Df::DEPTH_TEXTURE_AND_BUFFER_COPIES
694            | Df::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED
695            | Df::UNRESTRICTED_INDEX_BUFFER
696            | Df::INDIRECT_EXECUTION
697            | Df::VIEW_FORMATS
698            | Df::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES
699            | Df::NONBLOCKING_QUERY_RESOLVE
700            | Df::SHADER_F16_IN_F32
701            | Df::MSL2_1
702            | Df::LINEAR_INTERPOLATION;
703
704        // `VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL`
705        // and `VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL`
706        // is required for separate read-only depth stencil.
707        dl_flags.set(
708            Df::READ_ONLY_DEPTH_STENCIL,
709            caps.device_api_version >= vk::API_VERSION_1_1
710                || caps.supports_extension(khr::maintenance2::NAME),
711        );
712
713        dl_flags.set(
714            Df::SURFACE_VIEW_FORMATS,
715            caps.supports_extension(khr::swapchain_mutable_format::NAME)
716                || !caps.supports_extension(khr::swapchain::NAME),
717        );
718        dl_flags.set(Df::CUBE_ARRAY_TEXTURES, self.core.image_cube_array != 0);
719        dl_flags.set(Df::ANISOTROPIC_FILTERING, self.core.sampler_anisotropy != 0);
720        dl_flags.set(
721            Df::FRAGMENT_WRITABLE_STORAGE,
722            self.core.fragment_stores_and_atomics != 0,
723        );
724        dl_flags.set(Df::MULTISAMPLED_SHADING, self.core.sample_rate_shading != 0);
725        dl_flags.set(Df::INDEPENDENT_BLEND, self.core.independent_blend != 0);
726        dl_flags.set(
727            Df::FULL_DRAW_INDEX_UINT32,
728            self.core.full_draw_index_uint32 != 0,
729        );
730        dl_flags.set(Df::DEPTH_BIAS_CLAMP, self.core.depth_bias_clamp != 0);
731
732        features.set(
733            F::TIMESTAMP_QUERY
734                | F::TIMESTAMP_QUERY_INSIDE_ENCODERS
735                | F::TIMESTAMP_QUERY_INSIDE_PASSES,
736            // Vulkan strictly defines this as either 36-64, or zero.
737            queue_props.timestamp_valid_bits >= 36,
738        );
739        features.set(
740            F::INDIRECT_FIRST_INSTANCE,
741            self.core.draw_indirect_first_instance != 0,
742        );
743        //if self.core.dual_src_blend != 0
744        features.set(F::POLYGON_MODE_LINE, self.core.fill_mode_non_solid != 0);
745        features.set(F::POLYGON_MODE_POINT, self.core.fill_mode_non_solid != 0);
746        //if self.core.depth_bounds != 0 {
747        //if self.core.alpha_to_one != 0 {
748        //if self.core.multi_viewport != 0 {
749        features.set(
750            F::TEXTURE_COMPRESSION_ETC2,
751            self.core.texture_compression_etc2 != 0,
752        );
753        features.set(
754            F::TEXTURE_COMPRESSION_ASTC,
755            self.core.texture_compression_astc_ldr != 0,
756        );
757        features.set(
758            F::TEXTURE_COMPRESSION_BC,
759            self.core.texture_compression_bc != 0,
760        );
761        features.set(
762            F::TEXTURE_COMPRESSION_BC_SLICED_3D,
763            self.core.texture_compression_bc != 0, // BC guarantees Sliced 3D
764        );
765        features.set(
766            F::PIPELINE_STATISTICS_QUERY,
767            self.core.pipeline_statistics_query != 0,
768        );
769        features.set(
770            F::VERTEX_WRITABLE_STORAGE,
771            self.core.vertex_pipeline_stores_and_atomics != 0,
772        );
773
774        features.set(F::SHADER_F64, self.core.shader_float64 != 0);
775        features.set(F::SHADER_INT64, self.core.shader_int64 != 0);
776        if let Some(ref bit16) = self._16bit_storage {
777            features.set(
778                F::SHADER_I16,
779                self.core.shader_int16 != 0
780                    && bit16.storage_buffer16_bit_access != 0
781                    && bit16.uniform_and_storage_buffer16_bit_access != 0,
782            );
783        }
784
785        features.set(F::PRIMITIVE_INDEX, self.core.geometry_shader != 0);
786
787        if let Some(ref shader_atomic_int64) = self.shader_atomic_int64 {
788            features.set(
789                F::SHADER_INT64_ATOMIC_ALL_OPS | F::SHADER_INT64_ATOMIC_MIN_MAX,
790                shader_atomic_int64.shader_buffer_int64_atomics != 0
791                    && shader_atomic_int64.shader_shared_int64_atomics != 0,
792            );
793        }
794
795        if let Some(ref shader_image_atomic_int64) = self.shader_image_atomic_int64 {
796            features.set(
797                F::TEXTURE_INT64_ATOMIC,
798                shader_image_atomic_int64
799                    .shader_image_int64_atomics(true)
800                    .shader_image_int64_atomics
801                    != 0,
802            );
803        }
804
805        if let Some(ref shader_atomic_float) = self.shader_atomic_float {
806            features.set(
807                F::SHADER_FLOAT32_ATOMIC,
808                shader_atomic_float.shader_buffer_float32_atomics != 0
809                    && shader_atomic_float.shader_buffer_float32_atomic_add != 0,
810            );
811        }
812
813        if let Some(ref shader_barycentrics) = self.shader_barycentrics {
814            features.set(
815                F::SHADER_BARYCENTRICS | F::SHADER_PER_VERTEX,
816                shader_barycentrics.fragment_shader_barycentric != 0,
817            );
818        }
819
820        //if caps.supports_extension(khr::sampler_mirror_clamp_to_edge::NAME) {
821        //if caps.supports_extension(ext::sampler_filter_minmax::NAME) {
822        features.set(
823            F::MULTI_DRAW_INDIRECT_COUNT,
824            caps.supports_extension(khr::draw_indirect_count::NAME),
825        );
826        features.set(
827            F::CONSERVATIVE_RASTERIZATION,
828            caps.supports_extension(ext::conservative_rasterization::NAME),
829        );
830        features.set(
831            F::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN,
832            caps.supports_extension(khr::ray_tracing_position_fetch::NAME),
833        );
834
835        if let Some(ref descriptor_indexing) = self.descriptor_indexing {
836            // We use update-after-bind descriptors for all bind groups containing binding arrays.
837            //
838            // In those bind groups, we allow all binding types except uniform buffers to be present.
839            //
840            // As we can only switch between update-after-bind and not on a per bind group basis,
841            // all supported binding types need to be able to be marked update after bind.
842            //
843            // As such, we enable all features as a whole, rather individually.
844            let supports_descriptor_indexing =
845                // Sampled Images
846                descriptor_indexing.shader_sampled_image_array_non_uniform_indexing != 0
847                    && descriptor_indexing.descriptor_binding_sampled_image_update_after_bind != 0
848                    // Storage Images
849                    && descriptor_indexing.shader_storage_image_array_non_uniform_indexing != 0
850                    && descriptor_indexing.descriptor_binding_storage_image_update_after_bind != 0
851                    // Storage Buffers
852                    && descriptor_indexing.shader_storage_buffer_array_non_uniform_indexing != 0
853                    && descriptor_indexing.descriptor_binding_storage_buffer_update_after_bind != 0;
854
855            let descriptor_indexing_features = F::BUFFER_BINDING_ARRAY
856                | F::TEXTURE_BINDING_ARRAY
857                | F::STORAGE_RESOURCE_BINDING_ARRAY
858                | F::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
859                | F::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING;
860
861            features.set(descriptor_indexing_features, supports_descriptor_indexing);
862
863            let supports_partially_bound =
864                descriptor_indexing.descriptor_binding_partially_bound != 0;
865
866            features.set(F::PARTIALLY_BOUND_BINDING_ARRAY, supports_partially_bound);
867        }
868
869        features.set(F::DEPTH_CLIP_CONTROL, self.core.depth_clamp != 0);
870        features.set(F::DUAL_SOURCE_BLENDING, self.core.dual_src_blend != 0);
871        features.set(F::CLIP_DISTANCES, self.core.shader_clip_distance != 0);
872
873        if let Some(ref multiview) = self.multiview {
874            features.set(F::MULTIVIEW, multiview.multiview != 0);
875            features.set(F::SELECTIVE_MULTIVIEW, multiview.multiview != 0);
876        }
877
878        features.set(
879            F::TEXTURE_FORMAT_16BIT_NORM,
880            is_format_16bit_norm_supported(instance, phd),
881        );
882
883        if let Some(ref astc_hdr) = self.astc_hdr {
884            features.set(
885                F::TEXTURE_COMPRESSION_ASTC_HDR,
886                astc_hdr.texture_compression_astc_hdr != 0,
887            );
888        }
889
890        if self.core.texture_compression_astc_ldr != 0 {
891            features.set(
892                F::TEXTURE_COMPRESSION_ASTC_SLICED_3D,
893                supports_astc_3d(instance, phd),
894            );
895        }
896
897        if let (Some(ref f16_i8), Some(ref bit16)) = (self.shader_float16_int8, self._16bit_storage)
898        {
899            // Note `storage_input_output16` is not required, we polyfill `f16` I/O using `f32`
900            // types when this capability is not available
901            features.set(
902                F::SHADER_F16,
903                f16_i8.shader_float16 != 0
904                    && bit16.storage_buffer16_bit_access != 0
905                    && bit16.uniform_and_storage_buffer16_bit_access != 0,
906            );
907        }
908
909        if let Some(ref subgroup) = caps.subgroup {
910            if (caps.device_api_version >= vk::API_VERSION_1_3
911                || caps.supports_extension(ext::subgroup_size_control::NAME))
912                && subgroup.supported_operations.contains(
913                    vk::SubgroupFeatureFlags::BASIC
914                        | vk::SubgroupFeatureFlags::VOTE
915                        | vk::SubgroupFeatureFlags::ARITHMETIC
916                        | vk::SubgroupFeatureFlags::BALLOT
917                        | vk::SubgroupFeatureFlags::SHUFFLE
918                        | vk::SubgroupFeatureFlags::SHUFFLE_RELATIVE
919                        | vk::SubgroupFeatureFlags::QUAD,
920                )
921            {
922                features.set(
923                    F::SUBGROUP,
924                    subgroup
925                        .supported_stages
926                        .contains(vk::ShaderStageFlags::COMPUTE | vk::ShaderStageFlags::FRAGMENT),
927                );
928                features.set(
929                    F::SUBGROUP_VERTEX,
930                    subgroup
931                        .supported_stages
932                        .contains(vk::ShaderStageFlags::VERTEX),
933                );
934                features.insert(F::SUBGROUP_BARRIER);
935            }
936        }
937
938        let supports_depth_format = |format| {
939            supports_format(
940                instance,
941                phd,
942                format,
943                vk::ImageTiling::OPTIMAL,
944                depth_stencil_required_flags(),
945            )
946        };
947
948        let texture_s8 = supports_depth_format(vk::Format::S8_UINT);
949        let texture_d32 = supports_depth_format(vk::Format::D32_SFLOAT);
950        let texture_d24_s8 = supports_depth_format(vk::Format::D24_UNORM_S8_UINT);
951        let texture_d32_s8 = supports_depth_format(vk::Format::D32_SFLOAT_S8_UINT);
952
953        let stencil8 = texture_s8 || texture_d24_s8;
954        let depth24_plus_stencil8 = texture_d24_s8 || texture_d32_s8;
955
956        dl_flags.set(
957            Df::WEBGPU_TEXTURE_FORMAT_SUPPORT,
958            stencil8 && depth24_plus_stencil8 && texture_d32,
959        );
960
961        features.set(F::DEPTH32FLOAT_STENCIL8, texture_d32_s8);
962
963        let supports_acceleration_structures = caps
964            .supports_extension(khr::deferred_host_operations::NAME)
965            && caps.supports_extension(khr::acceleration_structure::NAME)
966            && caps.supports_extension(khr::buffer_device_address::NAME);
967
968        let supports_ray_query =
969            supports_acceleration_structures && caps.supports_extension(khr::ray_query::NAME);
970        let supports_acceleration_structure_binding_array = supports_ray_query
971            && self
972                .acceleration_structure
973                .as_ref()
974                .is_some_and(|features| {
975                    features.descriptor_binding_acceleration_structure_update_after_bind != 0
976                });
977
978        features.set(
979            F::EXPERIMENTAL_RAY_QUERY
980            // Although this doesn't really require ray queries, it does not make sense to be enabled if acceleration structures
981            // aren't enabled.
982                | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS,
983            supports_ray_query,
984        );
985
986        // Binding arrays of TLAS are supported on Vulkan when ray queries are supported.
987        //
988        // Note: this flag is used for shader-side `binding_array<acceleration_structure>` as well as
989        // allowing `BindGroupLayoutEntry::count = Some(...)` for `BindingType::AccelerationStructure`.
990        features.set(
991            F::ACCELERATION_STRUCTURE_BINDING_ARRAY,
992            supports_acceleration_structure_binding_array,
993        );
994
995        if supports_acceleration_structures
996            && caps.supports_extension(khr::ray_tracing_pipeline::NAME)
997        {
998            features.insert(
999                F::EXPERIMENTAL_RAY_TRACING_PIPELINES
1000                        // Same reason as for ray queries.
1001                        | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS,
1002            );
1003        }
1004
1005        let rg11b10ufloat_renderable = supports_format(
1006            instance,
1007            phd,
1008            vk::Format::B10G11R11_UFLOAT_PACK32,
1009            vk::ImageTiling::OPTIMAL,
1010            vk::FormatFeatureFlags::COLOR_ATTACHMENT
1011                | vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND,
1012        );
1013        features.set(F::RG11B10UFLOAT_RENDERABLE, rg11b10ufloat_renderable);
1014
1015        features.set(
1016            F::BGRA8UNORM_STORAGE,
1017            supports_bgra8unorm_storage(instance, phd, caps.device_api_version),
1018        );
1019
1020        features.set(
1021            F::FLOAT32_FILTERABLE,
1022            is_float32_filterable_supported(instance, phd),
1023        );
1024
1025        features.set(
1026            F::FLOAT32_BLENDABLE,
1027            is_float32_blendable_supported(instance, phd),
1028        );
1029
1030        if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion {
1031            features.set(
1032                F::TEXTURE_FORMAT_NV12,
1033                supports_format(
1034                    instance,
1035                    phd,
1036                    vk::Format::G8_B8R8_2PLANE_420_UNORM,
1037                    vk::ImageTiling::OPTIMAL,
1038                    vk::FormatFeatureFlags::SAMPLED_IMAGE
1039                        | vk::FormatFeatureFlags::TRANSFER_SRC
1040                        | vk::FormatFeatureFlags::TRANSFER_DST,
1041                ) && !caps.is_driver(vk::DriverId::MOLTENVK),
1042            );
1043        }
1044
1045        if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion {
1046            features.set(
1047                F::TEXTURE_FORMAT_P010,
1048                supports_format(
1049                    instance,
1050                    phd,
1051                    vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
1052                    vk::ImageTiling::OPTIMAL,
1053                    vk::FormatFeatureFlags::SAMPLED_IMAGE
1054                        | vk::FormatFeatureFlags::TRANSFER_SRC
1055                        | vk::FormatFeatureFlags::TRANSFER_DST,
1056                ) && !caps.is_driver(vk::DriverId::MOLTENVK),
1057            );
1058        }
1059
1060        features.set(
1061            F::VULKAN_GOOGLE_DISPLAY_TIMING,
1062            caps.supports_extension(google::display_timing::NAME),
1063        );
1064
1065        features.set(
1066            F::VULKAN_EXTERNAL_MEMORY_WIN32,
1067            caps.supports_extension(khr::external_memory_win32::NAME),
1068        );
1069        features.set(
1070            F::VULKAN_EXTERNAL_MEMORY_FD,
1071            caps.supports_extension(khr::external_memory_fd::NAME),
1072        );
1073        features.set(
1074            F::VULKAN_EXTERNAL_MEMORY_DMA_BUF,
1075            caps.supports_extension(khr::external_memory_fd::NAME)
1076                && caps.supports_extension(ext::external_memory_dma_buf::NAME)
1077                && caps.supports_extension(ext::image_drm_format_modifier::NAME),
1078        );
1079        features.set(
1080            F::EXPERIMENTAL_MESH_SHADER,
1081            caps.supports_extension(ext::mesh_shader::NAME),
1082        );
1083        features.set(
1084            F::EXPERIMENTAL_MESH_SHADER_POINTS,
1085            caps.supports_extension(ext::mesh_shader::NAME),
1086        );
1087        if let Some(ref mesh_shader) = self.mesh_shader {
1088            features.set(
1089                F::EXPERIMENTAL_MESH_SHADER_MULTIVIEW,
1090                mesh_shader.multiview_mesh_shader != 0,
1091            );
1092        }
1093
1094        // Not supported by default by `VK_KHR_portability_subset`, which we use on apple platforms.
1095        features.set(
1096            F::TEXTURE_COMPONENT_SWIZZLE,
1097            self.portability_subset
1098                .map(|p| p.image_view_format_swizzle == vk::TRUE)
1099                .unwrap_or(true),
1100        );
1101        features.set(
1102            F::MULTISAMPLE_ARRAY,
1103            self.portability_subset
1104                .map(|p| p.multisample_array_image == vk::TRUE)
1105                .unwrap_or(true),
1106        );
1107
1108        // Enable cooperative matrix if any configuration is supported. The SPIR-V
1109        // we emit for it uses `Device`-scope atomics under the Vulkan memory model,
1110        // so the device must also support `vulkanMemoryModelDeviceScope`, otherwise
1111        // those shaders trip `VUID-RuntimeSpirv-vulkanMemoryModel-06265`.
1112        features.set(
1113            F::EXPERIMENTAL_COOPERATIVE_MATRIX,
1114            !caps.cooperative_matrix_properties.is_empty()
1115                && self.vulkan_memory_model.is_some_and(|m| {
1116                    m.vulkan_memory_model == vk::TRUE
1117                        && m.vulkan_memory_model_device_scope == vk::TRUE
1118                }),
1119        );
1120
1121        features.set(
1122            F::SHADER_DRAW_INDEX,
1123            self.shader_draw_parameters
1124                .is_some_and(|a| a.shader_draw_parameters != 0)
1125                || caps.supports_extension(c"VK_KHR_shader_draw_parameters"),
1126        );
1127
1128        (features, dl_flags)
1129    }
1130}
1131
1132/// Vulkan "properties" structures gathered about a physical device.
1133///
1134/// This structure holds the properties of a [`vk::PhysicalDevice`]:
1135/// - the standard Vulkan device properties
1136/// - the `VkExtensionProperties` structs for all available extensions, and
1137/// - the per-extension properties structures for the available extensions that
1138///   `wgpu` cares about.
1139///
1140/// Generally, if you get it from any of these functions, it's stored
1141/// here:
1142/// - `vkEnumerateDeviceExtensionProperties`
1143/// - `vkGetPhysicalDeviceProperties`
1144/// - `vkGetPhysicalDeviceProperties2`
1145///
1146/// This also includes a copy of the device API version, since we can
1147/// use that as a shortcut for searching for an extension, if the
1148/// extension has been promoted to core in the current version.
1149///
1150/// This does not include device features; for those, see
1151/// [`PhysicalDeviceFeatures`].
1152#[derive(Default, Debug)]
1153pub struct PhysicalDeviceProperties {
1154    /// Extensions supported by the `vk::PhysicalDevice`,
1155    /// as returned by `vkEnumerateDeviceExtensionProperties`.
1156    supported_extensions: Vec<vk::ExtensionProperties>,
1157
1158    /// Properties of the `vk::PhysicalDevice`, as returned by
1159    /// `vkGetPhysicalDeviceProperties`.
1160    properties: vk::PhysicalDeviceProperties,
1161
1162    /// Additional `vk::PhysicalDevice` properties from the
1163    /// `VK_KHR_maintenance3` extension, promoted to Vulkan 1.1.
1164    maintenance_3: Option<vk::PhysicalDeviceMaintenance3Properties<'static>>,
1165
1166    /// Additional `vk::PhysicalDevice` properties from the
1167    /// `VK_KHR_maintenance4` extension, promoted to Vulkan 1.3.
1168    maintenance_4: Option<vk::PhysicalDeviceMaintenance4Properties<'static>>,
1169
1170    /// Additional `vk::PhysicalDevice` properties from the
1171    /// `VK_KHR_maintenance5` extension, promoted to Vulkan 1.4.
1172    maintenance_5: Option<vk::PhysicalDeviceMaintenance5PropertiesKHR<'static>>,
1173
1174    /// Additional `vk::PhysicalDevice` properties from the
1175    /// `VK_EXT_descriptor_indexing` extension, promoted to Vulkan 1.2.
1176    descriptor_indexing: Option<vk::PhysicalDeviceDescriptorIndexingPropertiesEXT<'static>>,
1177
1178    /// Additional `vk::PhysicalDevice` properties from the
1179    /// `VK_KHR_acceleration_structure` extension.
1180    acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructurePropertiesKHR<'static>>,
1181
1182    /// Additional `vk::PhysicalDevice` properties from the
1183    /// `VK_KHR_ray_tracing_pipeline` extension.
1184    ray_tracing_pipeline: Option<vk::PhysicalDeviceRayTracingPipelinePropertiesKHR<'static>>,
1185
1186    /// Additional `vk::PhysicalDevice` properties from the
1187    /// `VK_KHR_driver_properties` extension, promoted to Vulkan 1.2.
1188    driver: Option<vk::PhysicalDeviceDriverPropertiesKHR<'static>>,
1189
1190    /// Additional `vk::PhysicalDevice` properties from Vulkan 1.1.
1191    subgroup: Option<vk::PhysicalDeviceSubgroupProperties<'static>>,
1192
1193    /// Additional `vk::PhysicalDevice` properties from the
1194    /// `VK_EXT_subgroup_size_control` extension, promoted to Vulkan 1.3.
1195    subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlProperties<'static>>,
1196
1197    /// Additional `vk::PhysicalDevice` properties from the
1198    /// `VK_EXT_robustness2` extension.
1199    robustness2: Option<vk::PhysicalDeviceRobustness2PropertiesEXT<'static>>,
1200
1201    /// Additional `vk::PhysicalDevice` properties from the
1202    /// `VK_EXT_mesh_shader` extension.
1203    mesh_shader: Option<vk::PhysicalDeviceMeshShaderPropertiesEXT<'static>>,
1204
1205    /// Additional `vk::PhysicalDevice` properties from the
1206    /// `VK_KHR_multiview` extension.
1207    multiview: Option<vk::PhysicalDeviceMultiviewPropertiesKHR<'static>>,
1208
1209    /// `VK_EXT_pci_bus_info` extension.
1210    pci_bus_info: Option<vk::PhysicalDevicePCIBusInfoPropertiesEXT<'static>>,
1211
1212    /// The device API version.
1213    ///
1214    /// Which is the version of Vulkan supported for device-level functionality.
1215    ///
1216    /// It is associated with a `VkPhysicalDevice` and its children.
1217    device_api_version: u32,
1218
1219    /// Supported cooperative matrix configurations.
1220    ///
1221    /// This is determined by querying `vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR`.
1222    cooperative_matrix_properties: Vec<wgt::CooperativeMatrixProperties>,
1223}
1224
1225impl PhysicalDeviceProperties {
1226    pub fn properties(&self) -> vk::PhysicalDeviceProperties {
1227        self.properties
1228    }
1229
1230    pub fn supports_extension(&self, extension: &CStr) -> bool {
1231        self.supported_extensions
1232            .iter()
1233            .any(|ep| ep.extension_name_as_c_str() == Ok(extension))
1234    }
1235
1236    pub fn is_driver(&self, id: vk::DriverId) -> bool {
1237        self.driver.is_some_and(|driver| driver.driver_id == id)
1238    }
1239
1240    /// Map `requested_features` to the list of Vulkan extension strings required to create the logical device.
1241    fn get_required_extensions(&self, requested_features: wgt::Features) -> Vec<&'static CStr> {
1242        let mut extensions = Vec::new();
1243
1244        // Note that quite a few extensions depend on the `VK_KHR_get_physical_device_properties2` instance extension.
1245        // We enable `VK_KHR_get_physical_device_properties2` unconditionally (if available).
1246
1247        // Require `VK_KHR_swapchain`
1248        extensions.push(khr::swapchain::NAME);
1249
1250        if self.device_api_version < vk::API_VERSION_1_1 {
1251            // Require `VK_KHR_maintenance1`
1252            extensions.push(khr::maintenance1::NAME);
1253
1254            // Optional `VK_KHR_maintenance2`
1255            if self.supports_extension(khr::maintenance2::NAME) {
1256                extensions.push(khr::maintenance2::NAME);
1257            }
1258
1259            // Optional `VK_KHR_maintenance3`
1260            if self.supports_extension(khr::maintenance3::NAME) {
1261                extensions.push(khr::maintenance3::NAME);
1262            }
1263
1264            // Require `VK_KHR_storage_buffer_storage_class`
1265            extensions.push(khr::storage_buffer_storage_class::NAME);
1266
1267            // Require `VK_KHR_multiview` if the associated feature was requested
1268            if requested_features.contains(wgt::Features::MULTIVIEW) {
1269                extensions.push(khr::multiview::NAME);
1270            }
1271
1272            // Require `VK_KHR_sampler_ycbcr_conversion` if the associated feature was requested
1273            if requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12) {
1274                extensions.push(khr::sampler_ycbcr_conversion::NAME);
1275            }
1276
1277            // Require `VK_KHR_16bit_storage` if `SHADER_F16` or `SHADER_I16` was requested
1278            if requested_features.intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16)
1279            {
1280                // - Feature `SHADER_F16` also requires `VK_KHR_shader_float16_int8`, but we always
1281                //   require that anyway (if it is available) below.
1282                // - `VK_KHR_16bit_storage` requires `VK_KHR_storage_buffer_storage_class`, however
1283                //   we require that one already.
1284                extensions.push(khr::_16bit_storage::NAME);
1285            }
1286
1287            if requested_features.contains(wgt::Features::SHADER_DRAW_INDEX) {
1288                extensions.push(khr::shader_draw_parameters::NAME);
1289            }
1290        }
1291
1292        if self.device_api_version < vk::API_VERSION_1_2 {
1293            // Optional `VK_KHR_image_format_list`
1294            if self.supports_extension(khr::image_format_list::NAME) {
1295                extensions.push(khr::image_format_list::NAME);
1296            }
1297
1298            // Optional `VK_KHR_driver_properties`
1299            if self.supports_extension(khr::driver_properties::NAME) {
1300                extensions.push(khr::driver_properties::NAME);
1301            }
1302
1303            // Optional `VK_KHR_timeline_semaphore`
1304            if self.supports_extension(khr::timeline_semaphore::NAME) {
1305                extensions.push(khr::timeline_semaphore::NAME);
1306            }
1307
1308            // Require `VK_EXT_descriptor_indexing` if one of the associated features was requested
1309            if requested_features.intersects(INDEXING_FEATURES) {
1310                extensions.push(ext::descriptor_indexing::NAME);
1311            }
1312
1313            // Always require `VK_KHR_shader_float16_int8` if available as it enables
1314            // Int8 optimizations. Also require it even if it's not available but
1315            // requested so that we get a corresponding error message.
1316            if requested_features.contains(wgt::Features::SHADER_F16)
1317                || self.supports_extension(khr::shader_float16_int8::NAME)
1318            {
1319                extensions.push(khr::shader_float16_int8::NAME);
1320            }
1321
1322            if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1323                extensions.push(khr::spirv_1_4::NAME);
1324            }
1325
1326            //extensions.push(khr::sampler_mirror_clamp_to_edge::NAME);
1327            //extensions.push(ext::sampler_filter_minmax::NAME);
1328        }
1329
1330        if self.device_api_version < vk::API_VERSION_1_3 {
1331            // Optional `VK_KHR_maintenance4`
1332            if self.supports_extension(khr::maintenance4::NAME) {
1333                extensions.push(khr::maintenance4::NAME);
1334            }
1335
1336            // Optional `VK_EXT_image_robustness`
1337            if self.supports_extension(ext::image_robustness::NAME) {
1338                extensions.push(ext::image_robustness::NAME);
1339            }
1340
1341            // Require `VK_EXT_subgroup_size_control` if the associated feature was requested
1342            if requested_features.contains(wgt::Features::SUBGROUP) {
1343                extensions.push(ext::subgroup_size_control::NAME);
1344            }
1345
1346            // Optional `VK_KHR_shader_integer_dot_product`
1347            if self.supports_extension(khr::shader_integer_dot_product::NAME) {
1348                extensions.push(khr::shader_integer_dot_product::NAME);
1349            }
1350
1351            // Optional `VK_KHR_dynamic_rendering`.
1352            // Depends on:
1353            // - `VK_KHR_get_physical_device_properties2` or Vulkan 1.1, and `VK_KHR_depth_stencil_resolve`
1354            // - or Vulkan 1.2
1355            //
1356            // We only check Vulkan 1.2 for now, as `VK_KHR_depth_stencil_resolve`
1357            // also depends a bunch of extensions.
1358            if self.device_api_version >= vk::API_VERSION_1_2
1359                && self.supports_extension(khr::dynamic_rendering::NAME)
1360            {
1361                extensions.push(khr::dynamic_rendering::NAME);
1362            }
1363
1364            // Optional `VK_KHR_load_store_op_none`
1365            if self.supports_extension(khr::load_store_op_none::NAME) {
1366                extensions.push(khr::load_store_op_none::NAME);
1367            }
1368
1369            // Optional `VK_QCOM_render_pass_store_ops`
1370            if self.supports_extension(ash::qcom::render_pass_store_ops::NAME) {
1371                extensions.push(ash::qcom::render_pass_store_ops::NAME);
1372            }
1373
1374            // Optional `VK_EXT_load_store_op_none`
1375            if self.supports_extension(ext::load_store_op_none::NAME) {
1376                extensions.push(ext::load_store_op_none::NAME);
1377            }
1378        }
1379
1380        // Optional `VK_KHR_swapchain_mutable_format`
1381        if self.supports_extension(khr::swapchain_mutable_format::NAME) {
1382            extensions.push(khr::swapchain_mutable_format::NAME);
1383        }
1384
1385        // Optional `VK_EXT_robustness2`
1386        if self.supports_extension(ext::robustness2::NAME) {
1387            extensions.push(ext::robustness2::NAME);
1388        }
1389
1390        // Optional `VK_KHR_external_memory_win32`
1391        if self.supports_extension(khr::external_memory_win32::NAME) {
1392            extensions.push(khr::external_memory_win32::NAME);
1393        }
1394
1395        // Optional `VK_KHR_external_memory_fd`
1396        if self.supports_extension(khr::external_memory_fd::NAME) {
1397            extensions.push(khr::external_memory_fd::NAME);
1398        }
1399
1400        // Optional `VK_EXT_external_memory_dma`
1401        if self.supports_extension(ext::external_memory_dma_buf::NAME) {
1402            extensions.push(ext::external_memory_dma_buf::NAME);
1403        }
1404
1405        // Optional `VK_EXT_image_drm_format_modifier`
1406        if self.supports_extension(ext::image_drm_format_modifier::NAME) {
1407            extensions.push(ext::image_drm_format_modifier::NAME);
1408        }
1409
1410        // Optional `VK_EXT_memory_budget`
1411        if self.supports_extension(ext::memory_budget::NAME) {
1412            extensions.push(ext::memory_budget::NAME);
1413        } else {
1414            log::debug!("VK_EXT_memory_budget is not available.")
1415        }
1416
1417        // Require `VK_KHR_draw_indirect_count` if the associated feature was requested
1418        // Even though Vulkan 1.2 has promoted the extension to core, we must require the extension to avoid
1419        // large amounts of spaghetti involved with using PhysicalDeviceVulkan12Features.
1420        if requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT_COUNT) {
1421            extensions.push(khr::draw_indirect_count::NAME);
1422        }
1423
1424        // Require `VK_KHR_deferred_host_operations`, `VK_KHR_acceleration_structure` `VK_KHR_buffer_device_address` (for acceleration structures) if either `EXPERIMENTAL_RAY_QUERY` or `EXPERIMENTAL_RAY_TRACING_PIPELINES` were requested.
1425        if requested_features.intersects(
1426            wgt::Features::EXPERIMENTAL_RAY_QUERY
1427                | wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES,
1428        ) {
1429            extensions.push(khr::deferred_host_operations::NAME);
1430            extensions.push(khr::acceleration_structure::NAME);
1431            extensions.push(khr::buffer_device_address::NAME);
1432        }
1433
1434        // Require `VK_KHR_ray_query` if `EXPERIMENTAL_RAY_QUERY` was requested
1435        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
1436            extensions.push(khr::ray_query::NAME);
1437        }
1438
1439        // Require `VK_KHR_ray_tracing_pipeline` if `EXPERIMENTAL_RAY_TRACING_PIPELINES` was requested
1440        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) {
1441            extensions.push(khr::ray_tracing_pipeline::NAME);
1442        }
1443
1444        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
1445            extensions.push(khr::ray_tracing_position_fetch::NAME)
1446        }
1447
1448        // Require `VK_EXT_conservative_rasterization` if the associated feature was requested
1449        if requested_features.contains(wgt::Features::CONSERVATIVE_RASTERIZATION) {
1450            extensions.push(ext::conservative_rasterization::NAME);
1451        }
1452
1453        // Require `VK_KHR_portability_subset` on macOS/iOS
1454        #[cfg(target_vendor = "apple")]
1455        extensions.push(khr::portability_subset::NAME);
1456
1457        // Require `VK_EXT_texture_compression_astc_hdr` if the associated feature was requested
1458        if requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR) {
1459            extensions.push(ext::texture_compression_astc_hdr::NAME);
1460        }
1461
1462        // Require `VK_KHR_shader_atomic_int64` if the associated feature was requested
1463        if requested_features.intersects(
1464            wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
1465        ) {
1466            extensions.push(khr::shader_atomic_int64::NAME);
1467        }
1468
1469        // Require `VK_EXT_shader_image_atomic_int64` if the associated feature was requested
1470        if requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
1471            extensions.push(ext::shader_image_atomic_int64::NAME);
1472        }
1473
1474        // Require `VK_EXT_shader_atomic_float` if the associated feature was requested
1475        if requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
1476            extensions.push(ext::shader_atomic_float::NAME);
1477        }
1478
1479        // Require VK_GOOGLE_display_timing if the associated feature was requested
1480        if requested_features.contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING) {
1481            extensions.push(google::display_timing::NAME);
1482        }
1483
1484        if requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1485            extensions.push(ext::mesh_shader::NAME);
1486        }
1487
1488        // Require `VK_KHR_fragment_shader_barycentric` if an associated feature was requested
1489        // Vulkan bundles both barycentrics and per-vertex attributes under the same feature.
1490        if requested_features
1491            .intersects(wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX)
1492        {
1493            extensions.push(khr::fragment_shader_barycentric::NAME);
1494        }
1495
1496        // Require `VK_KHR_cooperative_matrix` if the associated feature was requested
1497        if requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX) {
1498            extensions.push(khr::cooperative_matrix::NAME);
1499        }
1500
1501        extensions
1502    }
1503
1504    fn to_wgpu_limits(&self) -> wgt::Limits {
1505        let limits = &self.properties.limits;
1506
1507        // Default is only implemented for tuples up to a certain size.
1508        let (
1509            mut max_task_workgroup_total_count,
1510            mut max_task_workgroups_per_dimension,
1511            mut max_mesh_workgroup_total_count,
1512            mut max_mesh_workgroups_per_dimension,
1513        ) = Default::default();
1514        let (
1515            mut max_task_invocations_per_workgroup,
1516            mut max_task_invocations_per_dimension,
1517            mut max_mesh_invocations_per_workgroup,
1518            mut max_mesh_invocations_per_dimension,
1519            mut max_task_payload_size,
1520            mut max_mesh_output_vertices,
1521            mut max_mesh_output_primitives,
1522            mut max_mesh_output_layers,
1523            mut max_mesh_multiview_view_count,
1524        ) = Default::default();
1525        if let Some(m) = self.mesh_shader {
1526            max_task_workgroup_total_count = m.max_task_work_group_total_count;
1527            max_task_workgroups_per_dimension =
1528                m.max_task_work_group_count.into_iter().min().unwrap();
1529            max_mesh_workgroup_total_count = m.max_mesh_work_group_total_count;
1530            max_mesh_workgroups_per_dimension =
1531                m.max_mesh_work_group_count.into_iter().min().unwrap();
1532            max_task_invocations_per_workgroup = m.max_task_work_group_invocations;
1533            max_task_invocations_per_dimension =
1534                m.max_task_work_group_size.into_iter().min().unwrap();
1535            max_mesh_invocations_per_workgroup = m.max_mesh_work_group_invocations;
1536            max_mesh_invocations_per_dimension =
1537                m.max_mesh_work_group_size.into_iter().min().unwrap();
1538            max_task_payload_size = m.max_task_payload_size;
1539            max_mesh_output_vertices = m.max_mesh_output_vertices;
1540            max_mesh_output_primitives = m.max_mesh_output_primitives;
1541            max_mesh_output_layers = m.max_mesh_output_layers;
1542            max_mesh_multiview_view_count = m.max_mesh_multiview_view_count;
1543        }
1544
1545        let max_memory_allocation_size = self
1546            .maintenance_3
1547            .map(|maintenance_3| maintenance_3.max_memory_allocation_size)
1548            .unwrap_or(u64::MAX);
1549        let max_buffer_size = self
1550            .maintenance_4
1551            .map(|maintenance_4| maintenance_4.max_buffer_size)
1552            .unwrap_or(u64::MAX);
1553        let max_buffer_size = max_buffer_size.min(max_memory_allocation_size);
1554
1555        // Prevent very large buffers on mesa and most android devices, and in all cases
1556        // don't risk confusing JS by exceeding the range of a double.
1557        let is_nvidia = self.properties.vendor_id == crate::auxil::db::nvidia::VENDOR;
1558        let max_buffer_size_cap =
1559            if (cfg!(target_os = "linux") || cfg!(target_os = "android")) && !is_nvidia {
1560                i32::MAX as u64
1561            } else {
1562                1u64 << 52
1563            };
1564
1565        let max_buffer_size = max_buffer_size.min(max_buffer_size_cap);
1566
1567        let mut max_binding_array_elements = 0;
1568        let mut max_sampler_binding_array_elements = 0;
1569        if let Some(ref descriptor_indexing) = self.descriptor_indexing {
1570            max_binding_array_elements = descriptor_indexing
1571                .max_descriptor_set_update_after_bind_sampled_images
1572                .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_images)
1573                .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_buffers)
1574                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_sampled_images)
1575                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_images)
1576                .min(
1577                    descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_buffers,
1578                );
1579
1580            max_sampler_binding_array_elements = descriptor_indexing
1581                .max_descriptor_set_update_after_bind_samplers
1582                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_samplers);
1583        }
1584
1585        const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2;
1586
1587        // When summed, the 3 limits below must be under Vulkan's maxFragmentCombinedOutputResources.
1588        // https://gpuweb.github.io/gpuweb/correspondence/#vulkan-maxFragmentCombinedOutputResources
1589        //
1590        // - maxStorageTexturesPerShaderStage, WebGPU default: 4
1591        // - maxStorageBuffersPerShaderStage, WebGPU default: 8
1592        // - maxColorAttachments, WebGPU default: 8
1593        //
1594        // However, maxFragmentCombinedOutputResources should be ignored on
1595        // intel/nvidia/amd/imgtec since it's not reported correctly.
1596        //
1597        // https://github.com/gpuweb/gpuweb/issues/3631#issuecomment-1498747606
1598        // https://github.com/gpuweb/gpuweb/issues/4018
1599        let mut max_storage_textures_per_shader_stage = limits
1600            .max_per_stage_descriptor_storage_images
1601            .min(limits.max_descriptor_set_storage_images / MAX_SHADER_STAGES_PER_PIPELINE);
1602        let mut max_storage_buffers_per_shader_stage = limits
1603            .max_per_stage_descriptor_storage_buffers
1604            .min(limits.max_descriptor_set_storage_buffers / MAX_SHADER_STAGES_PER_PIPELINE);
1605        let mut max_color_attachments = limits
1606            .max_color_attachments
1607            .min(limits.max_fragment_output_attachments);
1608
1609        let ignore_max_fragment_combined_output_resources_by_device = [
1610            crate::auxil::db::intel::VENDOR,
1611            crate::auxil::db::nvidia::VENDOR,
1612            crate::auxil::db::amd::VENDOR,
1613            crate::auxil::db::imgtec::VENDOR,
1614        ]
1615        .contains(&self.properties.vendor_id);
1616        let ignore_max_fragment_combined_output_resources_by_driver =
1617            self.is_driver(vk::DriverId::MESA_AGXV);
1618        let ignore_max_fragment_combined_output_resources =
1619            ignore_max_fragment_combined_output_resources_by_device
1620                || ignore_max_fragment_combined_output_resources_by_driver;
1621
1622        if !ignore_max_fragment_combined_output_resources {
1623            crate::auxil::cap_limits_to_be_under_the_sum_limit(
1624                [
1625                    &mut max_storage_textures_per_shader_stage,
1626                    &mut max_storage_buffers_per_shader_stage,
1627                    &mut max_color_attachments,
1628                ],
1629                limits.max_fragment_combined_output_resources,
1630            );
1631        }
1632
1633        // When summed, the 5 limits below must be under Vulkan's maxPerStageResources.
1634        //
1635        // - maxUniformBuffersPerShaderStage, WebGPU default: 12
1636        // - maxSampledTexturesPerShaderStage, WebGPU default: 16
1637        // - maxStorageTexturesPerShaderStage, WebGPU default: 4
1638        // - maxStorageBuffersPerShaderStage, WebGPU default: 8
1639        // - maxColorAttachments, WebGPU default: 8
1640        //
1641        // Note: Vulkan's texel buffers and input attachments also count towards
1642        // maxPerStageResources but we don't make use of them.
1643        let mut max_sampled_textures_per_shader_stage = limits
1644            .max_per_stage_descriptor_sampled_images
1645            .min(limits.max_descriptor_set_sampled_images / MAX_SHADER_STAGES_PER_PIPELINE);
1646        let mut max_uniform_buffers_per_shader_stage = limits
1647            .max_per_stage_descriptor_uniform_buffers
1648            .min(limits.max_descriptor_set_uniform_buffers / MAX_SHADER_STAGES_PER_PIPELINE);
1649
1650        crate::auxil::cap_limits_to_be_under_the_sum_limit(
1651            [
1652                &mut max_sampled_textures_per_shader_stage,
1653                &mut max_uniform_buffers_per_shader_stage,
1654                &mut max_storage_textures_per_shader_stage,
1655                &mut max_storage_buffers_per_shader_stage,
1656                &mut max_color_attachments,
1657            ],
1658            limits.max_per_stage_resources,
1659        );
1660
1661        // Acceleration structure limits
1662        let mut max_blas_geometry_count = 0;
1663        let mut max_blas_primitive_count = 0;
1664        let mut max_tlas_instance_count = 0;
1665        let mut max_acceleration_structures_per_shader_stage = 0;
1666        if let Some(properties) = self.acceleration_structure {
1667            max_blas_geometry_count = properties.max_geometry_count as u32;
1668            max_blas_primitive_count = properties.max_primitive_count as u32;
1669            max_tlas_instance_count = properties.max_instance_count as u32;
1670            max_acceleration_structures_per_shader_stage = properties
1671                .max_per_stage_descriptor_acceleration_structures
1672                .min(
1673                    properties.max_descriptor_set_acceleration_structures
1674                        / MAX_SHADER_STAGES_PER_PIPELINE,
1675                );
1676        }
1677
1678        // When summed, the 6 limits below must be under Vulkan's
1679        // maxPerSetDescriptors / MAX_SHADER_STAGES_PER_PIPELINE.
1680        //
1681        // - maxUniformBuffersPerShaderStage, WebGPU default: 12
1682        // - maxSampledTexturesPerShaderStage, WebGPU default: 16
1683        // - maxStorageTexturesPerShaderStage, WebGPU default: 4
1684        // - maxStorageBuffersPerShaderStage, WebGPU default: 8
1685        // - maxSamplersPerShaderStage, WebGPU default: 16
1686        // - maxAccelerationStructuresPerShaderStage, Native only
1687        //
1688        // Note: All Vulkan's descriptor types count towards maxPerSetDescriptors but
1689        // we don't use all of them.
1690        // See https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#interfaces-resources-limits
1691        let max_per_set_descriptors = self
1692            .maintenance_3
1693            .map(|maintenance_3| maintenance_3.max_per_set_descriptors)
1694            // The lowest value seen in reports is 312, use 256 as a safe default.
1695            // https://vulkan.gpuinfo.org/displayextensionproperty.php?extensionname=VK_KHR_maintenance3&extensionproperty=maxPerSetDescriptors&platform=all
1696            // https://vulkan.gpuinfo.org/displaycoreproperty.php?core=1.1&name=maxPerSetDescriptors&platform=all
1697            .unwrap_or(256);
1698
1699        let mut max_samplers_per_shader_stage = limits
1700            .max_per_stage_descriptor_samplers
1701            .min(limits.max_descriptor_set_samplers / MAX_SHADER_STAGES_PER_PIPELINE);
1702
1703        crate::auxil::cap_limits_to_be_under_the_sum_limit(
1704            [
1705                &mut max_sampled_textures_per_shader_stage,
1706                &mut max_uniform_buffers_per_shader_stage,
1707                &mut max_storage_textures_per_shader_stage,
1708                &mut max_storage_buffers_per_shader_stage,
1709                &mut max_samplers_per_shader_stage,
1710                &mut max_acceleration_structures_per_shader_stage,
1711            ],
1712            max_per_set_descriptors / MAX_SHADER_STAGES_PER_PIPELINE,
1713        );
1714
1715        // Use max(default, maxPerSetDescriptors) since the spec requires this
1716        // limit to be at least 1000. This is ok because we already lowered
1717        // all the other relevant per stage limits so their sum is lower
1718        // than maxPerSetDescriptors.
1719        let max_bindings_per_bind_group = 1000.max(max_per_set_descriptors);
1720
1721        // TODO: programmatically determine this, if possible. It's unclear whether we can
1722        // as of https://github.com/gpuweb/gpuweb/issues/2965#issuecomment-1361315447.
1723        //
1724        // In theory some tilers may not support this much. We can't tell however, and
1725        // the driver will throw a DEVICE_REMOVED if it goes too high in usage. This is fine.
1726        let max_color_attachment_bytes_per_sample =
1727            max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST;
1728
1729        let mut max_ray_dispatch_count = 0;
1730        let mut max_ray_recursion_depth = 0;
1731
1732        if let Some(properties) = self.ray_tracing_pipeline {
1733            max_ray_dispatch_count = properties.max_ray_dispatch_invocation_count;
1734            max_ray_recursion_depth = properties.max_ray_recursion_depth;
1735        }
1736
1737        let max_multiview_view_count = self
1738            .multiview
1739            .map(|a| a.max_multiview_view_count.min(32))
1740            .unwrap_or(0);
1741
1742        crate::auxil::adjust_raw_limits(wgt::Limits {
1743            //
1744            // WebGPU LIMITS:
1745            // Based on https://gpuweb.github.io/gpuweb/correspondence/#limits
1746            //
1747            max_texture_dimension_1d: limits.max_image_dimension1_d,
1748            max_texture_dimension_2d: limits
1749                .max_image_dimension2_d
1750                .min(limits.max_image_dimension_cube)
1751                .min(limits.max_framebuffer_width)
1752                .min(limits.max_framebuffer_height),
1753            max_texture_dimension_3d: limits.max_image_dimension3_d,
1754            max_texture_array_layers: limits.max_image_array_layers,
1755            max_bind_groups: limits.max_bound_descriptor_sets,
1756            // No limit.
1757            max_bind_groups_plus_vertex_buffers: u32::MAX,
1758            max_bindings_per_bind_group,
1759            max_dynamic_uniform_buffers_per_pipeline_layout: limits
1760                .max_descriptor_set_uniform_buffers_dynamic,
1761            max_dynamic_storage_buffers_per_pipeline_layout: limits
1762                .max_descriptor_set_storage_buffers_dynamic,
1763            max_samplers_per_shader_stage,
1764            max_sampled_textures_per_shader_stage,
1765            max_storage_textures_per_shader_stage,
1766            max_storage_buffers_per_shader_stage,
1767            max_uniform_buffers_per_shader_stage,
1768            max_vertex_buffers: limits.max_vertex_input_bindings,
1769            max_buffer_size,
1770            max_uniform_buffer_binding_size: limits
1771                .max_uniform_buffer_range
1772                .min(crate::auxil::MAX_I32_BINDING_SIZE)
1773                .into(),
1774            max_storage_buffer_binding_size: limits
1775                .max_storage_buffer_range
1776                .min(crate::auxil::MAX_I32_BINDING_SIZE)
1777                .into(),
1778            min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment as u32,
1779            min_storage_buffer_offset_alignment: limits.min_storage_buffer_offset_alignment as u32,
1780            max_vertex_attributes: limits.max_vertex_input_attributes,
1781            max_vertex_buffer_array_stride: limits.max_vertex_input_binding_stride,
1782            max_inter_stage_shader_variables: limits
1783                .max_vertex_output_components
1784                .min(limits.max_fragment_input_components)
1785                / 4
1786                - 1, // -1 for position
1787            max_color_attachments,
1788            max_color_attachment_bytes_per_sample,
1789            max_compute_workgroup_storage_size: limits.max_compute_shared_memory_size,
1790            max_compute_invocations_per_workgroup: limits.max_compute_work_group_invocations,
1791            max_compute_workgroup_size_x: limits.max_compute_work_group_size[0],
1792            max_compute_workgroup_size_y: limits.max_compute_work_group_size[1],
1793            max_compute_workgroup_size_z: limits.max_compute_work_group_size[2],
1794            max_compute_workgroups_per_dimension: limits.max_compute_work_group_count[0]
1795                .min(limits.max_compute_work_group_count[1])
1796                .min(limits.max_compute_work_group_count[2]),
1797            max_immediate_size: limits.max_push_constants_size,
1798            //
1799            // NATIVE (Non-WebGPU) LIMITS:
1800            //
1801            max_non_sampler_bindings: u32::MAX,
1802
1803            max_binding_array_elements_per_shader_stage: max_binding_array_elements,
1804            max_binding_array_sampler_elements_per_shader_stage: max_sampler_binding_array_elements,
1805            max_binding_array_acceleration_structure_elements_per_shader_stage: if self
1806                .descriptor_indexing
1807                .is_some()
1808            {
1809                max_acceleration_structures_per_shader_stage
1810            } else {
1811                0
1812            },
1813
1814            max_task_workgroup_total_count,
1815            max_task_workgroups_per_dimension,
1816            max_mesh_workgroup_total_count,
1817            max_mesh_workgroups_per_dimension,
1818
1819            max_task_invocations_per_workgroup,
1820            max_task_invocations_per_dimension,
1821
1822            max_mesh_invocations_per_workgroup,
1823            max_mesh_invocations_per_dimension,
1824
1825            max_task_payload_size,
1826            max_mesh_output_vertices,
1827            max_mesh_output_primitives,
1828            max_mesh_output_layers,
1829            max_mesh_multiview_view_count,
1830
1831            max_blas_primitive_count,
1832            max_blas_geometry_count,
1833            max_tlas_instance_count,
1834            max_acceleration_structures_per_shader_stage,
1835            max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX,
1836
1837            max_multiview_view_count,
1838
1839            max_ray_dispatch_count,
1840            max_ray_recursion_depth,
1841        })
1842    }
1843
1844    /// Return a `wgpu_hal::Alignments` structure describing this adapter.
1845    ///
1846    /// The `using_robustness2` argument says how this adapter will implement
1847    /// `wgpu_hal`'s guarantee that shaders can only read the [accessible
1848    /// region][ar] of bindgroup's buffer bindings:
1849    ///
1850    /// - If this adapter will depend on `VK_EXT_robustness2`'s
1851    ///   `robustBufferAccess2` feature to apply bounds checks to shader buffer
1852    ///   access, `using_robustness2` must be `true`.
1853    ///
1854    /// - Otherwise, this adapter must use Naga to inject bounds checks on
1855    ///   buffer accesses, and `using_robustness2` must be `false`.
1856    ///
1857    /// [ar]: ../../struct.BufferBinding.html#accessible-region
1858    fn to_hal_alignments(&self, using_robustness2: bool) -> crate::Alignments {
1859        let limits = &self.properties.limits;
1860        crate::Alignments {
1861            buffer_copy_offset: wgt::BufferSize::new(limits.optimal_buffer_copy_offset_alignment)
1862                .unwrap(),
1863            buffer_copy_pitch: wgt::BufferSize::new(limits.optimal_buffer_copy_row_pitch_alignment)
1864                .unwrap(),
1865            uniform_bounds_check_alignment: {
1866                let alignment = if using_robustness2 {
1867                    self.robustness2
1868                        .unwrap() // if we're using it, we should have its properties
1869                        .robust_uniform_buffer_access_size_alignment
1870                } else {
1871                    // If the `robustness2` properties are unavailable, then `robustness2` is not available either Naga-injected bounds checks are precise.
1872                    1
1873                };
1874                wgt::BufferSize::new(alignment).unwrap()
1875            },
1876            raw_tlas_instance_size: 64,
1877            ray_tracing_scratch_buffer_alignment: self.acceleration_structure.map_or(
1878                0,
1879                |acceleration_structure| {
1880                    acceleration_structure.min_acceleration_structure_scratch_offset_alignment
1881                },
1882            ),
1883            ray_tracing_pipeline_group_data_size: self
1884                .ray_tracing_pipeline
1885                .map_or(0, |ray_tracing_pipeline| {
1886                    ray_tracing_pipeline.shader_group_handle_size
1887                }),
1888            ray_tracing_pipeline_group_data_alignment: self
1889                .ray_tracing_pipeline
1890                .map_or(0, |ray_tracing_pipeline| {
1891                    ray_tracing_pipeline.shader_group_handle_alignment
1892                }),
1893            ray_tracing_pipeline_data_offset_alignment: self
1894                .ray_tracing_pipeline
1895                .map_or(0, |ray_tracing_pipeline| {
1896                    ray_tracing_pipeline.shader_group_base_alignment
1897                }),
1898        }
1899    }
1900}
1901
1902impl super::InstanceShared {
1903    fn inspect(
1904        &self,
1905        phd: vk::PhysicalDevice,
1906    ) -> (PhysicalDeviceProperties, PhysicalDeviceFeatures) {
1907        let capabilities = {
1908            let mut capabilities = PhysicalDeviceProperties::default();
1909            capabilities.supported_extensions =
1910                unsafe { self.raw.enumerate_device_extension_properties(phd).unwrap() };
1911            capabilities.properties = unsafe { self.raw.get_physical_device_properties(phd) };
1912            capabilities.device_api_version = capabilities.properties.api_version;
1913
1914            let supports_multiview = capabilities.device_api_version >= vk::API_VERSION_1_1
1915                || capabilities.supports_extension(khr::multiview::NAME);
1916
1917            if let Some(ref get_device_properties) = self.get_physical_device_properties {
1918                // Get these now to avoid borrowing conflicts later
1919                let supports_maintenance3 = capabilities.device_api_version >= vk::API_VERSION_1_1
1920                    || capabilities.supports_extension(khr::maintenance3::NAME);
1921                let supports_maintenance4 = capabilities.device_api_version >= vk::API_VERSION_1_3
1922                    || capabilities.supports_extension(khr::maintenance4::NAME);
1923                let supports_maintenance5 = capabilities.device_api_version
1924                    >= vk::make_api_version(0, 1, 4, 0) // TODO: Use `vk::API_VERSION_1_4` after `ash` is updated.
1925                    || capabilities.supports_extension(khr::maintenance5::NAME);
1926                let supports_descriptor_indexing = capabilities.device_api_version
1927                    >= vk::API_VERSION_1_2
1928                    || capabilities.supports_extension(ext::descriptor_indexing::NAME);
1929                let supports_driver_properties = capabilities.device_api_version
1930                    >= vk::API_VERSION_1_2
1931                    || capabilities.supports_extension(khr::driver_properties::NAME);
1932                let supports_subgroup_size_control = capabilities.device_api_version
1933                    >= vk::API_VERSION_1_3
1934                    || capabilities.supports_extension(ext::subgroup_size_control::NAME);
1935                let supports_robustness2 = capabilities.supports_extension(ext::robustness2::NAME);
1936                let supports_pci_bus_info =
1937                    capabilities.supports_extension(ext::pci_bus_info::NAME);
1938
1939                let supports_acceleration_structure =
1940                    capabilities.supports_extension(khr::acceleration_structure::NAME);
1941
1942                let supports_ray_tracing_pipeline =
1943                    capabilities.supports_extension(khr::ray_tracing_pipeline::NAME);
1944
1945                let supports_mesh_shader = capabilities.supports_extension(ext::mesh_shader::NAME);
1946
1947                let mut properties2 = vk::PhysicalDeviceProperties2KHR::default();
1948                if supports_maintenance3 {
1949                    let next = capabilities
1950                        .maintenance_3
1951                        .insert(vk::PhysicalDeviceMaintenance3Properties::default());
1952                    properties2 = properties2.push_next(next);
1953                }
1954
1955                if supports_maintenance4 {
1956                    let next = capabilities
1957                        .maintenance_4
1958                        .insert(vk::PhysicalDeviceMaintenance4Properties::default());
1959                    properties2 = properties2.push_next(next);
1960                }
1961
1962                if supports_maintenance5 {
1963                    let next = capabilities
1964                        .maintenance_5
1965                        .insert(vk::PhysicalDeviceMaintenance5PropertiesKHR::default());
1966                    properties2 = properties2.push_next(next);
1967                }
1968
1969                if supports_descriptor_indexing {
1970                    let next = capabilities
1971                        .descriptor_indexing
1972                        .insert(vk::PhysicalDeviceDescriptorIndexingPropertiesEXT::default());
1973                    properties2 = properties2.push_next(next);
1974                }
1975
1976                if supports_acceleration_structure {
1977                    let next = capabilities
1978                        .acceleration_structure
1979                        .insert(vk::PhysicalDeviceAccelerationStructurePropertiesKHR::default());
1980                    properties2 = properties2.push_next(next);
1981                }
1982
1983                if supports_ray_tracing_pipeline {
1984                    let next = capabilities
1985                        .ray_tracing_pipeline
1986                        .insert(vk::PhysicalDeviceRayTracingPipelinePropertiesKHR::default());
1987                    properties2 = properties2.push_next(next);
1988                }
1989
1990                if supports_driver_properties {
1991                    let next = capabilities
1992                        .driver
1993                        .insert(vk::PhysicalDeviceDriverPropertiesKHR::default());
1994                    properties2 = properties2.push_next(next);
1995                }
1996
1997                if capabilities.device_api_version >= vk::API_VERSION_1_1 {
1998                    let next = capabilities
1999                        .subgroup
2000                        .insert(vk::PhysicalDeviceSubgroupProperties::default());
2001                    properties2 = properties2.push_next(next);
2002                }
2003
2004                if supports_subgroup_size_control {
2005                    let next = capabilities
2006                        .subgroup_size_control
2007                        .insert(vk::PhysicalDeviceSubgroupSizeControlProperties::default());
2008                    properties2 = properties2.push_next(next);
2009                }
2010
2011                if supports_robustness2 {
2012                    let next = capabilities
2013                        .robustness2
2014                        .insert(vk::PhysicalDeviceRobustness2PropertiesEXT::default());
2015                    properties2 = properties2.push_next(next);
2016                }
2017
2018                if supports_pci_bus_info {
2019                    let next = capabilities
2020                        .pci_bus_info
2021                        .insert(vk::PhysicalDevicePCIBusInfoPropertiesEXT::default());
2022                    properties2 = properties2.push_next(next);
2023                }
2024
2025                if supports_mesh_shader {
2026                    let next = capabilities
2027                        .mesh_shader
2028                        .insert(vk::PhysicalDeviceMeshShaderPropertiesEXT::default());
2029                    properties2 = properties2.push_next(next);
2030                }
2031
2032                if supports_multiview {
2033                    let next = capabilities
2034                        .multiview
2035                        .insert(vk::PhysicalDeviceMultiviewProperties::default());
2036                    properties2 = properties2.push_next(next);
2037                }
2038
2039                unsafe {
2040                    get_device_properties.get_physical_device_properties2(phd, &mut properties2)
2041                };
2042
2043                // Query cooperative matrix properties
2044                if capabilities.supports_extension(khr::cooperative_matrix::NAME) {
2045                    let coop_matrix =
2046                        khr::cooperative_matrix::Instance::new(&self.entry, &self.raw);
2047                    capabilities.cooperative_matrix_properties =
2048                        query_cooperative_matrix_properties(&coop_matrix, phd);
2049                }
2050
2051                // Suppress some capabilities to avoid known problems
2052                if is_intel_igpu_outdated_for_robustness2(&capabilities) {
2053                    capabilities
2054                        .supported_extensions
2055                        .retain(|&x| x.extension_name_as_c_str() != Ok(ext::robustness2::NAME));
2056                    capabilities.robustness2 = None;
2057                }
2058
2059                // Due to https://gitlab.freedesktop.org/mesa/mesa/-/work_items/15725
2060                // TODO(https://github.com/gfx-rs/wgpu/issues/9742): enable on
2061                // fixed driver versions, when available
2062                if capabilities.is_driver(vk::DriverId::MESA_RADV) {
2063                    capabilities
2064                        .supported_extensions
2065                        .retain(|&x| x.extension_name_as_c_str() != Ok(ext::memory_budget::NAME));
2066                }
2067            };
2068            capabilities
2069        };
2070
2071        let mut features = PhysicalDeviceFeatures::default();
2072        features.core = if let Some(ref get_device_properties) = self.get_physical_device_properties
2073        {
2074            let core = vk::PhysicalDeviceFeatures::default();
2075            let mut features2 = vk::PhysicalDeviceFeatures2KHR::default().features(core);
2076
2077            // `VK_KHR_multiview` is promoted to 1.1
2078            if capabilities.device_api_version >= vk::API_VERSION_1_1
2079                || capabilities.supports_extension(khr::multiview::NAME)
2080            {
2081                let next = features
2082                    .multiview
2083                    .insert(vk::PhysicalDeviceMultiviewFeatures::default());
2084                features2 = features2.push_next(next);
2085            }
2086
2087            // `VK_KHR_sampler_ycbcr_conversion` is promoted to 1.1
2088            if capabilities.device_api_version >= vk::API_VERSION_1_1
2089                || capabilities.supports_extension(khr::sampler_ycbcr_conversion::NAME)
2090            {
2091                let next = features
2092                    .sampler_ycbcr_conversion
2093                    .insert(vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default());
2094                features2 = features2.push_next(next);
2095            }
2096
2097            if capabilities.supports_extension(ext::descriptor_indexing::NAME) {
2098                let next = features
2099                    .descriptor_indexing
2100                    .insert(vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default());
2101                features2 = features2.push_next(next);
2102            }
2103
2104            // `VK_KHR_timeline_semaphore` is promoted to 1.2, but has no
2105            // changes, so we can keep using the extension unconditionally.
2106            if capabilities.supports_extension(khr::timeline_semaphore::NAME) {
2107                let next = features
2108                    .timeline_semaphore
2109                    .insert(vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default());
2110                features2 = features2.push_next(next);
2111            }
2112
2113            // `VK_KHR_shader_atomic_int64` is promoted to 1.2, but has no
2114            // changes, so we can keep using the extension unconditionally.
2115            if capabilities.device_api_version >= vk::API_VERSION_1_2
2116                || capabilities.supports_extension(khr::shader_atomic_int64::NAME)
2117            {
2118                let next = features
2119                    .shader_atomic_int64
2120                    .insert(vk::PhysicalDeviceShaderAtomicInt64Features::default());
2121                features2 = features2.push_next(next);
2122            }
2123
2124            if capabilities.supports_extension(ext::shader_image_atomic_int64::NAME) {
2125                let next = features
2126                    .shader_image_atomic_int64
2127                    .insert(vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default());
2128                features2 = features2.push_next(next);
2129            }
2130            if capabilities.supports_extension(ext::shader_atomic_float::NAME) {
2131                let next = features
2132                    .shader_atomic_float
2133                    .insert(vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default());
2134                features2 = features2.push_next(next);
2135            }
2136            if capabilities.supports_extension(ext::image_robustness::NAME) {
2137                let next = features
2138                    .image_robustness
2139                    .insert(vk::PhysicalDeviceImageRobustnessFeaturesEXT::default());
2140                features2 = features2.push_next(next);
2141            }
2142            if capabilities.supports_extension(ext::robustness2::NAME) {
2143                let next = features
2144                    .robustness2
2145                    .insert(vk::PhysicalDeviceRobustness2FeaturesEXT::default());
2146                features2 = features2.push_next(next);
2147            }
2148            if capabilities.supports_extension(ext::texture_compression_astc_hdr::NAME) {
2149                let next = features
2150                    .astc_hdr
2151                    .insert(vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default());
2152                features2 = features2.push_next(next);
2153            }
2154
2155            // `VK_KHR_shader_float16_int8` is promoted to 1.2
2156            if capabilities.device_api_version >= vk::API_VERSION_1_2
2157                || capabilities.supports_extension(khr::shader_float16_int8::NAME)
2158            {
2159                let next = features
2160                    .shader_float16_int8
2161                    .insert(vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR::default());
2162                features2 = features2.push_next(next);
2163            }
2164
2165            if capabilities.supports_extension(khr::_16bit_storage::NAME) {
2166                let next = features
2167                    ._16bit_storage
2168                    .insert(vk::PhysicalDevice16BitStorageFeaturesKHR::default());
2169                features2 = features2.push_next(next);
2170            }
2171            if capabilities.supports_extension(khr::acceleration_structure::NAME) {
2172                let next = features
2173                    .acceleration_structure
2174                    .insert(vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default());
2175                features2 = features2.push_next(next);
2176            }
2177
2178            if capabilities.supports_extension(khr::ray_tracing_position_fetch::NAME) {
2179                let next = features
2180                    .position_fetch
2181                    .insert(vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default());
2182                features2 = features2.push_next(next);
2183            }
2184
2185            // `VK_KHR_maintenance4` is promoted to 1.3
2186            if capabilities.device_api_version >= vk::API_VERSION_1_3
2187                || capabilities.supports_extension(khr::maintenance4::NAME)
2188            {
2189                let next = features
2190                    .maintenance4
2191                    .insert(vk::PhysicalDeviceMaintenance4Features::default());
2192                features2 = features2.push_next(next);
2193            }
2194
2195            // `VK_KHR_zero_initialize_workgroup_memory` is promoted to 1.3
2196            if capabilities.device_api_version >= vk::API_VERSION_1_3
2197                || capabilities.supports_extension(khr::zero_initialize_workgroup_memory::NAME)
2198            {
2199                let next = features
2200                    .zero_initialize_workgroup_memory
2201                    .insert(vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default());
2202                features2 = features2.push_next(next);
2203            }
2204
2205            // `VK_EXT_subgroup_size_control` is promoted to 1.3
2206            if capabilities.device_api_version >= vk::API_VERSION_1_3
2207                || capabilities.supports_extension(ext::subgroup_size_control::NAME)
2208            {
2209                let next = features
2210                    .subgroup_size_control
2211                    .insert(vk::PhysicalDeviceSubgroupSizeControlFeatures::default());
2212                features2 = features2.push_next(next);
2213            }
2214
2215            if capabilities.supports_extension(ext::mesh_shader::NAME) {
2216                let next = features
2217                    .mesh_shader
2218                    .insert(vk::PhysicalDeviceMeshShaderFeaturesEXT::default());
2219                features2 = features2.push_next(next);
2220            }
2221
2222            // `VK_KHR_shader_integer_dot_product` is promoted to 1.3
2223            if capabilities.device_api_version >= vk::API_VERSION_1_3
2224                || capabilities.supports_extension(khr::shader_integer_dot_product::NAME)
2225            {
2226                let next = features
2227                    .shader_integer_dot_product
2228                    .insert(vk::PhysicalDeviceShaderIntegerDotProductFeatures::default());
2229                features2 = features2.push_next(next);
2230            }
2231
2232            if capabilities.supports_extension(khr::fragment_shader_barycentric::NAME) {
2233                let next = features
2234                    .shader_barycentrics
2235                    .insert(vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default());
2236                features2 = features2.push_next(next);
2237            }
2238
2239            if capabilities.supports_extension(khr::portability_subset::NAME) {
2240                let next = features
2241                    .portability_subset
2242                    .insert(vk::PhysicalDevicePortabilitySubsetFeaturesKHR::default());
2243                features2 = features2.push_next(next);
2244            }
2245
2246            if capabilities.supports_extension(khr::cooperative_matrix::NAME) {
2247                let next = features
2248                    .cooperative_matrix
2249                    .insert(vk::PhysicalDeviceCooperativeMatrixFeaturesKHR::default());
2250                features2 = features2.push_next(next);
2251            }
2252
2253            if capabilities.device_api_version >= vk::API_VERSION_1_2
2254                || capabilities.supports_extension(khr::vulkan_memory_model::NAME)
2255            {
2256                let next = features
2257                    .vulkan_memory_model
2258                    .insert(vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR::default());
2259                features2 = features2.push_next(next);
2260            }
2261
2262            if capabilities.device_api_version >= vk::API_VERSION_1_1 {
2263                let next = features
2264                    .shader_draw_parameters
2265                    .insert(vk::PhysicalDeviceShaderDrawParametersFeatures::default());
2266                features2 = features2.push_next(next);
2267            }
2268
2269            unsafe { get_device_properties.get_physical_device_features2(phd, &mut features2) };
2270            features2.features
2271        } else {
2272            unsafe { self.raw.get_physical_device_features(phd) }
2273        };
2274
2275        (capabilities, features)
2276    }
2277}
2278
2279impl super::Instance {
2280    pub fn expose_adapter(
2281        &self,
2282        phd: vk::PhysicalDevice,
2283    ) -> Option<crate::ExposedAdapter<super::Api>> {
2284        use crate::auxil::db;
2285
2286        let (phd_capabilities, phd_features) = self.shared.inspect(phd);
2287
2288        let mem_properties = {
2289            profiling::scope!("vkGetPhysicalDeviceMemoryProperties");
2290            unsafe { self.shared.raw.get_physical_device_memory_properties(phd) }
2291        };
2292        let memory_types = &mem_properties.memory_types_as_slice();
2293        let supports_lazily_allocated = memory_types.iter().any(|mem| {
2294            mem.property_flags
2295                .contains(vk::MemoryPropertyFlags::LAZILY_ALLOCATED)
2296        });
2297
2298        let device_type = match phd_capabilities.properties.device_type {
2299            vk::PhysicalDeviceType::OTHER => wgt::DeviceType::Other,
2300            vk::PhysicalDeviceType::INTEGRATED_GPU => wgt::DeviceType::IntegratedGpu,
2301            vk::PhysicalDeviceType::DISCRETE_GPU => wgt::DeviceType::DiscreteGpu,
2302            vk::PhysicalDeviceType::VIRTUAL_GPU => wgt::DeviceType::VirtualGpu,
2303            vk::PhysicalDeviceType::CPU => wgt::DeviceType::Cpu,
2304            _ => wgt::DeviceType::Other,
2305        };
2306        let info = wgt::AdapterInfo {
2307            name: {
2308                phd_capabilities
2309                    .properties
2310                    .device_name_as_c_str()
2311                    .ok()
2312                    .and_then(|name| name.to_str().ok())
2313                    .unwrap_or("?")
2314                    .to_owned()
2315            },
2316            vendor: phd_capabilities.properties.vendor_id,
2317            device: phd_capabilities.properties.device_id,
2318            device_pci_bus_id: phd_capabilities
2319                .pci_bus_info
2320                .filter(|info| info.pci_bus != 0 || info.pci_device != 0)
2321                .map(|info| {
2322                    format!(
2323                        "{:04x}:{:02x}:{:02x}.{}",
2324                        info.pci_domain, info.pci_bus, info.pci_device, info.pci_function
2325                    )
2326                })
2327                .unwrap_or_default(),
2328            driver: {
2329                phd_capabilities
2330                    .driver
2331                    .as_ref()
2332                    .and_then(|driver| driver.driver_name_as_c_str().ok())
2333                    .and_then(|name| name.to_str().ok())
2334                    .unwrap_or("?")
2335                    .to_owned()
2336            },
2337            driver_info: {
2338                phd_capabilities
2339                    .driver
2340                    .as_ref()
2341                    .and_then(|driver| driver.driver_info_as_c_str().ok())
2342                    .and_then(|name| name.to_str().ok())
2343                    .unwrap_or("?")
2344                    .to_owned()
2345            },
2346            subgroup_min_size: phd_capabilities
2347                .subgroup_size_control
2348                .map(|subgroup_size| subgroup_size.min_subgroup_size)
2349                .unwrap_or(wgt::MINIMUM_SUBGROUP_MIN_SIZE),
2350            subgroup_max_size: phd_capabilities
2351                .subgroup_size_control
2352                .map(|subgroup_size| subgroup_size.max_subgroup_size)
2353                .unwrap_or(wgt::MAXIMUM_SUBGROUP_MAX_SIZE),
2354            transient_saves_memory: Some(supports_lazily_allocated),
2355            ..wgt::AdapterInfo::new(device_type, wgt::Backend::Vulkan)
2356        };
2357        let mut workarounds = super::Workarounds::empty();
2358        {
2359            // TODO: only enable for particular devices
2360            workarounds |= super::Workarounds::SEPARATE_ENTRY_POINTS;
2361            workarounds.set(
2362                super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS,
2363                phd_capabilities.properties.vendor_id == db::qualcomm::VENDOR,
2364            );
2365            workarounds.set(
2366                super::Workarounds::FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16,
2367                phd_capabilities.properties.vendor_id == db::nvidia::VENDOR,
2368            );
2369        };
2370
2371        if let Some(driver) = phd_capabilities.driver {
2372            if driver.conformance_version.major == 0 {
2373                if driver.driver_id == vk::DriverId::MOLTENVK {
2374                    log::debug!("Adapter is not Vulkan compliant, but is MoltenVK, continuing");
2375                } else if self
2376                    .shared
2377                    .flags
2378                    .contains(wgt::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER)
2379                {
2380                    log::debug!("Adapter is not Vulkan compliant: {}", info.name);
2381                } else {
2382                    log::debug!(
2383                        "Adapter is not Vulkan compliant, hiding adapter: {}",
2384                        info.name
2385                    );
2386                    return None;
2387                }
2388            }
2389        }
2390        if phd_capabilities.device_api_version == vk::API_VERSION_1_0
2391            && !phd_capabilities.supports_extension(khr::storage_buffer_storage_class::NAME)
2392        {
2393            log::debug!(
2394                "SPIR-V storage buffer class is not supported, hiding adapter: {}",
2395                info.name
2396            );
2397            return None;
2398        }
2399        if !phd_capabilities.supports_extension(khr::maintenance1::NAME)
2400            && phd_capabilities.device_api_version < vk::API_VERSION_1_1
2401        {
2402            log::debug!(
2403                "VK_KHR_maintenance1 is not supported, hiding adapter: {}",
2404                info.name
2405            );
2406            return None;
2407        }
2408
2409        let queue_families = unsafe {
2410            self.shared
2411                .raw
2412                .get_physical_device_queue_family_properties(phd)
2413        };
2414        let queue_family_properties = queue_families.first()?;
2415        let queue_flags = queue_family_properties.queue_flags;
2416        if !queue_flags.contains(vk::QueueFlags::GRAPHICS) {
2417            log::debug!("The first queue only exposes {queue_flags:?}");
2418            return None;
2419        }
2420
2421        let (available_features, mut downlevel_flags) = phd_features.to_wgpu(
2422            &self.shared.raw,
2423            phd,
2424            &phd_capabilities,
2425            queue_family_properties,
2426        );
2427
2428        if phd_capabilities.is_driver(vk::DriverId::MESA_LLVMPIPE) {
2429            // The `F16_IN_F32` instructions do not normally require native `F16` support, but on
2430            // llvmpipe, they do.
2431            downlevel_flags.set(
2432                wgt::DownlevelFlags::SHADER_F16_IN_F32,
2433                available_features.contains(wgt::Features::SHADER_F16),
2434            );
2435        }
2436
2437        downlevel_flags.set(
2438            wgt::DownlevelFlags::TEXTURE_COMPRESSION,
2439            available_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC)
2440                || available_features.contains(
2441                    wgt::Features::TEXTURE_COMPRESSION_ETC2
2442                        | wgt::Features::TEXTURE_COMPRESSION_ASTC,
2443                ),
2444        );
2445
2446        let has_robust_buffer_access2 = phd_features
2447            .robustness2
2448            .as_ref()
2449            .map(|r| r.robust_buffer_access2 == 1)
2450            .unwrap_or_default();
2451
2452        let alignments = phd_capabilities.to_hal_alignments(has_robust_buffer_access2);
2453
2454        let private_caps = super::PrivateCapabilities {
2455            image_view_usage: phd_capabilities.device_api_version >= vk::API_VERSION_1_1
2456                || phd_capabilities.supports_extension(khr::maintenance2::NAME),
2457            timeline_semaphores: match phd_features.timeline_semaphore {
2458                Some(features) => features.timeline_semaphore == vk::TRUE,
2459                None => phd_features
2460                    .timeline_semaphore
2461                    .is_some_and(|ext| ext.timeline_semaphore != 0),
2462            },
2463            texture_d24: supports_format(
2464                &self.shared.raw,
2465                phd,
2466                vk::Format::X8_D24_UNORM_PACK32,
2467                vk::ImageTiling::OPTIMAL,
2468                depth_stencil_required_flags(),
2469            ),
2470            texture_d24_s8: supports_format(
2471                &self.shared.raw,
2472                phd,
2473                vk::Format::D24_UNORM_S8_UINT,
2474                vk::ImageTiling::OPTIMAL,
2475                depth_stencil_required_flags(),
2476            ),
2477            texture_s8: supports_format(
2478                &self.shared.raw,
2479                phd,
2480                vk::Format::S8_UINT,
2481                vk::ImageTiling::OPTIMAL,
2482                depth_stencil_required_flags(),
2483            ),
2484            multi_draw_indirect: phd_features.core.multi_draw_indirect != 0,
2485            max_draw_indirect_count: phd_capabilities.properties.limits.max_draw_indirect_count,
2486            non_coherent_map_mask: phd_capabilities.properties.limits.non_coherent_atom_size - 1,
2487            can_present: true,
2488            //TODO: make configurable
2489            robust_buffer_access: phd_features.core.robust_buffer_access != 0,
2490            robust_image_access: match phd_features.robustness2 {
2491                Some(ref f) => f.robust_image_access2 != 0,
2492                None => phd_features
2493                    .image_robustness
2494                    .is_some_and(|ext| ext.robust_image_access != 0),
2495            },
2496            robust_buffer_access2: has_robust_buffer_access2,
2497            robust_image_access2: phd_features
2498                .robustness2
2499                .as_ref()
2500                .map(|r| r.robust_image_access2 == 1)
2501                .unwrap_or_default(),
2502            zero_initialize_workgroup_memory: phd_features
2503                .zero_initialize_workgroup_memory
2504                .is_some_and(|ext| ext.shader_zero_initialize_workgroup_memory == vk::TRUE),
2505            image_format_list: phd_capabilities.device_api_version >= vk::API_VERSION_1_2
2506                || phd_capabilities.supports_extension(khr::image_format_list::NAME),
2507            maximum_samplers: phd_capabilities
2508                .properties
2509                .limits
2510                .max_sampler_allocation_count,
2511            shader_integer_dot_product: phd_features
2512                .shader_integer_dot_product
2513                .is_some_and(|ext| ext.shader_integer_dot_product != 0),
2514            shader_int8: phd_features
2515                .shader_float16_int8
2516                .is_some_and(|features| features.shader_int8 != 0),
2517            multiview_instance_index_limit: phd_capabilities
2518                .multiview
2519                .map(|a| a.max_multiview_instance_index)
2520                .unwrap_or(0),
2521            scratch_buffer_alignment: alignments.ray_tracing_scratch_buffer_alignment,
2522            depth_stencil_swizzle_one_support: phd_capabilities
2523                .maintenance_5
2524                .map(|maintenance_5| maintenance_5.depth_stencil_swizzle_one_support == vk::TRUE)
2525                .unwrap_or(false),
2526            ray_tracing_pipeline_group_data_size: alignments.ray_tracing_pipeline_group_data_size,
2527            store_op_none: phd_capabilities.device_api_version >= vk::API_VERSION_1_3
2528                || (phd_capabilities.device_api_version >= vk::API_VERSION_1_2
2529                    && phd_capabilities.supports_extension(khr::dynamic_rendering::NAME))
2530                || phd_capabilities.supports_extension(khr::load_store_op_none::NAME)
2531                || phd_capabilities.supports_extension(ash::qcom::render_pass_store_ops::NAME)
2532                || phd_capabilities.supports_extension(ext::load_store_op_none::NAME),
2533        };
2534        let capabilities = crate::Capabilities {
2535            limits: phd_capabilities.to_wgpu_limits(),
2536            alignments,
2537            downlevel: wgt::DownlevelCapabilities {
2538                flags: downlevel_flags,
2539                limits: wgt::DownlevelLimits {},
2540                shader_model: wgt::ShaderModel::Sm5, //TODO?
2541            },
2542            cooperative_matrix_properties: phd_capabilities.cooperative_matrix_properties.clone(),
2543        };
2544
2545        let adapter = super::Adapter {
2546            raw: phd,
2547            instance: Arc::clone(&self.shared),
2548            //queue_families,
2549            known_memory_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL
2550                | vk::MemoryPropertyFlags::HOST_VISIBLE
2551                | vk::MemoryPropertyFlags::HOST_COHERENT
2552                | vk::MemoryPropertyFlags::HOST_CACHED
2553                | vk::MemoryPropertyFlags::LAZILY_ALLOCATED,
2554            phd_capabilities,
2555            phd_features,
2556            downlevel_flags,
2557            private_caps,
2558            workarounds,
2559        };
2560
2561        Some(crate::ExposedAdapter {
2562            adapter,
2563            info,
2564            features: available_features,
2565            capabilities,
2566        })
2567    }
2568}
2569
2570impl super::Adapter {
2571    pub fn raw_physical_device(&self) -> vk::PhysicalDevice {
2572        self.raw
2573    }
2574
2575    pub fn get_physical_device_features(&self) -> &PhysicalDeviceFeatures {
2576        &self.phd_features
2577    }
2578
2579    pub fn physical_device_capabilities(&self) -> &PhysicalDeviceProperties {
2580        &self.phd_capabilities
2581    }
2582
2583    pub fn shared_instance(&self) -> &super::InstanceShared {
2584        &self.instance
2585    }
2586
2587    pub fn required_device_extensions(&self, features: wgt::Features) -> Vec<&'static CStr> {
2588        let (supported_extensions, unsupported_extensions) = self
2589            .phd_capabilities
2590            .get_required_extensions(features)
2591            .iter()
2592            .partition::<Vec<&CStr>, _>(|&&extension| {
2593                self.phd_capabilities.supports_extension(extension)
2594            });
2595
2596        if !unsupported_extensions.is_empty() {
2597            log::debug!("Missing extensions: {unsupported_extensions:?}");
2598        }
2599
2600        log::debug!("Supported extensions: {supported_extensions:?}");
2601        supported_extensions
2602    }
2603
2604    /// Create a `PhysicalDeviceFeatures` for opening a logical device with
2605    /// `features` from this adapter.
2606    ///
2607    /// The given `enabled_extensions` set must include all the extensions
2608    /// selected by [`required_device_extensions`] when passed `features`.
2609    /// Otherwise, the `PhysicalDeviceFeatures` value may not be able to select
2610    /// all the Vulkan features needed to represent `features` and this
2611    /// adapter's characteristics.
2612    ///
2613    /// Typically, you'd simply call `required_device_extensions`, and then pass
2614    /// its return value and the feature set you gave it directly to this
2615    /// function. But it's fine to add more extensions to the list.
2616    ///
2617    /// [`required_device_extensions`]: Self::required_device_extensions
2618    pub fn physical_device_features(
2619        &self,
2620        enabled_extensions: &[&'static CStr],
2621        features: wgt::Features,
2622    ) -> PhysicalDeviceFeatures {
2623        PhysicalDeviceFeatures::from_extensions_and_requested_features(
2624            &self.phd_capabilities,
2625            &self.phd_features,
2626            enabled_extensions,
2627            features,
2628            self.downlevel_flags,
2629            &self.private_caps,
2630        )
2631    }
2632
2633    /// # Safety
2634    ///
2635    /// - `raw_device` must be created from this adapter.
2636    /// - `raw_device` must be created using `family_index`, `enabled_extensions` and `physical_device_features()`
2637    /// - `enabled_extensions` must be a superset of `required_device_extensions()`.
2638    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_device`. If
2639    ///   `drop_callback` is [`Some`], `raw_device` must be valid until the callback is called.
2640    #[allow(clippy::too_many_arguments)]
2641    pub unsafe fn device_from_raw(
2642        &self,
2643        raw_device: ash::Device,
2644        drop_callback: Option<crate::DropCallback>,
2645        enabled_extensions: &[&'static CStr],
2646        features: wgt::Features,
2647        limits: &wgt::Limits,
2648        memory_hints: &wgt::MemoryHints,
2649        family_index: u32,
2650        queue_index: u32,
2651    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
2652        let mem_properties = {
2653            profiling::scope!("vkGetPhysicalDeviceMemoryProperties");
2654            unsafe {
2655                self.instance
2656                    .raw
2657                    .get_physical_device_memory_properties(self.raw)
2658            }
2659        };
2660        let queue_flags = unsafe {
2661            self.instance
2662                .raw
2663                .get_physical_device_queue_family_properties(self.raw)
2664                .get(family_index as usize)
2665                .map(|queue_family_properties| queue_family_properties.queue_flags)
2666                .ok_or(crate::DeviceError::Unexpected)?
2667        };
2668        let memory_types = &mem_properties.memory_types_as_slice();
2669        let valid_ash_memory_types = memory_types.iter().enumerate().fold(0, |u, (i, mem)| {
2670            if self.known_memory_flags.contains(mem.property_flags) {
2671                u | (1 << i)
2672            } else {
2673                u
2674            }
2675        });
2676
2677        // Note that VK_EXT_debug_utils is an instance extension (enabled at the instance
2678        // level) but contains a few functions that can be loaded directly on the Device for a
2679        // dispatch-table-less pointer.
2680        let debug_utils_fn = if self.instance.extensions.contains(&ext::debug_utils::NAME) {
2681            Some(ext::debug_utils::Device::new(
2682                &self.instance.raw,
2683                &raw_device,
2684            ))
2685        } else {
2686            None
2687        };
2688        let indirect_count_fn = if enabled_extensions.contains(&khr::draw_indirect_count::NAME) {
2689            Some(khr::draw_indirect_count::Device::new(
2690                &self.instance.raw,
2691                &raw_device,
2692            ))
2693        } else {
2694            None
2695        };
2696        let timeline_semaphore_fn = if enabled_extensions.contains(&khr::timeline_semaphore::NAME) {
2697            Some(super::ExtensionFn::Extension(
2698                khr::timeline_semaphore::Device::new(&self.instance.raw, &raw_device),
2699            ))
2700        } else if self.phd_capabilities.device_api_version >= vk::API_VERSION_1_2 {
2701            Some(super::ExtensionFn::Promoted)
2702        } else {
2703            None
2704        };
2705        let ray_tracing_fns = if enabled_extensions.contains(&khr::acceleration_structure::NAME)
2706            && enabled_extensions.contains(&khr::buffer_device_address::NAME)
2707        {
2708            Some(super::RayTracingDeviceExtensionFunctions {
2709                acceleration_structure: khr::acceleration_structure::Device::new(
2710                    &self.instance.raw,
2711                    &raw_device,
2712                ),
2713                buffer_device_address: khr::buffer_device_address::Device::new(
2714                    &self.instance.raw,
2715                    &raw_device,
2716                ),
2717            })
2718        } else {
2719            None
2720        };
2721        let ray_tracing_pipeline_fns =
2722            if enabled_extensions.contains(&khr::ray_tracing_pipeline::NAME) {
2723                Some(khr::ray_tracing_pipeline::Device::new(
2724                    &self.instance.raw,
2725                    &raw_device,
2726                ))
2727            } else {
2728                None
2729            };
2730        let mesh_shading_fns = if enabled_extensions.contains(&ext::mesh_shader::NAME) {
2731            Some(ext::mesh_shader::Device::new(
2732                &self.instance.raw,
2733                &raw_device,
2734            ))
2735        } else {
2736            None
2737        };
2738        let external_memory_fd_fn = if enabled_extensions.contains(&khr::external_memory_fd::NAME) {
2739            Some(khr::external_memory_fd::Device::new(
2740                &self.instance.raw,
2741                &raw_device,
2742            ))
2743        } else {
2744            None
2745        };
2746
2747        let naga_options = {
2748            use naga::back::spv;
2749
2750            // The following capabilities are always available
2751            // see https://registry.khronos.org/vulkan/specs/1.3-extensions/html/chap52.html#spirvenv-capabilities
2752            let mut capabilities = vec![
2753                spv::Capability::Shader,
2754                spv::Capability::Matrix,
2755                spv::Capability::Sampled1D,
2756                spv::Capability::Image1D,
2757                spv::Capability::ImageQuery,
2758                spv::Capability::DerivativeControl,
2759                spv::Capability::StorageImageExtendedFormats,
2760            ];
2761
2762            if self
2763                .downlevel_flags
2764                .contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES)
2765            {
2766                capabilities.push(spv::Capability::SampledCubeArray);
2767            }
2768
2769            if self
2770                .downlevel_flags
2771                .contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING)
2772            {
2773                capabilities.push(spv::Capability::SampleRateShading);
2774            }
2775
2776            if features.contains(wgt::Features::MULTIVIEW) {
2777                capabilities.push(spv::Capability::MultiView);
2778            }
2779
2780            if features.contains(wgt::Features::PRIMITIVE_INDEX) {
2781                capabilities.push(spv::Capability::Geometry);
2782            }
2783
2784            if features.intersects(wgt::Features::SUBGROUP | wgt::Features::SUBGROUP_VERTEX) {
2785                capabilities.push(spv::Capability::GroupNonUniform);
2786                capabilities.push(spv::Capability::GroupNonUniformVote);
2787                capabilities.push(spv::Capability::GroupNonUniformArithmetic);
2788                capabilities.push(spv::Capability::GroupNonUniformBallot);
2789                capabilities.push(spv::Capability::GroupNonUniformShuffle);
2790                capabilities.push(spv::Capability::GroupNonUniformShuffleRelative);
2791                capabilities.push(spv::Capability::GroupNonUniformQuad);
2792            }
2793
2794            if features.intersects(
2795                wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
2796                    | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
2797                    | wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS,
2798            ) {
2799                capabilities.push(spv::Capability::ShaderNonUniform);
2800            }
2801            if features.contains(wgt::Features::BGRA8UNORM_STORAGE) {
2802                capabilities.push(spv::Capability::StorageImageWriteWithoutFormat);
2803            }
2804
2805            if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
2806                capabilities.push(spv::Capability::RayQueryKHR);
2807            }
2808
2809            if features.contains(wgt::Features::SHADER_INT64) {
2810                capabilities.push(spv::Capability::Int64);
2811            }
2812
2813            if features.contains(wgt::Features::SHADER_F16) {
2814                capabilities.push(spv::Capability::Float16);
2815            }
2816
2817            if features.contains(wgt::Features::SHADER_I16) {
2818                capabilities.push(spv::Capability::Int16);
2819            }
2820
2821            if features.intersects(
2822                wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
2823                    | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX
2824                    | wgt::Features::TEXTURE_INT64_ATOMIC,
2825            ) {
2826                capabilities.push(spv::Capability::Int64Atomics);
2827            }
2828
2829            if features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
2830                capabilities.push(spv::Capability::Int64ImageEXT);
2831            }
2832
2833            if features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
2834                capabilities.push(spv::Capability::AtomicFloat32AddEXT);
2835            }
2836
2837            if features.contains(wgt::Features::CLIP_DISTANCES) {
2838                capabilities.push(spv::Capability::ClipDistance);
2839            }
2840
2841            // Vulkan bundles both barycentrics and per-vertex attributes under the same feature.
2842            if features
2843                .intersects(wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX)
2844            {
2845                capabilities.push(spv::Capability::FragmentBarycentricKHR);
2846            }
2847
2848            if features.contains(wgt::Features::SHADER_DRAW_INDEX) {
2849                capabilities.push(spv::Capability::DrawParameters);
2850            }
2851
2852            let mut flags = spv::WriterFlags::empty();
2853            flags.set(
2854                spv::WriterFlags::DEBUG,
2855                self.instance.flags.contains(wgt::InstanceFlags::DEBUG),
2856            );
2857            flags.set(
2858                spv::WriterFlags::LABEL_VARYINGS,
2859                self.phd_capabilities.properties.vendor_id != crate::auxil::db::qualcomm::VENDOR,
2860            );
2861            flags.set(
2862                spv::WriterFlags::FORCE_POINT_SIZE,
2863                //Note: we could technically disable this when we are compiling separate entry points,
2864                // and we know exactly that the primitive topology is not `PointList`.
2865                // But this requires cloning the `spv::Options` struct, which has heap allocations.
2866                true, // could check `super::Workarounds::SEPARATE_ENTRY_POINTS`
2867            );
2868            flags.set(
2869                spv::WriterFlags::PRINT_ON_RAY_QUERY_INITIALIZATION_FAIL
2870                    | spv::WriterFlags::PRINT_ON_TRACE_RAYS_FAIL,
2871                self.instance.flags.contains(wgt::InstanceFlags::DEBUG)
2872                    && (self.instance.instance_api_version >= vk::API_VERSION_1_3
2873                        || enabled_extensions.contains(&khr::shader_non_semantic_info::NAME)),
2874            );
2875            if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
2876                capabilities.push(spv::Capability::RayQueryKHR);
2877            }
2878            if features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) {
2879                capabilities.push(spv::Capability::RayTracingKHR);
2880            }
2881            if features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
2882                capabilities.push(spv::Capability::RayQueryPositionFetchKHR)
2883            }
2884            if features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
2885                capabilities.push(spv::Capability::MeshShadingEXT);
2886            }
2887            if features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX) {
2888                capabilities.push(spv::Capability::CooperativeMatrixKHR);
2889                // TODO: expose this more generally
2890                capabilities.push(spv::Capability::VulkanMemoryModel);
2891            }
2892            if self.private_caps.shader_integer_dot_product {
2893                // See <https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html#_new_spir_v_capabilities>.
2894                capabilities.extend(&[
2895                    spv::Capability::DotProductInputAllKHR,
2896                    spv::Capability::DotProductInput4x8BitKHR,
2897                    spv::Capability::DotProductInput4x8BitPackedKHR,
2898                    spv::Capability::DotProductKHR,
2899                ]);
2900            }
2901            if self.private_caps.shader_int8 {
2902                // See <https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceShaderFloat16Int8Features.html#extension-features-shaderInt8>.
2903                capabilities.extend(&[spv::Capability::Int8]);
2904            }
2905            spv::Options {
2906                lang_version: match self.phd_capabilities.device_api_version {
2907                    // Use maximum supported SPIR-V version according to
2908                    // <https://github.com/KhronosGroup/Vulkan-Docs/blob/19b7651/appendices/spirvenv.adoc?plain=1#L21-L40>.
2909                    vk::API_VERSION_1_0..vk::API_VERSION_1_1 => (1, 0),
2910                    vk::API_VERSION_1_1..vk::API_VERSION_1_2 => (1, 3),
2911                    vk::API_VERSION_1_2..vk::API_VERSION_1_3 => (1, 5),
2912                    vk::API_VERSION_1_3.. => (1, 6),
2913                    _ => unreachable!(),
2914                },
2915                flags,
2916                capabilities: Some(capabilities.iter().cloned().collect()),
2917                bounds_check_policies: naga::proc::BoundsCheckPolicies {
2918                    index: naga::proc::BoundsCheckPolicy::Restrict,
2919                    buffer: if self.private_caps.robust_buffer_access2 {
2920                        naga::proc::BoundsCheckPolicy::Unchecked
2921                    } else {
2922                        naga::proc::BoundsCheckPolicy::Restrict
2923                    },
2924                    image_load: if self.private_caps.robust_image_access {
2925                        naga::proc::BoundsCheckPolicy::Unchecked
2926                    } else {
2927                        naga::proc::BoundsCheckPolicy::Restrict
2928                    },
2929                    // TODO: support bounds checks on binding arrays
2930                    binding_array: naga::proc::BoundsCheckPolicy::Unchecked,
2931                },
2932                zero_initialize_workgroup_memory: if self
2933                    .private_caps
2934                    .zero_initialize_workgroup_memory
2935                {
2936                    spv::ZeroInitializeWorkgroupMemoryMode::Native
2937                } else {
2938                    spv::ZeroInitializeWorkgroupMemoryMode::Polyfill
2939                },
2940                force_loop_bounding: true,
2941                ray_query_initialization_tracking: true,
2942                use_storage_input_output_16: features.contains(wgt::Features::SHADER_F16)
2943                    && self.phd_features.supports_storage_input_output_16(),
2944                fake_missing_bindings: false,
2945                // We need to build this separately for each invocation, so just default it out here
2946                binding_map: BTreeMap::default(),
2947                debug_info: None,
2948                task_dispatch_limits: Some(naga::back::TaskDispatchLimits {
2949                    max_mesh_workgroups_per_dim: limits.max_mesh_workgroups_per_dimension,
2950                    max_mesh_workgroups_total: limits.max_mesh_workgroup_total_count,
2951                }),
2952                mesh_shader_primitive_indices_clamp: true,
2953                trace_ray_argument_validation: true,
2954                emit_int_div_checks: true,
2955            }
2956        };
2957
2958        let raw_queue = {
2959            profiling::scope!("vkGetDeviceQueue");
2960            unsafe { raw_device.get_device_queue(family_index, queue_index) }
2961        };
2962
2963        let driver_version = self
2964            .phd_capabilities
2965            .properties
2966            .driver_version
2967            .to_be_bytes();
2968        #[rustfmt::skip]
2969        let pipeline_cache_validation_key = [
2970            driver_version[0], driver_version[1], driver_version[2], driver_version[3],
2971            0, 0, 0, 0,
2972            0, 0, 0, 0,
2973            0, 0, 0, 0,
2974        ];
2975
2976        let drop_guard = crate::DropGuard::from_option(drop_callback);
2977
2978        let empty_descriptor_set_layout = unsafe {
2979            raw_device
2980                .create_descriptor_set_layout(&vk::DescriptorSetLayoutCreateInfo::default(), None)
2981                .map_err(super::map_host_device_oom_err)?
2982        };
2983
2984        let shared = Arc::new(super::DeviceShared {
2985            raw: raw_device,
2986            family_index,
2987            queue_flags,
2988            queue_index,
2989            raw_queue,
2990            drop_guard,
2991            instance: Arc::clone(&self.instance),
2992            physical_device: self.raw,
2993            enabled_extensions: enabled_extensions.into(),
2994            extension_fns: super::DeviceExtensionFunctions {
2995                debug_utils: debug_utils_fn,
2996                draw_indirect_count: indirect_count_fn,
2997                timeline_semaphore: timeline_semaphore_fn,
2998                ray_tracing: ray_tracing_fns,
2999                ray_tracing_pipelines: ray_tracing_pipeline_fns,
3000                mesh_shading: mesh_shading_fns,
3001                external_memory_fd: external_memory_fd_fn,
3002            },
3003            pipeline_cache_validation_key,
3004            vendor_id: self.phd_capabilities.properties.vendor_id,
3005            timestamp_period: self.phd_capabilities.properties.limits.timestamp_period,
3006            private_caps: self.private_caps.clone(),
3007            features,
3008            workarounds: self.workarounds,
3009            render_passes: Mutex::new(Default::default()),
3010            sampler_cache: Mutex::new(super::sampler::SamplerCache::new(
3011                self.private_caps.maximum_samplers,
3012            )),
3013            memory_allocations_counter: Default::default(),
3014
3015            texture_identity_factory: super::ResourceIdentityFactory::new(),
3016            texture_view_identity_factory: super::ResourceIdentityFactory::new(),
3017            empty_descriptor_set_layout,
3018        });
3019
3020        let relay_semaphores = super::RelaySemaphores::new(&shared)?;
3021
3022        let queue = super::Queue {
3023            raw: raw_queue,
3024            device: Arc::clone(&shared),
3025            family_index,
3026            relay_semaphores: Mutex::new(relay_semaphores),
3027            signal_semaphores: Mutex::new(SemaphoreList::new(SemaphoreListMode::Signal)),
3028            wait_semaphores: Mutex::new(SemaphoreList::new(SemaphoreListMode::Wait)),
3029            next_submit_chain: Mutex::new(None),
3030        };
3031
3032        let allocation_sizes = AllocationSizes::from_memory_hints(memory_hints).into();
3033
3034        let buffer_device_address = enabled_extensions.contains(&khr::buffer_device_address::NAME);
3035
3036        let mem_allocator =
3037            gpu_allocator::vulkan::Allocator::new(&gpu_allocator::vulkan::AllocatorCreateDesc {
3038                instance: self.instance.raw.clone(),
3039                device: shared.raw.clone(),
3040                physical_device: self.raw,
3041                debug_settings: Default::default(),
3042                buffer_device_address,
3043                allocation_sizes,
3044            })?;
3045
3046        let desc_allocator = super::descriptor::DescriptorAllocator::new(
3047            if let Some(di) = self.phd_capabilities.descriptor_indexing {
3048                di.max_update_after_bind_descriptors_in_all_pools
3049            } else {
3050                0
3051            },
3052        );
3053
3054        let device = super::Device {
3055            shared,
3056            mem_allocator: Mutex::new(mem_allocator),
3057            desc_allocator: Mutex::new(desc_allocator),
3058            valid_ash_memory_types,
3059            naga_options,
3060            #[cfg(feature = "renderdoc")]
3061            render_doc: Default::default(),
3062            counters: Default::default(),
3063        };
3064
3065        Ok(crate::OpenDevice { device, queue })
3066    }
3067
3068    pub fn texture_format_as_raw(&self, texture_format: wgt::TextureFormat) -> vk::Format {
3069        self.private_caps.map_texture_format(texture_format)
3070    }
3071
3072    /// # Safety:
3073    /// - Same as `open` plus
3074    /// - The callback may not change anything that the device does not support.
3075    /// - The callback may not remove features.
3076    pub unsafe fn open_with_callback<'a>(
3077        &self,
3078        features: wgt::Features,
3079        limits: &wgt::Limits,
3080        memory_hints: &wgt::MemoryHints,
3081        callback: Option<Box<super::CreateDeviceCallback<'a>>>,
3082    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
3083        let mut enabled_extensions = self.required_device_extensions(features);
3084        let mut enabled_phd_features = self.physical_device_features(&enabled_extensions, features);
3085
3086        let default_family_index = 0;
3087        let mut family_infos = vec![vk::DeviceQueueCreateInfo::default()
3088            .queue_family_index(default_family_index)
3089            .queue_priorities(&[1.0])];
3090
3091        let mut pre_info = vk::DeviceCreateInfo::default();
3092
3093        if let Some(callback) = callback {
3094            callback(super::CreateDeviceCallbackArgs {
3095                extensions: &mut enabled_extensions,
3096                device_features: &mut enabled_phd_features,
3097                queue_create_infos: &mut family_infos,
3098                create_info: &mut pre_info,
3099                _phantom: PhantomData,
3100            })
3101        }
3102
3103        let str_pointers = enabled_extensions
3104            .iter()
3105            .map(|&s| {
3106                // Safe because `enabled_extensions` entries have static lifetime.
3107                s.as_ptr()
3108            })
3109            .collect::<Vec<_>>();
3110
3111        let pre_info = pre_info
3112            .queue_create_infos(&family_infos)
3113            .enabled_extension_names(&str_pointers);
3114        let info = enabled_phd_features.add_to_device_create(pre_info);
3115        let raw_device = {
3116            profiling::scope!("vkCreateDevice");
3117            unsafe {
3118                self.instance
3119                    .raw
3120                    .create_device(self.raw, &info, None)
3121                    .map_err(map_err)?
3122            }
3123        };
3124        fn map_err(err: vk::Result) -> crate::DeviceError {
3125            match err {
3126                vk::Result::ERROR_TOO_MANY_OBJECTS => crate::DeviceError::OutOfMemory,
3127                vk::Result::ERROR_INITIALIZATION_FAILED => crate::DeviceError::Lost,
3128                vk::Result::ERROR_EXTENSION_NOT_PRESENT | vk::Result::ERROR_FEATURE_NOT_PRESENT => {
3129                    crate::hal_usage_error(err)
3130                }
3131                other => super::map_host_device_oom_and_lost_err(other),
3132            }
3133        }
3134
3135        unsafe {
3136            self.device_from_raw(
3137                raw_device,
3138                None,
3139                &enabled_extensions,
3140                features,
3141                limits,
3142                memory_hints,
3143                family_infos[0].queue_family_index,
3144                0,
3145            )
3146        }
3147    }
3148}
3149
3150impl crate::Adapter for super::Adapter {
3151    type A = super::Api;
3152
3153    unsafe fn open(
3154        &self,
3155        features: wgt::Features,
3156        limits: &wgt::Limits,
3157        memory_hints: &wgt::MemoryHints,
3158    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
3159        unsafe { self.open_with_callback(features, limits, memory_hints, None) }
3160    }
3161
3162    unsafe fn texture_format_capabilities(
3163        &self,
3164        format: wgt::TextureFormat,
3165    ) -> crate::TextureFormatCapabilities {
3166        use crate::TextureFormatCapabilities as Tfc;
3167
3168        let vk_format = self.private_caps.map_texture_format(format);
3169        let properties = unsafe {
3170            self.instance
3171                .raw
3172                .get_physical_device_format_properties(self.raw, vk_format)
3173        };
3174        let features = properties.optimal_tiling_features;
3175
3176        let mut flags = Tfc::empty();
3177        flags.set(
3178            Tfc::SAMPLED,
3179            features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE),
3180        );
3181        flags.set(
3182            Tfc::SAMPLED_LINEAR,
3183            features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR),
3184        );
3185        // flags.set(
3186        //     Tfc::SAMPLED_MINMAX,
3187        //     features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_MINMAX),
3188        // );
3189        flags.set(
3190            Tfc::STORAGE_READ_WRITE
3191                | Tfc::STORAGE_WRITE_ONLY
3192                | Tfc::STORAGE_READ_ONLY
3193                | Tfc::STORAGE_ATOMIC,
3194            features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE),
3195        );
3196        flags.set(
3197            Tfc::STORAGE_ATOMIC,
3198            features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
3199        );
3200        flags.set(
3201            Tfc::COLOR_ATTACHMENT,
3202            features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT),
3203        );
3204        flags.set(
3205            Tfc::COLOR_ATTACHMENT_BLEND,
3206            features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND),
3207        );
3208        flags.set(
3209            Tfc::DEPTH_STENCIL_ATTACHMENT,
3210            features.contains(vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT),
3211        );
3212        flags.set(
3213            Tfc::COPY_SRC,
3214            features.intersects(vk::FormatFeatureFlags::TRANSFER_SRC),
3215        );
3216        flags.set(
3217            Tfc::COPY_DST,
3218            features.intersects(vk::FormatFeatureFlags::TRANSFER_DST),
3219        );
3220        flags.set(
3221            Tfc::STORAGE_ATOMIC,
3222            features.intersects(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
3223        );
3224        // Vulkan is very permissive about MSAA
3225        flags.set(Tfc::MULTISAMPLE_RESOLVE, !format.is_compressed());
3226
3227        // get the supported sample counts
3228        let format_aspect = crate::FormatAspects::from(format);
3229        let limits = self.phd_capabilities.properties.limits;
3230
3231        let sample_flags = if format_aspect.contains(crate::FormatAspects::DEPTH) {
3232            limits
3233                .framebuffer_depth_sample_counts
3234                .min(limits.sampled_image_depth_sample_counts)
3235        } else if format_aspect.contains(crate::FormatAspects::STENCIL) {
3236            limits
3237                .framebuffer_stencil_sample_counts
3238                .min(limits.sampled_image_stencil_sample_counts)
3239        } else {
3240            let first_aspect = format_aspect
3241                .iter()
3242                .next()
3243                .expect("All texture should at least one aspect")
3244                .map();
3245
3246            // We should never get depth or stencil out of this, due to the above.
3247            assert_ne!(first_aspect, wgt::TextureAspect::DepthOnly);
3248            assert_ne!(first_aspect, wgt::TextureAspect::StencilOnly);
3249
3250            match format.sample_type(Some(first_aspect), None).unwrap() {
3251                wgt::TextureSampleType::Float { .. } => limits
3252                    .framebuffer_color_sample_counts
3253                    .min(limits.sampled_image_color_sample_counts),
3254                wgt::TextureSampleType::Sint | wgt::TextureSampleType::Uint => {
3255                    limits.sampled_image_integer_sample_counts
3256                }
3257                _ => unreachable!(),
3258            }
3259        };
3260
3261        flags.set(
3262            Tfc::MULTISAMPLE_X2,
3263            sample_flags.contains(vk::SampleCountFlags::TYPE_2),
3264        );
3265        flags.set(
3266            Tfc::MULTISAMPLE_X4,
3267            sample_flags.contains(vk::SampleCountFlags::TYPE_4),
3268        );
3269        flags.set(
3270            Tfc::MULTISAMPLE_X8,
3271            sample_flags.contains(vk::SampleCountFlags::TYPE_8),
3272        );
3273        flags.set(
3274            Tfc::MULTISAMPLE_X16,
3275            sample_flags.contains(vk::SampleCountFlags::TYPE_16),
3276        );
3277
3278        flags
3279    }
3280
3281    unsafe fn surface_capabilities(
3282        &self,
3283        surface: &super::Surface,
3284    ) -> Option<crate::SurfaceCapabilities> {
3285        surface.inner.surface_capabilities(self)
3286    }
3287
3288    unsafe fn surface_display_hdr_info(
3289        &self,
3290        surface: &super::Surface,
3291    ) -> Option<wgt::DisplayHdrInfo> {
3292        // Vulkan has no portable luminance query; the Win32 surface reads it
3293        // through DXGI (see `dxgi::hdr`). Every other surface reports `None`.
3294        surface.inner.display_hdr_info()
3295    }
3296
3297    unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
3298        // VK_GOOGLE_display_timing is the only way to get presentation
3299        // timestamps on vulkan right now and it is only ever available
3300        // on android and linux. This includes mac, but there's no alternative
3301        // on mac, so this is fine.
3302        #[cfg(unix)]
3303        {
3304            let mut timespec = libc::timespec::default();
3305            unsafe {
3306                libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut timespec);
3307            }
3308
3309            wgt::PresentationTimestamp(
3310                timespec.tv_sec as u128 * 1_000_000_000 + timespec.tv_nsec as u128,
3311            )
3312        }
3313        #[cfg(not(unix))]
3314        {
3315            wgt::PresentationTimestamp::INVALID_TIMESTAMP
3316        }
3317    }
3318
3319    fn get_ordered_buffer_usages(&self) -> wgt::BufferUses {
3320        wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE
3321    }
3322
3323    // Vulkan makes very few execution ordering guarantees
3324    // see https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#synchronization-implicit
3325    // We just don't want to insert barriers between inclusive uses
3326    // See https://github.com/gfx-rs/wgpu/issues/8853
3327    fn get_ordered_texture_usages(&self) -> wgt::TextureUses {
3328        wgt::TextureUses::INCLUSIVE
3329    }
3330}
3331
3332fn is_format_16bit_norm_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3333    [
3334        vk::Format::R16_UNORM,
3335        vk::Format::R16_SNORM,
3336        vk::Format::R16G16_UNORM,
3337        vk::Format::R16G16_SNORM,
3338        vk::Format::R16G16B16A16_UNORM,
3339        vk::Format::R16G16B16A16_SNORM,
3340    ]
3341    .into_iter()
3342    .all(|format| {
3343        supports_format(
3344            instance,
3345            phd,
3346            format,
3347            vk::ImageTiling::OPTIMAL,
3348            vk::FormatFeatureFlags::SAMPLED_IMAGE
3349                | vk::FormatFeatureFlags::STORAGE_IMAGE
3350                | vk::FormatFeatureFlags::TRANSFER_SRC
3351                | vk::FormatFeatureFlags::TRANSFER_DST,
3352        )
3353    })
3354}
3355
3356fn is_float32_filterable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3357    [
3358        vk::Format::R32_SFLOAT,
3359        vk::Format::R32G32_SFLOAT,
3360        vk::Format::R32G32B32A32_SFLOAT,
3361    ]
3362    .into_iter()
3363    .all(|format| {
3364        supports_format(
3365            instance,
3366            phd,
3367            format,
3368            vk::ImageTiling::OPTIMAL,
3369            vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR,
3370        )
3371    })
3372}
3373
3374fn is_float32_blendable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3375    [
3376        vk::Format::R32_SFLOAT,
3377        vk::Format::R32G32_SFLOAT,
3378        vk::Format::R32G32B32A32_SFLOAT,
3379    ]
3380    .into_iter()
3381    .all(|format| {
3382        supports_format(
3383            instance,
3384            phd,
3385            format,
3386            vk::ImageTiling::OPTIMAL,
3387            vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND,
3388        )
3389    })
3390}
3391
3392fn supports_format(
3393    instance: &ash::Instance,
3394    phd: vk::PhysicalDevice,
3395    format: vk::Format,
3396    tiling: vk::ImageTiling,
3397    features: vk::FormatFeatureFlags,
3398) -> bool {
3399    let properties = unsafe { instance.get_physical_device_format_properties(phd, format) };
3400    match tiling {
3401        vk::ImageTiling::LINEAR => properties.linear_tiling_features.contains(features),
3402        vk::ImageTiling::OPTIMAL => properties.optimal_tiling_features.contains(features),
3403        _ => false,
3404    }
3405}
3406
3407fn supports_astc_3d(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3408    [
3409        vk::Format::ASTC_4X4_UNORM_BLOCK,
3410        vk::Format::ASTC_4X4_SRGB_BLOCK,
3411        vk::Format::ASTC_5X4_UNORM_BLOCK,
3412        vk::Format::ASTC_5X4_SRGB_BLOCK,
3413        vk::Format::ASTC_5X5_UNORM_BLOCK,
3414        vk::Format::ASTC_5X5_SRGB_BLOCK,
3415        vk::Format::ASTC_6X5_UNORM_BLOCK,
3416        vk::Format::ASTC_6X5_SRGB_BLOCK,
3417        vk::Format::ASTC_6X6_UNORM_BLOCK,
3418        vk::Format::ASTC_6X6_SRGB_BLOCK,
3419        vk::Format::ASTC_8X5_UNORM_BLOCK,
3420        vk::Format::ASTC_8X5_SRGB_BLOCK,
3421        vk::Format::ASTC_8X6_UNORM_BLOCK,
3422        vk::Format::ASTC_8X6_SRGB_BLOCK,
3423        vk::Format::ASTC_8X8_UNORM_BLOCK,
3424        vk::Format::ASTC_8X8_SRGB_BLOCK,
3425        vk::Format::ASTC_10X5_UNORM_BLOCK,
3426        vk::Format::ASTC_10X5_SRGB_BLOCK,
3427        vk::Format::ASTC_10X6_UNORM_BLOCK,
3428        vk::Format::ASTC_10X6_SRGB_BLOCK,
3429        vk::Format::ASTC_10X8_UNORM_BLOCK,
3430        vk::Format::ASTC_10X8_SRGB_BLOCK,
3431        vk::Format::ASTC_10X10_UNORM_BLOCK,
3432        vk::Format::ASTC_10X10_SRGB_BLOCK,
3433        vk::Format::ASTC_12X10_UNORM_BLOCK,
3434        vk::Format::ASTC_12X10_SRGB_BLOCK,
3435        vk::Format::ASTC_12X12_UNORM_BLOCK,
3436        vk::Format::ASTC_12X12_SRGB_BLOCK,
3437    ]
3438    .into_iter()
3439    .all(|format| {
3440        unsafe {
3441            instance.get_physical_device_image_format_properties(
3442                phd,
3443                format,
3444                vk::ImageType::TYPE_3D,
3445                vk::ImageTiling::OPTIMAL,
3446                vk::ImageUsageFlags::SAMPLED,
3447                vk::ImageCreateFlags::empty(),
3448            )
3449        }
3450        .is_ok()
3451    })
3452}
3453
3454fn supports_bgra8unorm_storage(
3455    instance: &ash::Instance,
3456    phd: vk::PhysicalDevice,
3457    device_api_version: u32,
3458) -> bool {
3459    // See https://github.com/KhronosGroup/Vulkan-Docs/issues/2027#issuecomment-1380608011
3460
3461    // This check gates the function call and structures used below.
3462    // TODO: check for (`VK_KHR_get_physical_device_properties2` or VK1.1) and (`VK_KHR_format_feature_flags2` or VK1.3).
3463    // Right now we only check for VK1.3.
3464    if device_api_version < vk::API_VERSION_1_3 {
3465        return false;
3466    }
3467
3468    unsafe {
3469        let mut properties3 = vk::FormatProperties3::default();
3470        let mut properties2 = vk::FormatProperties2::default().push_next(&mut properties3);
3471
3472        instance.get_physical_device_format_properties2(
3473            phd,
3474            vk::Format::B8G8R8A8_UNORM,
3475            &mut properties2,
3476        );
3477
3478        let features2 = properties2.format_properties.optimal_tiling_features;
3479        let features3 = properties3.optimal_tiling_features;
3480
3481        features2.contains(vk::FormatFeatureFlags::STORAGE_IMAGE)
3482            && features3.contains(vk::FormatFeatureFlags2::STORAGE_WRITE_WITHOUT_FORMAT)
3483    }
3484}
3485
3486// For https://github.com/gfx-rs/wgpu/issues/4599
3487// Intel iGPUs with outdated drivers can break rendering if `VK_EXT_robustness2` is used.
3488// Driver version 31.0.101.2115 works, but there's probably an earlier functional version.
3489fn is_intel_igpu_outdated_for_robustness2(capabilities: &PhysicalDeviceProperties) -> bool {
3490    const DRIVER_VERSION_WORKING: u32 = (101 << 14) | 2115; // X.X.101.2115
3491
3492    let props = &capabilities.properties;
3493
3494    let is_outdated = props.vendor_id == crate::auxil::db::intel::VENDOR
3495        && props.device_type == vk::PhysicalDeviceType::INTEGRATED_GPU
3496        && props.driver_version < DRIVER_VERSION_WORKING
3497        && capabilities.is_driver(vk::DriverId::INTEL_PROPRIETARY_WINDOWS);
3498
3499    if is_outdated {
3500        log::debug!(
3501            "Disabling robustBufferAccess2 and robustImageAccess2: IntegratedGpu Intel Driver is outdated. Found with version 0x{:X}, less than the known good version 0x{:X} (31.0.101.2115)",
3502            props.driver_version,
3503            DRIVER_VERSION_WORKING
3504        );
3505    }
3506    is_outdated
3507}
3508
3509/// Convert Vulkan component type to wgt::CooperativeScalarType.
3510fn map_vk_component_type(ty: vk::ComponentTypeKHR) -> Option<wgt::CooperativeScalarType> {
3511    match ty {
3512        vk::ComponentTypeKHR::FLOAT16 => Some(wgt::CooperativeScalarType::F16),
3513        vk::ComponentTypeKHR::FLOAT32 => Some(wgt::CooperativeScalarType::F32),
3514        vk::ComponentTypeKHR::SINT32 => Some(wgt::CooperativeScalarType::I32),
3515        vk::ComponentTypeKHR::UINT32 => Some(wgt::CooperativeScalarType::U32),
3516        _ => None,
3517    }
3518}
3519
3520/// Convert Vulkan matrix size.
3521fn map_vk_cooperative_size(size: u32) -> Option<u32> {
3522    match size {
3523        8 | 16 => Some(size),
3524        _ => None,
3525    }
3526}
3527
3528/// Query all supported cooperative matrix configurations from Vulkan.
3529fn query_cooperative_matrix_properties(
3530    coop_matrix: &khr::cooperative_matrix::Instance,
3531    phd: vk::PhysicalDevice,
3532) -> Vec<wgt::CooperativeMatrixProperties> {
3533    let vk_properties =
3534        match unsafe { coop_matrix.get_physical_device_cooperative_matrix_properties(phd) } {
3535            Ok(props) => props,
3536            Err(e) => {
3537                log::warn!("Failed to query cooperative matrix properties: {e:?}");
3538                return Vec::new();
3539            }
3540        };
3541
3542    log::debug!(
3543        "Vulkan reports {} cooperative matrix configurations",
3544        vk_properties.len()
3545    );
3546
3547    let mut result = Vec::new();
3548    for prop in &vk_properties {
3549        log::debug!(
3550            "  Vulkan coop matrix: M={} N={} K={} A={:?} B={:?} C={:?} Result={:?} scope={:?} saturating={}",
3551            prop.m_size,
3552            prop.n_size,
3553            prop.k_size,
3554            prop.a_type,
3555            prop.b_type,
3556            prop.c_type,
3557            prop.result_type,
3558            prop.scope,
3559            prop.saturating_accumulation
3560        );
3561
3562        // Only include subgroup-scoped operations (the only scope we support)
3563        if prop.scope != vk::ScopeKHR::SUBGROUP {
3564            log::debug!("    Skipped: scope is not SUBGROUP");
3565            continue;
3566        }
3567
3568        // Map sizes - skip configurations with sizes we don't support
3569        let m_size = match map_vk_cooperative_size(prop.m_size) {
3570            Some(s) => s,
3571            None => {
3572                log::debug!("    Skipped: M size {} not supported", prop.m_size);
3573                continue;
3574            }
3575        };
3576        let n_size = match map_vk_cooperative_size(prop.n_size) {
3577            Some(s) => s,
3578            None => {
3579                log::debug!("    Skipped: N size {} not supported", prop.n_size);
3580                continue;
3581            }
3582        };
3583        let k_size = match map_vk_cooperative_size(prop.k_size) {
3584            Some(s) => s,
3585            None => {
3586                log::debug!("    Skipped: K size {} not supported", prop.k_size);
3587                continue;
3588            }
3589        };
3590
3591        // Map the component types - A and B must match, C and Result must match
3592        let ab_type = match map_vk_component_type(prop.a_type) {
3593            Some(t) if Some(t) == map_vk_component_type(prop.b_type) => t,
3594            _ => {
3595                log::debug!(
3596                    "    Skipped: A/B types {:?}/{:?} not supported or don't match",
3597                    prop.a_type,
3598                    prop.b_type
3599                );
3600                continue;
3601            }
3602        };
3603        let cr_type = match map_vk_component_type(prop.c_type) {
3604            Some(t) if Some(t) == map_vk_component_type(prop.result_type) => t,
3605            _ => {
3606                log::debug!(
3607                    "    Skipped: C/Result types {:?}/{:?} not supported or don't match",
3608                    prop.c_type,
3609                    prop.result_type
3610                );
3611                continue;
3612            }
3613        };
3614
3615        log::debug!("    Accepted!");
3616        result.push(wgt::CooperativeMatrixProperties {
3617            m_size,
3618            n_size,
3619            k_size,
3620            ab_type,
3621            cr_type,
3622            saturating_accumulation: prop.saturating_accumulation != 0,
3623        });
3624    }
3625
3626    log::debug!(
3627        "Found {} cooperative matrix configurations supported by wgpu",
3628        result.len()
3629    );
3630    result
3631}