Debian Codegraph @

third_party/rust/wgpu-hal/src/vulkan/adapter.rs

raw
1 use alloc::{borrow::ToOwned as _, collections::BTreeMap, sync::Arc, vec::Vec};
2 use core::ffi::CStr;
3
4 use ash::{ext, google, khr, vk};
5 use parking_lot::Mutex;
6
7 use super::conv;
8
9 fn depth_stencil_required_flags() -> vk::FormatFeatureFlags {
10 vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT
11 }
12
13 const INDEXING_FEATURES: wgt::Features = wgt::Features::TEXTURE_BINDING_ARRAY
14 .union(wgt::Features::BUFFER_BINDING_ARRAY)
15 .union(wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY)
16 .union(wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING)
17 .union(wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING)
18 .union(wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS)
19 .union(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
20
21 /// Features supported by a [`vk::PhysicalDevice`] and its extensions.
22 ///
23 /// This is used in two phases:
24 ///
25 /// - When enumerating adapters, this represents the features offered by the
26 /// adapter. [`Instance::expose_adapter`] calls `vkGetPhysicalDeviceFeatures2`
27 /// (or `vkGetPhysicalDeviceFeatures` if that is not available) to collect
28 /// this information about the `VkPhysicalDevice` represented by the
29 /// `wgpu_hal::ExposedAdapter`.
30 ///
31 /// - When opening a device, this represents the features we would like to
32 /// enable. At `wgpu_hal::Device` construction time,
33 /// [`PhysicalDeviceFeatures::from_extensions_and_requested_features`]
34 /// constructs an value of this type indicating which Vulkan features to
35 /// enable, based on the `wgpu_types::Features` requested.
36 ///
37 /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
38 #[derive(Debug, Default)]
39 pub struct PhysicalDeviceFeatures {
40 /// Basic Vulkan 1.0 features.
41 core: vk::PhysicalDeviceFeatures,
42
43 /// Features provided by `VK_EXT_descriptor_indexing`, promoted to Vulkan 1.2.
44 pub(super) descriptor_indexing:
45 Option<vk::PhysicalDeviceDescriptorIndexingFeaturesEXT<'static>>,
46
47 /// Features provided by `VK_KHR_timeline_semaphore`, promoted to Vulkan 1.2
48 timeline_semaphore: Option<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR<'static>>,
49
50 /// Features provided by `VK_EXT_image_robustness`, promoted to Vulkan 1.3
51 image_robustness: Option<vk::PhysicalDeviceImageRobustnessFeaturesEXT<'static>>,
52
53 /// Features provided by `VK_EXT_robustness2`.
54 robustness2: Option<vk::PhysicalDeviceRobustness2FeaturesEXT<'static>>,
55
56 /// Features provided by `VK_KHR_multiview`, promoted to Vulkan 1.1.
57 multiview: Option<vk::PhysicalDeviceMultiviewFeaturesKHR<'static>>,
58
59 /// Features provided by `VK_KHR_sampler_ycbcr_conversion`, promoted to Vulkan 1.1.
60 sampler_ycbcr_conversion: Option<vk::PhysicalDeviceSamplerYcbcrConversionFeatures<'static>>,
61
62 /// Features provided by `VK_EXT_texture_compression_astc_hdr`, promoted to Vulkan 1.3.
63 astc_hdr: Option<vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT<'static>>,
64
65 /// Features provided by `VK_KHR_shader_float16_int8` (promoted to Vulkan
66 /// 1.2) and `VK_KHR_16bit_storage` (promoted to Vulkan 1.1). We use these
67 /// features together, or not at all.
68 shader_float16: Option<(
69 vk::PhysicalDeviceShaderFloat16Int8Features<'static>,
70 vk::PhysicalDevice16BitStorageFeatures<'static>,
71 )>,
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_TRACING_ACCELERATION_STRUCTURE`], 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_TRACING_ACCELERATION_STRUCTURE`] is requested.
87 ///
88 /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
89 /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE
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_zero_initialize_workgroup_memory`, promoted
104 /// to Vulkan 1.3.
105 zero_initialize_workgroup_memory:
106 Option<vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures<'static>>,
107 position_fetch: Option<vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR<'static>>,
108
109 /// Features provided by `VK_KHR_shader_atomic_int64`, promoted to Vulkan 1.2.
110 shader_atomic_int64: Option<vk::PhysicalDeviceShaderAtomicInt64Features<'static>>,
111
112 /// Features provided by `VK_EXT_shader_image_atomic_int64`
113 shader_image_atomic_int64: Option<vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT<'static>>,
114
115 /// Features provided by `VK_EXT_shader_atomic_float`.
116 shader_atomic_float: Option<vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT<'static>>,
117
118 /// Features provided by `VK_EXT_subgroup_size_control`, promoted to Vulkan 1.3.
119 subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlFeatures<'static>>,
120
121 /// Features proved by `VK_KHR_maintenance4`, needed for mesh shaders
122 maintenance4: Option<vk::PhysicalDeviceMaintenance4FeaturesKHR<'static>>,
123
124 /// Features proved by `VK_EXT_mesh_shader`
125 mesh_shader: Option<vk::PhysicalDeviceMeshShaderFeaturesEXT<'static>>,
126
127 /// Features provided by `VK_KHR_shader_integer_dot_product`, promoted to Vulkan 1.3.
128 shader_integer_dot_product:
129 Option<vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR<'static>>,
130 }
131
132 impl PhysicalDeviceFeatures {
133 /// Add the members of `self` into `info.enabled_features` and its `p_next` chain.
134 pub fn add_to_device_create<'a>(
135 &'a mut self,
136 mut info: vk::DeviceCreateInfo<'a>,
137 ) -> vk::DeviceCreateInfo<'a> {
138 info = info.enabled_features(&self.core);
139 if let Some(ref mut feature) = self.descriptor_indexing {
140 info = info.push_next(feature);
141 }
142 if let Some(ref mut feature) = self.timeline_semaphore {
143 info = info.push_next(feature);
144 }
145 if let Some(ref mut feature) = self.image_robustness {
146 info = info.push_next(feature);
147 }
148 if let Some(ref mut feature) = self.robustness2 {
149 info = info.push_next(feature);
150 }
151 if let Some(ref mut feature) = self.multiview {
152 info = info.push_next(feature);
153 }
154 if let Some(ref mut feature) = self.astc_hdr {
155 info = info.push_next(feature);
156 }
157 if let Some((ref mut f16_i8_feature, ref mut _16bit_feature)) = self.shader_float16 {
158 info = info.push_next(f16_i8_feature);
159 info = info.push_next(_16bit_feature);
160 }
161 if let Some(ref mut feature) = self.zero_initialize_workgroup_memory {
162 info = info.push_next(feature);
163 }
164 if let Some(ref mut feature) = self.acceleration_structure {
165 info = info.push_next(feature);
166 }
167 if let Some(ref mut feature) = self.buffer_device_address {
168 info = info.push_next(feature);
169 }
170 if let Some(ref mut feature) = self.ray_query {
171 info = info.push_next(feature);
172 }
173 if let Some(ref mut feature) = self.shader_atomic_int64 {
174 info = info.push_next(feature);
175 }
176 if let Some(ref mut feature) = self.position_fetch {
177 info = info.push_next(feature);
178 }
179 if let Some(ref mut feature) = self.shader_image_atomic_int64 {
180 info = info.push_next(feature);
181 }
182 if let Some(ref mut feature) = self.shader_atomic_float {
183 info = info.push_next(feature);
184 }
185 if let Some(ref mut feature) = self.subgroup_size_control {
186 info = info.push_next(feature);
187 }
188 if let Some(ref mut feature) = self.maintenance4 {
189 info = info.push_next(feature);
190 }
191 if let Some(ref mut feature) = self.mesh_shader {
192 info = info.push_next(feature);
193 }
194 if let Some(ref mut feature) = self.shader_integer_dot_product {
195 info = info.push_next(feature);
196 }
197 info
198 }
199
200 /// Create a `PhysicalDeviceFeatures` that can be used to create a logical
201 /// device.
202 ///
203 /// Return a `PhysicalDeviceFeatures` value capturing all the Vulkan
204 /// features needed for the given [`Features`], [`DownlevelFlags`], and
205 /// [`PrivateCapabilities`]. You can use the returned value's
206 /// [`add_to_device_create`] method to configure a
207 /// [`vk::DeviceCreateInfo`] to build a logical device providing those
208 /// features.
209 ///
210 /// To ensure that the returned value is able to select all the Vulkan
211 /// features needed to express `requested_features`, `downlevel_flags`, and
212 /// `private_caps`:
213 ///
214 /// - The given `enabled_extensions` set must include all the extensions
215 /// selected by [`Adapter::required_device_extensions`] when passed
216 /// `features`.
217 ///
218 /// - The given `device_api_version` must be the Vulkan API version of the
219 /// physical device we will use to create the logical device.
220 ///
221 /// [`Features`]: wgt::Features
222 /// [`DownlevelFlags`]: wgt::DownlevelFlags
223 /// [`PrivateCapabilities`]: super::PrivateCapabilities
224 /// [`add_to_device_create`]: PhysicalDeviceFeatures::add_to_device_create
225 /// [`Adapter::required_device_extensions`]: super::Adapter::required_device_extensions
226 fn from_extensions_and_requested_features(
227 phd_capabilities: &PhysicalDeviceProperties,
228 _phd_features: &PhysicalDeviceFeatures,
229 enabled_extensions: &[&'static CStr],
230 requested_features: wgt::Features,
231 downlevel_flags: wgt::DownlevelFlags,
232 private_caps: &super::PrivateCapabilities,
233 ) -> Self {
234 let device_api_version = phd_capabilities.device_api_version;
235 let needs_bindless = requested_features.intersects(
236 wgt::Features::TEXTURE_BINDING_ARRAY
237 | wgt::Features::BUFFER_BINDING_ARRAY
238 | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY
239 | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
240 | wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
241 );
242 let needs_partially_bound =
243 requested_features.intersects(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
244
245 Self {
246 // vk::PhysicalDeviceFeatures is a struct composed of Bool32's while
247 // Features is a bitfield so we need to map everything manually
248 core: vk::PhysicalDeviceFeatures::default()
249 .robust_buffer_access(private_caps.robust_buffer_access)
250 .independent_blend(downlevel_flags.contains(wgt::DownlevelFlags::INDEPENDENT_BLEND))
251 .sample_rate_shading(
252 downlevel_flags.contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING),
253 )
254 .image_cube_array(
255 downlevel_flags.contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES),
256 )
257 .draw_indirect_first_instance(
258 requested_features.contains(wgt::Features::INDIRECT_FIRST_INSTANCE),
259 )
260 //.dual_src_blend(requested_features.contains(wgt::Features::DUAL_SRC_BLENDING))
261 .multi_draw_indirect(
262 requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT),
263 )
264 .fill_mode_non_solid(requested_features.intersects(
265 wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT,
266 ))
267 //.depth_bounds(requested_features.contains(wgt::Features::DEPTH_BOUNDS))
268 //.alpha_to_one(requested_features.contains(wgt::Features::ALPHA_TO_ONE))
269 //.multi_viewport(requested_features.contains(wgt::Features::MULTI_VIEWPORTS))
270 .sampler_anisotropy(
271 downlevel_flags.contains(wgt::DownlevelFlags::ANISOTROPIC_FILTERING),
272 )
273 .texture_compression_etc2(
274 requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ETC2),
275 )
276 .texture_compression_astc_ldr(
277 requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC),
278 )
279 .texture_compression_bc(
280 requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC),
281 // BC provides formats for Sliced 3D
282 )
283 //.occlusion_query_precise(requested_features.contains(wgt::Features::PRECISE_OCCLUSION_QUERY))
284 .pipeline_statistics_query(
285 requested_features.contains(wgt::Features::PIPELINE_STATISTICS_QUERY),
286 )
287 .vertex_pipeline_stores_and_atomics(
288 requested_features.contains(wgt::Features::VERTEX_WRITABLE_STORAGE),
289 )
290 .fragment_stores_and_atomics(
291 downlevel_flags.contains(wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE),
292 )
293 //.shader_image_gather_extended(
294 //.shader_storage_image_extended_formats(
295 .shader_uniform_buffer_array_dynamic_indexing(
296 requested_features.contains(wgt::Features::BUFFER_BINDING_ARRAY),
297 )
298 .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
299 wgt::Features::BUFFER_BINDING_ARRAY
300 | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
301 ))
302 .shader_sampled_image_array_dynamic_indexing(
303 requested_features.contains(wgt::Features::TEXTURE_BINDING_ARRAY),
304 )
305 .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
306 wgt::Features::TEXTURE_BINDING_ARRAY
307 | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
308 ))
309 //.shader_storage_image_array_dynamic_indexing(
310 //.shader_clip_distance(requested_features.contains(wgt::Features::SHADER_CLIP_DISTANCE))
311 //.shader_cull_distance(requested_features.contains(wgt::Features::SHADER_CULL_DISTANCE))
312 .shader_float64(requested_features.contains(wgt::Features::SHADER_F64))
313 .shader_int64(requested_features.contains(wgt::Features::SHADER_INT64))
314 .shader_int16(requested_features.contains(wgt::Features::SHADER_I16))
315 //.shader_resource_residency(requested_features.contains(wgt::Features::SHADER_RESOURCE_RESIDENCY))
316 .geometry_shader(requested_features.contains(wgt::Features::SHADER_PRIMITIVE_INDEX))
317 .depth_clamp(requested_features.contains(wgt::Features::DEPTH_CLIP_CONTROL))
318 .dual_src_blend(requested_features.contains(wgt::Features::DUAL_SOURCE_BLENDING)),
319 descriptor_indexing: if requested_features.intersects(INDEXING_FEATURES) {
320 Some(
321 vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default()
322 .shader_sampled_image_array_non_uniform_indexing(needs_bindless)
323 .shader_storage_image_array_non_uniform_indexing(needs_bindless)
324 .shader_storage_buffer_array_non_uniform_indexing(needs_bindless)
325 .descriptor_binding_sampled_image_update_after_bind(needs_bindless)
326 .descriptor_binding_storage_image_update_after_bind(needs_bindless)
327 .descriptor_binding_storage_buffer_update_after_bind(needs_bindless)
328 .descriptor_binding_partially_bound(needs_partially_bound),
329 )
330 } else {
331 None
332 },
333 timeline_semaphore: if device_api_version >= vk::API_VERSION_1_2
334 || enabled_extensions.contains(&khr::timeline_semaphore::NAME)
335 {
336 Some(
337 vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default()
338 .timeline_semaphore(private_caps.timeline_semaphores),
339 )
340 } else {
341 None
342 },
343 image_robustness: if device_api_version >= vk::API_VERSION_1_3
344 || enabled_extensions.contains(&ext::image_robustness::NAME)
345 {
346 Some(
347 vk::PhysicalDeviceImageRobustnessFeaturesEXT::default()
348 .robust_image_access(private_caps.robust_image_access),
349 )
350 } else {
351 None
352 },
353 robustness2: if enabled_extensions.contains(&ext::robustness2::NAME) {
354 Some(
355 vk::PhysicalDeviceRobustness2FeaturesEXT::default()
356 .robust_buffer_access2(private_caps.robust_buffer_access2)
357 .robust_image_access2(private_caps.robust_image_access2),
358 )
359 } else {
360 None
361 },
362 multiview: if device_api_version >= vk::API_VERSION_1_1
363 || enabled_extensions.contains(&khr::multiview::NAME)
364 {
365 Some(
366 vk::PhysicalDeviceMultiviewFeatures::default()
367 .multiview(requested_features.contains(wgt::Features::MULTIVIEW)),
368 )
369 } else {
370 None
371 },
372 sampler_ycbcr_conversion: if device_api_version >= vk::API_VERSION_1_1
373 || enabled_extensions.contains(&khr::sampler_ycbcr_conversion::NAME)
374 {
375 Some(
376 vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default(), // .sampler_ycbcr_conversion(requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12))
377 )
378 } else {
379 None
380 },
381 astc_hdr: if enabled_extensions.contains(&ext::texture_compression_astc_hdr::NAME) {
382 Some(
383 vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default()
384 .texture_compression_astc_hdr(true),
385 )
386 } else {
387 None
388 },
389 shader_float16: if requested_features.contains(wgt::Features::SHADER_F16) {
390 Some((
391 vk::PhysicalDeviceShaderFloat16Int8Features::default().shader_float16(true),
392 vk::PhysicalDevice16BitStorageFeatures::default()
393 .storage_buffer16_bit_access(true)
394 .storage_input_output16(true)
395 .uniform_and_storage_buffer16_bit_access(true),
396 ))
397 } else {
398 None
399 },
400 acceleration_structure: if enabled_extensions
401 .contains(&khr::acceleration_structure::NAME)
402 {
403 Some(
404 vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default()
405 .acceleration_structure(true),
406 )
407 } else {
408 None
409 },
410 buffer_device_address: if enabled_extensions.contains(&khr::buffer_device_address::NAME)
411 {
412 Some(
413 vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR::default()
414 .buffer_device_address(true),
415 )
416 } else {
417 None
418 },
419 ray_query: if enabled_extensions.contains(&khr::ray_query::NAME) {
420 Some(vk::PhysicalDeviceRayQueryFeaturesKHR::default().ray_query(true))
421 } else {
422 None
423 },
424 zero_initialize_workgroup_memory: if device_api_version >= vk::API_VERSION_1_3
425 || enabled_extensions.contains(&khr::zero_initialize_workgroup_memory::NAME)
426 {
427 Some(
428 vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default()
429 .shader_zero_initialize_workgroup_memory(
430 private_caps.zero_initialize_workgroup_memory,
431 ),
432 )
433 } else {
434 None
435 },
436 shader_atomic_int64: if device_api_version >= vk::API_VERSION_1_2
437 || enabled_extensions.contains(&khr::shader_atomic_int64::NAME)
438 {
439 let needed = requested_features.intersects(
440 wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
441 | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
442 );
443 Some(
444 vk::PhysicalDeviceShaderAtomicInt64Features::default()
445 .shader_buffer_int64_atomics(needed)
446 .shader_shared_int64_atomics(needed),
447 )
448 } else {
449 None
450 },
451 shader_image_atomic_int64: if enabled_extensions
452 .contains(&ext::shader_image_atomic_int64::NAME)
453 {
454 let needed = requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC);
455 Some(
456 vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default()
457 .shader_image_int64_atomics(needed),
458 )
459 } else {
460 None
461 },
462 shader_atomic_float: if enabled_extensions.contains(&ext::shader_atomic_float::NAME) {
463 let needed = requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC);
464 Some(
465 vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default()
466 .shader_buffer_float32_atomics(needed)
467 .shader_buffer_float32_atomic_add(needed),
468 )
469 } else {
470 None
471 },
472 subgroup_size_control: if device_api_version >= vk::API_VERSION_1_3
473 || enabled_extensions.contains(&ext::subgroup_size_control::NAME)
474 {
475 Some(
476 vk::PhysicalDeviceSubgroupSizeControlFeatures::default()
477 .subgroup_size_control(true),
478 )
479 } else {
480 None
481 },
482 position_fetch: if enabled_extensions.contains(&khr::ray_tracing_position_fetch::NAME) {
483 Some(
484 vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default()
485 .ray_tracing_position_fetch(true),
486 )
487 } else {
488 None
489 },
490 mesh_shader: if enabled_extensions.contains(&ext::mesh_shader::NAME) {
491 let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
492 let multiview_needed =
493 requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW);
494 Some(
495 vk::PhysicalDeviceMeshShaderFeaturesEXT::default()
496 .mesh_shader(needed)
497 .task_shader(needed)
498 .multiview_mesh_shader(multiview_needed),
499 )
500 } else {
501 None
502 },
503 maintenance4: if enabled_extensions.contains(&khr::maintenance4::NAME) {
504 let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
505 Some(vk::PhysicalDeviceMaintenance4FeaturesKHR::default().maintenance4(needed))
506 } else {
507 None
508 },
509 shader_integer_dot_product: if device_api_version >= vk::API_VERSION_1_3
510 || enabled_extensions.contains(&khr::shader_integer_dot_product::NAME)
511 {
512 Some(
513 vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR::default()
514 .shader_integer_dot_product(private_caps.shader_integer_dot_product),
515 )
516 } else {
517 None
518 },
519 }
520 }
521
522 /// Compute the wgpu [`Features`] and [`DownlevelFlags`] supported by a physical device.
523 ///
524 /// Given `self`, together with the instance and physical device it was
525 /// built from, and a `caps` also built from those, determine which wgpu
526 /// features and downlevel flags the device can support.
527 ///
528 /// [`Features`]: wgt::Features
529 /// [`DownlevelFlags`]: wgt::DownlevelFlags
530 fn to_wgpu(
531 &self,
532 instance: &ash::Instance,
533 phd: vk::PhysicalDevice,
534 caps: &PhysicalDeviceProperties,
535 ) -> (wgt::Features, wgt::DownlevelFlags) {
536 use wgt::{DownlevelFlags as Df, Features as F};
537 let mut features = F::empty()
538 | F::SPIRV_SHADER_PASSTHROUGH
539 | F::MAPPABLE_PRIMARY_BUFFERS
540 | F::PUSH_CONSTANTS
541 | F::ADDRESS_MODE_CLAMP_TO_BORDER
542 | F::ADDRESS_MODE_CLAMP_TO_ZERO
543 | F::TIMESTAMP_QUERY
544 | F::TIMESTAMP_QUERY_INSIDE_ENCODERS
545 | F::TIMESTAMP_QUERY_INSIDE_PASSES
546 | F::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
547 | F::CLEAR_TEXTURE
548 | F::PIPELINE_CACHE
549 | F::TEXTURE_ATOMIC;
550
551 let mut dl_flags = Df::COMPUTE_SHADERS
552 | Df::BASE_VERTEX
553 | Df::READ_ONLY_DEPTH_STENCIL
554 | Df::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES
555 | Df::COMPARISON_SAMPLERS
556 | Df::VERTEX_STORAGE
557 | Df::FRAGMENT_STORAGE
558 | Df::DEPTH_TEXTURE_AND_BUFFER_COPIES
559 | Df::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED
560 | Df::UNRESTRICTED_INDEX_BUFFER
561 | Df::INDIRECT_EXECUTION
562 | Df::VIEW_FORMATS
563 | Df::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES
564 | Df::NONBLOCKING_QUERY_RESOLVE;
565
566 dl_flags.set(
567 Df::SURFACE_VIEW_FORMATS,
568 caps.supports_extension(khr::swapchain_mutable_format::NAME),
569 );
570 dl_flags.set(Df::CUBE_ARRAY_TEXTURES, self.core.image_cube_array != 0);
571 dl_flags.set(Df::ANISOTROPIC_FILTERING, self.core.sampler_anisotropy != 0);
572 dl_flags.set(
573 Df::FRAGMENT_WRITABLE_STORAGE,
574 self.core.fragment_stores_and_atomics != 0,
575 );
576 dl_flags.set(Df::MULTISAMPLED_SHADING, self.core.sample_rate_shading != 0);
577 dl_flags.set(Df::INDEPENDENT_BLEND, self.core.independent_blend != 0);
578 dl_flags.set(
579 Df::FULL_DRAW_INDEX_UINT32,
580 self.core.full_draw_index_uint32 != 0,
581 );
582 dl_flags.set(Df::DEPTH_BIAS_CLAMP, self.core.depth_bias_clamp != 0);
583
584 features.set(
585 F::INDIRECT_FIRST_INSTANCE,
586 self.core.draw_indirect_first_instance != 0,
587 );
588 //if self.core.dual_src_blend != 0
589 features.set(F::MULTI_DRAW_INDIRECT, self.core.multi_draw_indirect != 0);
590 features.set(F::POLYGON_MODE_LINE, self.core.fill_mode_non_solid != 0);
591 features.set(F::POLYGON_MODE_POINT, self.core.fill_mode_non_solid != 0);
592 //if self.core.depth_bounds != 0 {
593 //if self.core.alpha_to_one != 0 {
594 //if self.core.multi_viewport != 0 {
595 features.set(
596 F::TEXTURE_COMPRESSION_ETC2,
597 self.core.texture_compression_etc2 != 0,
598 );
599 features.set(
600 F::TEXTURE_COMPRESSION_ASTC,
601 self.core.texture_compression_astc_ldr != 0,
602 );
603 features.set(
604 F::TEXTURE_COMPRESSION_BC,
605 self.core.texture_compression_bc != 0,
606 );
607 features.set(
608 F::TEXTURE_COMPRESSION_BC_SLICED_3D,
609 self.core.texture_compression_bc != 0, // BC guarantees Sliced 3D
610 );
611 features.set(
612 F::PIPELINE_STATISTICS_QUERY,
613 self.core.pipeline_statistics_query != 0,
614 );
615 features.set(
616 F::VERTEX_WRITABLE_STORAGE,
617 self.core.vertex_pipeline_stores_and_atomics != 0,
618 );
619
620 features.set(F::SHADER_F64, self.core.shader_float64 != 0);
621 features.set(F::SHADER_INT64, self.core.shader_int64 != 0);
622 features.set(F::SHADER_I16, self.core.shader_int16 != 0);
623
624 features.set(F::SHADER_PRIMITIVE_INDEX, self.core.geometry_shader != 0);
625
626 if let Some(ref shader_atomic_int64) = self.shader_atomic_int64 {
627 features.set(
628 F::SHADER_INT64_ATOMIC_ALL_OPS | F::SHADER_INT64_ATOMIC_MIN_MAX,
629 shader_atomic_int64.shader_buffer_int64_atomics != 0
630 && shader_atomic_int64.shader_shared_int64_atomics != 0,
631 );
632 }
633
634 if let Some(ref shader_image_atomic_int64) = self.shader_image_atomic_int64 {
635 features.set(
636 F::TEXTURE_INT64_ATOMIC,
637 shader_image_atomic_int64
638 .shader_image_int64_atomics(true)
639 .shader_image_int64_atomics
640 != 0,
641 );
642 }
643
644 if let Some(ref shader_atomic_float) = self.shader_atomic_float {
645 features.set(
646 F::SHADER_FLOAT32_ATOMIC,
647 shader_atomic_float.shader_buffer_float32_atomics != 0
648 && shader_atomic_float.shader_buffer_float32_atomic_add != 0,
649 );
650 }
651
652 //if caps.supports_extension(khr::sampler_mirror_clamp_to_edge::NAME) {
653 //if caps.supports_extension(ext::sampler_filter_minmax::NAME) {
654 features.set(
655 F::MULTI_DRAW_INDIRECT_COUNT,
656 caps.supports_extension(khr::draw_indirect_count::NAME),
657 );
658 features.set(
659 F::CONSERVATIVE_RASTERIZATION,
660 caps.supports_extension(ext::conservative_rasterization::NAME),
661 );
662 features.set(
663 F::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN,
664 caps.supports_extension(khr::ray_tracing_position_fetch::NAME),
665 );
666
667 if let Some(ref descriptor_indexing) = self.descriptor_indexing {
668 // We use update-after-bind descriptors for all bind groups containing binding arrays.
669 //
670 // In those bind groups, we allow all binding types except uniform buffers to be present.
671 //
672 // As we can only switch between update-after-bind and not on a per bind group basis,
673 // all supported binding types need to be able to be marked update after bind.
674 //
675 // As such, we enable all features as a whole, rather individually.
676 let supports_descriptor_indexing =
677 // Sampled Images
678 descriptor_indexing.shader_sampled_image_array_non_uniform_indexing != 0
679 && descriptor_indexing.descriptor_binding_sampled_image_update_after_bind != 0
680 // Storage Images
681 && descriptor_indexing.shader_storage_image_array_non_uniform_indexing != 0
682 && descriptor_indexing.descriptor_binding_storage_image_update_after_bind != 0
683 // Storage Buffers
684 && descriptor_indexing.shader_storage_buffer_array_non_uniform_indexing != 0
685 && descriptor_indexing.descriptor_binding_storage_buffer_update_after_bind != 0;
686
687 let descriptor_indexing_features = F::BUFFER_BINDING_ARRAY
688 | F::TEXTURE_BINDING_ARRAY
689 | F::STORAGE_RESOURCE_BINDING_ARRAY
690 | F::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
691 | F::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING;
692
693 features.set(descriptor_indexing_features, supports_descriptor_indexing);
694
695 let supports_partially_bound =
696 descriptor_indexing.descriptor_binding_partially_bound != 0;
697
698 features.set(F::PARTIALLY_BOUND_BINDING_ARRAY, supports_partially_bound);
699 }
700
701 features.set(F::DEPTH_CLIP_CONTROL, self.core.depth_clamp != 0);
702 features.set(F::DUAL_SOURCE_BLENDING, self.core.dual_src_blend != 0);
703
704 if let Some(ref multiview) = self.multiview {
705 features.set(F::MULTIVIEW, multiview.multiview != 0);
706 }
707
708 features.set(
709 F::TEXTURE_FORMAT_16BIT_NORM,
710 is_format_16bit_norm_supported(instance, phd),
711 );
712
713 if let Some(ref astc_hdr) = self.astc_hdr {
714 features.set(
715 F::TEXTURE_COMPRESSION_ASTC_HDR,
716 astc_hdr.texture_compression_astc_hdr != 0,
717 );
718 }
719
720 if self.core.texture_compression_astc_ldr != 0 {
721 features.set(
722 F::TEXTURE_COMPRESSION_ASTC_SLICED_3D,
723 supports_astc_3d(instance, phd),
724 );
725 }
726
727 if let Some((ref f16_i8, ref bit16)) = self.shader_float16 {
728 features.set(
729 F::SHADER_F16,
730 f16_i8.shader_float16 != 0
731 && bit16.storage_buffer16_bit_access != 0
732 && bit16.uniform_and_storage_buffer16_bit_access != 0
733 && bit16.storage_input_output16 != 0,
734 );
735 }
736
737 if let Some(ref subgroup) = caps.subgroup {
738 if (caps.device_api_version >= vk::API_VERSION_1_3
739 || caps.supports_extension(ext::subgroup_size_control::NAME))
740 && subgroup.supported_operations.contains(
741 vk::SubgroupFeatureFlags::BASIC
742 | vk::SubgroupFeatureFlags::VOTE
743 | vk::SubgroupFeatureFlags::ARITHMETIC
744 | vk::SubgroupFeatureFlags::BALLOT
745 | vk::SubgroupFeatureFlags::SHUFFLE
746 | vk::SubgroupFeatureFlags::SHUFFLE_RELATIVE,
747 )
748 {
749 features.set(
750 F::SUBGROUP,
751 subgroup
752 .supported_stages
753 .contains(vk::ShaderStageFlags::COMPUTE | vk::ShaderStageFlags::FRAGMENT),
754 );
755 features.set(
756 F::SUBGROUP_VERTEX,
757 subgroup
758 .supported_stages
759 .contains(vk::ShaderStageFlags::VERTEX),
760 );
761 features.insert(F::SUBGROUP_BARRIER);
762 }
763 }
764
765 let supports_depth_format = |format| {
766 supports_format(
767 instance,
768 phd,
769 format,
770 vk::ImageTiling::OPTIMAL,
771 depth_stencil_required_flags(),
772 )
773 };
774
775 let texture_s8 = supports_depth_format(vk::Format::S8_UINT);
776 let texture_d32 = supports_depth_format(vk::Format::D32_SFLOAT);
777 let texture_d24_s8 = supports_depth_format(vk::Format::D24_UNORM_S8_UINT);
778 let texture_d32_s8 = supports_depth_format(vk::Format::D32_SFLOAT_S8_UINT);
779
780 let stencil8 = texture_s8 || texture_d24_s8;
781 let depth24_plus_stencil8 = texture_d24_s8 || texture_d32_s8;
782
783 dl_flags.set(
784 Df::WEBGPU_TEXTURE_FORMAT_SUPPORT,
785 stencil8 && depth24_plus_stencil8 && texture_d32,
786 );
787
788 features.set(F::DEPTH32FLOAT_STENCIL8, texture_d32_s8);
789
790 features.set(
791 F::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE,
792 caps.supports_extension(khr::deferred_host_operations::NAME)
793 && caps.supports_extension(khr::acceleration_structure::NAME)
794 && caps.supports_extension(khr::buffer_device_address::NAME),
795 );
796
797 features.set(
798 F::EXPERIMENTAL_RAY_QUERY,
799 caps.supports_extension(khr::ray_query::NAME),
800 );
801
802 let rg11b10ufloat_renderable = supports_format(
803 instance,
804 phd,
805 vk::Format::B10G11R11_UFLOAT_PACK32,
806 vk::ImageTiling::OPTIMAL,
807 vk::FormatFeatureFlags::COLOR_ATTACHMENT
808 | vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND,
809 );
810 features.set(F::RG11B10UFLOAT_RENDERABLE, rg11b10ufloat_renderable);
811
812 features.set(
813 F::BGRA8UNORM_STORAGE,
814 supports_bgra8unorm_storage(instance, phd, caps.device_api_version),
815 );
816
817 features.set(
818 F::FLOAT32_FILTERABLE,
819 is_float32_filterable_supported(instance, phd),
820 );
821
822 if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion {
823 features.set(
824 F::TEXTURE_FORMAT_NV12,
825 supports_format(
826 instance,
827 phd,
828 vk::Format::G8_B8R8_2PLANE_420_UNORM,
829 vk::ImageTiling::OPTIMAL,
830 vk::FormatFeatureFlags::SAMPLED_IMAGE
831 | vk::FormatFeatureFlags::TRANSFER_SRC
832 | vk::FormatFeatureFlags::TRANSFER_DST,
833 ) && !caps
834 .driver
835 .map(|driver| driver.driver_id == vk::DriverId::MOLTENVK)
836 .unwrap_or_default(),
837 );
838 }
839
840 features.set(
841 F::VULKAN_GOOGLE_DISPLAY_TIMING,
842 caps.supports_extension(google::display_timing::NAME),
843 );
844
845 features.set(
846 F::VULKAN_EXTERNAL_MEMORY_WIN32,
847 caps.supports_extension(khr::external_memory_win32::NAME),
848 );
849 features.set(
850 F::EXPERIMENTAL_MESH_SHADER,
851 caps.supports_extension(ext::mesh_shader::NAME),
852 );
853 if let Some(ref mesh_shader) = self.mesh_shader {
854 features.set(
855 F::EXPERIMENTAL_MESH_SHADER_MULTIVIEW,
856 mesh_shader.multiview_mesh_shader != 0,
857 );
858 }
859 (features, dl_flags)
860 }
861 }
862
863 /// Vulkan "properties" structures gathered about a physical device.
864 ///
865 /// This structure holds the properties of a [`vk::PhysicalDevice`]:
866 /// - the standard Vulkan device properties
867 /// - the `VkExtensionProperties` structs for all available extensions, and
868 /// - the per-extension properties structures for the available extensions that
869 /// `wgpu` cares about.
870 ///
871 /// Generally, if you get it from any of these functions, it's stored
872 /// here:
873 /// - `vkEnumerateDeviceExtensionProperties`
874 /// - `vkGetPhysicalDeviceProperties`
875 /// - `vkGetPhysicalDeviceProperties2`
876 ///
877 /// This also includes a copy of the device API version, since we can
878 /// use that as a shortcut for searching for an extension, if the
879 /// extension has been promoted to core in the current version.
880 ///
881 /// This does not include device features; for those, see
882 /// [`PhysicalDeviceFeatures`].
883 #[derive(Default, Debug)]
884 pub struct PhysicalDeviceProperties {
885 /// Extensions supported by the `vk::PhysicalDevice`,
886 /// as returned by `vkEnumerateDeviceExtensionProperties`.
887 supported_extensions: Vec<vk::ExtensionProperties>,
888
889 /// Properties of the `vk::PhysicalDevice`, as returned by
890 /// `vkGetPhysicalDeviceProperties`.
891 properties: vk::PhysicalDeviceProperties,
892
893 /// Additional `vk::PhysicalDevice` properties from the
894 /// `VK_KHR_maintenance3` extension, promoted to Vulkan 1.1.
895 maintenance_3: Option<vk::PhysicalDeviceMaintenance3Properties<'static>>,
896
897 /// Additional `vk::PhysicalDevice` properties from the
898 /// `VK_EXT_descriptor_indexing` extension, promoted to Vulkan 1.2.
899 descriptor_indexing: Option<vk::PhysicalDeviceDescriptorIndexingPropertiesEXT<'static>>,
900
901 /// Additional `vk::PhysicalDevice` properties from the
902 /// `VK_KHR_acceleration_structure` extension.
903 acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructurePropertiesKHR<'static>>,
904
905 /// Additional `vk::PhysicalDevice` properties from the
906 /// `VK_KHR_driver_properties` extension, promoted to Vulkan 1.2.
907 driver: Option<vk::PhysicalDeviceDriverPropertiesKHR<'static>>,
908
909 /// Additional `vk::PhysicalDevice` properties from Vulkan 1.1.
910 subgroup: Option<vk::PhysicalDeviceSubgroupProperties<'static>>,
911
912 /// Additional `vk::PhysicalDevice` properties from the
913 /// `VK_EXT_subgroup_size_control` extension, promoted to Vulkan 1.3.
914 subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlProperties<'static>>,
915
916 /// Additional `vk::PhysicalDevice` properties from the
917 /// `VK_EXT_robustness2` extension.
918 robustness2: Option<vk::PhysicalDeviceRobustness2PropertiesEXT<'static>>,
919
920 /// Additional `vk::PhysicalDevice` properties from the
921 /// `VK_EXT_mesh_shader` extension.
922 _mesh_shader: Option<vk::PhysicalDeviceMeshShaderPropertiesEXT<'static>>,
923
924 /// The device API version.
925 ///
926 /// Which is the version of Vulkan supported for device-level functionality.
927 ///
928 /// It is associated with a `VkPhysicalDevice` and its children.
929 device_api_version: u32,
930 }
931
932 impl PhysicalDeviceProperties {
933 pub fn properties(&self) -> vk::PhysicalDeviceProperties {
934 self.properties
935 }
936
937 pub fn supports_extension(&self, extension: &CStr) -> bool {
938 self.supported_extensions
939 .iter()
940 .any(|ep| ep.extension_name_as_c_str() == Ok(extension))
941 }
942
943 /// Map `requested_features` to the list of Vulkan extension strings required to create the logical device.
944 fn get_required_extensions(&self, requested_features: wgt::Features) -> Vec<&'static CStr> {
945 let mut extensions = Vec::new();
946
947 // Note that quite a few extensions depend on the `VK_KHR_get_physical_device_properties2` instance extension.
948 // We enable `VK_KHR_get_physical_device_properties2` unconditionally (if available).
949
950 // Require `VK_KHR_swapchain`
951 extensions.push(khr::swapchain::NAME);
952
953 if self.device_api_version < vk::API_VERSION_1_1 {
954 // Require `VK_KHR_maintenance1`
955 extensions.push(khr::maintenance1::NAME);
956
957 // Optional `VK_KHR_maintenance2`
958 if self.supports_extension(khr::maintenance2::NAME) {
959 extensions.push(khr::maintenance2::NAME);
960 }
961
962 // Optional `VK_KHR_maintenance3`
963 if self.supports_extension(khr::maintenance3::NAME) {
964 extensions.push(khr::maintenance3::NAME);
965 }
966
967 // Require `VK_KHR_storage_buffer_storage_class`
968 extensions.push(khr::storage_buffer_storage_class::NAME);
969
970 // Require `VK_KHR_multiview` if the associated feature was requested
971 if requested_features.contains(wgt::Features::MULTIVIEW) {
972 extensions.push(khr::multiview::NAME);
973 }
974
975 // Require `VK_KHR_sampler_ycbcr_conversion` if the associated feature was requested
976 if requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12) {
977 extensions.push(khr::sampler_ycbcr_conversion::NAME);
978 }
979 }
980
981 if self.device_api_version < vk::API_VERSION_1_2 {
982 // Optional `VK_KHR_image_format_list`
983 if self.supports_extension(khr::image_format_list::NAME) {
984 extensions.push(khr::image_format_list::NAME);
985 }
986
987 // Optional `VK_KHR_driver_properties`
988 if self.supports_extension(khr::driver_properties::NAME) {
989 extensions.push(khr::driver_properties::NAME);
990 }
991
992 // Optional `VK_KHR_timeline_semaphore`
993 if self.supports_extension(khr::timeline_semaphore::NAME) {
994 extensions.push(khr::timeline_semaphore::NAME);
995 }
996
997 // Require `VK_EXT_descriptor_indexing` if one of the associated features was requested
998 if requested_features.intersects(INDEXING_FEATURES) {
999 extensions.push(ext::descriptor_indexing::NAME);
1000 }
1001
1002 // Require `VK_KHR_shader_float16_int8` and `VK_KHR_16bit_storage` if the associated feature was requested
1003 if requested_features.contains(wgt::Features::SHADER_F16) {
1004 extensions.push(khr::shader_float16_int8::NAME);
1005 // `VK_KHR_16bit_storage` requires `VK_KHR_storage_buffer_storage_class`, however we require that one already
1006 if self.device_api_version < vk::API_VERSION_1_1 {
1007 extensions.push(khr::_16bit_storage::NAME);
1008 }
1009 }
1010
1011 if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1012 extensions.push(khr::spirv_1_4::NAME);
1013 }
1014
1015 //extensions.push(khr::sampler_mirror_clamp_to_edge::NAME);
1016 //extensions.push(ext::sampler_filter_minmax::NAME);
1017 }
1018
1019 if self.device_api_version < vk::API_VERSION_1_3 {
1020 // Optional `VK_EXT_image_robustness`
1021 if self.supports_extension(ext::image_robustness::NAME) {
1022 extensions.push(ext::image_robustness::NAME);
1023 }
1024
1025 // Require `VK_EXT_subgroup_size_control` if the associated feature was requested
1026 if requested_features.contains(wgt::Features::SUBGROUP) {
1027 extensions.push(ext::subgroup_size_control::NAME);
1028 }
1029
1030 if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1031 extensions.push(khr::maintenance4::NAME);
1032 }
1033
1034 // Optional `VK_KHR_shader_integer_dot_product`
1035 if self.supports_extension(khr::shader_integer_dot_product::NAME) {
1036 extensions.push(khr::shader_integer_dot_product::NAME);
1037 }
1038 }
1039
1040 // Optional `VK_KHR_swapchain_mutable_format`
1041 if self.supports_extension(khr::swapchain_mutable_format::NAME) {
1042 extensions.push(khr::swapchain_mutable_format::NAME);
1043 }
1044
1045 // Optional `VK_EXT_robustness2`
1046 if self.supports_extension(ext::robustness2::NAME) {
1047 extensions.push(ext::robustness2::NAME);
1048 }
1049
1050 // Optional `VK_KHR_external_memory_win32`
1051 if self.supports_extension(khr::external_memory_win32::NAME) {
1052 extensions.push(khr::external_memory_win32::NAME);
1053 }
1054
1055 // Optional `VK_KHR_external_memory_fd`
1056 if self.supports_extension(khr::external_memory_fd::NAME) {
1057 extensions.push(khr::external_memory_fd::NAME);
1058 }
1059
1060 // Optional `VK_EXT_external_memory_dma`
1061 if self.supports_extension(ext::external_memory_dma_buf::NAME) {
1062 extensions.push(ext::external_memory_dma_buf::NAME);
1063 }
1064
1065 // Optional `VK_EXT_memory_budget`
1066 if self.supports_extension(ext::memory_budget::NAME) {
1067 extensions.push(ext::memory_budget::NAME);
1068 } else {
1069 log::warn!("VK_EXT_memory_budget is not available.")
1070 }
1071
1072 // Require `VK_KHR_draw_indirect_count` if the associated feature was requested
1073 // Even though Vulkan 1.2 has promoted the extension to core, we must require the extension to avoid
1074 // large amounts of spaghetti involved with using PhysicalDeviceVulkan12Features.
1075 if requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT_COUNT) {
1076 extensions.push(khr::draw_indirect_count::NAME);
1077 }
1078
1079 // Require `VK_KHR_deferred_host_operations`, `VK_KHR_acceleration_structure` and `VK_KHR_buffer_device_address` if the feature `RAY_TRACING` was requested
1080 if requested_features
1081 .contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE)
1082 {
1083 extensions.push(khr::deferred_host_operations::NAME);
1084 extensions.push(khr::acceleration_structure::NAME);
1085 extensions.push(khr::buffer_device_address::NAME);
1086 }
1087
1088 // Require `VK_KHR_ray_query` if the associated feature was requested
1089 if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
1090 extensions.push(khr::ray_query::NAME);
1091 }
1092
1093 if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
1094 extensions.push(khr::ray_tracing_position_fetch::NAME)
1095 }
1096
1097 // Require `VK_EXT_conservative_rasterization` if the associated feature was requested
1098 if requested_features.contains(wgt::Features::CONSERVATIVE_RASTERIZATION) {
1099 extensions.push(ext::conservative_rasterization::NAME);
1100 }
1101
1102 // Require `VK_KHR_portability_subset` on macOS/iOS
1103 #[cfg(target_vendor = "apple")]
1104 extensions.push(khr::portability_subset::NAME);
1105
1106 // Require `VK_EXT_texture_compression_astc_hdr` if the associated feature was requested
1107 if requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR) {
1108 extensions.push(ext::texture_compression_astc_hdr::NAME);
1109 }
1110
1111 // Require `VK_KHR_shader_atomic_int64` if the associated feature was requested
1112 if requested_features.intersects(
1113 wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
1114 ) {
1115 extensions.push(khr::shader_atomic_int64::NAME);
1116 }
1117
1118 // Require `VK_EXT_shader_image_atomic_int64` if the associated feature was requested
1119 if requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
1120 extensions.push(ext::shader_image_atomic_int64::NAME);
1121 }
1122
1123 // Require `VK_EXT_shader_atomic_float` if the associated feature was requested
1124 if requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
1125 extensions.push(ext::shader_atomic_float::NAME);
1126 }
1127
1128 // Require VK_GOOGLE_display_timing if the associated feature was requested
1129 if requested_features.contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING) {
1130 extensions.push(google::display_timing::NAME);
1131 }
1132
1133 if requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1134 extensions.push(ext::mesh_shader::NAME);
1135 }
1136
1137 extensions
1138 }
1139
1140 fn to_wgpu_limits(&self) -> wgt::Limits {
1141 let limits = &self.properties.limits;
1142
1143 let max_compute_workgroup_sizes = limits.max_compute_work_group_size;
1144 let max_compute_workgroups_per_dimension = limits.max_compute_work_group_count[0]
1145 .min(limits.max_compute_work_group_count[1])
1146 .min(limits.max_compute_work_group_count[2]);
1147
1148 // Prevent very large buffers on mesa and most android devices.
1149 let is_nvidia = self.properties.vendor_id == crate::auxil::db::nvidia::VENDOR;
1150 let max_buffer_size =
1151 if (cfg!(target_os = "linux") || cfg!(target_os = "android")) && !is_nvidia {
1152 i32::MAX as u64
1153 } else {
1154 u64::MAX
1155 };
1156
1157 let mut max_binding_array_elements = 0;
1158 let mut max_sampler_binding_array_elements = 0;
1159 if let Some(ref descriptor_indexing) = self.descriptor_indexing {
1160 max_binding_array_elements = descriptor_indexing
1161 .max_descriptor_set_update_after_bind_sampled_images
1162 .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_images)
1163 .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_buffers)
1164 .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_sampled_images)
1165 .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_images)
1166 .min(
1167 descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_buffers,
1168 );
1169
1170 max_sampler_binding_array_elements = descriptor_indexing
1171 .max_descriptor_set_update_after_bind_samplers
1172 .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_samplers);
1173 }
1174
1175 // TODO: programmatically determine this, if possible. It's unclear whether we can
1176 // as of https://github.com/gpuweb/gpuweb/issues/2965#issuecomment-1361315447.
1177 //
1178 // In theory some tilers may not support this much. We can't tell however, and
1179 // the driver will throw a DEVICE_REMOVED if it goes too high in usage. This is fine.
1180 //
1181 // 16 bytes per sample is the maximum size for a color attachment.
1182 let max_color_attachment_bytes_per_sample =
1183 limits.max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST;
1184
1185 wgt::Limits {
1186 max_texture_dimension_1d: limits.max_image_dimension1_d,
1187 max_texture_dimension_2d: limits.max_image_dimension2_d,
1188 max_texture_dimension_3d: limits.max_image_dimension3_d,
1189 max_texture_array_layers: limits.max_image_array_layers,
1190 max_bind_groups: limits
1191 .max_bound_descriptor_sets
1192 .min(crate::MAX_BIND_GROUPS as u32),
1193 max_bindings_per_bind_group: wgt::Limits::default().max_bindings_per_bind_group,
1194 max_dynamic_uniform_buffers_per_pipeline_layout: limits
1195 .max_descriptor_set_uniform_buffers_dynamic,
1196 max_dynamic_storage_buffers_per_pipeline_layout: limits
1197 .max_descriptor_set_storage_buffers_dynamic,
1198 max_sampled_textures_per_shader_stage: limits.max_per_stage_descriptor_sampled_images,
1199 max_samplers_per_shader_stage: limits.max_per_stage_descriptor_samplers,
1200 max_storage_buffers_per_shader_stage: limits.max_per_stage_descriptor_storage_buffers,
1201 max_storage_textures_per_shader_stage: limits.max_per_stage_descriptor_storage_images,
1202 max_uniform_buffers_per_shader_stage: limits.max_per_stage_descriptor_uniform_buffers,
1203 max_binding_array_elements_per_shader_stage: max_binding_array_elements,
1204 max_binding_array_sampler_elements_per_shader_stage: max_sampler_binding_array_elements,
1205 max_uniform_buffer_binding_size: limits
1206 .max_uniform_buffer_range
1207 .min(crate::auxil::MAX_I32_BINDING_SIZE),
1208 max_storage_buffer_binding_size: limits
1209 .max_storage_buffer_range
1210 .min(crate::auxil::MAX_I32_BINDING_SIZE),
1211 max_vertex_buffers: limits
1212 .max_vertex_input_bindings
1213 .min(crate::MAX_VERTEX_BUFFERS as u32),
1214 max_vertex_attributes: limits.max_vertex_input_attributes,
1215 max_vertex_buffer_array_stride: limits.max_vertex_input_binding_stride,
1216 min_subgroup_size: self
1217 .subgroup_size_control
1218 .map(|subgroup_size| subgroup_size.min_subgroup_size)
1219 .unwrap_or(0),
1220 max_subgroup_size: self
1221 .subgroup_size_control
1222 .map(|subgroup_size| subgroup_size.max_subgroup_size)
1223 .unwrap_or(0),
1224 max_push_constant_size: limits.max_push_constants_size,
1225 min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment as u32,
1226 min_storage_buffer_offset_alignment: limits.min_storage_buffer_offset_alignment as u32,
1227 max_inter_stage_shader_components: limits
1228 .max_vertex_output_components
1229 .min(limits.max_fragment_input_components),
1230 max_color_attachments: limits
1231 .max_color_attachments
1232 .min(crate::MAX_COLOR_ATTACHMENTS as u32),
1233 max_color_attachment_bytes_per_sample,
1234 max_compute_workgroup_storage_size: limits.max_compute_shared_memory_size,
1235 max_compute_invocations_per_workgroup: limits.max_compute_work_group_invocations,
1236 max_compute_workgroup_size_x: max_compute_workgroup_sizes[0],
1237 max_compute_workgroup_size_y: max_compute_workgroup_sizes[1],
1238 max_compute_workgroup_size_z: max_compute_workgroup_sizes[2],
1239 max_compute_workgroups_per_dimension,
1240 max_buffer_size,
1241 max_non_sampler_bindings: u32::MAX,
1242 }
1243 }
1244
1245 /// Return a `wgpu_hal::Alignments` structure describing this adapter.
1246 ///
1247 /// The `using_robustness2` argument says how this adapter will implement
1248 /// `wgpu_hal`'s guarantee that shaders can only read the [accessible
1249 /// region][ar] of bindgroup's buffer bindings:
1250 ///
1251 /// - If this adapter will depend on `VK_EXT_robustness2`'s
1252 /// `robustBufferAccess2` feature to apply bounds checks to shader buffer
1253 /// access, `using_robustness2` must be `true`.
1254 ///
1255 /// - Otherwise, this adapter must use Naga to inject bounds checks on
1256 /// buffer accesses, and `using_robustness2` must be `false`.
1257 ///
1258 /// [ar]: ../../struct.BufferBinding.html#accessible-region
1259 fn to_hal_alignments(&self, using_robustness2: bool) -> crate::Alignments {
1260 let limits = &self.properties.limits;
1261 crate::Alignments {
1262 buffer_copy_offset: wgt::BufferSize::new(limits.optimal_buffer_copy_offset_alignment)
1263 .unwrap(),
1264 buffer_copy_pitch: wgt::BufferSize::new(limits.optimal_buffer_copy_row_pitch_alignment)
1265 .unwrap(),
1266 uniform_bounds_check_alignment: {
1267 let alignment = if using_robustness2 {
1268 self.robustness2
1269 .unwrap() // if we're using it, we should have its properties
1270 .robust_uniform_buffer_access_size_alignment
1271 } else {
1272 // If the `robustness2` properties are unavailable, then `robustness2` is not available either Naga-injected bounds checks are precise.
1273 1
1274 };
1275 wgt::BufferSize::new(alignment).unwrap()
1276 },
1277 raw_tlas_instance_size: 64,
1278 ray_tracing_scratch_buffer_alignment: self.acceleration_structure.map_or(
1279 0,
1280 |acceleration_structure| {
1281 acceleration_structure.min_acceleration_structure_scratch_offset_alignment
1282 },
1283 ),
1284 }
1285 }
1286 }
1287
1288 impl super::InstanceShared {
1289 fn inspect(
1290 &self,
1291 phd: vk::PhysicalDevice,
1292 ) -> (PhysicalDeviceProperties, PhysicalDeviceFeatures) {
1293 let capabilities = {
1294 let mut capabilities = PhysicalDeviceProperties::default();
1295 capabilities.supported_extensions =
1296 unsafe { self.raw.enumerate_device_extension_properties(phd).unwrap() };
1297 capabilities.properties = unsafe { self.raw.get_physical_device_properties(phd) };
1298 capabilities.device_api_version = capabilities.properties.api_version;
1299
1300 if let Some(ref get_device_properties) = self.get_physical_device_properties {
1301 // Get these now to avoid borrowing conflicts later
1302 let supports_maintenance3 = capabilities.device_api_version >= vk::API_VERSION_1_1
1303 || capabilities.supports_extension(khr::maintenance3::NAME);
1304 let supports_descriptor_indexing = capabilities.device_api_version
1305 >= vk::API_VERSION_1_2
1306 || capabilities.supports_extension(ext::descriptor_indexing::NAME);
1307 let supports_driver_properties = capabilities.device_api_version
1308 >= vk::API_VERSION_1_2
1309 || capabilities.supports_extension(khr::driver_properties::NAME);
1310 let supports_subgroup_size_control = capabilities.device_api_version
1311 >= vk::API_VERSION_1_3
1312 || capabilities.supports_extension(ext::subgroup_size_control::NAME);
1313 let supports_robustness2 = capabilities.supports_extension(ext::robustness2::NAME);
1314
1315 let supports_acceleration_structure =
1316 capabilities.supports_extension(khr::acceleration_structure::NAME);
1317
1318 let supports_mesh_shader = capabilities.supports_extension(ext::mesh_shader::NAME);
1319
1320 let mut properties2 = vk::PhysicalDeviceProperties2KHR::default();
1321 if supports_maintenance3 {
1322 let next = capabilities
1323 .maintenance_3
1324 .insert(vk::PhysicalDeviceMaintenance3Properties::default());
1325 properties2 = properties2.push_next(next);
1326 }
1327
1328 if supports_descriptor_indexing {
1329 let next = capabilities
1330 .descriptor_indexing
1331 .insert(vk::PhysicalDeviceDescriptorIndexingPropertiesEXT::default());
1332 properties2 = properties2.push_next(next);
1333 }
1334
1335 if supports_acceleration_structure {
1336 let next = capabilities
1337 .acceleration_structure
1338 .insert(vk::PhysicalDeviceAccelerationStructurePropertiesKHR::default());
1339 properties2 = properties2.push_next(next);
1340 }
1341
1342 if supports_driver_properties {
1343 let next = capabilities
1344 .driver
1345 .insert(vk::PhysicalDeviceDriverPropertiesKHR::default());
1346 properties2 = properties2.push_next(next);
1347 }
1348
1349 if capabilities.device_api_version >= vk::API_VERSION_1_1 {
1350 let next = capabilities
1351 .subgroup
1352 .insert(vk::PhysicalDeviceSubgroupProperties::default());
1353 properties2 = properties2.push_next(next);
1354 }
1355
1356 if supports_subgroup_size_control {
1357 let next = capabilities
1358 .subgroup_size_control
1359 .insert(vk::PhysicalDeviceSubgroupSizeControlProperties::default());
1360 properties2 = properties2.push_next(next);
1361 }
1362
1363 if supports_robustness2 {
1364 let next = capabilities
1365 .robustness2
1366 .insert(vk::PhysicalDeviceRobustness2PropertiesEXT::default());
1367 properties2 = properties2.push_next(next);
1368 }
1369
1370 if supports_mesh_shader {
1371 let next = capabilities
1372 ._mesh_shader
1373 .insert(vk::PhysicalDeviceMeshShaderPropertiesEXT::default());
1374 properties2 = properties2.push_next(next);
1375 }
1376
1377 unsafe {
1378 get_device_properties.get_physical_device_properties2(phd, &mut properties2)
1379 };
1380
1381 if is_intel_igpu_outdated_for_robustness2(
1382 capabilities.properties,
1383 capabilities.driver,
1384 ) {
1385 capabilities
1386 .supported_extensions
1387 .retain(|&x| x.extension_name_as_c_str() != Ok(ext::robustness2::NAME));
1388 capabilities.robustness2 = None;
1389 }
1390 };
1391 capabilities
1392 };
1393
1394 let mut features = PhysicalDeviceFeatures::default();
1395 features.core = if let Some(ref get_device_properties) = self.get_physical_device_properties
1396 {
1397 let core = vk::PhysicalDeviceFeatures::default();
1398 let mut features2 = vk::PhysicalDeviceFeatures2KHR::default().features(core);
1399
1400 // `VK_KHR_multiview` is promoted to 1.1
1401 if capabilities.device_api_version >= vk::API_VERSION_1_1
1402 || capabilities.supports_extension(khr::multiview::NAME)
1403 {
1404 let next = features
1405 .multiview
1406 .insert(vk::PhysicalDeviceMultiviewFeatures::default());
1407 features2 = features2.push_next(next);
1408 }
1409
1410 // `VK_KHR_sampler_ycbcr_conversion` is promoted to 1.1
1411 if capabilities.device_api_version >= vk::API_VERSION_1_1
1412 || capabilities.supports_extension(khr::sampler_ycbcr_conversion::NAME)
1413 {
1414 let next = features
1415 .sampler_ycbcr_conversion
1416 .insert(vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default());
1417 features2 = features2.push_next(next);
1418 }
1419
1420 if capabilities.supports_extension(ext::descriptor_indexing::NAME) {
1421 let next = features
1422 .descriptor_indexing
1423 .insert(vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default());
1424 features2 = features2.push_next(next);
1425 }
1426
1427 // `VK_KHR_timeline_semaphore` is promoted to 1.2, but has no
1428 // changes, so we can keep using the extension unconditionally.
1429 if capabilities.supports_extension(khr::timeline_semaphore::NAME) {
1430 let next = features
1431 .timeline_semaphore
1432 .insert(vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default());
1433 features2 = features2.push_next(next);
1434 }
1435
1436 // `VK_KHR_shader_atomic_int64` is promoted to 1.2, but has no
1437 // changes, so we can keep using the extension unconditionally.
1438 if capabilities.device_api_version >= vk::API_VERSION_1_2
1439 || capabilities.supports_extension(khr::shader_atomic_int64::NAME)
1440 {
1441 let next = features
1442 .shader_atomic_int64
1443 .insert(vk::PhysicalDeviceShaderAtomicInt64Features::default());
1444 features2 = features2.push_next(next);
1445 }
1446
1447 if capabilities.supports_extension(ext::shader_image_atomic_int64::NAME) {
1448 let next = features
1449 .shader_image_atomic_int64
1450 .insert(vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default());
1451 features2 = features2.push_next(next);
1452 }
1453 if capabilities.supports_extension(ext::shader_atomic_float::NAME) {
1454 let next = features
1455 .shader_atomic_float
1456 .insert(vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default());
1457 features2 = features2.push_next(next);
1458 }
1459 if capabilities.supports_extension(ext::image_robustness::NAME) {
1460 let next = features
1461 .image_robustness
1462 .insert(vk::PhysicalDeviceImageRobustnessFeaturesEXT::default());
1463 features2 = features2.push_next(next);
1464 }
1465 if capabilities.supports_extension(ext::robustness2::NAME) {
1466 let next = features
1467 .robustness2
1468 .insert(vk::PhysicalDeviceRobustness2FeaturesEXT::default());
1469 features2 = features2.push_next(next);
1470 }
1471 if capabilities.supports_extension(ext::texture_compression_astc_hdr::NAME) {
1472 let next = features
1473 .astc_hdr
1474 .insert(vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default());
1475 features2 = features2.push_next(next);
1476 }
1477 if capabilities.supports_extension(khr::shader_float16_int8::NAME)
1478 && capabilities.supports_extension(khr::_16bit_storage::NAME)
1479 {
1480 let next = features.shader_float16.insert((
1481 vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR::default(),
1482 vk::PhysicalDevice16BitStorageFeaturesKHR::default(),
1483 ));
1484 features2 = features2.push_next(&mut next.0);
1485 features2 = features2.push_next(&mut next.1);
1486 }
1487 if capabilities.supports_extension(khr::acceleration_structure::NAME) {
1488 let next = features
1489 .acceleration_structure
1490 .insert(vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default());
1491 features2 = features2.push_next(next);
1492 }
1493
1494 if capabilities.supports_extension(khr::ray_tracing_position_fetch::NAME) {
1495 let next = features
1496 .position_fetch
1497 .insert(vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default());
1498 features2 = features2.push_next(next);
1499 }
1500
1501 // `VK_KHR_zero_initialize_workgroup_memory` is promoted to 1.3
1502 if capabilities.device_api_version >= vk::API_VERSION_1_3
1503 || capabilities.supports_extension(khr::zero_initialize_workgroup_memory::NAME)
1504 {
1505 let next = features
1506 .zero_initialize_workgroup_memory
1507 .insert(vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default());
1508 features2 = features2.push_next(next);
1509 }
1510
1511 // `VK_EXT_subgroup_size_control` is promoted to 1.3
1512 if capabilities.device_api_version >= vk::API_VERSION_1_3
1513 || capabilities.supports_extension(ext::subgroup_size_control::NAME)
1514 {
1515 let next = features
1516 .subgroup_size_control
1517 .insert(vk::PhysicalDeviceSubgroupSizeControlFeatures::default());
1518 features2 = features2.push_next(next);
1519 }
1520
1521 if capabilities.supports_extension(ext::mesh_shader::NAME) {
1522 let next = features
1523 .mesh_shader
1524 .insert(vk::PhysicalDeviceMeshShaderFeaturesEXT::default());
1525 features2 = features2.push_next(next);
1526 }
1527
1528 // `VK_KHR_shader_integer_dot_product` is promoted to 1.3
1529 if capabilities.device_api_version >= vk::API_VERSION_1_3
1530 || capabilities.supports_extension(khr::shader_integer_dot_product::NAME)
1531 {
1532 let next = features
1533 .shader_integer_dot_product
1534 .insert(vk::PhysicalDeviceShaderIntegerDotProductFeatures::default());
1535 features2 = features2.push_next(next);
1536 }
1537
1538 unsafe { get_device_properties.get_physical_device_features2(phd, &mut features2) };
1539 features2.features
1540 } else {
1541 unsafe { self.raw.get_physical_device_features(phd) }
1542 };
1543
1544 (capabilities, features)
1545 }
1546 }
1547
1548 impl super::Instance {
1549 pub fn expose_adapter(
1550 &self,
1551 phd: vk::PhysicalDevice,
1552 ) -> Option<crate::ExposedAdapter<super::Api>> {
1553 use crate::auxil::db;
1554
1555 let (phd_capabilities, phd_features) = self.shared.inspect(phd);
1556
1557 let info = wgt::AdapterInfo {
1558 name: {
1559 phd_capabilities
1560 .properties
1561 .device_name_as_c_str()
1562 .ok()
1563 .and_then(|name| name.to_str().ok())
1564 .unwrap_or("?")
1565 .to_owned()
1566 },
1567 vendor: phd_capabilities.properties.vendor_id,
1568 device: phd_capabilities.properties.device_id,
1569 device_type: match phd_capabilities.properties.device_type {
1570 vk::PhysicalDeviceType::OTHER => wgt::DeviceType::Other,
1571 vk::PhysicalDeviceType::INTEGRATED_GPU => wgt::DeviceType::IntegratedGpu,
1572 vk::PhysicalDeviceType::DISCRETE_GPU => wgt::DeviceType::DiscreteGpu,
1573 vk::PhysicalDeviceType::VIRTUAL_GPU => wgt::DeviceType::VirtualGpu,
1574 vk::PhysicalDeviceType::CPU => wgt::DeviceType::Cpu,
1575 _ => wgt::DeviceType::Other,
1576 },
1577 driver: {
1578 phd_capabilities
1579 .driver
1580 .as_ref()
1581 .and_then(|driver| driver.driver_name_as_c_str().ok())
1582 .and_then(|name| name.to_str().ok())
1583 .unwrap_or("?")
1584 .to_owned()
1585 },
1586 driver_info: {
1587 phd_capabilities
1588 .driver
1589 .as_ref()
1590 .and_then(|driver| driver.driver_info_as_c_str().ok())
1591 .and_then(|name| name.to_str().ok())
1592 .unwrap_or("?")
1593 .to_owned()
1594 },
1595 backend: wgt::Backend::Vulkan,
1596 };
1597 let (available_features, downlevel_flags) =
1598 phd_features.to_wgpu(&self.shared.raw, phd, &phd_capabilities);
1599 let mut workarounds = super::Workarounds::empty();
1600 {
1601 // TODO: only enable for particular devices
1602 workarounds |= super::Workarounds::SEPARATE_ENTRY_POINTS;
1603 workarounds.set(
1604 super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS,
1605 phd_capabilities.properties.vendor_id == db::qualcomm::VENDOR,
1606 );
1607 workarounds.set(
1608 super::Workarounds::FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16,
1609 phd_capabilities.properties.vendor_id == db::nvidia::VENDOR,
1610 );
1611 };
1612
1613 if let Some(driver) = phd_capabilities.driver {
1614 if driver.conformance_version.major == 0 {
1615 if driver.driver_id == vk::DriverId::MOLTENVK {
1616 log::debug!("Adapter is not Vulkan compliant, but is MoltenVK, continuing");
1617 } else if self
1618 .shared
1619 .flags
1620 .contains(wgt::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER)
1621 {
1622 log::warn!("Adapter is not Vulkan compliant: {}", info.name);
1623 } else {
1624 log::warn!(
1625 "Adapter is not Vulkan compliant, hiding adapter: {}",
1626 info.name
1627 );
1628 return None;
1629 }
1630 }
1631 }
1632 if phd_capabilities.device_api_version == vk::API_VERSION_1_0
1633 && !phd_capabilities.supports_extension(khr::storage_buffer_storage_class::NAME)
1634 {
1635 log::warn!(
1636 "SPIR-V storage buffer class is not supported, hiding adapter: {}",
1637 info.name
1638 );
1639 return None;
1640 }
1641 if !phd_capabilities.supports_extension(khr::maintenance1::NAME)
1642 && phd_capabilities.device_api_version < vk::API_VERSION_1_1
1643 {
1644 log::warn!(
1645 "VK_KHR_maintenance1 is not supported, hiding adapter: {}",
1646 info.name
1647 );
1648 return None;
1649 }
1650
1651 let queue_families = unsafe {
1652 self.shared
1653 .raw
1654 .get_physical_device_queue_family_properties(phd)
1655 };
1656 let queue_flags = queue_families.first()?.queue_flags;
1657 if !queue_flags.contains(vk::QueueFlags::GRAPHICS) {
1658 log::warn!("The first queue only exposes {:?}", queue_flags);
1659 return None;
1660 }
1661
1662 let private_caps = super::PrivateCapabilities {
1663 image_view_usage: phd_capabilities.device_api_version >= vk::API_VERSION_1_1
1664 || phd_capabilities.supports_extension(khr::maintenance2::NAME),
1665 timeline_semaphores: match phd_features.timeline_semaphore {
1666 Some(features) => features.timeline_semaphore == vk::TRUE,
1667 None => phd_features
1668 .timeline_semaphore
1669 .is_some_and(|ext| ext.timeline_semaphore != 0),
1670 },
1671 texture_d24: supports_format(
1672 &self.shared.raw,
1673 phd,
1674 vk::Format::X8_D24_UNORM_PACK32,
1675 vk::ImageTiling::OPTIMAL,
1676 depth_stencil_required_flags(),
1677 ),
1678 texture_d24_s8: supports_format(
1679 &self.shared.raw,
1680 phd,
1681 vk::Format::D24_UNORM_S8_UINT,
1682 vk::ImageTiling::OPTIMAL,
1683 depth_stencil_required_flags(),
1684 ),
1685 texture_s8: supports_format(
1686 &self.shared.raw,
1687 phd,
1688 vk::Format::S8_UINT,
1689 vk::ImageTiling::OPTIMAL,
1690 depth_stencil_required_flags(),
1691 ),
1692 non_coherent_map_mask: phd_capabilities.properties.limits.non_coherent_atom_size - 1,
1693 can_present: true,
1694 //TODO: make configurable
1695 robust_buffer_access: phd_features.core.robust_buffer_access != 0,
1696 robust_image_access: match phd_features.robustness2 {
1697 Some(ref f) => f.robust_image_access2 != 0,
1698 None => phd_features
1699 .image_robustness
1700 .is_some_and(|ext| ext.robust_image_access != 0),
1701 },
1702 robust_buffer_access2: phd_features
1703 .robustness2
1704 .as_ref()
1705 .map(|r| r.robust_buffer_access2 == 1)
1706 .unwrap_or_default(),
1707 robust_image_access2: phd_features
1708 .robustness2
1709 .as_ref()
1710 .map(|r| r.robust_image_access2 == 1)
1711 .unwrap_or_default(),
1712 zero_initialize_workgroup_memory: phd_features
1713 .zero_initialize_workgroup_memory
1714 .is_some_and(|ext| ext.shader_zero_initialize_workgroup_memory == vk::TRUE),
1715 image_format_list: phd_capabilities.device_api_version >= vk::API_VERSION_1_2
1716 || phd_capabilities.supports_extension(khr::image_format_list::NAME),
1717 maximum_samplers: phd_capabilities
1718 .properties
1719 .limits
1720 .max_sampler_allocation_count,
1721 shader_integer_dot_product: phd_features
1722 .shader_integer_dot_product
1723 .is_some_and(|ext| ext.shader_integer_dot_product != 0),
1724 };
1725 let capabilities = crate::Capabilities {
1726 limits: phd_capabilities.to_wgpu_limits(),
1727 alignments: phd_capabilities.to_hal_alignments(private_caps.robust_buffer_access2),
1728 downlevel: wgt::DownlevelCapabilities {
1729 flags: downlevel_flags,
1730 limits: wgt::DownlevelLimits {},
1731 shader_model: wgt::ShaderModel::Sm5, //TODO?
1732 },
1733 };
1734
1735 let adapter = super::Adapter {
1736 raw: phd,
1737 instance: Arc::clone(&self.shared),
1738 //queue_families,
1739 known_memory_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL
1740 | vk::MemoryPropertyFlags::HOST_VISIBLE
1741 | vk::MemoryPropertyFlags::HOST_COHERENT
1742 | vk::MemoryPropertyFlags::HOST_CACHED
1743 | vk::MemoryPropertyFlags::LAZILY_ALLOCATED,
1744 phd_capabilities,
1745 phd_features,
1746 downlevel_flags,
1747 private_caps,
1748 workarounds,
1749 };
1750
1751 Some(crate::ExposedAdapter {
1752 adapter,
1753 info,
1754 features: available_features,
1755 capabilities,
1756 })
1757 }
1758 }
1759
1760 impl super::Adapter {
1761 pub fn raw_physical_device(&self) -> vk::PhysicalDevice {
1762 self.raw
1763 }
1764
1765 pub fn physical_device_capabilities(&self) -> &PhysicalDeviceProperties {
1766 &self.phd_capabilities
1767 }
1768
1769 pub fn shared_instance(&self) -> &super::InstanceShared {
1770 &self.instance
1771 }
1772
1773 pub fn required_device_extensions(&self, features: wgt::Features) -> Vec<&'static CStr> {
1774 let (supported_extensions, unsupported_extensions) = self
1775 .phd_capabilities
1776 .get_required_extensions(features)
1777 .iter()
1778 .partition::<Vec<&CStr>, _>(|&&extension| {
1779 self.phd_capabilities.supports_extension(extension)
1780 });
1781
1782 if !unsupported_extensions.is_empty() {
1783 log::warn!("Missing extensions: {:?}", unsupported_extensions);
1784 }
1785
1786 log::debug!("Supported extensions: {:?}", supported_extensions);
1787 supported_extensions
1788 }
1789
1790 /// Create a `PhysicalDeviceFeatures` for opening a logical device with
1791 /// `features` from this adapter.
1792 ///
1793 /// The given `enabled_extensions` set must include all the extensions
1794 /// selected by [`required_device_extensions`] when passed `features`.
1795 /// Otherwise, the `PhysicalDeviceFeatures` value may not be able to select
1796 /// all the Vulkan features needed to represent `features` and this
1797 /// adapter's characteristics.
1798 ///
1799 /// Typically, you'd simply call `required_device_extensions`, and then pass
1800 /// its return value and the feature set you gave it directly to this
1801 /// function. But it's fine to add more extensions to the list.
1802 ///
1803 /// [`required_device_extensions`]: Self::required_device_extensions
1804 pub fn physical_device_features(
1805 &self,
1806 enabled_extensions: &[&'static CStr],
1807 features: wgt::Features,
1808 ) -> PhysicalDeviceFeatures {
1809 PhysicalDeviceFeatures::from_extensions_and_requested_features(
1810 &self.phd_capabilities,
1811 &self.phd_features,
1812 enabled_extensions,
1813 features,
1814 self.downlevel_flags,
1815 &self.private_caps,
1816 )
1817 }
1818
1819 /// # Safety
1820 ///
1821 /// - `raw_device` must be created from this adapter.
1822 /// - `raw_device` must be created using `family_index`, `enabled_extensions` and `physical_device_features()`
1823 /// - `enabled_extensions` must be a superset of `required_device_extensions()`.
1824 /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_device`. If
1825 /// `drop_callback` is [`Some`], `raw_device` must be valid until the callback is called.
1826 #[allow(clippy::too_many_arguments)]
1827 pub unsafe fn device_from_raw(
1828 &self,
1829 raw_device: ash::Device,
1830 drop_callback: Option<crate::DropCallback>,
1831 enabled_extensions: &[&'static CStr],
1832 features: wgt::Features,
1833 memory_hints: &wgt::MemoryHints,
1834 family_index: u32,
1835 queue_index: u32,
1836 ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
1837 let mem_properties = {
1838 profiling::scope!("vkGetPhysicalDeviceMemoryProperties");
1839 unsafe {
1840 self.instance
1841 .raw
1842 .get_physical_device_memory_properties(self.raw)
1843 }
1844 };
1845 let memory_types = &mem_properties.memory_types_as_slice();
1846 let valid_ash_memory_types = memory_types.iter().enumerate().fold(0, |u, (i, mem)| {
1847 if self.known_memory_flags.contains(mem.property_flags) {
1848 u | (1 << i)
1849 } else {
1850 u
1851 }
1852 });
1853
1854 let swapchain_fn = khr::swapchain::Device::new(&self.instance.raw, &raw_device);
1855
1856 // Note that VK_EXT_debug_utils is an instance extension (enabled at the instance
1857 // level) but contains a few functions that can be loaded directly on the Device for a
1858 // dispatch-table-less pointer.
1859 let debug_utils_fn = if self.instance.extensions.contains(&ext::debug_utils::NAME) {
1860 Some(ext::debug_utils::Device::new(
1861 &self.instance.raw,
1862 &raw_device,
1863 ))
1864 } else {
1865 None
1866 };
1867 let indirect_count_fn = if enabled_extensions.contains(&khr::draw_indirect_count::NAME) {
1868 Some(khr::draw_indirect_count::Device::new(
1869 &self.instance.raw,
1870 &raw_device,
1871 ))
1872 } else {
1873 None
1874 };
1875 let timeline_semaphore_fn = if enabled_extensions.contains(&khr::timeline_semaphore::NAME) {
1876 Some(super::ExtensionFn::Extension(
1877 khr::timeline_semaphore::Device::new(&self.instance.raw, &raw_device),
1878 ))
1879 } else if self.phd_capabilities.device_api_version >= vk::API_VERSION_1_2 {
1880 Some(super::ExtensionFn::Promoted)
1881 } else {
1882 None
1883 };
1884 let ray_tracing_fns = if enabled_extensions.contains(&khr::acceleration_structure::NAME)
1885 && enabled_extensions.contains(&khr::buffer_device_address::NAME)
1886 {
1887 Some(super::RayTracingDeviceExtensionFunctions {
1888 acceleration_structure: khr::acceleration_structure::Device::new(
1889 &self.instance.raw,
1890 &raw_device,
1891 ),
1892 buffer_device_address: khr::buffer_device_address::Device::new(
1893 &self.instance.raw,
1894 &raw_device,
1895 ),
1896 })
1897 } else {
1898 None
1899 };
1900 let mesh_shading_fns = if enabled_extensions.contains(&ext::mesh_shader::NAME) {
1901 Some(ext::mesh_shader::Device::new(
1902 &self.instance.raw,
1903 &raw_device,
1904 ))
1905 } else {
1906 None
1907 };
1908
1909 let naga_options = {
1910 use naga::back::spv;
1911
1912 // The following capabilities are always available
1913 // see https://registry.khronos.org/vulkan/specs/1.3-extensions/html/chap52.html#spirvenv-capabilities
1914 let mut capabilities = vec![
1915 spv::Capability::Shader,
1916 spv::Capability::Matrix,
1917 spv::Capability::Sampled1D,
1918 spv::Capability::Image1D,
1919 spv::Capability::ImageQuery,
1920 spv::Capability::DerivativeControl,
1921 spv::Capability::StorageImageExtendedFormats,
1922 ];
1923
1924 if self
1925 .downlevel_flags
1926 .contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES)
1927 {
1928 capabilities.push(spv::Capability::SampledCubeArray);
1929 }
1930
1931 if self
1932 .downlevel_flags
1933 .contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING)
1934 {
1935 capabilities.push(spv::Capability::SampleRateShading);
1936 }
1937
1938 if features.contains(wgt::Features::MULTIVIEW) {
1939 capabilities.push(spv::Capability::MultiView);
1940 }
1941
1942 if features.contains(wgt::Features::SHADER_PRIMITIVE_INDEX) {
1943 capabilities.push(spv::Capability::Geometry);
1944 }
1945
1946 if features.intersects(wgt::Features::SUBGROUP | wgt::Features::SUBGROUP_VERTEX) {
1947 capabilities.push(spv::Capability::GroupNonUniform);
1948 capabilities.push(spv::Capability::GroupNonUniformVote);
1949 capabilities.push(spv::Capability::GroupNonUniformArithmetic);
1950 capabilities.push(spv::Capability::GroupNonUniformBallot);
1951 capabilities.push(spv::Capability::GroupNonUniformShuffle);
1952 capabilities.push(spv::Capability::GroupNonUniformShuffleRelative);
1953 }
1954
1955 if features.intersects(
1956 wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
1957 | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
1958 | wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS,
1959 ) {
1960 capabilities.push(spv::Capability::ShaderNonUniform);
1961 }
1962 if features.contains(wgt::Features::BGRA8UNORM_STORAGE) {
1963 capabilities.push(spv::Capability::StorageImageWriteWithoutFormat);
1964 }
1965
1966 if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
1967 capabilities.push(spv::Capability::RayQueryKHR);
1968 }
1969
1970 if features.contains(wgt::Features::SHADER_INT64) {
1971 capabilities.push(spv::Capability::Int64);
1972 }
1973
1974 if features.contains(wgt::Features::SHADER_F16) {
1975 capabilities.push(spv::Capability::Float16);
1976 }
1977
1978 if features.intersects(
1979 wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
1980 | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX
1981 | wgt::Features::TEXTURE_INT64_ATOMIC,
1982 ) {
1983 capabilities.push(spv::Capability::Int64Atomics);
1984 }
1985
1986 if features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
1987 capabilities.push(spv::Capability::Int64ImageEXT);
1988 }
1989
1990 if features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
1991 capabilities.push(spv::Capability::AtomicFloat32AddEXT);
1992 }
1993
1994 let mut flags = spv::WriterFlags::empty();
1995 flags.set(
1996 spv::WriterFlags::DEBUG,
1997 self.instance.flags.contains(wgt::InstanceFlags::DEBUG),
1998 );
1999 flags.set(
2000 spv::WriterFlags::LABEL_VARYINGS,
2001 self.phd_capabilities.properties.vendor_id != crate::auxil::db::qualcomm::VENDOR,
2002 );
2003 flags.set(
2004 spv::WriterFlags::FORCE_POINT_SIZE,
2005 //Note: we could technically disable this when we are compiling separate entry points,
2006 // and we know exactly that the primitive topology is not `PointList`.
2007 // But this requires cloning the `spv::Options` struct, which has heap allocations.
2008 true, // could check `super::Workarounds::SEPARATE_ENTRY_POINTS`
2009 );
2010 if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
2011 capabilities.push(spv::Capability::RayQueryKHR);
2012 }
2013 if features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
2014 capabilities.push(spv::Capability::RayQueryPositionFetchKHR)
2015 }
2016 if self.private_caps.shader_integer_dot_product {
2017 // See <https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html#_new_spir_v_capabilities>.
2018 capabilities.extend(&[
2019 spv::Capability::DotProductInputAllKHR,
2020 spv::Capability::DotProductInput4x8BitKHR,
2021 spv::Capability::DotProductInput4x8BitPackedKHR,
2022 spv::Capability::DotProductKHR,
2023 ]);
2024 }
2025 spv::Options {
2026 lang_version: match self.phd_capabilities.device_api_version {
2027 // Use maximum supported SPIR-V version according to
2028 // <https://github.com/KhronosGroup/Vulkan-Docs/blob/19b7651/appendices/spirvenv.adoc?plain=1#L21-L40>.
2029 vk::API_VERSION_1_0..vk::API_VERSION_1_1 => (1, 0),
2030 vk::API_VERSION_1_1..vk::API_VERSION_1_2 => (1, 3),
2031 vk::API_VERSION_1_2..vk::API_VERSION_1_3 => (1, 5),
2032 vk::API_VERSION_1_3.. => (1, 6),
2033 _ => unreachable!(),
2034 },
2035 flags,
2036 capabilities: Some(capabilities.iter().cloned().collect()),
2037 bounds_check_policies: naga::proc::BoundsCheckPolicies {
2038 index: naga::proc::BoundsCheckPolicy::Restrict,
2039 buffer: if self.private_caps.robust_buffer_access2 {
2040 naga::proc::BoundsCheckPolicy::Unchecked
2041 } else {
2042 naga::proc::BoundsCheckPolicy::Restrict
2043 },
2044 image_load: if self.private_caps.robust_image_access {
2045 naga::proc::BoundsCheckPolicy::Unchecked
2046 } else {
2047 naga::proc::BoundsCheckPolicy::Restrict
2048 },
2049 // TODO: support bounds checks on binding arrays
2050 binding_array: naga::proc::BoundsCheckPolicy::Unchecked,
2051 },
2052 zero_initialize_workgroup_memory: if self
2053 .private_caps
2054 .zero_initialize_workgroup_memory
2055 {
2056 spv::ZeroInitializeWorkgroupMemoryMode::Native
2057 } else {
2058 spv::ZeroInitializeWorkgroupMemoryMode::Polyfill
2059 },
2060 force_loop_bounding: true,
2061 // We need to build this separately for each invocation, so just default it out here
2062 binding_map: BTreeMap::default(),
2063 debug_info: None,
2064 }
2065 };
2066
2067 let raw_queue = {
2068 profiling::scope!("vkGetDeviceQueue");
2069 unsafe { raw_device.get_device_queue(family_index, queue_index) }
2070 };
2071
2072 let driver_version = self
2073 .phd_capabilities
2074 .properties
2075 .driver_version
2076 .to_be_bytes();
2077 #[rustfmt::skip]
2078 let pipeline_cache_validation_key = [
2079 driver_version[0], driver_version[1], driver_version[2], driver_version[3],
2080 0, 0, 0, 0,
2081 0, 0, 0, 0,
2082 0, 0, 0, 0,
2083 ];
2084
2085 let drop_guard = crate::DropGuard::from_option(drop_callback);
2086
2087 let shared = Arc::new(super::DeviceShared {
2088 raw: raw_device,
2089 family_index,
2090 queue_index,
2091 raw_queue,
2092 drop_guard,
2093 instance: Arc::clone(&self.instance),
2094 physical_device: self.raw,
2095 enabled_extensions: enabled_extensions.into(),
2096 extension_fns: super::DeviceExtensionFunctions {
2097 debug_utils: debug_utils_fn,
2098 draw_indirect_count: indirect_count_fn,
2099 timeline_semaphore: timeline_semaphore_fn,
2100 ray_tracing: ray_tracing_fns,
2101 mesh_shading: mesh_shading_fns,
2102 },
2103 pipeline_cache_validation_key,
2104 vendor_id: self.phd_capabilities.properties.vendor_id,
2105 timestamp_period: self.phd_capabilities.properties.limits.timestamp_period,
2106 private_caps: self.private_caps.clone(),
2107 features,
2108 workarounds: self.workarounds,
2109 render_passes: Mutex::new(Default::default()),
2110 sampler_cache: Mutex::new(super::sampler::SamplerCache::new(
2111 self.private_caps.maximum_samplers,
2112 )),
2113 memory_allocations_counter: Default::default(),
2114 });
2115
2116 let relay_semaphores = super::RelaySemaphores::new(&shared)?;
2117
2118 let queue = super::Queue {
2119 raw: raw_queue,
2120 swapchain_fn,
2121 device: Arc::clone(&shared),
2122 family_index,
2123 relay_semaphores: Mutex::new(relay_semaphores),
2124 signal_semaphores: Mutex::new((Vec::new(), Vec::new())),
2125 };
2126
2127 let mem_allocator = {
2128 let limits = self.phd_capabilities.properties.limits;
2129
2130 // Note: the parameters here are not set in stone nor where they picked with
2131 // strong confidence.
2132 // `final_free_list_chunk` should be bigger than starting_free_list_chunk if
2133 // we want the behavior of starting with smaller block sizes and using larger
2134 // ones only after we observe that the small ones aren't enough, which I think
2135 // is a good "I don't know what the workload is going to be like" approach.
2136 //
2137 // For reference, `VMA`, and `gpu_allocator` both start with 256 MB blocks
2138 // (then VMA doubles the block size each time it needs a new block).
2139 // At some point it would be good to experiment with real workloads
2140 //
2141 // TODO(#5925): The plan is to switch the Vulkan backend from `gpu_alloc` to
2142 // `gpu_allocator` which has a different (simpler) set of configuration options.
2143 //
2144 // TODO: These parameters should take hardware capabilities into account.
2145 let mb = 1024 * 1024;
2146 let perf_cfg = gpu_alloc::Config {
2147 starting_free_list_chunk: 128 * mb,
2148 final_free_list_chunk: 512 * mb,
2149 minimal_buddy_size: 1,
2150 initial_buddy_dedicated_size: 8 * mb,
2151 dedicated_threshold: 32 * mb,
2152 preferred_dedicated_threshold: mb,
2153 transient_dedicated_threshold: 128 * mb,
2154 };
2155 let mem_usage_cfg = gpu_alloc::Config {
2156 starting_free_list_chunk: 8 * mb,
2157 final_free_list_chunk: 64 * mb,
2158 minimal_buddy_size: 1,
2159 initial_buddy_dedicated_size: 8 * mb,
2160 dedicated_threshold: 8 * mb,
2161 preferred_dedicated_threshold: mb,
2162 transient_dedicated_threshold: 16 * mb,
2163 };
2164 let config = match memory_hints {
2165 wgt::MemoryHints::Performance => perf_cfg,
2166 wgt::MemoryHints::MemoryUsage => mem_usage_cfg,
2167 wgt::MemoryHints::Manual {
2168 suballocated_device_memory_block_size,
2169 } => gpu_alloc::Config {
2170 starting_free_list_chunk: suballocated_device_memory_block_size.start,
2171 final_free_list_chunk: suballocated_device_memory_block_size.end,
2172 initial_buddy_dedicated_size: suballocated_device_memory_block_size.start,
2173 ..perf_cfg
2174 },
2175 };
2176
2177 let max_memory_allocation_size =
2178 if let Some(maintenance_3) = self.phd_capabilities.maintenance_3 {
2179 maintenance_3.max_memory_allocation_size
2180 } else {
2181 u64::MAX
2182 };
2183 let properties = gpu_alloc::DeviceProperties {
2184 max_memory_allocation_count: limits.max_memory_allocation_count,
2185 max_memory_allocation_size,
2186 non_coherent_atom_size: limits.non_coherent_atom_size,
2187 memory_types: memory_types
2188 .iter()
2189 .map(|memory_type| gpu_alloc::MemoryType {
2190 props: gpu_alloc::MemoryPropertyFlags::from_bits_truncate(
2191 memory_type.property_flags.as_raw() as u8,
2192 ),
2193 heap: memory_type.heap_index,
2194 })
2195 .collect(),
2196 memory_heaps: mem_properties
2197 .memory_heaps_as_slice()
2198 .iter()
2199 .map(|&memory_heap| gpu_alloc::MemoryHeap {
2200 size: memory_heap.size,
2201 })
2202 .collect(),
2203 buffer_device_address: enabled_extensions
2204 .contains(&khr::buffer_device_address::NAME),
2205 };
2206 gpu_alloc::GpuAllocator::new(config, properties)
2207 };
2208 let desc_allocator = gpu_descriptor::DescriptorAllocator::new(
2209 if let Some(di) = self.phd_capabilities.descriptor_indexing {
2210 di.max_update_after_bind_descriptors_in_all_pools
2211 } else {
2212 0
2213 },
2214 );
2215
2216 let device = super::Device {
2217 shared,
2218 mem_allocator: Mutex::new(mem_allocator),
2219 desc_allocator: Mutex::new(desc_allocator),
2220 valid_ash_memory_types,
2221 naga_options,
2222 #[cfg(feature = "renderdoc")]
2223 render_doc: Default::default(),
2224 counters: Default::default(),
2225 };
2226
2227 Ok(crate::OpenDevice { device, queue })
2228 }
2229
2230 pub fn texture_format_as_raw(&self, texture_format: wgt::TextureFormat) -> vk::Format {
2231 self.private_caps.map_texture_format(texture_format)
2232 }
2233 }
2234
2235 impl crate::Adapter for super::Adapter {
2236 type A = super::Api;
2237
2238 unsafe fn open(
2239 &self,
2240 features: wgt::Features,
2241 _limits: &wgt::Limits,
2242 memory_hints: &wgt::MemoryHints,
2243 ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
2244 let enabled_extensions = self.required_device_extensions(features);
2245 let mut enabled_phd_features = self.physical_device_features(&enabled_extensions, features);
2246
2247 let family_index = 0; //TODO
2248 let family_info = vk::DeviceQueueCreateInfo::default()
2249 .queue_family_index(family_index)
2250 .queue_priorities(&[1.0]);
2251 let family_infos = [family_info];
2252
2253 let str_pointers = enabled_extensions
2254 .iter()
2255 .map(|&s| {
2256 // Safe because `enabled_extensions` entries have static lifetime.
2257 s.as_ptr()
2258 })
2259 .collect::<Vec<_>>();
2260
2261 let pre_info = vk::DeviceCreateInfo::default()
2262 .queue_create_infos(&family_infos)
2263 .enabled_extension_names(&str_pointers);
2264 let info = enabled_phd_features.add_to_device_create(pre_info);
2265 let raw_device = {
2266 profiling::scope!("vkCreateDevice");
2267 unsafe {
2268 self.instance
2269 .raw
2270 .create_device(self.raw, &info, None)
2271 .map_err(map_err)?
2272 }
2273 };
2274 fn map_err(err: vk::Result) -> crate::DeviceError {
2275 match err {
2276 vk::Result::ERROR_TOO_MANY_OBJECTS => crate::DeviceError::OutOfMemory,
2277 vk::Result::ERROR_INITIALIZATION_FAILED => crate::DeviceError::Lost,
2278 vk::Result::ERROR_EXTENSION_NOT_PRESENT | vk::Result::ERROR_FEATURE_NOT_PRESENT => {
2279 crate::hal_usage_error(err)
2280 }
2281 other => super::map_host_device_oom_and_lost_err(other),
2282 }
2283 }
2284
2285 unsafe {
2286 self.device_from_raw(
2287 raw_device,
2288 None,
2289 &enabled_extensions,
2290 features,
2291 memory_hints,
2292 family_info.queue_family_index,
2293 0,
2294 )
2295 }
2296 }
2297
2298 unsafe fn texture_format_capabilities(
2299 &self,
2300 format: wgt::TextureFormat,
2301 ) -> crate::TextureFormatCapabilities {
2302 use crate::TextureFormatCapabilities as Tfc;
2303
2304 let vk_format = self.private_caps.map_texture_format(format);
2305 let properties = unsafe {
2306 self.instance
2307 .raw
2308 .get_physical_device_format_properties(self.raw, vk_format)
2309 };
2310 let features = properties.optimal_tiling_features;
2311
2312 let mut flags = Tfc::empty();
2313 flags.set(
2314 Tfc::SAMPLED,
2315 features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE),
2316 );
2317 flags.set(
2318 Tfc::SAMPLED_LINEAR,
2319 features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR),
2320 );
2321 // flags.set(
2322 // Tfc::SAMPLED_MINMAX,
2323 // features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_MINMAX),
2324 // );
2325 flags.set(
2326 Tfc::STORAGE_READ_WRITE
2327 | Tfc::STORAGE_WRITE_ONLY
2328 | Tfc::STORAGE_READ_ONLY
2329 | Tfc::STORAGE_ATOMIC,
2330 features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE),
2331 );
2332 flags.set(
2333 Tfc::STORAGE_ATOMIC,
2334 features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
2335 );
2336 flags.set(
2337 Tfc::COLOR_ATTACHMENT,
2338 features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT),
2339 );
2340 flags.set(
2341 Tfc::COLOR_ATTACHMENT_BLEND,
2342 features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND),
2343 );
2344 flags.set(
2345 Tfc::DEPTH_STENCIL_ATTACHMENT,
2346 features.contains(vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT),
2347 );
2348 flags.set(
2349 Tfc::COPY_SRC,
2350 features.intersects(vk::FormatFeatureFlags::TRANSFER_SRC),
2351 );
2352 flags.set(
2353 Tfc::COPY_DST,
2354 features.intersects(vk::FormatFeatureFlags::TRANSFER_DST),
2355 );
2356 flags.set(
2357 Tfc::STORAGE_ATOMIC,
2358 features.intersects(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
2359 );
2360 // Vulkan is very permissive about MSAA
2361 flags.set(Tfc::MULTISAMPLE_RESOLVE, !format.is_compressed());
2362
2363 // get the supported sample counts
2364 let format_aspect = crate::FormatAspects::from(format);
2365 let limits = self.phd_capabilities.properties.limits;
2366
2367 let sample_flags = if format_aspect.contains(crate::FormatAspects::DEPTH) {
2368 limits
2369 .framebuffer_depth_sample_counts
2370 .min(limits.sampled_image_depth_sample_counts)
2371 } else if format_aspect.contains(crate::FormatAspects::STENCIL) {
2372 limits
2373 .framebuffer_stencil_sample_counts
2374 .min(limits.sampled_image_stencil_sample_counts)
2375 } else {
2376 let first_aspect = format_aspect
2377 .iter()
2378 .next()
2379 .expect("All texture should at least one aspect")
2380 .map();
2381
2382 // We should never get depth or stencil out of this, due to the above.
2383 assert_ne!(first_aspect, wgt::TextureAspect::DepthOnly);
2384 assert_ne!(first_aspect, wgt::TextureAspect::StencilOnly);
2385
2386 match format.sample_type(Some(first_aspect), None).unwrap() {
2387 wgt::TextureSampleType::Float { .. } => limits
2388 .framebuffer_color_sample_counts
2389 .min(limits.sampled_image_color_sample_counts),
2390 wgt::TextureSampleType::Sint | wgt::TextureSampleType::Uint => {
2391 limits.sampled_image_integer_sample_counts
2392 }
2393 _ => unreachable!(),
2394 }
2395 };
2396
2397 flags.set(
2398 Tfc::MULTISAMPLE_X2,
2399 sample_flags.contains(vk::SampleCountFlags::TYPE_2),
2400 );
2401 flags.set(
2402 Tfc::MULTISAMPLE_X4,
2403 sample_flags.contains(vk::SampleCountFlags::TYPE_4),
2404 );
2405 flags.set(
2406 Tfc::MULTISAMPLE_X8,
2407 sample_flags.contains(vk::SampleCountFlags::TYPE_8),
2408 );
2409 flags.set(
2410 Tfc::MULTISAMPLE_X16,
2411 sample_flags.contains(vk::SampleCountFlags::TYPE_16),
2412 );
2413
2414 flags
2415 }
2416
2417 unsafe fn surface_capabilities(
2418 &self,
2419 surface: &super::Surface,
2420 ) -> Option<crate::SurfaceCapabilities> {
2421 if !self.private_caps.can_present {
2422 return None;
2423 }
2424 let queue_family_index = 0; //TODO
2425 {
2426 profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR");
2427 match unsafe {
2428 surface.functor.get_physical_device_surface_support(
2429 self.raw,
2430 queue_family_index,
2431 surface.raw,
2432 )
2433 } {
2434 Ok(true) => (),
2435 Ok(false) => return None,
2436 Err(e) => {
2437 log::error!("get_physical_device_surface_support: {}", e);
2438 return None;
2439 }
2440 }
2441 }
2442
2443 let caps = {
2444 profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
2445 match unsafe {
2446 surface
2447 .functor
2448 .get_physical_device_surface_capabilities(self.raw, surface.raw)
2449 } {
2450 Ok(caps) => caps,
2451 Err(e) => {
2452 log::error!("get_physical_device_surface_capabilities: {}", e);
2453 return None;
2454 }
2455 }
2456 };
2457
2458 // If image count is 0, the support number of images is unlimited.
2459 let max_image_count = if caps.max_image_count == 0 {
2460 !0
2461 } else {
2462 caps.max_image_count
2463 };
2464
2465 // `0xFFFFFFFF` indicates that the extent depends on the created swapchain.
2466 let current_extent = if caps.current_extent.width != !0 && caps.current_extent.height != !0
2467 {
2468 Some(wgt::Extent3d {
2469 width: caps.current_extent.width,
2470 height: caps.current_extent.height,
2471 depth_or_array_layers: 1,
2472 })
2473 } else {
2474 None
2475 };
2476
2477 let raw_present_modes = {
2478 profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR");
2479 match unsafe {
2480 surface
2481 .functor
2482 .get_physical_device_surface_present_modes(self.raw, surface.raw)
2483 } {
2484 Ok(present_modes) => present_modes,
2485 Err(e) => {
2486 log::error!("get_physical_device_surface_present_modes: {}", e);
2487 // Per definition of `SurfaceCapabilities`, there must be at least one present mode.
2488 return None;
2489 }
2490 }
2491 };
2492
2493 let raw_surface_formats = {
2494 profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR");
2495 match unsafe {
2496 surface
2497 .functor
2498 .get_physical_device_surface_formats(self.raw, surface.raw)
2499 } {
2500 Ok(formats) => formats,
2501 Err(e) => {
2502 log::error!("get_physical_device_surface_formats: {}", e);
2503 // Per definition of `SurfaceCapabilities`, there must be at least one present format.
2504 return None;
2505 }
2506 }
2507 };
2508
2509 let formats = raw_surface_formats
2510 .into_iter()
2511 .filter_map(conv::map_vk_surface_formats)
2512 .collect();
2513 Some(crate::SurfaceCapabilities {
2514 formats,
2515 // TODO: Right now we're always trunkating the swap chain
2516 // (presumably - we're actually setting the min image count which isn't necessarily the swap chain size)
2517 // Instead, we should use extensions when available to wait in present.
2518 // See https://github.com/gfx-rs/wgpu/issues/2869
2519 maximum_frame_latency: (caps.min_image_count - 1)..=(max_image_count - 1), // Note this can't underflow since both `min_image_count` is at least one and we already patched `max_image_count`.
2520 current_extent,
2521 usage: conv::map_vk_image_usage(caps.supported_usage_flags),
2522 present_modes: raw_present_modes
2523 .into_iter()
2524 .flat_map(conv::map_vk_present_mode)
2525 .collect(),
2526 composite_alpha_modes: conv::map_vk_composite_alpha(caps.supported_composite_alpha),
2527 })
2528 }
2529
2530 unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
2531 // VK_GOOGLE_display_timing is the only way to get presentation
2532 // timestamps on vulkan right now and it is only ever available
2533 // on android and linux. This includes mac, but there's no alternative
2534 // on mac, so this is fine.
2535 #[cfg(unix)]
2536 {
2537 let mut timespec = libc::timespec {
2538 tv_sec: 0,
2539 tv_nsec: 0,
2540 };
2541 unsafe {
2542 libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut timespec);
2543 }
2544
2545 wgt::PresentationTimestamp(
2546 timespec.tv_sec as u128 * 1_000_000_000 + timespec.tv_nsec as u128,
2547 )
2548 }
2549 #[cfg(not(unix))]
2550 {
2551 wgt::PresentationTimestamp::INVALID_TIMESTAMP
2552 }
2553 }
2554 }
2555
2556 fn is_format_16bit_norm_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
2557 let tiling = vk::ImageTiling::OPTIMAL;
2558 let features = vk::FormatFeatureFlags::SAMPLED_IMAGE
2559 | vk::FormatFeatureFlags::STORAGE_IMAGE
2560 | vk::FormatFeatureFlags::TRANSFER_SRC
2561 | vk::FormatFeatureFlags::TRANSFER_DST;
2562 let r16unorm = supports_format(instance, phd, vk::Format::R16_UNORM, tiling, features);
2563 let r16snorm = supports_format(instance, phd, vk::Format::R16_SNORM, tiling, features);
2564 let rg16unorm = supports_format(instance, phd, vk::Format::R16G16_UNORM, tiling, features);
2565 let rg16snorm = supports_format(instance, phd, vk::Format::R16G16_SNORM, tiling, features);
2566 let rgba16unorm = supports_format(
2567 instance,
2568 phd,
2569 vk::Format::R16G16B16A16_UNORM,
2570 tiling,
2571 features,
2572 );
2573 let rgba16snorm = supports_format(
2574 instance,
2575 phd,
2576 vk::Format::R16G16B16A16_SNORM,
2577 tiling,
2578 features,
2579 );
2580
2581 r16unorm && r16snorm && rg16unorm && rg16snorm && rgba16unorm && rgba16snorm
2582 }
2583
2584 fn is_float32_filterable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
2585 let tiling = vk::ImageTiling::OPTIMAL;
2586 let features = vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR;
2587 let r_float = supports_format(instance, phd, vk::Format::R32_SFLOAT, tiling, features);
2588 let rg_float = supports_format(instance, phd, vk::Format::R32G32_SFLOAT, tiling, features);
2589 let rgba_float = supports_format(
2590 instance,
2591 phd,
2592 vk::Format::R32G32B32A32_SFLOAT,
2593 tiling,
2594 features,
2595 );
2596 r_float && rg_float && rgba_float
2597 }
2598
2599 fn supports_format(
2600 instance: &ash::Instance,
2601 phd: vk::PhysicalDevice,
2602 format: vk::Format,
2603 tiling: vk::ImageTiling,
2604 features: vk::FormatFeatureFlags,
2605 ) -> bool {
2606 let properties = unsafe { instance.get_physical_device_format_properties(phd, format) };
2607 match tiling {
2608 vk::ImageTiling::LINEAR => properties.linear_tiling_features.contains(features),
2609 vk::ImageTiling::OPTIMAL => properties.optimal_tiling_features.contains(features),
2610 _ => false,
2611 }
2612 }
2613
2614 fn supports_astc_3d(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
2615 let mut supports = true;
2616
2617 let astc_formats = [
2618 vk::Format::ASTC_4X4_UNORM_BLOCK,
2619 vk::Format::ASTC_4X4_SRGB_BLOCK,
2620 vk::Format::ASTC_5X4_UNORM_BLOCK,
2621 vk::Format::ASTC_5X4_SRGB_BLOCK,
2622 vk::Format::ASTC_5X5_UNORM_BLOCK,
2623 vk::Format::ASTC_5X5_SRGB_BLOCK,
2624 vk::Format::ASTC_6X5_UNORM_BLOCK,
2625 vk::Format::ASTC_6X5_SRGB_BLOCK,
2626 vk::Format::ASTC_6X6_UNORM_BLOCK,
2627 vk::Format::ASTC_6X6_SRGB_BLOCK,
2628 vk::Format::ASTC_8X5_UNORM_BLOCK,
2629 vk::Format::ASTC_8X5_SRGB_BLOCK,
2630 vk::Format::ASTC_8X6_UNORM_BLOCK,
2631 vk::Format::ASTC_8X6_SRGB_BLOCK,
2632 vk::Format::ASTC_8X8_UNORM_BLOCK,
2633 vk::Format::ASTC_8X8_SRGB_BLOCK,
2634 vk::Format::ASTC_10X5_UNORM_BLOCK,
2635 vk::Format::ASTC_10X5_SRGB_BLOCK,
2636 vk::Format::ASTC_10X6_UNORM_BLOCK,
2637 vk::Format::ASTC_10X6_SRGB_BLOCK,
2638 vk::Format::ASTC_10X8_UNORM_BLOCK,
2639 vk::Format::ASTC_10X8_SRGB_BLOCK,
2640 vk::Format::ASTC_10X10_UNORM_BLOCK,
2641 vk::Format::ASTC_10X10_SRGB_BLOCK,
2642 vk::Format::ASTC_12X10_UNORM_BLOCK,
2643 vk::Format::ASTC_12X10_SRGB_BLOCK,
2644 vk::Format::ASTC_12X12_UNORM_BLOCK,
2645 vk::Format::ASTC_12X12_SRGB_BLOCK,
2646 ];
2647
2648 for &format in &astc_formats {
2649 let result = unsafe {
2650 instance.get_physical_device_image_format_properties(
2651 phd,
2652 format,
2653 vk::ImageType::TYPE_3D,
2654 vk::ImageTiling::OPTIMAL,
2655 vk::ImageUsageFlags::SAMPLED,
2656 vk::ImageCreateFlags::empty(),
2657 )
2658 };
2659 if result.is_err() {
2660 supports = false;
2661 break;
2662 }
2663 }
2664
2665 supports
2666 }
2667
2668 fn supports_bgra8unorm_storage(
2669 instance: &ash::Instance,
2670 phd: vk::PhysicalDevice,
2671 device_api_version: u32,
2672 ) -> bool {
2673 // See https://github.com/KhronosGroup/Vulkan-Docs/issues/2027#issuecomment-1380608011
2674
2675 // This check gates the function call and structures used below.
2676 // TODO: check for (`VK_KHR_get_physical_device_properties2` or VK1.1) and (`VK_KHR_format_feature_flags2` or VK1.3).
2677 // Right now we only check for VK1.3.
2678 if device_api_version < vk::API_VERSION_1_3 {
2679 return false;
2680 }
2681
2682 unsafe {
2683 let mut properties3 = vk::FormatProperties3::default();
2684 let mut properties2 = vk::FormatProperties2::default().push_next(&mut properties3);
2685
2686 instance.get_physical_device_format_properties2(
2687 phd,
2688 vk::Format::B8G8R8A8_UNORM,
2689 &mut properties2,
2690 );
2691
2692 let features2 = properties2.format_properties.optimal_tiling_features;
2693 let features3 = properties3.optimal_tiling_features;
2694
2695 features2.contains(vk::FormatFeatureFlags::STORAGE_IMAGE)
2696 && features3.contains(vk::FormatFeatureFlags2::STORAGE_WRITE_WITHOUT_FORMAT)
2697 }
2698 }
2699
2700 // For https://github.com/gfx-rs/wgpu/issues/4599
2701 // Intel iGPUs with outdated drivers can break rendering if `VK_EXT_robustness2` is used.
2702 // Driver version 31.0.101.2115 works, but there's probably an earlier functional version.
2703 fn is_intel_igpu_outdated_for_robustness2(
2704 props: vk::PhysicalDeviceProperties,
2705 driver: Option<vk::PhysicalDeviceDriverPropertiesKHR>,
2706 ) -> bool {
2707 const DRIVER_VERSION_WORKING: u32 = (101 << 14) | 2115; // X.X.101.2115
2708
2709 let is_outdated = props.vendor_id == crate::auxil::db::intel::VENDOR
2710 && props.device_type == vk::PhysicalDeviceType::INTEGRATED_GPU
2711 && props.driver_version < DRIVER_VERSION_WORKING
2712 && driver
2713 .map(|driver| driver.driver_id == vk::DriverId::INTEL_PROPRIETARY_WINDOWS)
2714 .unwrap_or_default();
2715
2716 if is_outdated {
2717 log::warn!(
2718 "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)",
2719 props.driver_version,
2720 DRIVER_VERSION_WORKING
2721 );
2722 }
2723 is_outdated
2724 }