| 1 |
use alloc::{ |
| 2 |
borrow::{Cow, ToOwned as _}, |
| 3 |
collections::BTreeMap, |
| 4 |
ffi::CString, |
| 5 |
sync::Arc, |
| 6 |
vec::Vec, |
| 7 |
}; |
| 8 |
use core::{ |
| 9 |
ffi::CStr, |
| 10 |
mem::{self, MaybeUninit}, |
| 11 |
num::NonZeroU32, |
| 12 |
ptr, |
| 13 |
}; |
| 14 |
|
| 15 |
use arrayvec::ArrayVec; |
| 16 |
use ash::{ext, khr, vk}; |
| 17 |
use hashbrown::hash_map::Entry; |
| 18 |
use parking_lot::Mutex; |
| 19 |
|
| 20 |
use super::{conv, RawTlasInstance}; |
| 21 |
use crate::TlasInstance; |
| 22 |
|
| 23 |
impl super::DeviceShared { |
| 24 |
/// Set the name of `object` to `name`. |
| 25 |
/// |
| 26 |
/// If `name` contains an interior null byte, then the name set will be truncated to that byte. |
| 27 |
/// |
| 28 |
/// # Safety |
| 29 |
/// |
| 30 |
/// It must be valid to set `object`'s debug name |
| 31 |
pub(super) unsafe fn set_object_name(&self, object: impl vk::Handle, name: &str) { |
| 32 |
let Some(extension) = self.extension_fns.debug_utils.as_ref() else { |
| 33 |
return; |
| 34 |
}; |
| 35 |
|
| 36 |
// Keep variables outside the if-else block to ensure they do not |
| 37 |
// go out of scope while we hold a pointer to them |
| 38 |
let mut buffer: [u8; 64] = [0u8; 64]; |
| 39 |
let buffer_vec: Vec<u8>; |
| 40 |
|
| 41 |
// Append a null terminator to the string |
| 42 |
let name_bytes = if name.len() < buffer.len() { |
| 43 |
// Common case, string is very small. Allocate a copy on the stack. |
| 44 |
buffer[..name.len()].copy_from_slice(name.as_bytes()); |
| 45 |
// Add null terminator |
| 46 |
buffer[name.len()] = 0; |
| 47 |
&buffer[..name.len() + 1] |
| 48 |
} else { |
| 49 |
// Less common case, the string is large. |
| 50 |
// This requires a heap allocation. |
| 51 |
buffer_vec = name |
| 52 |
.as_bytes() |
| 53 |
.iter() |
| 54 |
.cloned() |
| 55 |
.chain(core::iter::once(0)) |
| 56 |
.collect(); |
| 57 |
&buffer_vec |
| 58 |
}; |
| 59 |
|
| 60 |
let name = CStr::from_bytes_until_nul(name_bytes).expect("We have added a null byte"); |
| 61 |
|
| 62 |
let _result = unsafe { |
| 63 |
extension.set_debug_utils_object_name( |
| 64 |
&vk::DebugUtilsObjectNameInfoEXT::default() |
| 65 |
.object_handle(object) |
| 66 |
.object_name(name), |
| 67 |
) |
| 68 |
}; |
| 69 |
} |
| 70 |
|
| 71 |
pub fn make_render_pass( |
| 72 |
&self, |
| 73 |
key: super::RenderPassKey, |
| 74 |
) -> Result<vk::RenderPass, crate::DeviceError> { |
| 75 |
Ok(match self.render_passes.lock().entry(key) { |
| 76 |
Entry::Occupied(e) => *e.get(), |
| 77 |
Entry::Vacant(e) => { |
| 78 |
let super::RenderPassKey { |
| 79 |
ref colors, |
| 80 |
ref depth_stencil, |
| 81 |
sample_count, |
| 82 |
multiview, |
| 83 |
} = *e.key(); |
| 84 |
|
| 85 |
let mut vk_attachments = Vec::new(); |
| 86 |
let mut color_refs = Vec::with_capacity(colors.len()); |
| 87 |
let mut resolve_refs = Vec::with_capacity(color_refs.capacity()); |
| 88 |
let mut ds_ref = None; |
| 89 |
let samples = vk::SampleCountFlags::from_raw(sample_count); |
| 90 |
let unused = vk::AttachmentReference { |
| 91 |
attachment: vk::ATTACHMENT_UNUSED, |
| 92 |
layout: vk::ImageLayout::UNDEFINED, |
| 93 |
}; |
| 94 |
for cat in colors.iter() { |
| 95 |
let (color_ref, resolve_ref) = |
| 96 |
if let Some(super::ColorAttachmentKey { base, resolve }) = cat { |
| 97 |
let super::AttachmentKey { |
| 98 |
format, |
| 99 |
layout, |
| 100 |
ops, |
| 101 |
} = *base; |
| 102 |
|
| 103 |
let color_ref = vk::AttachmentReference { |
| 104 |
attachment: vk_attachments.len() as u32, |
| 105 |
layout, |
| 106 |
}; |
| 107 |
vk_attachments.push({ |
| 108 |
let (load_op, store_op) = conv::map_attachment_ops(ops); |
| 109 |
vk::AttachmentDescription::default() |
| 110 |
.format(format) |
| 111 |
.samples(samples) |
| 112 |
.load_op(load_op) |
| 113 |
.store_op(store_op) |
| 114 |
.initial_layout(layout) |
| 115 |
.final_layout(layout) |
| 116 |
}); |
| 117 |
let resolve_ref = if let Some(rat) = resolve { |
| 118 |
let super::AttachmentKey { |
| 119 |
format, |
| 120 |
layout, |
| 121 |
ops, |
| 122 |
} = *rat; |
| 123 |
|
| 124 |
let (load_op, store_op) = conv::map_attachment_ops(ops); |
| 125 |
let vk_attachment = vk::AttachmentDescription::default() |
| 126 |
.format(format) |
| 127 |
.samples(vk::SampleCountFlags::TYPE_1) |
| 128 |
.load_op(load_op) |
| 129 |
.store_op(store_op) |
| 130 |
.initial_layout(layout) |
| 131 |
.final_layout(layout); |
| 132 |
vk_attachments.push(vk_attachment); |
| 133 |
|
| 134 |
vk::AttachmentReference { |
| 135 |
attachment: vk_attachments.len() as u32 - 1, |
| 136 |
layout, |
| 137 |
} |
| 138 |
} else { |
| 139 |
unused |
| 140 |
}; |
| 141 |
|
| 142 |
(color_ref, resolve_ref) |
| 143 |
} else { |
| 144 |
(unused, unused) |
| 145 |
}; |
| 146 |
|
| 147 |
color_refs.push(color_ref); |
| 148 |
resolve_refs.push(resolve_ref); |
| 149 |
} |
| 150 |
|
| 151 |
if let Some(ds) = depth_stencil { |
| 152 |
let super::DepthStencilAttachmentKey { |
| 153 |
ref base, |
| 154 |
stencil_ops, |
| 155 |
} = *ds; |
| 156 |
|
| 157 |
let super::AttachmentKey { |
| 158 |
format, |
| 159 |
layout, |
| 160 |
ops, |
| 161 |
} = *base; |
| 162 |
|
| 163 |
ds_ref = Some(vk::AttachmentReference { |
| 164 |
attachment: vk_attachments.len() as u32, |
| 165 |
layout, |
| 166 |
}); |
| 167 |
let (load_op, store_op) = conv::map_attachment_ops(ops); |
| 168 |
let (stencil_load_op, stencil_store_op) = conv::map_attachment_ops(stencil_ops); |
| 169 |
let vk_attachment = vk::AttachmentDescription::default() |
| 170 |
.format(format) |
| 171 |
.samples(samples) |
| 172 |
.load_op(load_op) |
| 173 |
.store_op(store_op) |
| 174 |
.stencil_load_op(stencil_load_op) |
| 175 |
.stencil_store_op(stencil_store_op) |
| 176 |
.initial_layout(layout) |
| 177 |
.final_layout(layout); |
| 178 |
vk_attachments.push(vk_attachment); |
| 179 |
} |
| 180 |
|
| 181 |
let vk_subpasses = [{ |
| 182 |
let mut vk_subpass = vk::SubpassDescription::default() |
| 183 |
.pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) |
| 184 |
.color_attachments(&color_refs) |
| 185 |
.resolve_attachments(&resolve_refs); |
| 186 |
|
| 187 |
if self |
| 188 |
.workarounds |
| 189 |
.contains(super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS) |
| 190 |
&& resolve_refs.is_empty() |
| 191 |
{ |
| 192 |
vk_subpass.p_resolve_attachments = ptr::null(); |
| 193 |
} |
| 194 |
|
| 195 |
if let Some(ref reference) = ds_ref { |
| 196 |
vk_subpass = vk_subpass.depth_stencil_attachment(reference) |
| 197 |
} |
| 198 |
vk_subpass |
| 199 |
}]; |
| 200 |
|
| 201 |
let mut vk_info = vk::RenderPassCreateInfo::default() |
| 202 |
.attachments(&vk_attachments) |
| 203 |
.subpasses(&vk_subpasses); |
| 204 |
|
| 205 |
let mut multiview_info; |
| 206 |
let mask; |
| 207 |
if let Some(multiview) = multiview { |
| 208 |
// Sanity checks, better to panic here than cause a driver crash |
| 209 |
assert!(multiview.get() <= 8); |
| 210 |
assert!(multiview.get() > 1); |
| 211 |
|
| 212 |
// Right now we enable all bits on the view masks and correlation masks. |
| 213 |
// This means we're rendering to all views in the subpass, and that all views |
| 214 |
// can be rendered concurrently. |
| 215 |
mask = [(1 << multiview.get()) - 1]; |
| 216 |
|
| 217 |
// On Vulkan 1.1 or later, this is an alias for core functionality |
| 218 |
multiview_info = vk::RenderPassMultiviewCreateInfoKHR::default() |
| 219 |
.view_masks(&mask) |
| 220 |
.correlation_masks(&mask); |
| 221 |
vk_info = vk_info.push_next(&mut multiview_info); |
| 222 |
} |
| 223 |
|
| 224 |
let raw = unsafe { |
| 225 |
self.raw |
| 226 |
.create_render_pass(&vk_info, None) |
| 227 |
.map_err(super::map_host_device_oom_err)? |
| 228 |
}; |
| 229 |
|
| 230 |
*e.insert(raw) |
| 231 |
} |
| 232 |
}) |
| 233 |
} |
| 234 |
|
| 235 |
fn make_memory_ranges<'a, I: 'a + Iterator<Item = crate::MemoryRange>>( |
| 236 |
&self, |
| 237 |
buffer: &'a super::Buffer, |
| 238 |
ranges: I, |
| 239 |
) -> Option<impl 'a + Iterator<Item = vk::MappedMemoryRange>> { |
| 240 |
let block = buffer.block.as_ref()?.lock(); |
| 241 |
let mask = self.private_caps.non_coherent_map_mask; |
| 242 |
Some(ranges.map(move |range| { |
| 243 |
vk::MappedMemoryRange::default() |
| 244 |
.memory(*block.memory()) |
| 245 |
.offset((block.offset() + range.start) & !mask) |
| 246 |
.size((range.end - range.start + mask) & !mask) |
| 247 |
})) |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
impl gpu_alloc::MemoryDevice<vk::DeviceMemory> for super::DeviceShared { |
| 252 |
unsafe fn allocate_memory( |
| 253 |
&self, |
| 254 |
size: u64, |
| 255 |
memory_type: u32, |
| 256 |
flags: gpu_alloc::AllocationFlags, |
| 257 |
) -> Result<vk::DeviceMemory, gpu_alloc::OutOfMemory> { |
| 258 |
let mut info = vk::MemoryAllocateInfo::default() |
| 259 |
.allocation_size(size) |
| 260 |
.memory_type_index(memory_type); |
| 261 |
|
| 262 |
let mut info_flags; |
| 263 |
|
| 264 |
if flags.contains(gpu_alloc::AllocationFlags::DEVICE_ADDRESS) { |
| 265 |
info_flags = vk::MemoryAllocateFlagsInfo::default() |
| 266 |
.flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); |
| 267 |
info = info.push_next(&mut info_flags); |
| 268 |
} |
| 269 |
|
| 270 |
match unsafe { self.raw.allocate_memory(&info, None) } { |
| 271 |
Ok(memory) => { |
| 272 |
self.memory_allocations_counter.add(1); |
| 273 |
Ok(memory) |
| 274 |
} |
| 275 |
Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => { |
| 276 |
Err(gpu_alloc::OutOfMemory::OutOfDeviceMemory) |
| 277 |
} |
| 278 |
Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => { |
| 279 |
Err(gpu_alloc::OutOfMemory::OutOfHostMemory) |
| 280 |
} |
| 281 |
// We don't use VK_KHR_external_memory |
| 282 |
// VK_ERROR_INVALID_EXTERNAL_HANDLE |
| 283 |
// We don't use VK_KHR_buffer_device_address |
| 284 |
// VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR |
| 285 |
Err(err) => handle_unexpected(err), |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
unsafe fn deallocate_memory(&self, memory: vk::DeviceMemory) { |
| 290 |
self.memory_allocations_counter.sub(1); |
| 291 |
|
| 292 |
unsafe { self.raw.free_memory(memory, None) }; |
| 293 |
} |
| 294 |
|
| 295 |
unsafe fn map_memory( |
| 296 |
&self, |
| 297 |
memory: &mut vk::DeviceMemory, |
| 298 |
offset: u64, |
| 299 |
size: u64, |
| 300 |
) -> Result<ptr::NonNull<u8>, gpu_alloc::DeviceMapError> { |
| 301 |
match unsafe { |
| 302 |
self.raw |
| 303 |
.map_memory(*memory, offset, size, vk::MemoryMapFlags::empty()) |
| 304 |
} { |
| 305 |
Ok(ptr) => Ok(ptr::NonNull::new(ptr.cast::<u8>()) |
| 306 |
.expect("Pointer to memory mapping must not be null")), |
| 307 |
Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => { |
| 308 |
Err(gpu_alloc::DeviceMapError::OutOfDeviceMemory) |
| 309 |
} |
| 310 |
Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => { |
| 311 |
Err(gpu_alloc::DeviceMapError::OutOfHostMemory) |
| 312 |
} |
| 313 |
Err(vk::Result::ERROR_MEMORY_MAP_FAILED) => Err(gpu_alloc::DeviceMapError::MapFailed), |
| 314 |
Err(err) => handle_unexpected(err), |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
unsafe fn unmap_memory(&self, memory: &mut vk::DeviceMemory) { |
| 319 |
unsafe { self.raw.unmap_memory(*memory) }; |
| 320 |
} |
| 321 |
|
| 322 |
unsafe fn invalidate_memory_ranges( |
| 323 |
&self, |
| 324 |
_ranges: &[gpu_alloc::MappedMemoryRange<'_, vk::DeviceMemory>], |
| 325 |
) -> Result<(), gpu_alloc::OutOfMemory> { |
| 326 |
// should never be called |
| 327 |
unimplemented!() |
| 328 |
} |
| 329 |
|
| 330 |
unsafe fn flush_memory_ranges( |
| 331 |
&self, |
| 332 |
_ranges: &[gpu_alloc::MappedMemoryRange<'_, vk::DeviceMemory>], |
| 333 |
) -> Result<(), gpu_alloc::OutOfMemory> { |
| 334 |
// should never be called |
| 335 |
unimplemented!() |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
impl |
| 340 |
gpu_descriptor::DescriptorDevice<vk::DescriptorSetLayout, vk::DescriptorPool, vk::DescriptorSet> |
| 341 |
for super::DeviceShared |
| 342 |
{ |
| 343 |
unsafe fn create_descriptor_pool( |
| 344 |
&self, |
| 345 |
descriptor_count: &gpu_descriptor::DescriptorTotalCount, |
| 346 |
max_sets: u32, |
| 347 |
flags: gpu_descriptor::DescriptorPoolCreateFlags, |
| 348 |
) -> Result<vk::DescriptorPool, gpu_descriptor::CreatePoolError> { |
| 349 |
//Note: ignoring other types, since they can't appear here |
| 350 |
let unfiltered_counts = [ |
| 351 |
(vk::DescriptorType::SAMPLER, descriptor_count.sampler), |
| 352 |
( |
| 353 |
vk::DescriptorType::SAMPLED_IMAGE, |
| 354 |
descriptor_count.sampled_image, |
| 355 |
), |
| 356 |
( |
| 357 |
vk::DescriptorType::STORAGE_IMAGE, |
| 358 |
descriptor_count.storage_image, |
| 359 |
), |
| 360 |
( |
| 361 |
vk::DescriptorType::UNIFORM_BUFFER, |
| 362 |
descriptor_count.uniform_buffer, |
| 363 |
), |
| 364 |
( |
| 365 |
vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC, |
| 366 |
descriptor_count.uniform_buffer_dynamic, |
| 367 |
), |
| 368 |
( |
| 369 |
vk::DescriptorType::STORAGE_BUFFER, |
| 370 |
descriptor_count.storage_buffer, |
| 371 |
), |
| 372 |
( |
| 373 |
vk::DescriptorType::STORAGE_BUFFER_DYNAMIC, |
| 374 |
descriptor_count.storage_buffer_dynamic, |
| 375 |
), |
| 376 |
( |
| 377 |
vk::DescriptorType::ACCELERATION_STRUCTURE_KHR, |
| 378 |
descriptor_count.acceleration_structure, |
| 379 |
), |
| 380 |
]; |
| 381 |
|
| 382 |
let filtered_counts = unfiltered_counts |
| 383 |
.iter() |
| 384 |
.cloned() |
| 385 |
.filter(|&(_, count)| count != 0) |
| 386 |
.map(|(ty, count)| vk::DescriptorPoolSize { |
| 387 |
ty, |
| 388 |
descriptor_count: count, |
| 389 |
}) |
| 390 |
.collect::<ArrayVec<_, 8>>(); |
| 391 |
|
| 392 |
let mut vk_flags = |
| 393 |
if flags.contains(gpu_descriptor::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND) { |
| 394 |
vk::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND |
| 395 |
} else { |
| 396 |
vk::DescriptorPoolCreateFlags::empty() |
| 397 |
}; |
| 398 |
if flags.contains(gpu_descriptor::DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET) { |
| 399 |
vk_flags |= vk::DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET; |
| 400 |
} |
| 401 |
let vk_info = vk::DescriptorPoolCreateInfo::default() |
| 402 |
.max_sets(max_sets) |
| 403 |
.flags(vk_flags) |
| 404 |
.pool_sizes(&filtered_counts); |
| 405 |
|
| 406 |
match unsafe { self.raw.create_descriptor_pool(&vk_info, None) } { |
| 407 |
Ok(pool) => Ok(pool), |
| 408 |
Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => { |
| 409 |
Err(gpu_descriptor::CreatePoolError::OutOfHostMemory) |
| 410 |
} |
| 411 |
Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => { |
| 412 |
Err(gpu_descriptor::CreatePoolError::OutOfDeviceMemory) |
| 413 |
} |
| 414 |
Err(vk::Result::ERROR_FRAGMENTATION) => { |
| 415 |
Err(gpu_descriptor::CreatePoolError::Fragmentation) |
| 416 |
} |
| 417 |
Err(err) => handle_unexpected(err), |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
unsafe fn destroy_descriptor_pool(&self, pool: vk::DescriptorPool) { |
| 422 |
unsafe { self.raw.destroy_descriptor_pool(pool, None) } |
| 423 |
} |
| 424 |
|
| 425 |
unsafe fn alloc_descriptor_sets<'a>( |
| 426 |
&self, |
| 427 |
pool: &mut vk::DescriptorPool, |
| 428 |
layouts: impl ExactSizeIterator<Item = &'a vk::DescriptorSetLayout>, |
| 429 |
sets: &mut impl Extend<vk::DescriptorSet>, |
| 430 |
) -> Result<(), gpu_descriptor::DeviceAllocationError> { |
| 431 |
let result = unsafe { |
| 432 |
self.raw.allocate_descriptor_sets( |
| 433 |
&vk::DescriptorSetAllocateInfo::default() |
| 434 |
.descriptor_pool(*pool) |
| 435 |
.set_layouts( |
| 436 |
&smallvec::SmallVec::<[vk::DescriptorSetLayout; 32]>::from_iter( |
| 437 |
layouts.cloned(), |
| 438 |
), |
| 439 |
), |
| 440 |
) |
| 441 |
}; |
| 442 |
|
| 443 |
match result { |
| 444 |
Ok(vk_sets) => { |
| 445 |
sets.extend(vk_sets); |
| 446 |
Ok(()) |
| 447 |
} |
| 448 |
Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) |
| 449 |
| Err(vk::Result::ERROR_OUT_OF_POOL_MEMORY) => { |
| 450 |
Err(gpu_descriptor::DeviceAllocationError::OutOfHostMemory) |
| 451 |
} |
| 452 |
Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => { |
| 453 |
Err(gpu_descriptor::DeviceAllocationError::OutOfDeviceMemory) |
| 454 |
} |
| 455 |
Err(vk::Result::ERROR_FRAGMENTED_POOL) => { |
| 456 |
Err(gpu_descriptor::DeviceAllocationError::FragmentedPool) |
| 457 |
} |
| 458 |
Err(err) => handle_unexpected(err), |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
unsafe fn dealloc_descriptor_sets<'a>( |
| 463 |
&self, |
| 464 |
pool: &mut vk::DescriptorPool, |
| 465 |
sets: impl Iterator<Item = vk::DescriptorSet>, |
| 466 |
) { |
| 467 |
let result = unsafe { |
| 468 |
self.raw.free_descriptor_sets( |
| 469 |
*pool, |
| 470 |
&smallvec::SmallVec::<[vk::DescriptorSet; 32]>::from_iter(sets), |
| 471 |
) |
| 472 |
}; |
| 473 |
match result { |
| 474 |
Ok(()) => {} |
| 475 |
Err(err) => handle_unexpected(err), |
| 476 |
} |
| 477 |
} |
| 478 |
} |
| 479 |
|
| 480 |
struct CompiledStage { |
| 481 |
create_info: vk::PipelineShaderStageCreateInfo<'static>, |
| 482 |
_entry_point: CString, |
| 483 |
temp_raw_module: Option<vk::ShaderModule>, |
| 484 |
} |
| 485 |
|
| 486 |
impl super::Device { |
| 487 |
pub(super) unsafe fn create_swapchain( |
| 488 |
&self, |
| 489 |
surface: &super::Surface, |
| 490 |
config: &crate::SurfaceConfiguration, |
| 491 |
provided_old_swapchain: Option<super::Swapchain>, |
| 492 |
) -> Result<super::Swapchain, crate::SurfaceError> { |
| 493 |
profiling::scope!("Device::create_swapchain"); |
| 494 |
let functor = khr::swapchain::Device::new(&surface.instance.raw, &self.shared.raw); |
| 495 |
|
| 496 |
let old_swapchain = match provided_old_swapchain { |
| 497 |
Some(osc) => osc.raw, |
| 498 |
None => vk::SwapchainKHR::null(), |
| 499 |
}; |
| 500 |
|
| 501 |
let color_space = if config.format == wgt::TextureFormat::Rgba16Float { |
| 502 |
// Enable wide color gamut mode |
| 503 |
// Vulkan swapchain for Android only supports DISPLAY_P3_NONLINEAR_EXT and EXTENDED_SRGB_LINEAR_EXT |
| 504 |
vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT |
| 505 |
} else { |
| 506 |
vk::ColorSpaceKHR::SRGB_NONLINEAR |
| 507 |
}; |
| 508 |
|
| 509 |
let original_format = self.shared.private_caps.map_texture_format(config.format); |
| 510 |
let mut raw_flags = vk::SwapchainCreateFlagsKHR::empty(); |
| 511 |
let mut raw_view_formats: Vec<vk::Format> = vec![]; |
| 512 |
if !config.view_formats.is_empty() { |
| 513 |
raw_flags |= vk::SwapchainCreateFlagsKHR::MUTABLE_FORMAT; |
| 514 |
raw_view_formats = config |
| 515 |
.view_formats |
| 516 |
.iter() |
| 517 |
.map(|f| self.shared.private_caps.map_texture_format(*f)) |
| 518 |
.collect(); |
| 519 |
raw_view_formats.push(original_format); |
| 520 |
} |
| 521 |
|
| 522 |
let mut info = vk::SwapchainCreateInfoKHR::default() |
| 523 |
.flags(raw_flags) |
| 524 |
.surface(surface.raw) |
| 525 |
.min_image_count(config.maximum_frame_latency + 1) // TODO: https://github.com/gfx-rs/wgpu/issues/2869 |
| 526 |
.image_format(original_format) |
| 527 |
.image_color_space(color_space) |
| 528 |
.image_extent(vk::Extent2D { |
| 529 |
width: config.extent.width, |
| 530 |
height: config.extent.height, |
| 531 |
}) |
| 532 |
.image_array_layers(config.extent.depth_or_array_layers) |
| 533 |
.image_usage(conv::map_texture_usage(config.usage)) |
| 534 |
.image_sharing_mode(vk::SharingMode::EXCLUSIVE) |
| 535 |
.pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY) |
| 536 |
.composite_alpha(conv::map_composite_alpha_mode(config.composite_alpha_mode)) |
| 537 |
.present_mode(conv::map_present_mode(config.present_mode)) |
| 538 |
.clipped(true) |
| 539 |
.old_swapchain(old_swapchain); |
| 540 |
|
| 541 |
let mut format_list_info = vk::ImageFormatListCreateInfo::default(); |
| 542 |
if !raw_view_formats.is_empty() { |
| 543 |
format_list_info = format_list_info.view_formats(&raw_view_formats); |
| 544 |
info = info.push_next(&mut format_list_info); |
| 545 |
} |
| 546 |
|
| 547 |
let result = { |
| 548 |
profiling::scope!("vkCreateSwapchainKHR"); |
| 549 |
unsafe { functor.create_swapchain(&info, None) } |
| 550 |
}; |
| 551 |
|
| 552 |
// doing this before bailing out with error |
| 553 |
if old_swapchain != vk::SwapchainKHR::null() { |
| 554 |
unsafe { functor.destroy_swapchain(old_swapchain, None) } |
| 555 |
} |
| 556 |
|
| 557 |
let raw = match result { |
| 558 |
Ok(swapchain) => swapchain, |
| 559 |
Err(error) => { |
| 560 |
return Err(match error { |
| 561 |
vk::Result::ERROR_SURFACE_LOST_KHR |
| 562 |
| vk::Result::ERROR_INITIALIZATION_FAILED => crate::SurfaceError::Lost, |
| 563 |
vk::Result::ERROR_NATIVE_WINDOW_IN_USE_KHR => { |
| 564 |
crate::SurfaceError::Other("Native window is in use") |
| 565 |
} |
| 566 |
// We don't use VK_EXT_image_compression_control |
| 567 |
// VK_ERROR_COMPRESSION_EXHAUSTED_EXT |
| 568 |
other => super::map_host_device_oom_and_lost_err(other).into(), |
| 569 |
}); |
| 570 |
} |
| 571 |
}; |
| 572 |
|
| 573 |
let images = |
| 574 |
unsafe { functor.get_swapchain_images(raw) }.map_err(super::map_host_device_oom_err)?; |
| 575 |
|
| 576 |
// NOTE: It's important that we define at least images.len() wait |
| 577 |
// semaphores, since we prospectively need to provide the call to |
| 578 |
// acquire the next image with an unsignaled semaphore. |
| 579 |
let surface_semaphores = (0..=images.len()) |
| 580 |
.map(|_| { |
| 581 |
super::SwapchainImageSemaphores::new(&self.shared) |
| 582 |
.map(Mutex::new) |
| 583 |
.map(Arc::new) |
| 584 |
}) |
| 585 |
.collect::<Result<Vec<_>, _>>()?; |
| 586 |
|
| 587 |
Ok(super::Swapchain { |
| 588 |
raw, |
| 589 |
functor, |
| 590 |
device: Arc::clone(&self.shared), |
| 591 |
images, |
| 592 |
config: config.clone(), |
| 593 |
surface_semaphores, |
| 594 |
next_semaphore_index: 0, |
| 595 |
next_present_time: None, |
| 596 |
}) |
| 597 |
} |
| 598 |
|
| 599 |
/// # Safety |
| 600 |
/// |
| 601 |
/// - `vk_image` must be created respecting `desc` |
| 602 |
/// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `vk_image`. If |
| 603 |
/// `drop_callback` is [`Some`], `vk_image` must be valid until the callback is called. |
| 604 |
/// - If the `ImageCreateFlags` does not contain `MUTABLE_FORMAT`, the `view_formats` of `desc` must be empty. |
| 605 |
pub unsafe fn texture_from_raw( |
| 606 |
vk_image: vk::Image, |
| 607 |
desc: &crate::TextureDescriptor, |
| 608 |
drop_callback: Option<crate::DropCallback>, |
| 609 |
) -> super::Texture { |
| 610 |
let mut raw_flags = vk::ImageCreateFlags::empty(); |
| 611 |
let mut view_formats = vec![]; |
| 612 |
for tf in desc.view_formats.iter() { |
| 613 |
if *tf == desc.format { |
| 614 |
continue; |
| 615 |
} |
| 616 |
view_formats.push(*tf); |
| 617 |
} |
| 618 |
if !view_formats.is_empty() { |
| 619 |
raw_flags |= |
| 620 |
vk::ImageCreateFlags::MUTABLE_FORMAT | vk::ImageCreateFlags::EXTENDED_USAGE; |
| 621 |
view_formats.push(desc.format) |
| 622 |
} |
| 623 |
if desc.format.is_multi_planar_format() { |
| 624 |
raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; |
| 625 |
} |
| 626 |
|
| 627 |
let drop_guard = crate::DropGuard::from_option(drop_callback); |
| 628 |
|
| 629 |
super::Texture { |
| 630 |
raw: vk_image, |
| 631 |
drop_guard, |
| 632 |
external_memory: None, |
| 633 |
block: None, |
| 634 |
format: desc.format, |
| 635 |
copy_size: desc.copy_extent(), |
| 636 |
} |
| 637 |
} |
| 638 |
|
| 639 |
#[cfg(windows)] |
| 640 |
fn find_memory_type_index( |
| 641 |
&self, |
| 642 |
type_bits_req: u32, |
| 643 |
flags_req: vk::MemoryPropertyFlags, |
| 644 |
) -> Option<usize> { |
| 645 |
let mem_properties = unsafe { |
| 646 |
self.shared |
| 647 |
.instance |
| 648 |
.raw |
| 649 |
.get_physical_device_memory_properties(self.shared.physical_device) |
| 650 |
}; |
| 651 |
|
| 652 |
// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceMemoryProperties.html |
| 653 |
for (i, mem_ty) in mem_properties.memory_types_as_slice().iter().enumerate() { |
| 654 |
let types_bits = 1 << i; |
| 655 |
let is_required_memory_type = type_bits_req & types_bits != 0; |
| 656 |
let has_required_properties = mem_ty.property_flags & flags_req == flags_req; |
| 657 |
if is_required_memory_type && has_required_properties { |
| 658 |
return Some(i); |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
None |
| 663 |
} |
| 664 |
|
| 665 |
fn create_image_without_memory( |
| 666 |
&self, |
| 667 |
desc: &crate::TextureDescriptor, |
| 668 |
external_memory_image_create_info: Option<&mut vk::ExternalMemoryImageCreateInfo>, |
| 669 |
) -> Result<ImageWithoutMemory, crate::DeviceError> { |
| 670 |
let copy_size = desc.copy_extent(); |
| 671 |
|
| 672 |
let mut raw_flags = vk::ImageCreateFlags::empty(); |
| 673 |
if desc.dimension == wgt::TextureDimension::D3 |
| 674 |
&& desc.usage.contains(wgt::TextureUses::COLOR_TARGET) |
| 675 |
{ |
| 676 |
raw_flags |= vk::ImageCreateFlags::TYPE_2D_ARRAY_COMPATIBLE; |
| 677 |
} |
| 678 |
if desc.is_cube_compatible() { |
| 679 |
raw_flags |= vk::ImageCreateFlags::CUBE_COMPATIBLE; |
| 680 |
} |
| 681 |
|
| 682 |
let original_format = self.shared.private_caps.map_texture_format(desc.format); |
| 683 |
let mut vk_view_formats = vec![]; |
| 684 |
if !desc.view_formats.is_empty() { |
| 685 |
raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; |
| 686 |
|
| 687 |
if self.shared.private_caps.image_format_list { |
| 688 |
vk_view_formats = desc |
| 689 |
.view_formats |
| 690 |
.iter() |
| 691 |
.map(|f| self.shared.private_caps.map_texture_format(*f)) |
| 692 |
.collect(); |
| 693 |
vk_view_formats.push(original_format) |
| 694 |
} |
| 695 |
} |
| 696 |
if desc.format.is_multi_planar_format() { |
| 697 |
raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; |
| 698 |
} |
| 699 |
|
| 700 |
let mut vk_info = vk::ImageCreateInfo::default() |
| 701 |
.flags(raw_flags) |
| 702 |
.image_type(conv::map_texture_dimension(desc.dimension)) |
| 703 |
.format(original_format) |
| 704 |
.extent(conv::map_copy_extent(©_size)) |
| 705 |
.mip_levels(desc.mip_level_count) |
| 706 |
.array_layers(desc.array_layer_count()) |
| 707 |
.samples(vk::SampleCountFlags::from_raw(desc.sample_count)) |
| 708 |
.tiling(vk::ImageTiling::OPTIMAL) |
| 709 |
.usage(conv::map_texture_usage(desc.usage)) |
| 710 |
.sharing_mode(vk::SharingMode::EXCLUSIVE) |
| 711 |
.initial_layout(vk::ImageLayout::UNDEFINED); |
| 712 |
|
| 713 |
let mut format_list_info = vk::ImageFormatListCreateInfo::default(); |
| 714 |
if !vk_view_formats.is_empty() { |
| 715 |
format_list_info = format_list_info.view_formats(&vk_view_formats); |
| 716 |
vk_info = vk_info.push_next(&mut format_list_info); |
| 717 |
} |
| 718 |
|
| 719 |
if let Some(ext_info) = external_memory_image_create_info { |
| 720 |
vk_info = vk_info.push_next(ext_info); |
| 721 |
} |
| 722 |
|
| 723 |
let raw = unsafe { self.shared.raw.create_image(&vk_info, None) }.map_err(map_err)?; |
| 724 |
fn map_err(err: vk::Result) -> crate::DeviceError { |
| 725 |
// We don't use VK_EXT_image_compression_control |
| 726 |
// VK_ERROR_COMPRESSION_EXHAUSTED_EXT |
| 727 |
super::map_host_device_oom_and_ioca_err(err) |
| 728 |
} |
| 729 |
let req = unsafe { self.shared.raw.get_image_memory_requirements(raw) }; |
| 730 |
|
| 731 |
Ok(ImageWithoutMemory { |
| 732 |
raw, |
| 733 |
requirements: req, |
| 734 |
copy_size, |
| 735 |
}) |
| 736 |
} |
| 737 |
|
| 738 |
/// # Safety |
| 739 |
/// |
| 740 |
/// - Vulkan (with VK_KHR_external_memory_win32) |
| 741 |
/// - The `d3d11_shared_handle` must be valid and respecting `desc` |
| 742 |
/// - `VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT` flag is used because we need to hold a reference to the handle |
| 743 |
#[cfg(windows)] |
| 744 |
pub unsafe fn texture_from_d3d11_shared_handle( |
| 745 |
&self, |
| 746 |
d3d11_shared_handle: windows::Win32::Foundation::HANDLE, |
| 747 |
desc: &crate::TextureDescriptor, |
| 748 |
) -> Result<super::Texture, crate::DeviceError> { |
| 749 |
if !self |
| 750 |
.shared |
| 751 |
.features |
| 752 |
.contains(wgt::Features::VULKAN_EXTERNAL_MEMORY_WIN32) |
| 753 |
{ |
| 754 |
log::error!("Vulkan driver does not support VK_KHR_external_memory_win32"); |
| 755 |
return Err(crate::DeviceError::ResourceCreationFailed); |
| 756 |
} |
| 757 |
|
| 758 |
let mut external_memory_image_info = vk::ExternalMemoryImageCreateInfo::default() |
| 759 |
.handle_types(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE); |
| 760 |
|
| 761 |
let image = |
| 762 |
self.create_image_without_memory(desc, Some(&mut external_memory_image_info))?; |
| 763 |
|
| 764 |
let mut import_memory_info = vk::ImportMemoryWin32HandleInfoKHR::default() |
| 765 |
.handle_type(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE) |
| 766 |
.handle(d3d11_shared_handle.0 as _); |
| 767 |
|
| 768 |
let mem_type_index = self |
| 769 |
.find_memory_type_index( |
| 770 |
image.requirements.memory_type_bits, |
| 771 |
vk::MemoryPropertyFlags::DEVICE_LOCAL, |
| 772 |
) |
| 773 |
.ok_or(crate::DeviceError::ResourceCreationFailed)?; |
| 774 |
|
| 775 |
let memory_allocate_info = vk::MemoryAllocateInfo::default() |
| 776 |
.allocation_size(image.requirements.size) |
| 777 |
.memory_type_index(mem_type_index as _) |
| 778 |
.push_next(&mut import_memory_info); |
| 779 |
let memory = unsafe { self.shared.raw.allocate_memory(&memory_allocate_info, None) } |
| 780 |
.map_err(super::map_host_device_oom_err)?; |
| 781 |
|
| 782 |
unsafe { self.shared.raw.bind_image_memory(image.raw, memory, 0) } |
| 783 |
.map_err(super::map_host_device_oom_err)?; |
| 784 |
|
| 785 |
if let Some(label) = desc.label { |
| 786 |
unsafe { self.shared.set_object_name(image.raw, label) }; |
| 787 |
} |
| 788 |
|
| 789 |
self.counters.textures.add(1); |
| 790 |
|
| 791 |
Ok(super::Texture { |
| 792 |
raw: image.raw, |
| 793 |
drop_guard: None, |
| 794 |
external_memory: Some(memory), |
| 795 |
block: None, |
| 796 |
format: desc.format, |
| 797 |
copy_size: image.copy_size, |
| 798 |
}) |
| 799 |
} |
| 800 |
|
| 801 |
/// # Safety |
| 802 |
/// |
| 803 |
/// - `vk_buffer`'s memory must be managed by the caller |
| 804 |
/// - Externally imported buffers can't be mapped by `wgpu` |
| 805 |
pub unsafe fn buffer_from_raw(vk_buffer: vk::Buffer) -> super::Buffer { |
| 806 |
super::Buffer { |
| 807 |
raw: vk_buffer, |
| 808 |
block: None, |
| 809 |
} |
| 810 |
} |
| 811 |
|
| 812 |
fn create_shader_module_impl( |
| 813 |
&self, |
| 814 |
spv: &[u32], |
| 815 |
) -> Result<vk::ShaderModule, crate::DeviceError> { |
| 816 |
let vk_info = vk::ShaderModuleCreateInfo::default() |
| 817 |
.flags(vk::ShaderModuleCreateFlags::empty()) |
| 818 |
.code(spv); |
| 819 |
|
| 820 |
let raw = unsafe { |
| 821 |
profiling::scope!("vkCreateShaderModule"); |
| 822 |
self.shared |
| 823 |
.raw |
| 824 |
.create_shader_module(&vk_info, None) |
| 825 |
.map_err(map_err)? |
| 826 |
}; |
| 827 |
fn map_err(err: vk::Result) -> crate::DeviceError { |
| 828 |
// We don't use VK_NV_glsl_shader |
| 829 |
// VK_ERROR_INVALID_SHADER_NV |
| 830 |
super::map_host_device_oom_err(err) |
| 831 |
} |
| 832 |
Ok(raw) |
| 833 |
} |
| 834 |
|
| 835 |
fn compile_stage( |
| 836 |
&self, |
| 837 |
stage: &crate::ProgrammableStage<super::ShaderModule>, |
| 838 |
naga_stage: naga::ShaderStage, |
| 839 |
binding_map: &naga::back::spv::BindingMap, |
| 840 |
) -> Result<CompiledStage, crate::PipelineError> { |
| 841 |
let stage_flags = crate::auxil::map_naga_stage(naga_stage); |
| 842 |
let vk_module = match *stage.module { |
| 843 |
super::ShaderModule::Raw(raw) => raw, |
| 844 |
super::ShaderModule::Intermediate { |
| 845 |
ref naga_shader, |
| 846 |
runtime_checks, |
| 847 |
} => { |
| 848 |
let pipeline_options = naga::back::spv::PipelineOptions { |
| 849 |
entry_point: stage.entry_point.to_owned(), |
| 850 |
shader_stage: naga_stage, |
| 851 |
}; |
| 852 |
let needs_temp_options = !runtime_checks.bounds_checks |
| 853 |
|| !runtime_checks.force_loop_bounding |
| 854 |
|| !binding_map.is_empty() |
| 855 |
|| naga_shader.debug_source.is_some() |
| 856 |
|| !stage.zero_initialize_workgroup_memory; |
| 857 |
let mut temp_options; |
| 858 |
let options = if needs_temp_options { |
| 859 |
temp_options = self.naga_options.clone(); |
| 860 |
if !runtime_checks.bounds_checks { |
| 861 |
temp_options.bounds_check_policies = naga::proc::BoundsCheckPolicies { |
| 862 |
index: naga::proc::BoundsCheckPolicy::Unchecked, |
| 863 |
buffer: naga::proc::BoundsCheckPolicy::Unchecked, |
| 864 |
image_load: naga::proc::BoundsCheckPolicy::Unchecked, |
| 865 |
binding_array: naga::proc::BoundsCheckPolicy::Unchecked, |
| 866 |
}; |
| 867 |
} |
| 868 |
if !runtime_checks.force_loop_bounding { |
| 869 |
temp_options.force_loop_bounding = false; |
| 870 |
} |
| 871 |
if !binding_map.is_empty() { |
| 872 |
temp_options.binding_map = binding_map.clone(); |
| 873 |
} |
| 874 |
|
| 875 |
if let Some(ref debug) = naga_shader.debug_source { |
| 876 |
temp_options.debug_info = Some(naga::back::spv::DebugInfo { |
| 877 |
source_code: &debug.source_code, |
| 878 |
file_name: debug.file_name.as_ref().as_ref(), |
| 879 |
language: naga::back::spv::SourceLanguage::WGSL, |
| 880 |
}) |
| 881 |
} |
| 882 |
if !stage.zero_initialize_workgroup_memory { |
| 883 |
temp_options.zero_initialize_workgroup_memory = |
| 884 |
naga::back::spv::ZeroInitializeWorkgroupMemoryMode::None; |
| 885 |
} |
| 886 |
|
| 887 |
&temp_options |
| 888 |
} else { |
| 889 |
&self.naga_options |
| 890 |
}; |
| 891 |
|
| 892 |
let (module, info) = naga::back::pipeline_constants::process_overrides( |
| 893 |
&naga_shader.module, |
| 894 |
&naga_shader.info, |
| 895 |
stage.constants, |
| 896 |
) |
| 897 |
.map_err(|e| { |
| 898 |
crate::PipelineError::PipelineConstants(stage_flags, format!("{e}")) |
| 899 |
})?; |
| 900 |
|
| 901 |
let spv = { |
| 902 |
profiling::scope!("naga::spv::write_vec"); |
| 903 |
naga::back::spv::write_vec(&module, &info, options, Some(&pipeline_options)) |
| 904 |
} |
| 905 |
.map_err(|e| crate::PipelineError::Linkage(stage_flags, format!("{e}")))?; |
| 906 |
self.create_shader_module_impl(&spv)? |
| 907 |
} |
| 908 |
}; |
| 909 |
|
| 910 |
let mut flags = vk::PipelineShaderStageCreateFlags::empty(); |
| 911 |
if self.shared.features.contains(wgt::Features::SUBGROUP) { |
| 912 |
flags |= vk::PipelineShaderStageCreateFlags::ALLOW_VARYING_SUBGROUP_SIZE |
| 913 |
} |
| 914 |
|
| 915 |
let entry_point = CString::new(stage.entry_point).unwrap(); |
| 916 |
let mut create_info = vk::PipelineShaderStageCreateInfo::default() |
| 917 |
.flags(flags) |
| 918 |
.stage(conv::map_shader_stage(stage_flags)) |
| 919 |
.module(vk_module); |
| 920 |
|
| 921 |
// Circumvent struct lifetime check because of a self-reference inside CompiledStage |
| 922 |
create_info.p_name = entry_point.as_ptr(); |
| 923 |
|
| 924 |
Ok(CompiledStage { |
| 925 |
create_info, |
| 926 |
_entry_point: entry_point, |
| 927 |
temp_raw_module: match *stage.module { |
| 928 |
super::ShaderModule::Raw(_) => None, |
| 929 |
super::ShaderModule::Intermediate { .. } => Some(vk_module), |
| 930 |
}, |
| 931 |
}) |
| 932 |
} |
| 933 |
|
| 934 |
/// Returns the queue family index of the device's internal queue. |
| 935 |
/// |
| 936 |
/// This is useful for constructing memory barriers needed for queue family ownership transfer when |
| 937 |
/// external memory is involved (from/to `VK_QUEUE_FAMILY_EXTERNAL_KHR` and `VK_QUEUE_FAMILY_FOREIGN_EXT` |
| 938 |
/// for example). |
| 939 |
pub fn queue_family_index(&self) -> u32 { |
| 940 |
self.shared.family_index |
| 941 |
} |
| 942 |
|
| 943 |
pub fn queue_index(&self) -> u32 { |
| 944 |
self.shared.queue_index |
| 945 |
} |
| 946 |
|
| 947 |
pub fn raw_device(&self) -> &ash::Device { |
| 948 |
&self.shared.raw |
| 949 |
} |
| 950 |
|
| 951 |
pub fn raw_physical_device(&self) -> vk::PhysicalDevice { |
| 952 |
self.shared.physical_device |
| 953 |
} |
| 954 |
|
| 955 |
pub fn raw_queue(&self) -> vk::Queue { |
| 956 |
self.shared.raw_queue |
| 957 |
} |
| 958 |
|
| 959 |
pub fn enabled_device_extensions(&self) -> &[&'static CStr] { |
| 960 |
&self.shared.enabled_extensions |
| 961 |
} |
| 962 |
|
| 963 |
pub fn shared_instance(&self) -> &super::InstanceShared { |
| 964 |
&self.shared.instance |
| 965 |
} |
| 966 |
|
| 967 |
fn error_if_would_oom_on_resource_allocation( |
| 968 |
&self, |
| 969 |
needs_host_access: bool, |
| 970 |
size: u64, |
| 971 |
) -> Result<(), crate::DeviceError> { |
| 972 |
let Some(threshold) = self |
| 973 |
.shared |
| 974 |
.instance |
| 975 |
.memory_budget_thresholds |
| 976 |
.for_resource_creation |
| 977 |
else { |
| 978 |
return Ok(()); |
| 979 |
}; |
| 980 |
|
| 981 |
if !self |
| 982 |
.shared |
| 983 |
.enabled_extensions |
| 984 |
.contains(&ext::memory_budget::NAME) |
| 985 |
{ |
| 986 |
return Ok(()); |
| 987 |
} |
| 988 |
|
| 989 |
let get_physical_device_properties = self |
| 990 |
.shared |
| 991 |
.instance |
| 992 |
.get_physical_device_properties |
| 993 |
.as_ref() |
| 994 |
.unwrap(); |
| 995 |
|
| 996 |
let mut memory_budget_properties = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default(); |
| 997 |
|
| 998 |
let mut memory_properties = |
| 999 |
vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut memory_budget_properties); |
| 1000 |
|
| 1001 |
unsafe { |
| 1002 |
get_physical_device_properties.get_physical_device_memory_properties2( |
| 1003 |
self.shared.physical_device, |
| 1004 |
&mut memory_properties, |
| 1005 |
); |
| 1006 |
} |
| 1007 |
|
| 1008 |
let mut host_visible_heaps = [false; vk::MAX_MEMORY_HEAPS]; |
| 1009 |
let mut device_local_heaps = [false; vk::MAX_MEMORY_HEAPS]; |
| 1010 |
|
| 1011 |
let memory_properties = memory_properties.memory_properties; |
| 1012 |
|
| 1013 |
for i in 0..memory_properties.memory_type_count { |
| 1014 |
let memory_type = memory_properties.memory_types[i as usize]; |
| 1015 |
let flags = memory_type.property_flags; |
| 1016 |
|
| 1017 |
if flags.intersects( |
| 1018 |
vk::MemoryPropertyFlags::LAZILY_ALLOCATED | vk::MemoryPropertyFlags::PROTECTED, |
| 1019 |
) { |
| 1020 |
continue; // not used by gpu-alloc |
| 1021 |
} |
| 1022 |
|
| 1023 |
if flags.contains(vk::MemoryPropertyFlags::HOST_VISIBLE) { |
| 1024 |
host_visible_heaps[memory_type.heap_index as usize] = true; |
| 1025 |
} |
| 1026 |
|
| 1027 |
if flags.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL) { |
| 1028 |
device_local_heaps[memory_type.heap_index as usize] = true; |
| 1029 |
} |
| 1030 |
} |
| 1031 |
|
| 1032 |
let heaps = if needs_host_access { |
| 1033 |
host_visible_heaps |
| 1034 |
} else { |
| 1035 |
device_local_heaps |
| 1036 |
}; |
| 1037 |
|
| 1038 |
// NOTE: We might end up checking multiple heaps since gpu-alloc doesn't have a way |
| 1039 |
// for us to query the heap the resource will end up on. But this is unlikely, |
| 1040 |
// there is usually only one heap on integrated GPUs and two on dedicated GPUs. |
| 1041 |
|
| 1042 |
for (i, check) in heaps.iter().enumerate() { |
| 1043 |
if !check { |
| 1044 |
continue; |
| 1045 |
} |
| 1046 |
|
| 1047 |
let heap_usage = memory_budget_properties.heap_usage[i]; |
| 1048 |
let heap_budget = memory_budget_properties.heap_budget[i]; |
| 1049 |
|
| 1050 |
if heap_usage + size >= heap_budget / 100 * threshold as u64 { |
| 1051 |
return Err(crate::DeviceError::OutOfMemory); |
| 1052 |
} |
| 1053 |
} |
| 1054 |
|
| 1055 |
Ok(()) |
| 1056 |
} |
| 1057 |
} |
| 1058 |
|
| 1059 |
impl crate::Device for super::Device { |
| 1060 |
type A = super::Api; |
| 1061 |
|
| 1062 |
unsafe fn create_buffer( |
| 1063 |
&self, |
| 1064 |
desc: &crate::BufferDescriptor, |
| 1065 |
) -> Result<super::Buffer, crate::DeviceError> { |
| 1066 |
let vk_info = vk::BufferCreateInfo::default() |
| 1067 |
.size(desc.size) |
| 1068 |
.usage(conv::map_buffer_usage(desc.usage)) |
| 1069 |
.sharing_mode(vk::SharingMode::EXCLUSIVE); |
| 1070 |
|
| 1071 |
let raw = unsafe { |
| 1072 |
self.shared |
| 1073 |
.raw |
| 1074 |
.create_buffer(&vk_info, None) |
| 1075 |
.map_err(super::map_host_device_oom_and_ioca_err)? |
| 1076 |
}; |
| 1077 |
let req = unsafe { self.shared.raw.get_buffer_memory_requirements(raw) }; |
| 1078 |
|
| 1079 |
let mut alloc_usage = if desc |
| 1080 |
.usage |
| 1081 |
.intersects(wgt::BufferUses::MAP_READ | wgt::BufferUses::MAP_WRITE) |
| 1082 |
{ |
| 1083 |
let mut flags = gpu_alloc::UsageFlags::HOST_ACCESS; |
| 1084 |
//TODO: find a way to use `crate::MemoryFlags::PREFER_COHERENT` |
| 1085 |
flags.set( |
| 1086 |
gpu_alloc::UsageFlags::DOWNLOAD, |
| 1087 |
desc.usage.contains(wgt::BufferUses::MAP_READ), |
| 1088 |
); |
| 1089 |
flags.set( |
| 1090 |
gpu_alloc::UsageFlags::UPLOAD, |
| 1091 |
desc.usage.contains(wgt::BufferUses::MAP_WRITE), |
| 1092 |
); |
| 1093 |
flags |
| 1094 |
} else { |
| 1095 |
gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS |
| 1096 |
}; |
| 1097 |
alloc_usage.set( |
| 1098 |
gpu_alloc::UsageFlags::TRANSIENT, |
| 1099 |
desc.memory_flags.contains(crate::MemoryFlags::TRANSIENT), |
| 1100 |
); |
| 1101 |
|
| 1102 |
let needs_host_access = alloc_usage.contains(gpu_alloc::UsageFlags::HOST_ACCESS); |
| 1103 |
|
| 1104 |
self.error_if_would_oom_on_resource_allocation(needs_host_access, req.size) |
| 1105 |
.inspect_err(|_| { |
| 1106 |
unsafe { self.shared.raw.destroy_buffer(raw, None) }; |
| 1107 |
})?; |
| 1108 |
|
| 1109 |
let alignment_mask = req.alignment - 1; |
| 1110 |
|
| 1111 |
let block = unsafe { |
| 1112 |
self.mem_allocator.lock().alloc( |
| 1113 |
&*self.shared, |
| 1114 |
gpu_alloc::Request { |
| 1115 |
size: req.size, |
| 1116 |
align_mask: alignment_mask, |
| 1117 |
usage: alloc_usage, |
| 1118 |
memory_types: req.memory_type_bits & self.valid_ash_memory_types, |
| 1119 |
}, |
| 1120 |
) |
| 1121 |
} |
| 1122 |
.inspect_err(|_| { |
| 1123 |
unsafe { self.shared.raw.destroy_buffer(raw, None) }; |
| 1124 |
})?; |
| 1125 |
|
| 1126 |
unsafe { |
| 1127 |
self.shared |
| 1128 |
.raw |
| 1129 |
.bind_buffer_memory(raw, *block.memory(), block.offset()) |
| 1130 |
} |
| 1131 |
.map_err(super::map_host_device_oom_and_ioca_err) |
| 1132 |
.inspect_err(|_| { |
| 1133 |
unsafe { self.shared.raw.destroy_buffer(raw, None) }; |
| 1134 |
})?; |
| 1135 |
|
| 1136 |
if let Some(label) = desc.label { |
| 1137 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 1138 |
} |
| 1139 |
|
| 1140 |
self.counters.buffer_memory.add(block.size() as isize); |
| 1141 |
self.counters.buffers.add(1); |
| 1142 |
|
| 1143 |
Ok(super::Buffer { |
| 1144 |
raw, |
| 1145 |
block: Some(Mutex::new(block)), |
| 1146 |
}) |
| 1147 |
} |
| 1148 |
unsafe fn destroy_buffer(&self, buffer: super::Buffer) { |
| 1149 |
unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) }; |
| 1150 |
if let Some(block) = buffer.block { |
| 1151 |
let block = block.into_inner(); |
| 1152 |
self.counters.buffer_memory.sub(block.size() as isize); |
| 1153 |
unsafe { self.mem_allocator.lock().dealloc(&*self.shared, block) }; |
| 1154 |
} |
| 1155 |
|
| 1156 |
self.counters.buffers.sub(1); |
| 1157 |
} |
| 1158 |
|
| 1159 |
unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) { |
| 1160 |
self.counters.buffers.add(1); |
| 1161 |
} |
| 1162 |
|
| 1163 |
unsafe fn map_buffer( |
| 1164 |
&self, |
| 1165 |
buffer: &super::Buffer, |
| 1166 |
range: crate::MemoryRange, |
| 1167 |
) -> Result<crate::BufferMapping, crate::DeviceError> { |
| 1168 |
if let Some(ref block) = buffer.block { |
| 1169 |
let size = range.end - range.start; |
| 1170 |
let mut block = block.lock(); |
| 1171 |
let ptr = unsafe { block.map(&*self.shared, range.start, size as usize)? }; |
| 1172 |
let is_coherent = block |
| 1173 |
.props() |
| 1174 |
.contains(gpu_alloc::MemoryPropertyFlags::HOST_COHERENT); |
| 1175 |
Ok(crate::BufferMapping { ptr, is_coherent }) |
| 1176 |
} else { |
| 1177 |
crate::hal_usage_error("tried to map external buffer") |
| 1178 |
} |
| 1179 |
} |
| 1180 |
unsafe fn unmap_buffer(&self, buffer: &super::Buffer) { |
| 1181 |
if let Some(ref block) = buffer.block { |
| 1182 |
unsafe { block.lock().unmap(&*self.shared) }; |
| 1183 |
} else { |
| 1184 |
crate::hal_usage_error("tried to unmap external buffer") |
| 1185 |
} |
| 1186 |
} |
| 1187 |
|
| 1188 |
unsafe fn flush_mapped_ranges<I>(&self, buffer: &super::Buffer, ranges: I) |
| 1189 |
where |
| 1190 |
I: Iterator<Item = crate::MemoryRange>, |
| 1191 |
{ |
| 1192 |
if let Some(vk_ranges) = self.shared.make_memory_ranges(buffer, ranges) { |
| 1193 |
unsafe { |
| 1194 |
self.shared |
| 1195 |
.raw |
| 1196 |
.flush_mapped_memory_ranges( |
| 1197 |
&smallvec::SmallVec::<[vk::MappedMemoryRange; 32]>::from_iter(vk_ranges), |
| 1198 |
) |
| 1199 |
} |
| 1200 |
.unwrap(); |
| 1201 |
} |
| 1202 |
} |
| 1203 |
unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &super::Buffer, ranges: I) |
| 1204 |
where |
| 1205 |
I: Iterator<Item = crate::MemoryRange>, |
| 1206 |
{ |
| 1207 |
if let Some(vk_ranges) = self.shared.make_memory_ranges(buffer, ranges) { |
| 1208 |
unsafe { |
| 1209 |
self.shared |
| 1210 |
.raw |
| 1211 |
.invalidate_mapped_memory_ranges(&smallvec::SmallVec::< |
| 1212 |
[vk::MappedMemoryRange; 32], |
| 1213 |
>::from_iter(vk_ranges)) |
| 1214 |
} |
| 1215 |
.unwrap(); |
| 1216 |
} |
| 1217 |
} |
| 1218 |
|
| 1219 |
unsafe fn create_texture( |
| 1220 |
&self, |
| 1221 |
desc: &crate::TextureDescriptor, |
| 1222 |
) -> Result<super::Texture, crate::DeviceError> { |
| 1223 |
let image = self.create_image_without_memory(desc, None)?; |
| 1224 |
|
| 1225 |
self.error_if_would_oom_on_resource_allocation(false, image.requirements.size) |
| 1226 |
.inspect_err(|_| { |
| 1227 |
unsafe { self.shared.raw.destroy_image(image.raw, None) }; |
| 1228 |
})?; |
| 1229 |
|
| 1230 |
let block = unsafe { |
| 1231 |
self.mem_allocator.lock().alloc( |
| 1232 |
&*self.shared, |
| 1233 |
gpu_alloc::Request { |
| 1234 |
size: image.requirements.size, |
| 1235 |
align_mask: image.requirements.alignment - 1, |
| 1236 |
usage: gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, |
| 1237 |
memory_types: image.requirements.memory_type_bits & self.valid_ash_memory_types, |
| 1238 |
}, |
| 1239 |
) |
| 1240 |
} |
| 1241 |
.inspect_err(|_| { |
| 1242 |
unsafe { self.shared.raw.destroy_image(image.raw, None) }; |
| 1243 |
})?; |
| 1244 |
|
| 1245 |
self.counters.texture_memory.add(block.size() as isize); |
| 1246 |
|
| 1247 |
unsafe { |
| 1248 |
self.shared |
| 1249 |
.raw |
| 1250 |
.bind_image_memory(image.raw, *block.memory(), block.offset()) |
| 1251 |
} |
| 1252 |
.map_err(super::map_host_device_oom_err) |
| 1253 |
.inspect_err(|_| { |
| 1254 |
unsafe { self.shared.raw.destroy_image(image.raw, None) }; |
| 1255 |
})?; |
| 1256 |
|
| 1257 |
if let Some(label) = desc.label { |
| 1258 |
unsafe { self.shared.set_object_name(image.raw, label) }; |
| 1259 |
} |
| 1260 |
|
| 1261 |
self.counters.textures.add(1); |
| 1262 |
|
| 1263 |
Ok(super::Texture { |
| 1264 |
raw: image.raw, |
| 1265 |
drop_guard: None, |
| 1266 |
external_memory: None, |
| 1267 |
block: Some(block), |
| 1268 |
format: desc.format, |
| 1269 |
copy_size: image.copy_size, |
| 1270 |
}) |
| 1271 |
} |
| 1272 |
unsafe fn destroy_texture(&self, texture: super::Texture) { |
| 1273 |
if texture.drop_guard.is_none() { |
| 1274 |
unsafe { self.shared.raw.destroy_image(texture.raw, None) }; |
| 1275 |
} |
| 1276 |
if let Some(memory) = texture.external_memory { |
| 1277 |
unsafe { self.shared.raw.free_memory(memory, None) }; |
| 1278 |
} |
| 1279 |
if let Some(block) = texture.block { |
| 1280 |
self.counters.texture_memory.sub(block.size() as isize); |
| 1281 |
|
| 1282 |
unsafe { self.mem_allocator.lock().dealloc(&*self.shared, block) }; |
| 1283 |
} |
| 1284 |
|
| 1285 |
self.counters.textures.sub(1); |
| 1286 |
} |
| 1287 |
|
| 1288 |
unsafe fn add_raw_texture(&self, _texture: &super::Texture) { |
| 1289 |
self.counters.textures.add(1); |
| 1290 |
} |
| 1291 |
|
| 1292 |
unsafe fn create_texture_view( |
| 1293 |
&self, |
| 1294 |
texture: &super::Texture, |
| 1295 |
desc: &crate::TextureViewDescriptor, |
| 1296 |
) -> Result<super::TextureView, crate::DeviceError> { |
| 1297 |
let subresource_range = conv::map_subresource_range(&desc.range, texture.format); |
| 1298 |
let raw_format = self.shared.private_caps.map_texture_format(desc.format); |
| 1299 |
let mut vk_info = vk::ImageViewCreateInfo::default() |
| 1300 |
.flags(vk::ImageViewCreateFlags::empty()) |
| 1301 |
.image(texture.raw) |
| 1302 |
.view_type(conv::map_view_dimension(desc.dimension)) |
| 1303 |
.format(raw_format) |
| 1304 |
.subresource_range(subresource_range); |
| 1305 |
let layers = |
| 1306 |
NonZeroU32::new(subresource_range.layer_count).expect("Unexpected zero layer count"); |
| 1307 |
|
| 1308 |
let mut image_view_info; |
| 1309 |
if self.shared.private_caps.image_view_usage && !desc.usage.is_empty() { |
| 1310 |
image_view_info = |
| 1311 |
vk::ImageViewUsageCreateInfo::default().usage(conv::map_texture_usage(desc.usage)); |
| 1312 |
vk_info = vk_info.push_next(&mut image_view_info); |
| 1313 |
} |
| 1314 |
|
| 1315 |
let raw = unsafe { self.shared.raw.create_image_view(&vk_info, None) } |
| 1316 |
.map_err(super::map_host_device_oom_and_ioca_err)?; |
| 1317 |
|
| 1318 |
if let Some(label) = desc.label { |
| 1319 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 1320 |
} |
| 1321 |
|
| 1322 |
self.counters.texture_views.add(1); |
| 1323 |
|
| 1324 |
Ok(super::TextureView { |
| 1325 |
raw_texture: texture.raw, |
| 1326 |
raw, |
| 1327 |
layers, |
| 1328 |
format: desc.format, |
| 1329 |
raw_format, |
| 1330 |
base_mip_level: desc.range.base_mip_level, |
| 1331 |
dimension: desc.dimension, |
| 1332 |
}) |
| 1333 |
} |
| 1334 |
unsafe fn destroy_texture_view(&self, view: super::TextureView) { |
| 1335 |
unsafe { self.shared.raw.destroy_image_view(view.raw, None) }; |
| 1336 |
|
| 1337 |
self.counters.texture_views.sub(1); |
| 1338 |
} |
| 1339 |
|
| 1340 |
unsafe fn create_sampler( |
| 1341 |
&self, |
| 1342 |
desc: &crate::SamplerDescriptor, |
| 1343 |
) -> Result<super::Sampler, crate::DeviceError> { |
| 1344 |
let mut create_info = vk::SamplerCreateInfo::default() |
| 1345 |
.flags(vk::SamplerCreateFlags::empty()) |
| 1346 |
.mag_filter(conv::map_filter_mode(desc.mag_filter)) |
| 1347 |
.min_filter(conv::map_filter_mode(desc.min_filter)) |
| 1348 |
.mipmap_mode(conv::map_mip_filter_mode(desc.mipmap_filter)) |
| 1349 |
.address_mode_u(conv::map_address_mode(desc.address_modes[0])) |
| 1350 |
.address_mode_v(conv::map_address_mode(desc.address_modes[1])) |
| 1351 |
.address_mode_w(conv::map_address_mode(desc.address_modes[2])) |
| 1352 |
.min_lod(desc.lod_clamp.start) |
| 1353 |
.max_lod(desc.lod_clamp.end); |
| 1354 |
|
| 1355 |
if let Some(fun) = desc.compare { |
| 1356 |
create_info = create_info |
| 1357 |
.compare_enable(true) |
| 1358 |
.compare_op(conv::map_comparison(fun)); |
| 1359 |
} |
| 1360 |
|
| 1361 |
if desc.anisotropy_clamp != 1 { |
| 1362 |
// We only enable anisotropy if it is supported, and wgpu-hal interface guarantees |
| 1363 |
// the clamp is in the range [1, 16] which is always supported if anisotropy is. |
| 1364 |
create_info = create_info |
| 1365 |
.anisotropy_enable(true) |
| 1366 |
.max_anisotropy(desc.anisotropy_clamp as f32); |
| 1367 |
} |
| 1368 |
|
| 1369 |
if let Some(color) = desc.border_color { |
| 1370 |
create_info = create_info.border_color(conv::map_border_color(color)); |
| 1371 |
} |
| 1372 |
|
| 1373 |
let raw = self |
| 1374 |
.shared |
| 1375 |
.sampler_cache |
| 1376 |
.lock() |
| 1377 |
.create_sampler(&self.shared.raw, create_info)?; |
| 1378 |
|
| 1379 |
// Note: Cached samplers will just continually overwrite the label |
| 1380 |
// |
| 1381 |
// https://github.com/gfx-rs/wgpu/issues/6867 |
| 1382 |
if let Some(label) = desc.label { |
| 1383 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 1384 |
} |
| 1385 |
|
| 1386 |
self.counters.samplers.add(1); |
| 1387 |
|
| 1388 |
Ok(super::Sampler { raw, create_info }) |
| 1389 |
} |
| 1390 |
unsafe fn destroy_sampler(&self, sampler: super::Sampler) { |
| 1391 |
self.shared.sampler_cache.lock().destroy_sampler( |
| 1392 |
&self.shared.raw, |
| 1393 |
sampler.create_info, |
| 1394 |
sampler.raw, |
| 1395 |
); |
| 1396 |
|
| 1397 |
self.counters.samplers.sub(1); |
| 1398 |
} |
| 1399 |
|
| 1400 |
unsafe fn create_command_encoder( |
| 1401 |
&self, |
| 1402 |
desc: &crate::CommandEncoderDescriptor<super::Queue>, |
| 1403 |
) -> Result<super::CommandEncoder, crate::DeviceError> { |
| 1404 |
let vk_info = vk::CommandPoolCreateInfo::default() |
| 1405 |
.queue_family_index(desc.queue.family_index) |
| 1406 |
.flags(vk::CommandPoolCreateFlags::TRANSIENT); |
| 1407 |
|
| 1408 |
let raw = unsafe { |
| 1409 |
self.shared |
| 1410 |
.raw |
| 1411 |
.create_command_pool(&vk_info, None) |
| 1412 |
.map_err(super::map_host_device_oom_err)? |
| 1413 |
}; |
| 1414 |
|
| 1415 |
self.counters.command_encoders.add(1); |
| 1416 |
|
| 1417 |
Ok(super::CommandEncoder { |
| 1418 |
raw, |
| 1419 |
device: Arc::clone(&self.shared), |
| 1420 |
active: vk::CommandBuffer::null(), |
| 1421 |
bind_point: vk::PipelineBindPoint::default(), |
| 1422 |
temp: super::Temp::default(), |
| 1423 |
free: Vec::new(), |
| 1424 |
discarded: Vec::new(), |
| 1425 |
rpass_debug_marker_active: false, |
| 1426 |
end_of_pass_timer_query: None, |
| 1427 |
framebuffers: Default::default(), |
| 1428 |
temp_texture_views: Default::default(), |
| 1429 |
counters: Arc::clone(&self.counters), |
| 1430 |
}) |
| 1431 |
} |
| 1432 |
|
| 1433 |
unsafe fn create_bind_group_layout( |
| 1434 |
&self, |
| 1435 |
desc: &crate::BindGroupLayoutDescriptor, |
| 1436 |
) -> Result<super::BindGroupLayout, crate::DeviceError> { |
| 1437 |
let mut desc_count = gpu_descriptor::DescriptorTotalCount::default(); |
| 1438 |
let mut types = Vec::new(); |
| 1439 |
for entry in desc.entries { |
| 1440 |
let count = entry.count.map_or(1, |c| c.get()); |
| 1441 |
if entry.binding as usize >= types.len() { |
| 1442 |
types.resize( |
| 1443 |
entry.binding as usize + 1, |
| 1444 |
(vk::DescriptorType::INPUT_ATTACHMENT, 0), |
| 1445 |
); |
| 1446 |
} |
| 1447 |
types[entry.binding as usize] = ( |
| 1448 |
conv::map_binding_type(entry.ty), |
| 1449 |
entry.count.map_or(1, |c| c.get()), |
| 1450 |
); |
| 1451 |
|
| 1452 |
match entry.ty { |
| 1453 |
wgt::BindingType::Buffer { |
| 1454 |
ty, |
| 1455 |
has_dynamic_offset, |
| 1456 |
.. |
| 1457 |
} => match ty { |
| 1458 |
wgt::BufferBindingType::Uniform => { |
| 1459 |
if has_dynamic_offset { |
| 1460 |
desc_count.uniform_buffer_dynamic += count; |
| 1461 |
} else { |
| 1462 |
desc_count.uniform_buffer += count; |
| 1463 |
} |
| 1464 |
} |
| 1465 |
wgt::BufferBindingType::Storage { .. } => { |
| 1466 |
if has_dynamic_offset { |
| 1467 |
desc_count.storage_buffer_dynamic += count; |
| 1468 |
} else { |
| 1469 |
desc_count.storage_buffer += count; |
| 1470 |
} |
| 1471 |
} |
| 1472 |
}, |
| 1473 |
wgt::BindingType::Sampler { .. } => { |
| 1474 |
desc_count.sampler += count; |
| 1475 |
} |
| 1476 |
wgt::BindingType::Texture { .. } => { |
| 1477 |
desc_count.sampled_image += count; |
| 1478 |
} |
| 1479 |
wgt::BindingType::StorageTexture { .. } => { |
| 1480 |
desc_count.storage_image += count; |
| 1481 |
} |
| 1482 |
wgt::BindingType::AccelerationStructure { .. } => { |
| 1483 |
desc_count.acceleration_structure += count; |
| 1484 |
} |
| 1485 |
} |
| 1486 |
} |
| 1487 |
|
| 1488 |
//Note: not bothering with on stack array here as it's low frequency |
| 1489 |
let vk_bindings = desc |
| 1490 |
.entries |
| 1491 |
.iter() |
| 1492 |
.map(|entry| vk::DescriptorSetLayoutBinding { |
| 1493 |
binding: entry.binding, |
| 1494 |
descriptor_type: types[entry.binding as usize].0, |
| 1495 |
descriptor_count: types[entry.binding as usize].1, |
| 1496 |
stage_flags: conv::map_shader_stage(entry.visibility), |
| 1497 |
p_immutable_samplers: ptr::null(), |
| 1498 |
_marker: Default::default(), |
| 1499 |
}) |
| 1500 |
.collect::<Vec<_>>(); |
| 1501 |
|
| 1502 |
let binding_arrays: Vec<_> = desc |
| 1503 |
.entries |
| 1504 |
.iter() |
| 1505 |
.enumerate() |
| 1506 |
.filter_map(|(idx, entry)| entry.count.map(|count| (idx as u32, count))) |
| 1507 |
.collect(); |
| 1508 |
|
| 1509 |
let vk_info = vk::DescriptorSetLayoutCreateInfo::default() |
| 1510 |
.bindings(&vk_bindings) |
| 1511 |
.flags(if !binding_arrays.is_empty() { |
| 1512 |
vk::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL |
| 1513 |
} else { |
| 1514 |
vk::DescriptorSetLayoutCreateFlags::empty() |
| 1515 |
}); |
| 1516 |
|
| 1517 |
let partially_bound = desc |
| 1518 |
.flags |
| 1519 |
.contains(crate::BindGroupLayoutFlags::PARTIALLY_BOUND); |
| 1520 |
|
| 1521 |
let binding_flag_vec = desc |
| 1522 |
.entries |
| 1523 |
.iter() |
| 1524 |
.map(|entry| { |
| 1525 |
let mut flags = vk::DescriptorBindingFlags::empty(); |
| 1526 |
|
| 1527 |
if partially_bound && entry.count.is_some() { |
| 1528 |
flags |= vk::DescriptorBindingFlags::PARTIALLY_BOUND; |
| 1529 |
} |
| 1530 |
|
| 1531 |
if entry.count.is_some() { |
| 1532 |
flags |= vk::DescriptorBindingFlags::UPDATE_AFTER_BIND; |
| 1533 |
} |
| 1534 |
|
| 1535 |
flags |
| 1536 |
}) |
| 1537 |
.collect::<Vec<_>>(); |
| 1538 |
|
| 1539 |
let mut binding_flag_info = vk::DescriptorSetLayoutBindingFlagsCreateInfo::default() |
| 1540 |
.binding_flags(&binding_flag_vec); |
| 1541 |
|
| 1542 |
let vk_info = vk_info.push_next(&mut binding_flag_info); |
| 1543 |
|
| 1544 |
let raw = unsafe { |
| 1545 |
self.shared |
| 1546 |
.raw |
| 1547 |
.create_descriptor_set_layout(&vk_info, None) |
| 1548 |
.map_err(super::map_host_device_oom_err)? |
| 1549 |
}; |
| 1550 |
|
| 1551 |
if let Some(label) = desc.label { |
| 1552 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 1553 |
} |
| 1554 |
|
| 1555 |
self.counters.bind_group_layouts.add(1); |
| 1556 |
|
| 1557 |
Ok(super::BindGroupLayout { |
| 1558 |
raw, |
| 1559 |
desc_count, |
| 1560 |
types: types.into_boxed_slice(), |
| 1561 |
binding_arrays, |
| 1562 |
}) |
| 1563 |
} |
| 1564 |
unsafe fn destroy_bind_group_layout(&self, bg_layout: super::BindGroupLayout) { |
| 1565 |
unsafe { |
| 1566 |
self.shared |
| 1567 |
.raw |
| 1568 |
.destroy_descriptor_set_layout(bg_layout.raw, None) |
| 1569 |
}; |
| 1570 |
|
| 1571 |
self.counters.bind_group_layouts.sub(1); |
| 1572 |
} |
| 1573 |
|
| 1574 |
unsafe fn create_pipeline_layout( |
| 1575 |
&self, |
| 1576 |
desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>, |
| 1577 |
) -> Result<super::PipelineLayout, crate::DeviceError> { |
| 1578 |
//Note: not bothering with on stack array here as it's low frequency |
| 1579 |
let vk_set_layouts = desc |
| 1580 |
.bind_group_layouts |
| 1581 |
.iter() |
| 1582 |
.map(|bgl| bgl.raw) |
| 1583 |
.collect::<Vec<_>>(); |
| 1584 |
let vk_push_constant_ranges = desc |
| 1585 |
.push_constant_ranges |
| 1586 |
.iter() |
| 1587 |
.map(|pcr| vk::PushConstantRange { |
| 1588 |
stage_flags: conv::map_shader_stage(pcr.stages), |
| 1589 |
offset: pcr.range.start, |
| 1590 |
size: pcr.range.end - pcr.range.start, |
| 1591 |
}) |
| 1592 |
.collect::<Vec<_>>(); |
| 1593 |
|
| 1594 |
let vk_info = vk::PipelineLayoutCreateInfo::default() |
| 1595 |
.flags(vk::PipelineLayoutCreateFlags::empty()) |
| 1596 |
.set_layouts(&vk_set_layouts) |
| 1597 |
.push_constant_ranges(&vk_push_constant_ranges); |
| 1598 |
|
| 1599 |
let raw = { |
| 1600 |
profiling::scope!("vkCreatePipelineLayout"); |
| 1601 |
unsafe { |
| 1602 |
self.shared |
| 1603 |
.raw |
| 1604 |
.create_pipeline_layout(&vk_info, None) |
| 1605 |
.map_err(super::map_host_device_oom_err)? |
| 1606 |
} |
| 1607 |
}; |
| 1608 |
|
| 1609 |
if let Some(label) = desc.label { |
| 1610 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 1611 |
} |
| 1612 |
|
| 1613 |
let mut binding_arrays = BTreeMap::new(); |
| 1614 |
for (group, &layout) in desc.bind_group_layouts.iter().enumerate() { |
| 1615 |
for &(binding, binding_array_size) in &layout.binding_arrays { |
| 1616 |
binding_arrays.insert( |
| 1617 |
naga::ResourceBinding { |
| 1618 |
group: group as u32, |
| 1619 |
binding, |
| 1620 |
}, |
| 1621 |
naga::back::spv::BindingInfo { |
| 1622 |
binding_array_size: Some(binding_array_size.get()), |
| 1623 |
}, |
| 1624 |
); |
| 1625 |
} |
| 1626 |
} |
| 1627 |
|
| 1628 |
self.counters.pipeline_layouts.add(1); |
| 1629 |
|
| 1630 |
Ok(super::PipelineLayout { |
| 1631 |
raw, |
| 1632 |
binding_arrays, |
| 1633 |
}) |
| 1634 |
} |
| 1635 |
unsafe fn destroy_pipeline_layout(&self, pipeline_layout: super::PipelineLayout) { |
| 1636 |
unsafe { |
| 1637 |
self.shared |
| 1638 |
.raw |
| 1639 |
.destroy_pipeline_layout(pipeline_layout.raw, None) |
| 1640 |
}; |
| 1641 |
|
| 1642 |
self.counters.pipeline_layouts.sub(1); |
| 1643 |
} |
| 1644 |
|
| 1645 |
unsafe fn create_bind_group( |
| 1646 |
&self, |
| 1647 |
desc: &crate::BindGroupDescriptor< |
| 1648 |
super::BindGroupLayout, |
| 1649 |
super::Buffer, |
| 1650 |
super::Sampler, |
| 1651 |
super::TextureView, |
| 1652 |
super::AccelerationStructure, |
| 1653 |
>, |
| 1654 |
) -> Result<super::BindGroup, crate::DeviceError> { |
| 1655 |
let contains_binding_arrays = !desc.layout.binding_arrays.is_empty(); |
| 1656 |
|
| 1657 |
let desc_set_layout_flags = if contains_binding_arrays { |
| 1658 |
gpu_descriptor::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND |
| 1659 |
} else { |
| 1660 |
gpu_descriptor::DescriptorSetLayoutCreateFlags::empty() |
| 1661 |
}; |
| 1662 |
|
| 1663 |
let mut vk_sets = unsafe { |
| 1664 |
self.desc_allocator.lock().allocate( |
| 1665 |
&*self.shared, |
| 1666 |
&desc.layout.raw, |
| 1667 |
desc_set_layout_flags, |
| 1668 |
&desc.layout.desc_count, |
| 1669 |
1, |
| 1670 |
)? |
| 1671 |
}; |
| 1672 |
|
| 1673 |
let set = vk_sets.pop().unwrap(); |
| 1674 |
if let Some(label) = desc.label { |
| 1675 |
unsafe { self.shared.set_object_name(*set.raw(), label) }; |
| 1676 |
} |
| 1677 |
|
| 1678 |
/// Helper for splitting off and initializing a given number of elements on a pre-allocated |
| 1679 |
/// stack, based on items returned from an [`ExactSizeIterator`]. Typically created from a |
| 1680 |
/// [`MaybeUninit`] slice (see [`Vec::spare_capacity_mut()`]). |
| 1681 |
/// The updated [`ExtensionStack`] of remaining uninitialized elements is returned, safely |
| 1682 |
/// representing that the initialized and remaining elements are two independent mutable |
| 1683 |
/// borrows. |
| 1684 |
struct ExtendStack<'a, T> { |
| 1685 |
remainder: &'a mut [MaybeUninit<T>], |
| 1686 |
} |
| 1687 |
|
| 1688 |
impl<'a, T> ExtendStack<'a, T> { |
| 1689 |
fn from_vec_capacity(vec: &'a mut Vec<T>) -> Self { |
| 1690 |
Self { |
| 1691 |
remainder: vec.spare_capacity_mut(), |
| 1692 |
} |
| 1693 |
} |
| 1694 |
|
| 1695 |
fn extend_one(self, value: T) -> (Self, &'a mut T) { |
| 1696 |
let (to_init, remainder) = self.remainder.split_first_mut().unwrap(); |
| 1697 |
let init = to_init.write(value); |
| 1698 |
(Self { remainder }, init) |
| 1699 |
} |
| 1700 |
|
| 1701 |
fn extend( |
| 1702 |
self, |
| 1703 |
iter: impl IntoIterator<Item = T> + ExactSizeIterator, |
| 1704 |
) -> (Self, &'a mut [T]) { |
| 1705 |
let (to_init, remainder) = self.remainder.split_at_mut(iter.len()); |
| 1706 |
|
| 1707 |
for (value, to_init) in iter.into_iter().zip(to_init.iter_mut()) { |
| 1708 |
to_init.write(value); |
| 1709 |
} |
| 1710 |
|
| 1711 |
// we can't use the safe (yet unstable) MaybeUninit::write_slice() here because of having an iterator to write |
| 1712 |
|
| 1713 |
let init = { |
| 1714 |
// SAFETY: The loop above has initialized exactly as many items as to_init is |
| 1715 |
// long, so it is safe to cast away the MaybeUninit<T> wrapper into T. |
| 1716 |
|
| 1717 |
// Additional safety docs from unstable slice_assume_init_mut |
| 1718 |
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a |
| 1719 |
// mutable reference which is also guaranteed to be valid for writes. |
| 1720 |
unsafe { mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(to_init) } |
| 1721 |
}; |
| 1722 |
(Self { remainder }, init) |
| 1723 |
} |
| 1724 |
} |
| 1725 |
|
| 1726 |
let mut writes = Vec::with_capacity(desc.entries.len()); |
| 1727 |
let mut buffer_infos = Vec::with_capacity(desc.buffers.len()); |
| 1728 |
let mut buffer_infos = ExtendStack::from_vec_capacity(&mut buffer_infos); |
| 1729 |
let mut image_infos = Vec::with_capacity(desc.samplers.len() + desc.textures.len()); |
| 1730 |
let mut image_infos = ExtendStack::from_vec_capacity(&mut image_infos); |
| 1731 |
// TODO: This length could be reduced to just the number of top-level acceleration |
| 1732 |
// structure bindings, where multiple consecutive TLAS bindings that are set via |
| 1733 |
// one `WriteDescriptorSet` count towards one "info" struct, not the total number of |
| 1734 |
// acceleration structure bindings to write: |
| 1735 |
let mut acceleration_structure_infos = |
| 1736 |
Vec::with_capacity(desc.acceleration_structures.len()); |
| 1737 |
let mut acceleration_structure_infos = |
| 1738 |
ExtendStack::from_vec_capacity(&mut acceleration_structure_infos); |
| 1739 |
let mut raw_acceleration_structures = |
| 1740 |
Vec::with_capacity(desc.acceleration_structures.len()); |
| 1741 |
let mut raw_acceleration_structures = |
| 1742 |
ExtendStack::from_vec_capacity(&mut raw_acceleration_structures); |
| 1743 |
for entry in desc.entries { |
| 1744 |
let (ty, size) = desc.layout.types[entry.binding as usize]; |
| 1745 |
if size == 0 { |
| 1746 |
continue; // empty slot |
| 1747 |
} |
| 1748 |
let mut write = vk::WriteDescriptorSet::default() |
| 1749 |
.dst_set(*set.raw()) |
| 1750 |
.dst_binding(entry.binding) |
| 1751 |
.descriptor_type(ty); |
| 1752 |
|
| 1753 |
write = match ty { |
| 1754 |
vk::DescriptorType::SAMPLER => { |
| 1755 |
let start = entry.resource_index; |
| 1756 |
let end = start + entry.count; |
| 1757 |
let local_image_infos; |
| 1758 |
(image_infos, local_image_infos) = |
| 1759 |
image_infos.extend(desc.samplers[start as usize..end as usize].iter().map( |
| 1760 |
|sampler| vk::DescriptorImageInfo::default().sampler(sampler.raw), |
| 1761 |
)); |
| 1762 |
write.image_info(local_image_infos) |
| 1763 |
} |
| 1764 |
vk::DescriptorType::SAMPLED_IMAGE | vk::DescriptorType::STORAGE_IMAGE => { |
| 1765 |
let start = entry.resource_index; |
| 1766 |
let end = start + entry.count; |
| 1767 |
let local_image_infos; |
| 1768 |
(image_infos, local_image_infos) = |
| 1769 |
image_infos.extend(desc.textures[start as usize..end as usize].iter().map( |
| 1770 |
|binding| { |
| 1771 |
let layout = |
| 1772 |
conv::derive_image_layout(binding.usage, binding.view.format); |
| 1773 |
vk::DescriptorImageInfo::default() |
| 1774 |
.image_view(binding.view.raw) |
| 1775 |
.image_layout(layout) |
| 1776 |
}, |
| 1777 |
)); |
| 1778 |
write.image_info(local_image_infos) |
| 1779 |
} |
| 1780 |
vk::DescriptorType::UNIFORM_BUFFER |
| 1781 |
| vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC |
| 1782 |
| vk::DescriptorType::STORAGE_BUFFER |
| 1783 |
| vk::DescriptorType::STORAGE_BUFFER_DYNAMIC => { |
| 1784 |
let start = entry.resource_index; |
| 1785 |
let end = start + entry.count; |
| 1786 |
let local_buffer_infos; |
| 1787 |
(buffer_infos, local_buffer_infos) = |
| 1788 |
buffer_infos.extend(desc.buffers[start as usize..end as usize].iter().map( |
| 1789 |
|binding| { |
| 1790 |
vk::DescriptorBufferInfo::default() |
| 1791 |
.buffer(binding.buffer.raw) |
| 1792 |
.offset(binding.offset) |
| 1793 |
.range( |
| 1794 |
binding.size.map_or(vk::WHOLE_SIZE, wgt::BufferSize::get), |
| 1795 |
) |
| 1796 |
}, |
| 1797 |
)); |
| 1798 |
write.buffer_info(local_buffer_infos) |
| 1799 |
} |
| 1800 |
vk::DescriptorType::ACCELERATION_STRUCTURE_KHR => { |
| 1801 |
let start = entry.resource_index; |
| 1802 |
let end = start + entry.count; |
| 1803 |
|
| 1804 |
let local_raw_acceleration_structures; |
| 1805 |
( |
| 1806 |
raw_acceleration_structures, |
| 1807 |
local_raw_acceleration_structures, |
| 1808 |
) = raw_acceleration_structures.extend( |
| 1809 |
desc.acceleration_structures[start as usize..end as usize] |
| 1810 |
.iter() |
| 1811 |
.map(|acceleration_structure| acceleration_structure.raw), |
| 1812 |
); |
| 1813 |
|
| 1814 |
let local_acceleration_structure_infos; |
| 1815 |
( |
| 1816 |
acceleration_structure_infos, |
| 1817 |
local_acceleration_structure_infos, |
| 1818 |
) = acceleration_structure_infos.extend_one( |
| 1819 |
vk::WriteDescriptorSetAccelerationStructureKHR::default() |
| 1820 |
.acceleration_structures(local_raw_acceleration_structures), |
| 1821 |
); |
| 1822 |
|
| 1823 |
write |
| 1824 |
.descriptor_count(entry.count) |
| 1825 |
.push_next(local_acceleration_structure_infos) |
| 1826 |
} |
| 1827 |
_ => unreachable!(), |
| 1828 |
}; |
| 1829 |
|
| 1830 |
writes.push(write); |
| 1831 |
} |
| 1832 |
|
| 1833 |
unsafe { self.shared.raw.update_descriptor_sets(&writes, &[]) }; |
| 1834 |
|
| 1835 |
self.counters.bind_groups.add(1); |
| 1836 |
|
| 1837 |
Ok(super::BindGroup { set }) |
| 1838 |
} |
| 1839 |
|
| 1840 |
unsafe fn destroy_bind_group(&self, group: super::BindGroup) { |
| 1841 |
unsafe { |
| 1842 |
self.desc_allocator |
| 1843 |
.lock() |
| 1844 |
.free(&*self.shared, Some(group.set)) |
| 1845 |
}; |
| 1846 |
|
| 1847 |
self.counters.bind_groups.sub(1); |
| 1848 |
} |
| 1849 |
|
| 1850 |
unsafe fn create_shader_module( |
| 1851 |
&self, |
| 1852 |
desc: &crate::ShaderModuleDescriptor, |
| 1853 |
shader: crate::ShaderInput, |
| 1854 |
) -> Result<super::ShaderModule, crate::ShaderError> { |
| 1855 |
let spv = match shader { |
| 1856 |
crate::ShaderInput::Naga(naga_shader) => { |
| 1857 |
if self |
| 1858 |
.shared |
| 1859 |
.workarounds |
| 1860 |
.contains(super::Workarounds::SEPARATE_ENTRY_POINTS) |
| 1861 |
|| !naga_shader.module.overrides.is_empty() |
| 1862 |
{ |
| 1863 |
return Ok(super::ShaderModule::Intermediate { |
| 1864 |
naga_shader, |
| 1865 |
runtime_checks: desc.runtime_checks, |
| 1866 |
}); |
| 1867 |
} |
| 1868 |
let mut naga_options = self.naga_options.clone(); |
| 1869 |
naga_options.debug_info = |
| 1870 |
naga_shader |
| 1871 |
.debug_source |
| 1872 |
.as_ref() |
| 1873 |
.map(|d| naga::back::spv::DebugInfo { |
| 1874 |
source_code: d.source_code.as_ref(), |
| 1875 |
file_name: d.file_name.as_ref().as_ref(), |
| 1876 |
language: naga::back::spv::SourceLanguage::WGSL, |
| 1877 |
}); |
| 1878 |
if !desc.runtime_checks.bounds_checks { |
| 1879 |
naga_options.bounds_check_policies = naga::proc::BoundsCheckPolicies { |
| 1880 |
index: naga::proc::BoundsCheckPolicy::Unchecked, |
| 1881 |
buffer: naga::proc::BoundsCheckPolicy::Unchecked, |
| 1882 |
image_load: naga::proc::BoundsCheckPolicy::Unchecked, |
| 1883 |
binding_array: naga::proc::BoundsCheckPolicy::Unchecked, |
| 1884 |
}; |
| 1885 |
} |
| 1886 |
Cow::Owned( |
| 1887 |
naga::back::spv::write_vec( |
| 1888 |
&naga_shader.module, |
| 1889 |
&naga_shader.info, |
| 1890 |
&naga_options, |
| 1891 |
None, |
| 1892 |
) |
| 1893 |
.map_err(|e| crate::ShaderError::Compilation(format!("{e}")))?, |
| 1894 |
) |
| 1895 |
} |
| 1896 |
crate::ShaderInput::Msl { .. } => { |
| 1897 |
panic!("MSL_SHADER_PASSTHROUGH is not enabled for this backend") |
| 1898 |
} |
| 1899 |
crate::ShaderInput::SpirV(spv) => Cow::Borrowed(spv), |
| 1900 |
}; |
| 1901 |
|
| 1902 |
let raw = self.create_shader_module_impl(&spv)?; |
| 1903 |
|
| 1904 |
if let Some(label) = desc.label { |
| 1905 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 1906 |
} |
| 1907 |
|
| 1908 |
self.counters.shader_modules.add(1); |
| 1909 |
|
| 1910 |
Ok(super::ShaderModule::Raw(raw)) |
| 1911 |
} |
| 1912 |
|
| 1913 |
unsafe fn destroy_shader_module(&self, module: super::ShaderModule) { |
| 1914 |
match module { |
| 1915 |
super::ShaderModule::Raw(raw) => { |
| 1916 |
unsafe { self.shared.raw.destroy_shader_module(raw, None) }; |
| 1917 |
} |
| 1918 |
super::ShaderModule::Intermediate { .. } => {} |
| 1919 |
} |
| 1920 |
|
| 1921 |
self.counters.shader_modules.sub(1); |
| 1922 |
} |
| 1923 |
|
| 1924 |
unsafe fn create_render_pipeline( |
| 1925 |
&self, |
| 1926 |
desc: &crate::RenderPipelineDescriptor< |
| 1927 |
super::PipelineLayout, |
| 1928 |
super::ShaderModule, |
| 1929 |
super::PipelineCache, |
| 1930 |
>, |
| 1931 |
) -> Result<super::RenderPipeline, crate::PipelineError> { |
| 1932 |
let dynamic_states = [ |
| 1933 |
vk::DynamicState::VIEWPORT, |
| 1934 |
vk::DynamicState::SCISSOR, |
| 1935 |
vk::DynamicState::BLEND_CONSTANTS, |
| 1936 |
vk::DynamicState::STENCIL_REFERENCE, |
| 1937 |
]; |
| 1938 |
let mut compatible_rp_key = super::RenderPassKey { |
| 1939 |
sample_count: desc.multisample.count, |
| 1940 |
multiview: desc.multiview, |
| 1941 |
..Default::default() |
| 1942 |
}; |
| 1943 |
let mut stages = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); |
| 1944 |
let mut vertex_buffers = Vec::with_capacity(desc.vertex_buffers.len()); |
| 1945 |
let mut vertex_attributes = Vec::new(); |
| 1946 |
|
| 1947 |
for (i, vb) in desc.vertex_buffers.iter().enumerate() { |
| 1948 |
vertex_buffers.push(vk::VertexInputBindingDescription { |
| 1949 |
binding: i as u32, |
| 1950 |
stride: vb.array_stride as u32, |
| 1951 |
input_rate: match vb.step_mode { |
| 1952 |
wgt::VertexStepMode::Vertex => vk::VertexInputRate::VERTEX, |
| 1953 |
wgt::VertexStepMode::Instance => vk::VertexInputRate::INSTANCE, |
| 1954 |
}, |
| 1955 |
}); |
| 1956 |
for at in vb.attributes { |
| 1957 |
vertex_attributes.push(vk::VertexInputAttributeDescription { |
| 1958 |
location: at.shader_location, |
| 1959 |
binding: i as u32, |
| 1960 |
format: conv::map_vertex_format(at.format), |
| 1961 |
offset: at.offset as u32, |
| 1962 |
}); |
| 1963 |
} |
| 1964 |
} |
| 1965 |
|
| 1966 |
let vk_vertex_input = vk::PipelineVertexInputStateCreateInfo::default() |
| 1967 |
.vertex_binding_descriptions(&vertex_buffers) |
| 1968 |
.vertex_attribute_descriptions(&vertex_attributes); |
| 1969 |
|
| 1970 |
let vk_input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() |
| 1971 |
.topology(conv::map_topology(desc.primitive.topology)) |
| 1972 |
.primitive_restart_enable(desc.primitive.strip_index_format.is_some()); |
| 1973 |
|
| 1974 |
let compiled_vs = self.compile_stage( |
| 1975 |
&desc.vertex_stage, |
| 1976 |
naga::ShaderStage::Vertex, |
| 1977 |
&desc.layout.binding_arrays, |
| 1978 |
)?; |
| 1979 |
stages.push(compiled_vs.create_info); |
| 1980 |
let compiled_fs = match desc.fragment_stage { |
| 1981 |
Some(ref stage) => { |
| 1982 |
let compiled = self.compile_stage( |
| 1983 |
stage, |
| 1984 |
naga::ShaderStage::Fragment, |
| 1985 |
&desc.layout.binding_arrays, |
| 1986 |
)?; |
| 1987 |
stages.push(compiled.create_info); |
| 1988 |
Some(compiled) |
| 1989 |
} |
| 1990 |
None => None, |
| 1991 |
}; |
| 1992 |
|
| 1993 |
let mut vk_rasterization = vk::PipelineRasterizationStateCreateInfo::default() |
| 1994 |
.polygon_mode(conv::map_polygon_mode(desc.primitive.polygon_mode)) |
| 1995 |
.front_face(conv::map_front_face(desc.primitive.front_face)) |
| 1996 |
.line_width(1.0) |
| 1997 |
.depth_clamp_enable(desc.primitive.unclipped_depth); |
| 1998 |
if let Some(face) = desc.primitive.cull_mode { |
| 1999 |
vk_rasterization = vk_rasterization.cull_mode(conv::map_cull_face(face)) |
| 2000 |
} |
| 2001 |
let mut vk_rasterization_conservative_state = |
| 2002 |
vk::PipelineRasterizationConservativeStateCreateInfoEXT::default() |
| 2003 |
.conservative_rasterization_mode( |
| 2004 |
vk::ConservativeRasterizationModeEXT::OVERESTIMATE, |
| 2005 |
); |
| 2006 |
if desc.primitive.conservative { |
| 2007 |
vk_rasterization = vk_rasterization.push_next(&mut vk_rasterization_conservative_state); |
| 2008 |
} |
| 2009 |
|
| 2010 |
let mut vk_depth_stencil = vk::PipelineDepthStencilStateCreateInfo::default(); |
| 2011 |
if let Some(ref ds) = desc.depth_stencil { |
| 2012 |
let vk_format = self.shared.private_caps.map_texture_format(ds.format); |
| 2013 |
let vk_layout = if ds.is_read_only(desc.primitive.cull_mode) { |
| 2014 |
vk::ImageLayout::DEPTH_STENCIL_READ_ONLY_OPTIMAL |
| 2015 |
} else { |
| 2016 |
vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL |
| 2017 |
}; |
| 2018 |
compatible_rp_key.depth_stencil = Some(super::DepthStencilAttachmentKey { |
| 2019 |
base: super::AttachmentKey::compatible(vk_format, vk_layout), |
| 2020 |
stencil_ops: crate::AttachmentOps::all(), |
| 2021 |
}); |
| 2022 |
|
| 2023 |
if ds.is_depth_enabled() { |
| 2024 |
vk_depth_stencil = vk_depth_stencil |
| 2025 |
.depth_test_enable(true) |
| 2026 |
.depth_write_enable(ds.depth_write_enabled) |
| 2027 |
.depth_compare_op(conv::map_comparison(ds.depth_compare)); |
| 2028 |
} |
| 2029 |
if ds.stencil.is_enabled() { |
| 2030 |
let s = &ds.stencil; |
| 2031 |
let front = conv::map_stencil_face(&s.front, s.read_mask, s.write_mask); |
| 2032 |
let back = conv::map_stencil_face(&s.back, s.read_mask, s.write_mask); |
| 2033 |
vk_depth_stencil = vk_depth_stencil |
| 2034 |
.stencil_test_enable(true) |
| 2035 |
.front(front) |
| 2036 |
.back(back); |
| 2037 |
} |
| 2038 |
|
| 2039 |
if ds.bias.is_enabled() { |
| 2040 |
vk_rasterization = vk_rasterization |
| 2041 |
.depth_bias_enable(true) |
| 2042 |
.depth_bias_constant_factor(ds.bias.constant as f32) |
| 2043 |
.depth_bias_clamp(ds.bias.clamp) |
| 2044 |
.depth_bias_slope_factor(ds.bias.slope_scale); |
| 2045 |
} |
| 2046 |
} |
| 2047 |
|
| 2048 |
let vk_viewport = vk::PipelineViewportStateCreateInfo::default() |
| 2049 |
.flags(vk::PipelineViewportStateCreateFlags::empty()) |
| 2050 |
.scissor_count(1) |
| 2051 |
.viewport_count(1); |
| 2052 |
|
| 2053 |
let vk_sample_mask = [ |
| 2054 |
desc.multisample.mask as u32, |
| 2055 |
(desc.multisample.mask >> 32) as u32, |
| 2056 |
]; |
| 2057 |
let vk_multisample = vk::PipelineMultisampleStateCreateInfo::default() |
| 2058 |
.rasterization_samples(vk::SampleCountFlags::from_raw(desc.multisample.count)) |
| 2059 |
.alpha_to_coverage_enable(desc.multisample.alpha_to_coverage_enabled) |
| 2060 |
.sample_mask(&vk_sample_mask); |
| 2061 |
|
| 2062 |
let mut vk_attachments = Vec::with_capacity(desc.color_targets.len()); |
| 2063 |
for cat in desc.color_targets { |
| 2064 |
let (key, attarchment) = if let Some(cat) = cat.as_ref() { |
| 2065 |
let mut vk_attachment = vk::PipelineColorBlendAttachmentState::default() |
| 2066 |
.color_write_mask(vk::ColorComponentFlags::from_raw(cat.write_mask.bits())); |
| 2067 |
if let Some(ref blend) = cat.blend { |
| 2068 |
let (color_op, color_src, color_dst) = conv::map_blend_component(&blend.color); |
| 2069 |
let (alpha_op, alpha_src, alpha_dst) = conv::map_blend_component(&blend.alpha); |
| 2070 |
vk_attachment = vk_attachment |
| 2071 |
.blend_enable(true) |
| 2072 |
.color_blend_op(color_op) |
| 2073 |
.src_color_blend_factor(color_src) |
| 2074 |
.dst_color_blend_factor(color_dst) |
| 2075 |
.alpha_blend_op(alpha_op) |
| 2076 |
.src_alpha_blend_factor(alpha_src) |
| 2077 |
.dst_alpha_blend_factor(alpha_dst); |
| 2078 |
} |
| 2079 |
|
| 2080 |
let vk_format = self.shared.private_caps.map_texture_format(cat.format); |
| 2081 |
( |
| 2082 |
Some(super::ColorAttachmentKey { |
| 2083 |
base: super::AttachmentKey::compatible( |
| 2084 |
vk_format, |
| 2085 |
vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, |
| 2086 |
), |
| 2087 |
resolve: None, |
| 2088 |
}), |
| 2089 |
vk_attachment, |
| 2090 |
) |
| 2091 |
} else { |
| 2092 |
(None, vk::PipelineColorBlendAttachmentState::default()) |
| 2093 |
}; |
| 2094 |
|
| 2095 |
compatible_rp_key.colors.push(key); |
| 2096 |
vk_attachments.push(attarchment); |
| 2097 |
} |
| 2098 |
|
| 2099 |
let vk_color_blend = |
| 2100 |
vk::PipelineColorBlendStateCreateInfo::default().attachments(&vk_attachments); |
| 2101 |
|
| 2102 |
let vk_dynamic_state = |
| 2103 |
vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); |
| 2104 |
|
| 2105 |
let raw_pass = self.shared.make_render_pass(compatible_rp_key)?; |
| 2106 |
|
| 2107 |
let vk_infos = [{ |
| 2108 |
vk::GraphicsPipelineCreateInfo::default() |
| 2109 |
.layout(desc.layout.raw) |
| 2110 |
.stages(&stages) |
| 2111 |
.vertex_input_state(&vk_vertex_input) |
| 2112 |
.input_assembly_state(&vk_input_assembly) |
| 2113 |
.rasterization_state(&vk_rasterization) |
| 2114 |
.viewport_state(&vk_viewport) |
| 2115 |
.multisample_state(&vk_multisample) |
| 2116 |
.depth_stencil_state(&vk_depth_stencil) |
| 2117 |
.color_blend_state(&vk_color_blend) |
| 2118 |
.dynamic_state(&vk_dynamic_state) |
| 2119 |
.render_pass(raw_pass) |
| 2120 |
}]; |
| 2121 |
|
| 2122 |
let pipeline_cache = desc |
| 2123 |
.cache |
| 2124 |
.map(|it| it.raw) |
| 2125 |
.unwrap_or(vk::PipelineCache::null()); |
| 2126 |
|
| 2127 |
let mut raw_vec = { |
| 2128 |
profiling::scope!("vkCreateGraphicsPipelines"); |
| 2129 |
unsafe { |
| 2130 |
self.shared |
| 2131 |
.raw |
| 2132 |
.create_graphics_pipelines(pipeline_cache, &vk_infos, None) |
| 2133 |
.map_err(|(_, e)| super::map_pipeline_err(e)) |
| 2134 |
}? |
| 2135 |
}; |
| 2136 |
|
| 2137 |
let raw = raw_vec.pop().unwrap(); |
| 2138 |
if let Some(label) = desc.label { |
| 2139 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 2140 |
} |
| 2141 |
|
| 2142 |
if let Some(raw_module) = compiled_vs.temp_raw_module { |
| 2143 |
unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; |
| 2144 |
} |
| 2145 |
if let Some(CompiledStage { |
| 2146 |
temp_raw_module: Some(raw_module), |
| 2147 |
.. |
| 2148 |
}) = compiled_fs |
| 2149 |
{ |
| 2150 |
unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; |
| 2151 |
} |
| 2152 |
|
| 2153 |
self.counters.render_pipelines.add(1); |
| 2154 |
|
| 2155 |
Ok(super::RenderPipeline { raw }) |
| 2156 |
} |
| 2157 |
unsafe fn create_mesh_pipeline( |
| 2158 |
&self, |
| 2159 |
desc: &crate::MeshPipelineDescriptor< |
| 2160 |
<Self::A as crate::Api>::PipelineLayout, |
| 2161 |
<Self::A as crate::Api>::ShaderModule, |
| 2162 |
<Self::A as crate::Api>::PipelineCache, |
| 2163 |
>, |
| 2164 |
) -> Result<<Self::A as crate::Api>::RenderPipeline, crate::PipelineError> { |
| 2165 |
let dynamic_states = [ |
| 2166 |
vk::DynamicState::VIEWPORT, |
| 2167 |
vk::DynamicState::SCISSOR, |
| 2168 |
vk::DynamicState::BLEND_CONSTANTS, |
| 2169 |
vk::DynamicState::STENCIL_REFERENCE, |
| 2170 |
]; |
| 2171 |
let mut compatible_rp_key = super::RenderPassKey { |
| 2172 |
sample_count: desc.multisample.count, |
| 2173 |
multiview: desc.multiview, |
| 2174 |
..Default::default() |
| 2175 |
}; |
| 2176 |
let mut stages = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); |
| 2177 |
|
| 2178 |
let vk_input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() |
| 2179 |
.topology(conv::map_topology(desc.primitive.topology)) |
| 2180 |
.primitive_restart_enable(desc.primitive.strip_index_format.is_some()); |
| 2181 |
|
| 2182 |
let compiled_ts = match desc.task_stage { |
| 2183 |
Some(ref stage) => { |
| 2184 |
let mut compiled = self.compile_stage( |
| 2185 |
stage, |
| 2186 |
naga::ShaderStage::Task, |
| 2187 |
&desc.layout.binding_arrays, |
| 2188 |
)?; |
| 2189 |
compiled.create_info.stage = vk::ShaderStageFlags::TASK_EXT; |
| 2190 |
stages.push(compiled.create_info); |
| 2191 |
Some(compiled) |
| 2192 |
} |
| 2193 |
None => None, |
| 2194 |
}; |
| 2195 |
|
| 2196 |
let mut compiled_ms = self.compile_stage( |
| 2197 |
&desc.mesh_stage, |
| 2198 |
naga::ShaderStage::Mesh, |
| 2199 |
&desc.layout.binding_arrays, |
| 2200 |
)?; |
| 2201 |
compiled_ms.create_info.stage = vk::ShaderStageFlags::MESH_EXT; |
| 2202 |
stages.push(compiled_ms.create_info); |
| 2203 |
let compiled_fs = match desc.fragment_stage { |
| 2204 |
Some(ref stage) => { |
| 2205 |
let compiled = self.compile_stage( |
| 2206 |
stage, |
| 2207 |
naga::ShaderStage::Fragment, |
| 2208 |
&desc.layout.binding_arrays, |
| 2209 |
)?; |
| 2210 |
stages.push(compiled.create_info); |
| 2211 |
Some(compiled) |
| 2212 |
} |
| 2213 |
None => None, |
| 2214 |
}; |
| 2215 |
|
| 2216 |
let mut vk_rasterization = vk::PipelineRasterizationStateCreateInfo::default() |
| 2217 |
.polygon_mode(conv::map_polygon_mode(desc.primitive.polygon_mode)) |
| 2218 |
.front_face(conv::map_front_face(desc.primitive.front_face)) |
| 2219 |
.line_width(1.0) |
| 2220 |
.depth_clamp_enable(desc.primitive.unclipped_depth); |
| 2221 |
if let Some(face) = desc.primitive.cull_mode { |
| 2222 |
vk_rasterization = vk_rasterization.cull_mode(conv::map_cull_face(face)) |
| 2223 |
} |
| 2224 |
let mut vk_rasterization_conservative_state = |
| 2225 |
vk::PipelineRasterizationConservativeStateCreateInfoEXT::default() |
| 2226 |
.conservative_rasterization_mode( |
| 2227 |
vk::ConservativeRasterizationModeEXT::OVERESTIMATE, |
| 2228 |
); |
| 2229 |
if desc.primitive.conservative { |
| 2230 |
vk_rasterization = vk_rasterization.push_next(&mut vk_rasterization_conservative_state); |
| 2231 |
} |
| 2232 |
|
| 2233 |
let mut vk_depth_stencil = vk::PipelineDepthStencilStateCreateInfo::default(); |
| 2234 |
if let Some(ref ds) = desc.depth_stencil { |
| 2235 |
let vk_format = self.shared.private_caps.map_texture_format(ds.format); |
| 2236 |
let vk_layout = if ds.is_read_only(desc.primitive.cull_mode) { |
| 2237 |
vk::ImageLayout::DEPTH_STENCIL_READ_ONLY_OPTIMAL |
| 2238 |
} else { |
| 2239 |
vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL |
| 2240 |
}; |
| 2241 |
compatible_rp_key.depth_stencil = Some(super::DepthStencilAttachmentKey { |
| 2242 |
base: super::AttachmentKey::compatible(vk_format, vk_layout), |
| 2243 |
stencil_ops: crate::AttachmentOps::all(), |
| 2244 |
}); |
| 2245 |
|
| 2246 |
if ds.is_depth_enabled() { |
| 2247 |
vk_depth_stencil = vk_depth_stencil |
| 2248 |
.depth_test_enable(true) |
| 2249 |
.depth_write_enable(ds.depth_write_enabled) |
| 2250 |
.depth_compare_op(conv::map_comparison(ds.depth_compare)); |
| 2251 |
} |
| 2252 |
if ds.stencil.is_enabled() { |
| 2253 |
let s = &ds.stencil; |
| 2254 |
let front = conv::map_stencil_face(&s.front, s.read_mask, s.write_mask); |
| 2255 |
let back = conv::map_stencil_face(&s.back, s.read_mask, s.write_mask); |
| 2256 |
vk_depth_stencil = vk_depth_stencil |
| 2257 |
.stencil_test_enable(true) |
| 2258 |
.front(front) |
| 2259 |
.back(back); |
| 2260 |
} |
| 2261 |
|
| 2262 |
if ds.bias.is_enabled() { |
| 2263 |
vk_rasterization = vk_rasterization |
| 2264 |
.depth_bias_enable(true) |
| 2265 |
.depth_bias_constant_factor(ds.bias.constant as f32) |
| 2266 |
.depth_bias_clamp(ds.bias.clamp) |
| 2267 |
.depth_bias_slope_factor(ds.bias.slope_scale); |
| 2268 |
} |
| 2269 |
} |
| 2270 |
|
| 2271 |
let vk_viewport = vk::PipelineViewportStateCreateInfo::default() |
| 2272 |
.flags(vk::PipelineViewportStateCreateFlags::empty()) |
| 2273 |
.scissor_count(1) |
| 2274 |
.viewport_count(1); |
| 2275 |
|
| 2276 |
let vk_sample_mask = [ |
| 2277 |
desc.multisample.mask as u32, |
| 2278 |
(desc.multisample.mask >> 32) as u32, |
| 2279 |
]; |
| 2280 |
let vk_multisample = vk::PipelineMultisampleStateCreateInfo::default() |
| 2281 |
.rasterization_samples(vk::SampleCountFlags::from_raw(desc.multisample.count)) |
| 2282 |
.alpha_to_coverage_enable(desc.multisample.alpha_to_coverage_enabled) |
| 2283 |
.sample_mask(&vk_sample_mask); |
| 2284 |
|
| 2285 |
let mut vk_attachments = Vec::with_capacity(desc.color_targets.len()); |
| 2286 |
for cat in desc.color_targets { |
| 2287 |
let (key, attarchment) = if let Some(cat) = cat.as_ref() { |
| 2288 |
let mut vk_attachment = vk::PipelineColorBlendAttachmentState::default() |
| 2289 |
.color_write_mask(vk::ColorComponentFlags::from_raw(cat.write_mask.bits())); |
| 2290 |
if let Some(ref blend) = cat.blend { |
| 2291 |
let (color_op, color_src, color_dst) = conv::map_blend_component(&blend.color); |
| 2292 |
let (alpha_op, alpha_src, alpha_dst) = conv::map_blend_component(&blend.alpha); |
| 2293 |
vk_attachment = vk_attachment |
| 2294 |
.blend_enable(true) |
| 2295 |
.color_blend_op(color_op) |
| 2296 |
.src_color_blend_factor(color_src) |
| 2297 |
.dst_color_blend_factor(color_dst) |
| 2298 |
.alpha_blend_op(alpha_op) |
| 2299 |
.src_alpha_blend_factor(alpha_src) |
| 2300 |
.dst_alpha_blend_factor(alpha_dst); |
| 2301 |
} |
| 2302 |
|
| 2303 |
let vk_format = self.shared.private_caps.map_texture_format(cat.format); |
| 2304 |
( |
| 2305 |
Some(super::ColorAttachmentKey { |
| 2306 |
base: super::AttachmentKey::compatible( |
| 2307 |
vk_format, |
| 2308 |
vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, |
| 2309 |
), |
| 2310 |
resolve: None, |
| 2311 |
}), |
| 2312 |
vk_attachment, |
| 2313 |
) |
| 2314 |
} else { |
| 2315 |
(None, vk::PipelineColorBlendAttachmentState::default()) |
| 2316 |
}; |
| 2317 |
|
| 2318 |
compatible_rp_key.colors.push(key); |
| 2319 |
vk_attachments.push(attarchment); |
| 2320 |
} |
| 2321 |
|
| 2322 |
let vk_color_blend = |
| 2323 |
vk::PipelineColorBlendStateCreateInfo::default().attachments(&vk_attachments); |
| 2324 |
|
| 2325 |
let vk_dynamic_state = |
| 2326 |
vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); |
| 2327 |
|
| 2328 |
let raw_pass = self.shared.make_render_pass(compatible_rp_key)?; |
| 2329 |
|
| 2330 |
let vk_infos = [{ |
| 2331 |
vk::GraphicsPipelineCreateInfo::default() |
| 2332 |
.layout(desc.layout.raw) |
| 2333 |
.stages(&stages) |
| 2334 |
.input_assembly_state(&vk_input_assembly) |
| 2335 |
.rasterization_state(&vk_rasterization) |
| 2336 |
.viewport_state(&vk_viewport) |
| 2337 |
.multisample_state(&vk_multisample) |
| 2338 |
.depth_stencil_state(&vk_depth_stencil) |
| 2339 |
.color_blend_state(&vk_color_blend) |
| 2340 |
.dynamic_state(&vk_dynamic_state) |
| 2341 |
.render_pass(raw_pass) |
| 2342 |
}]; |
| 2343 |
|
| 2344 |
let pipeline_cache = desc |
| 2345 |
.cache |
| 2346 |
.map(|it| it.raw) |
| 2347 |
.unwrap_or(vk::PipelineCache::null()); |
| 2348 |
|
| 2349 |
let mut raw_vec = { |
| 2350 |
profiling::scope!("vkCreateGraphicsPipelines"); |
| 2351 |
unsafe { |
| 2352 |
self.shared |
| 2353 |
.raw |
| 2354 |
.create_graphics_pipelines(pipeline_cache, &vk_infos, None) |
| 2355 |
.map_err(|(_, e)| super::map_pipeline_err(e)) |
| 2356 |
}? |
| 2357 |
}; |
| 2358 |
|
| 2359 |
let raw = raw_vec.pop().unwrap(); |
| 2360 |
if let Some(label) = desc.label { |
| 2361 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 2362 |
} |
| 2363 |
// NOTE: this could leak shaders in case of an error. |
| 2364 |
if let Some(CompiledStage { |
| 2365 |
temp_raw_module: Some(raw_module), |
| 2366 |
.. |
| 2367 |
}) = compiled_ts |
| 2368 |
{ |
| 2369 |
unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; |
| 2370 |
} |
| 2371 |
if let Some(raw_module) = compiled_ms.temp_raw_module { |
| 2372 |
unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; |
| 2373 |
} |
| 2374 |
if let Some(CompiledStage { |
| 2375 |
temp_raw_module: Some(raw_module), |
| 2376 |
.. |
| 2377 |
}) = compiled_fs |
| 2378 |
{ |
| 2379 |
unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; |
| 2380 |
} |
| 2381 |
|
| 2382 |
self.counters.render_pipelines.add(1); |
| 2383 |
|
| 2384 |
Ok(super::RenderPipeline { raw }) |
| 2385 |
} |
| 2386 |
|
| 2387 |
unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) { |
| 2388 |
unsafe { self.shared.raw.destroy_pipeline(pipeline.raw, None) }; |
| 2389 |
|
| 2390 |
self.counters.render_pipelines.sub(1); |
| 2391 |
} |
| 2392 |
|
| 2393 |
unsafe fn create_compute_pipeline( |
| 2394 |
&self, |
| 2395 |
desc: &crate::ComputePipelineDescriptor< |
| 2396 |
super::PipelineLayout, |
| 2397 |
super::ShaderModule, |
| 2398 |
super::PipelineCache, |
| 2399 |
>, |
| 2400 |
) -> Result<super::ComputePipeline, crate::PipelineError> { |
| 2401 |
let compiled = self.compile_stage( |
| 2402 |
&desc.stage, |
| 2403 |
naga::ShaderStage::Compute, |
| 2404 |
&desc.layout.binding_arrays, |
| 2405 |
)?; |
| 2406 |
|
| 2407 |
let vk_infos = [{ |
| 2408 |
vk::ComputePipelineCreateInfo::default() |
| 2409 |
.layout(desc.layout.raw) |
| 2410 |
.stage(compiled.create_info) |
| 2411 |
}]; |
| 2412 |
|
| 2413 |
let pipeline_cache = desc |
| 2414 |
.cache |
| 2415 |
.map(|it| it.raw) |
| 2416 |
.unwrap_or(vk::PipelineCache::null()); |
| 2417 |
|
| 2418 |
let mut raw_vec = { |
| 2419 |
profiling::scope!("vkCreateComputePipelines"); |
| 2420 |
unsafe { |
| 2421 |
self.shared |
| 2422 |
.raw |
| 2423 |
.create_compute_pipelines(pipeline_cache, &vk_infos, None) |
| 2424 |
.map_err(|(_, e)| super::map_pipeline_err(e)) |
| 2425 |
}? |
| 2426 |
}; |
| 2427 |
|
| 2428 |
let raw = raw_vec.pop().unwrap(); |
| 2429 |
if let Some(label) = desc.label { |
| 2430 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 2431 |
} |
| 2432 |
|
| 2433 |
if let Some(raw_module) = compiled.temp_raw_module { |
| 2434 |
unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; |
| 2435 |
} |
| 2436 |
|
| 2437 |
self.counters.compute_pipelines.add(1); |
| 2438 |
|
| 2439 |
Ok(super::ComputePipeline { raw }) |
| 2440 |
} |
| 2441 |
|
| 2442 |
unsafe fn destroy_compute_pipeline(&self, pipeline: super::ComputePipeline) { |
| 2443 |
unsafe { self.shared.raw.destroy_pipeline(pipeline.raw, None) }; |
| 2444 |
|
| 2445 |
self.counters.compute_pipelines.sub(1); |
| 2446 |
} |
| 2447 |
|
| 2448 |
unsafe fn create_pipeline_cache( |
| 2449 |
&self, |
| 2450 |
desc: &crate::PipelineCacheDescriptor<'_>, |
| 2451 |
) -> Result<super::PipelineCache, crate::PipelineCacheError> { |
| 2452 |
let mut info = vk::PipelineCacheCreateInfo::default(); |
| 2453 |
if let Some(data) = desc.data { |
| 2454 |
info = info.initial_data(data) |
| 2455 |
} |
| 2456 |
profiling::scope!("vkCreatePipelineCache"); |
| 2457 |
let raw = unsafe { self.shared.raw.create_pipeline_cache(&info, None) } |
| 2458 |
.map_err(super::map_host_device_oom_err)?; |
| 2459 |
|
| 2460 |
Ok(super::PipelineCache { raw }) |
| 2461 |
} |
| 2462 |
fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> { |
| 2463 |
Some(self.shared.pipeline_cache_validation_key) |
| 2464 |
} |
| 2465 |
unsafe fn destroy_pipeline_cache(&self, cache: super::PipelineCache) { |
| 2466 |
unsafe { self.shared.raw.destroy_pipeline_cache(cache.raw, None) } |
| 2467 |
} |
| 2468 |
unsafe fn create_query_set( |
| 2469 |
&self, |
| 2470 |
desc: &wgt::QuerySetDescriptor<crate::Label>, |
| 2471 |
) -> Result<super::QuerySet, crate::DeviceError> { |
| 2472 |
// Assume each query is 256 bytes. |
| 2473 |
// On an AMD W6800 with driver version 32.0.12030.9, occlusion queries are 256. |
| 2474 |
self.error_if_would_oom_on_resource_allocation(true, desc.count as u64 * 256)?; |
| 2475 |
|
| 2476 |
let (vk_type, pipeline_statistics) = match desc.ty { |
| 2477 |
wgt::QueryType::Occlusion => ( |
| 2478 |
vk::QueryType::OCCLUSION, |
| 2479 |
vk::QueryPipelineStatisticFlags::empty(), |
| 2480 |
), |
| 2481 |
wgt::QueryType::PipelineStatistics(statistics) => ( |
| 2482 |
vk::QueryType::PIPELINE_STATISTICS, |
| 2483 |
conv::map_pipeline_statistics(statistics), |
| 2484 |
), |
| 2485 |
wgt::QueryType::Timestamp => ( |
| 2486 |
vk::QueryType::TIMESTAMP, |
| 2487 |
vk::QueryPipelineStatisticFlags::empty(), |
| 2488 |
), |
| 2489 |
}; |
| 2490 |
|
| 2491 |
let vk_info = vk::QueryPoolCreateInfo::default() |
| 2492 |
.query_type(vk_type) |
| 2493 |
.query_count(desc.count) |
| 2494 |
.pipeline_statistics(pipeline_statistics); |
| 2495 |
|
| 2496 |
let raw = unsafe { self.shared.raw.create_query_pool(&vk_info, None) } |
| 2497 |
.map_err(super::map_host_device_oom_err)?; |
| 2498 |
if let Some(label) = desc.label { |
| 2499 |
unsafe { self.shared.set_object_name(raw, label) }; |
| 2500 |
} |
| 2501 |
|
| 2502 |
self.counters.query_sets.add(1); |
| 2503 |
|
| 2504 |
Ok(super::QuerySet { raw }) |
| 2505 |
} |
| 2506 |
|
| 2507 |
unsafe fn destroy_query_set(&self, set: super::QuerySet) { |
| 2508 |
unsafe { self.shared.raw.destroy_query_pool(set.raw, None) }; |
| 2509 |
|
| 2510 |
self.counters.query_sets.sub(1); |
| 2511 |
} |
| 2512 |
|
| 2513 |
unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> { |
| 2514 |
self.counters.fences.add(1); |
| 2515 |
|
| 2516 |
Ok(if self.shared.private_caps.timeline_semaphores { |
| 2517 |
let mut sem_type_info = |
| 2518 |
vk::SemaphoreTypeCreateInfo::default().semaphore_type(vk::SemaphoreType::TIMELINE); |
| 2519 |
let vk_info = vk::SemaphoreCreateInfo::default().push_next(&mut sem_type_info); |
| 2520 |
let raw = unsafe { self.shared.raw.create_semaphore(&vk_info, None) } |
| 2521 |
.map_err(super::map_host_device_oom_err)?; |
| 2522 |
|
| 2523 |
super::Fence::TimelineSemaphore(raw) |
| 2524 |
} else { |
| 2525 |
super::Fence::FencePool { |
| 2526 |
last_completed: 0, |
| 2527 |
active: Vec::new(), |
| 2528 |
free: Vec::new(), |
| 2529 |
} |
| 2530 |
}) |
| 2531 |
} |
| 2532 |
unsafe fn destroy_fence(&self, fence: super::Fence) { |
| 2533 |
match fence { |
| 2534 |
super::Fence::TimelineSemaphore(raw) => { |
| 2535 |
unsafe { self.shared.raw.destroy_semaphore(raw, None) }; |
| 2536 |
} |
| 2537 |
super::Fence::FencePool { |
| 2538 |
active, |
| 2539 |
free, |
| 2540 |
last_completed: _, |
| 2541 |
} => { |
| 2542 |
for (_, raw) in active { |
| 2543 |
unsafe { self.shared.raw.destroy_fence(raw, None) }; |
| 2544 |
} |
| 2545 |
for raw in free { |
| 2546 |
unsafe { self.shared.raw.destroy_fence(raw, None) }; |
| 2547 |
} |
| 2548 |
} |
| 2549 |
} |
| 2550 |
|
| 2551 |
self.counters.fences.sub(1); |
| 2552 |
} |
| 2553 |
unsafe fn get_fence_value( |
| 2554 |
&self, |
| 2555 |
fence: &super::Fence, |
| 2556 |
) -> Result<crate::FenceValue, crate::DeviceError> { |
| 2557 |
fence.get_latest( |
| 2558 |
&self.shared.raw, |
| 2559 |
self.shared.extension_fns.timeline_semaphore.as_ref(), |
| 2560 |
) |
| 2561 |
} |
| 2562 |
unsafe fn wait( |
| 2563 |
&self, |
| 2564 |
fence: &super::Fence, |
| 2565 |
wait_value: crate::FenceValue, |
| 2566 |
timeout_ms: u32, |
| 2567 |
) -> Result<bool, crate::DeviceError> { |
| 2568 |
let timeout_ns = timeout_ms as u64 * super::MILLIS_TO_NANOS; |
| 2569 |
self.shared.wait_for_fence(fence, wait_value, timeout_ns) |
| 2570 |
} |
| 2571 |
|
| 2572 |
unsafe fn start_graphics_debugger_capture(&self) -> bool { |
| 2573 |
#[cfg(feature = "renderdoc")] |
| 2574 |
{ |
| 2575 |
// Renderdoc requires us to give us the pointer that vkInstance _points to_. |
| 2576 |
let raw_vk_instance = |
| 2577 |
vk::Handle::as_raw(self.shared.instance.raw.handle()) as *mut *mut _; |
| 2578 |
let raw_vk_instance_dispatch_table = unsafe { *raw_vk_instance }; |
| 2579 |
unsafe { |
| 2580 |
self.render_doc |
| 2581 |
.start_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) |
| 2582 |
} |
| 2583 |
} |
| 2584 |
#[cfg(not(feature = "renderdoc"))] |
| 2585 |
false |
| 2586 |
} |
| 2587 |
unsafe fn stop_graphics_debugger_capture(&self) { |
| 2588 |
#[cfg(feature = "renderdoc")] |
| 2589 |
{ |
| 2590 |
// Renderdoc requires us to give us the pointer that vkInstance _points to_. |
| 2591 |
let raw_vk_instance = |
| 2592 |
vk::Handle::as_raw(self.shared.instance.raw.handle()) as *mut *mut _; |
| 2593 |
let raw_vk_instance_dispatch_table = unsafe { *raw_vk_instance }; |
| 2594 |
|
| 2595 |
unsafe { |
| 2596 |
self.render_doc |
| 2597 |
.end_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) |
| 2598 |
} |
| 2599 |
} |
| 2600 |
} |
| 2601 |
|
| 2602 |
unsafe fn pipeline_cache_get_data(&self, cache: &super::PipelineCache) -> Option<Vec<u8>> { |
| 2603 |
let data = unsafe { self.raw_device().get_pipeline_cache_data(cache.raw) }; |
| 2604 |
data.ok() |
| 2605 |
} |
| 2606 |
|
| 2607 |
unsafe fn get_acceleration_structure_build_sizes<'a>( |
| 2608 |
&self, |
| 2609 |
desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, super::Buffer>, |
| 2610 |
) -> crate::AccelerationStructureBuildSizes { |
| 2611 |
const CAPACITY: usize = 8; |
| 2612 |
|
| 2613 |
let ray_tracing_functions = self |
| 2614 |
.shared |
| 2615 |
.extension_fns |
| 2616 |
.ray_tracing |
| 2617 |
.as_ref() |
| 2618 |
.expect("Feature `RAY_TRACING` not enabled"); |
| 2619 |
|
| 2620 |
let (geometries, primitive_counts) = match *desc.entries { |
| 2621 |
crate::AccelerationStructureEntries::Instances(ref instances) => { |
| 2622 |
let instance_data = vk::AccelerationStructureGeometryInstancesDataKHR::default(); |
| 2623 |
|
| 2624 |
let geometry = vk::AccelerationStructureGeometryKHR::default() |
| 2625 |
.geometry_type(vk::GeometryTypeKHR::INSTANCES) |
| 2626 |
.geometry(vk::AccelerationStructureGeometryDataKHR { |
| 2627 |
instances: instance_data, |
| 2628 |
}); |
| 2629 |
|
| 2630 |
( |
| 2631 |
smallvec::smallvec![geometry], |
| 2632 |
smallvec::smallvec![instances.count], |
| 2633 |
) |
| 2634 |
} |
| 2635 |
crate::AccelerationStructureEntries::Triangles(ref in_geometries) => { |
| 2636 |
let mut primitive_counts = |
| 2637 |
smallvec::SmallVec::<[u32; CAPACITY]>::with_capacity(in_geometries.len()); |
| 2638 |
let mut geometries = smallvec::SmallVec::< |
| 2639 |
[vk::AccelerationStructureGeometryKHR; CAPACITY], |
| 2640 |
>::with_capacity(in_geometries.len()); |
| 2641 |
|
| 2642 |
for triangles in in_geometries { |
| 2643 |
let mut triangle_data = |
| 2644 |
vk::AccelerationStructureGeometryTrianglesDataKHR::default() |
| 2645 |
.index_type(vk::IndexType::NONE_KHR) |
| 2646 |
.vertex_format(conv::map_vertex_format(triangles.vertex_format)) |
| 2647 |
.max_vertex(triangles.vertex_count) |
| 2648 |
.vertex_stride(triangles.vertex_stride) |
| 2649 |
// The vulkan spec suggests we could pass a non-zero invalid address here if fetching |
| 2650 |
// the real address has significant overhead, but we pass the real one to be on the |
| 2651 |
// safe side for now. |
| 2652 |
// from https://registry.khronos.org/vulkan/specs/latest/man/html/vkGetAccelerationStructureBuildSizesKHR.html |
| 2653 |
// > The srcAccelerationStructure, dstAccelerationStructure, and mode members |
| 2654 |
// > of pBuildInfo are ignored. Any VkDeviceOrHostAddressKHR or VkDeviceOrHostAddressConstKHR |
| 2655 |
// > members of pBuildInfo are ignored by this command, except that the hostAddress |
| 2656 |
// > member of VkAccelerationStructureGeometryTrianglesDataKHR::transformData will |
| 2657 |
// > be examined to check if it is NULL. |
| 2658 |
.transform_data(vk::DeviceOrHostAddressConstKHR { |
| 2659 |
device_address: if desc |
| 2660 |
.flags |
| 2661 |
.contains(wgt::AccelerationStructureFlags::USE_TRANSFORM) |
| 2662 |
{ |
| 2663 |
unsafe { |
| 2664 |
ray_tracing_functions |
| 2665 |
.buffer_device_address |
| 2666 |
.get_buffer_device_address( |
| 2667 |
&vk::BufferDeviceAddressInfo::default().buffer( |
| 2668 |
triangles |
| 2669 |
.transform |
| 2670 |
.as_ref() |
| 2671 |
.unwrap() |
| 2672 |
.buffer |
| 2673 |
.raw, |
| 2674 |
), |
| 2675 |
) |
| 2676 |
} |
| 2677 |
} else { |
| 2678 |
0 |
| 2679 |
}, |
| 2680 |
}); |
| 2681 |
|
| 2682 |
let pritive_count = if let Some(ref indices) = triangles.indices { |
| 2683 |
triangle_data = |
| 2684 |
triangle_data.index_type(conv::map_index_format(indices.format)); |
| 2685 |
indices.count / 3 |
| 2686 |
} else { |
| 2687 |
triangles.vertex_count |
| 2688 |
}; |
| 2689 |
|
| 2690 |
let geometry = vk::AccelerationStructureGeometryKHR::default() |
| 2691 |
.geometry_type(vk::GeometryTypeKHR::TRIANGLES) |
| 2692 |
.geometry(vk::AccelerationStructureGeometryDataKHR { |
| 2693 |
triangles: triangle_data, |
| 2694 |
}) |
| 2695 |
.flags(conv::map_acceleration_structure_geometry_flags( |
| 2696 |
triangles.flags, |
| 2697 |
)); |
| 2698 |
|
| 2699 |
geometries.push(geometry); |
| 2700 |
primitive_counts.push(pritive_count); |
| 2701 |
} |
| 2702 |
(geometries, primitive_counts) |
| 2703 |
} |
| 2704 |
crate::AccelerationStructureEntries::AABBs(ref in_geometries) => { |
| 2705 |
let mut primitive_counts = |
| 2706 |
smallvec::SmallVec::<[u32; CAPACITY]>::with_capacity(in_geometries.len()); |
| 2707 |
let mut geometries = smallvec::SmallVec::< |
| 2708 |
[vk::AccelerationStructureGeometryKHR; CAPACITY], |
| 2709 |
>::with_capacity(in_geometries.len()); |
| 2710 |
for aabb in in_geometries { |
| 2711 |
let aabbs_data = vk::AccelerationStructureGeometryAabbsDataKHR::default() |
| 2712 |
.stride(aabb.stride); |
| 2713 |
|
| 2714 |
let geometry = vk::AccelerationStructureGeometryKHR::default() |
| 2715 |
.geometry_type(vk::GeometryTypeKHR::AABBS) |
| 2716 |
.geometry(vk::AccelerationStructureGeometryDataKHR { aabbs: aabbs_data }) |
| 2717 |
.flags(conv::map_acceleration_structure_geometry_flags(aabb.flags)); |
| 2718 |
|
| 2719 |
geometries.push(geometry); |
| 2720 |
primitive_counts.push(aabb.count); |
| 2721 |
} |
| 2722 |
(geometries, primitive_counts) |
| 2723 |
} |
| 2724 |
}; |
| 2725 |
|
| 2726 |
let ty = match *desc.entries { |
| 2727 |
crate::AccelerationStructureEntries::Instances(_) => { |
| 2728 |
vk::AccelerationStructureTypeKHR::TOP_LEVEL |
| 2729 |
} |
| 2730 |
_ => vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL, |
| 2731 |
}; |
| 2732 |
|
| 2733 |
let geometry_info = vk::AccelerationStructureBuildGeometryInfoKHR::default() |
| 2734 |
.ty(ty) |
| 2735 |
.flags(conv::map_acceleration_structure_flags(desc.flags)) |
| 2736 |
.geometries(&geometries); |
| 2737 |
|
| 2738 |
let mut raw = Default::default(); |
| 2739 |
unsafe { |
| 2740 |
ray_tracing_functions |
| 2741 |
.acceleration_structure |
| 2742 |
.get_acceleration_structure_build_sizes( |
| 2743 |
vk::AccelerationStructureBuildTypeKHR::DEVICE, |
| 2744 |
&geometry_info, |
| 2745 |
&primitive_counts, |
| 2746 |
&mut raw, |
| 2747 |
) |
| 2748 |
} |
| 2749 |
|
| 2750 |
crate::AccelerationStructureBuildSizes { |
| 2751 |
acceleration_structure_size: raw.acceleration_structure_size, |
| 2752 |
update_scratch_size: raw.update_scratch_size, |
| 2753 |
build_scratch_size: raw.build_scratch_size, |
| 2754 |
} |
| 2755 |
} |
| 2756 |
|
| 2757 |
unsafe fn get_acceleration_structure_device_address( |
| 2758 |
&self, |
| 2759 |
acceleration_structure: &super::AccelerationStructure, |
| 2760 |
) -> wgt::BufferAddress { |
| 2761 |
let ray_tracing_functions = self |
| 2762 |
.shared |
| 2763 |
.extension_fns |
| 2764 |
.ray_tracing |
| 2765 |
.as_ref() |
| 2766 |
.expect("Feature `RAY_TRACING` not enabled"); |
| 2767 |
|
| 2768 |
unsafe { |
| 2769 |
ray_tracing_functions |
| 2770 |
.acceleration_structure |
| 2771 |
.get_acceleration_structure_device_address( |
| 2772 |
&vk::AccelerationStructureDeviceAddressInfoKHR::default() |
| 2773 |
.acceleration_structure(acceleration_structure.raw), |
| 2774 |
) |
| 2775 |
} |
| 2776 |
} |
| 2777 |
|
| 2778 |
unsafe fn create_acceleration_structure( |
| 2779 |
&self, |
| 2780 |
desc: &crate::AccelerationStructureDescriptor, |
| 2781 |
) -> Result<super::AccelerationStructure, crate::DeviceError> { |
| 2782 |
let ray_tracing_functions = self |
| 2783 |
.shared |
| 2784 |
.extension_fns |
| 2785 |
.ray_tracing |
| 2786 |
.as_ref() |
| 2787 |
.expect("Feature `RAY_TRACING` not enabled"); |
| 2788 |
|
| 2789 |
let vk_buffer_info = vk::BufferCreateInfo::default() |
| 2790 |
.size(desc.size) |
| 2791 |
.usage( |
| 2792 |
vk::BufferUsageFlags::ACCELERATION_STRUCTURE_STORAGE_KHR |
| 2793 |
| vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS, |
| 2794 |
) |
| 2795 |
.sharing_mode(vk::SharingMode::EXCLUSIVE); |
| 2796 |
|
| 2797 |
unsafe { |
| 2798 |
let raw_buffer = self |
| 2799 |
.shared |
| 2800 |
.raw |
| 2801 |
.create_buffer(&vk_buffer_info, None) |
| 2802 |
.map_err(super::map_host_device_oom_and_ioca_err)?; |
| 2803 |
let req = self.shared.raw.get_buffer_memory_requirements(raw_buffer); |
| 2804 |
|
| 2805 |
self.error_if_would_oom_on_resource_allocation(false, req.size) |
| 2806 |
.inspect_err(|_| { |
| 2807 |
self.shared.raw.destroy_buffer(raw_buffer, None); |
| 2808 |
})?; |
| 2809 |
|
| 2810 |
let block = self |
| 2811 |
.mem_allocator |
| 2812 |
.lock() |
| 2813 |
.alloc( |
| 2814 |
&*self.shared, |
| 2815 |
gpu_alloc::Request { |
| 2816 |
size: req.size, |
| 2817 |
align_mask: req.alignment - 1, |
| 2818 |
usage: gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, |
| 2819 |
memory_types: req.memory_type_bits & self.valid_ash_memory_types, |
| 2820 |
}, |
| 2821 |
) |
| 2822 |
.inspect_err(|_| { |
| 2823 |
self.shared.raw.destroy_buffer(raw_buffer, None); |
| 2824 |
})?; |
| 2825 |
|
| 2826 |
self.shared |
| 2827 |
.raw |
| 2828 |
.bind_buffer_memory(raw_buffer, *block.memory(), block.offset()) |
| 2829 |
.map_err(super::map_host_device_oom_and_ioca_err) |
| 2830 |
.inspect_err(|_| { |
| 2831 |
self.shared.raw.destroy_buffer(raw_buffer, None); |
| 2832 |
})?; |
| 2833 |
|
| 2834 |
if let Some(label) = desc.label { |
| 2835 |
self.shared.set_object_name(raw_buffer, label); |
| 2836 |
} |
| 2837 |
|
| 2838 |
let vk_info = vk::AccelerationStructureCreateInfoKHR::default() |
| 2839 |
.buffer(raw_buffer) |
| 2840 |
.offset(0) |
| 2841 |
.size(desc.size) |
| 2842 |
.ty(conv::map_acceleration_structure_format(desc.format)); |
| 2843 |
|
| 2844 |
let raw_acceleration_structure = ray_tracing_functions |
| 2845 |
.acceleration_structure |
| 2846 |
.create_acceleration_structure(&vk_info, None) |
| 2847 |
.map_err(super::map_host_oom_and_ioca_err) |
| 2848 |
.inspect_err(|_| { |
| 2849 |
self.shared.raw.destroy_buffer(raw_buffer, None); |
| 2850 |
})?; |
| 2851 |
|
| 2852 |
if let Some(label) = desc.label { |
| 2853 |
self.shared |
| 2854 |
.set_object_name(raw_acceleration_structure, label); |
| 2855 |
} |
| 2856 |
|
| 2857 |
let pool = if desc.allow_compaction { |
| 2858 |
let vk_info = vk::QueryPoolCreateInfo::default() |
| 2859 |
.query_type(vk::QueryType::ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR) |
| 2860 |
.query_count(1); |
| 2861 |
|
| 2862 |
let raw = self |
| 2863 |
.shared |
| 2864 |
.raw |
| 2865 |
.create_query_pool(&vk_info, None) |
| 2866 |
.map_err(super::map_host_device_oom_err) |
| 2867 |
.inspect_err(|_| { |
| 2868 |
ray_tracing_functions |
| 2869 |
.acceleration_structure |
| 2870 |
.destroy_acceleration_structure(raw_acceleration_structure, None); |
| 2871 |
self.shared.raw.destroy_buffer(raw_buffer, None); |
| 2872 |
})?; |
| 2873 |
Some(raw) |
| 2874 |
} else { |
| 2875 |
None |
| 2876 |
}; |
| 2877 |
|
| 2878 |
Ok(super::AccelerationStructure { |
| 2879 |
raw: raw_acceleration_structure, |
| 2880 |
buffer: raw_buffer, |
| 2881 |
block: Mutex::new(block), |
| 2882 |
compacted_size_query: pool, |
| 2883 |
}) |
| 2884 |
} |
| 2885 |
} |
| 2886 |
|
| 2887 |
unsafe fn destroy_acceleration_structure( |
| 2888 |
&self, |
| 2889 |
acceleration_structure: super::AccelerationStructure, |
| 2890 |
) { |
| 2891 |
let ray_tracing_functions = self |
| 2892 |
.shared |
| 2893 |
.extension_fns |
| 2894 |
.ray_tracing |
| 2895 |
.as_ref() |
| 2896 |
.expect("Feature `RAY_TRACING` not enabled"); |
| 2897 |
|
| 2898 |
unsafe { |
| 2899 |
ray_tracing_functions |
| 2900 |
.acceleration_structure |
| 2901 |
.destroy_acceleration_structure(acceleration_structure.raw, None); |
| 2902 |
self.shared |
| 2903 |
.raw |
| 2904 |
.destroy_buffer(acceleration_structure.buffer, None); |
| 2905 |
self.mem_allocator |
| 2906 |
.lock() |
| 2907 |
.dealloc(&*self.shared, acceleration_structure.block.into_inner()); |
| 2908 |
if let Some(query) = acceleration_structure.compacted_size_query { |
| 2909 |
self.shared.raw.destroy_query_pool(query, None) |
| 2910 |
} |
| 2911 |
} |
| 2912 |
} |
| 2913 |
|
| 2914 |
fn get_internal_counters(&self) -> wgt::HalCounters { |
| 2915 |
self.counters |
| 2916 |
.memory_allocations |
| 2917 |
.set(self.shared.memory_allocations_counter.read()); |
| 2918 |
|
| 2919 |
self.counters.as_ref().clone() |
| 2920 |
} |
| 2921 |
|
| 2922 |
fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> { |
| 2923 |
const MAX_U24: u32 = (1u32 << 24u32) - 1u32; |
| 2924 |
let temp = RawTlasInstance { |
| 2925 |
transform: instance.transform, |
| 2926 |
custom_data_and_mask: (instance.custom_data & MAX_U24) |
| 2927 |
| (u32::from(instance.mask) << 24), |
| 2928 |
shader_binding_table_record_offset_and_flags: 0, |
| 2929 |
acceleration_structure_reference: instance.blas_address, |
| 2930 |
}; |
| 2931 |
bytemuck::bytes_of(&temp).to_vec() |
| 2932 |
} |
| 2933 |
|
| 2934 |
fn check_if_oom(&self) -> Result<(), crate::DeviceError> { |
| 2935 |
let Some(threshold) = self |
| 2936 |
.shared |
| 2937 |
.instance |
| 2938 |
.memory_budget_thresholds |
| 2939 |
.for_device_loss |
| 2940 |
else { |
| 2941 |
return Ok(()); |
| 2942 |
}; |
| 2943 |
|
| 2944 |
if !self |
| 2945 |
.shared |
| 2946 |
.enabled_extensions |
| 2947 |
.contains(&ext::memory_budget::NAME) |
| 2948 |
{ |
| 2949 |
return Ok(()); |
| 2950 |
} |
| 2951 |
|
| 2952 |
let get_physical_device_properties = self |
| 2953 |
.shared |
| 2954 |
.instance |
| 2955 |
.get_physical_device_properties |
| 2956 |
.as_ref() |
| 2957 |
.unwrap(); |
| 2958 |
|
| 2959 |
let mut memory_budget_properties = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default(); |
| 2960 |
|
| 2961 |
let mut memory_properties = |
| 2962 |
vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut memory_budget_properties); |
| 2963 |
|
| 2964 |
unsafe { |
| 2965 |
get_physical_device_properties.get_physical_device_memory_properties2( |
| 2966 |
self.shared.physical_device, |
| 2967 |
&mut memory_properties, |
| 2968 |
); |
| 2969 |
} |
| 2970 |
|
| 2971 |
let memory_properties = memory_properties.memory_properties; |
| 2972 |
|
| 2973 |
for i in 0..memory_properties.memory_heap_count { |
| 2974 |
let heap_usage = memory_budget_properties.heap_usage[i as usize]; |
| 2975 |
let heap_budget = memory_budget_properties.heap_budget[i as usize]; |
| 2976 |
|
| 2977 |
if heap_usage >= heap_budget / 100 * threshold as u64 { |
| 2978 |
return Err(crate::DeviceError::OutOfMemory); |
| 2979 |
} |
| 2980 |
} |
| 2981 |
|
| 2982 |
Ok(()) |
| 2983 |
} |
| 2984 |
} |
| 2985 |
|
| 2986 |
impl super::DeviceShared { |
| 2987 |
pub(super) fn new_binary_semaphore(&self) -> Result<vk::Semaphore, crate::DeviceError> { |
| 2988 |
unsafe { |
| 2989 |
self.raw |
| 2990 |
.create_semaphore(&vk::SemaphoreCreateInfo::default(), None) |
| 2991 |
.map_err(super::map_host_device_oom_err) |
| 2992 |
} |
| 2993 |
} |
| 2994 |
|
| 2995 |
pub(super) fn wait_for_fence( |
| 2996 |
&self, |
| 2997 |
fence: &super::Fence, |
| 2998 |
wait_value: crate::FenceValue, |
| 2999 |
timeout_ns: u64, |
| 3000 |
) -> Result<bool, crate::DeviceError> { |
| 3001 |
profiling::scope!("Device::wait"); |
| 3002 |
match *fence { |
| 3003 |
super::Fence::TimelineSemaphore(raw) => { |
| 3004 |
let semaphores = [raw]; |
| 3005 |
let values = [wait_value]; |
| 3006 |
let vk_info = vk::SemaphoreWaitInfo::default() |
| 3007 |
.semaphores(&semaphores) |
| 3008 |
.values(&values); |
| 3009 |
let result = match self.extension_fns.timeline_semaphore { |
| 3010 |
Some(super::ExtensionFn::Extension(ref ext)) => unsafe { |
| 3011 |
ext.wait_semaphores(&vk_info, timeout_ns) |
| 3012 |
}, |
| 3013 |
Some(super::ExtensionFn::Promoted) => unsafe { |
| 3014 |
self.raw.wait_semaphores(&vk_info, timeout_ns) |
| 3015 |
}, |
| 3016 |
None => unreachable!(), |
| 3017 |
}; |
| 3018 |
match result { |
| 3019 |
Ok(()) => Ok(true), |
| 3020 |
Err(vk::Result::TIMEOUT) => Ok(false), |
| 3021 |
Err(other) => Err(super::map_host_device_oom_and_lost_err(other)), |
| 3022 |
} |
| 3023 |
} |
| 3024 |
super::Fence::FencePool { |
| 3025 |
last_completed, |
| 3026 |
ref active, |
| 3027 |
free: _, |
| 3028 |
} => { |
| 3029 |
if wait_value <= last_completed { |
| 3030 |
Ok(true) |
| 3031 |
} else { |
| 3032 |
match active.iter().find(|&&(value, _)| value >= wait_value) { |
| 3033 |
Some(&(_, raw)) => { |
| 3034 |
match unsafe { self.raw.wait_for_fences(&[raw], true, timeout_ns) } { |
| 3035 |
Ok(()) => Ok(true), |
| 3036 |
Err(vk::Result::TIMEOUT) => Ok(false), |
| 3037 |
Err(other) => Err(super::map_host_device_oom_and_lost_err(other)), |
| 3038 |
} |
| 3039 |
} |
| 3040 |
None => { |
| 3041 |
crate::hal_usage_error(format!( |
| 3042 |
"no signals reached value {wait_value}" |
| 3043 |
)); |
| 3044 |
} |
| 3045 |
} |
| 3046 |
} |
| 3047 |
} |
| 3048 |
} |
| 3049 |
} |
| 3050 |
} |
| 3051 |
|
| 3052 |
impl From<gpu_alloc::AllocationError> for crate::DeviceError { |
| 3053 |
fn from(error: gpu_alloc::AllocationError) -> Self { |
| 3054 |
use gpu_alloc::AllocationError as Ae; |
| 3055 |
match error { |
| 3056 |
Ae::OutOfDeviceMemory | Ae::OutOfHostMemory | Ae::TooManyObjects => Self::OutOfMemory, |
| 3057 |
Ae::NoCompatibleMemoryTypes => crate::hal_usage_error(error), |
| 3058 |
} |
| 3059 |
} |
| 3060 |
} |
| 3061 |
impl From<gpu_alloc::MapError> for crate::DeviceError { |
| 3062 |
fn from(error: gpu_alloc::MapError) -> Self { |
| 3063 |
use gpu_alloc::MapError as Me; |
| 3064 |
match error { |
| 3065 |
Me::OutOfDeviceMemory | Me::OutOfHostMemory | Me::MapFailed => Self::OutOfMemory, |
| 3066 |
Me::NonHostVisible | Me::AlreadyMapped => crate::hal_usage_error(error), |
| 3067 |
} |
| 3068 |
} |
| 3069 |
} |
| 3070 |
impl From<gpu_descriptor::AllocationError> for crate::DeviceError { |
| 3071 |
fn from(error: gpu_descriptor::AllocationError) -> Self { |
| 3072 |
use gpu_descriptor::AllocationError as Ae; |
| 3073 |
match error { |
| 3074 |
Ae::OutOfDeviceMemory | Ae::OutOfHostMemory | Ae::Fragmentation => Self::OutOfMemory, |
| 3075 |
} |
| 3076 |
} |
| 3077 |
} |
| 3078 |
|
| 3079 |
/// We usually map unexpected vulkan errors to the [`crate::DeviceError::Unexpected`] |
| 3080 |
/// variant to be more robust even in cases where the driver is not |
| 3081 |
/// complying with the spec. |
| 3082 |
/// |
| 3083 |
/// However, we implement a few Trait methods that don't have an equivalent |
| 3084 |
/// error variant. In those cases we use this function. |
| 3085 |
fn handle_unexpected(err: vk::Result) -> ! { |
| 3086 |
panic!("Unexpected Vulkan error: `{err}`") |
| 3087 |
} |
| 3088 |
|
| 3089 |
struct ImageWithoutMemory { |
| 3090 |
raw: vk::Image, |
| 3091 |
requirements: vk::MemoryRequirements, |
| 3092 |
copy_size: crate::CopyExtent, |
| 3093 |
} |