diff options
| author | Alex Collini <pipodi93@gmail.com> | 2026-11-22 09:53:47 +0100 |
|---|---|---|
| committer | Alex Collini <pipodi93@gmail.com> | 2026-11-22 09:53:47 +0100 |
| commit | 4f7aeb8d4df9126a7e620455fa8d7cf08ea521f9 (patch) | |
| tree | 827a90af1501a3974406d23396034c10c990f0f9 /runtime/src | |
| parent | 3a1ea887e451b638aa5c565a5e14e81c435e0043 (diff) | |
| parent | 426023a585b47ba04509d5f3e5e52d6ae40e1109 (diff) | |
Merge main 426023a5 into #753
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/command_list.h | 9 | ||||
| -rw-r--r-- | runtime/src/gfx10_descriptors.h | 8 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 41 | ||||
| -rw-r--r-- | runtime/src/pe_loader.h | 11 | ||||
| -rw-r--r-- | runtime/src/resource_tiling.h | 14 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 621 | ||||
| -rw-r--r-- | runtime/src/vulkan_bindless.h | 184 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 143 |
8 files changed, 904 insertions, 127 deletions
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index f786ce60f..25b2db1e8 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -330,10 +330,18 @@ struct CopyResource { | |||
| 330 | ResourceId src; | 330 | ResourceId src; |
| 331 | }; | 331 | }; |
| 332 | 332 | ||
| 333 | // D3D12_RESOLVE_MODE values a region resolve replays. | ||
| 334 | namespace d3d12_resolve_mode { | ||
| 335 | inline constexpr std::uint32_t minimum = 1; | ||
| 336 | inline constexpr std::uint32_t maximum = 2; | ||
| 337 | inline constexpr std::uint32_t average = 3; | ||
| 338 | } | ||
| 339 | |||
| 333 | struct ResolveRegion { | 340 | struct ResolveRegion { |
| 334 | std::uint32_t dst_x; | 341 | std::uint32_t dst_x; |
| 335 | std::uint32_t dst_y; | 342 | std::uint32_t dst_y; |
| 336 | std::optional<Rect> src_rect; | 343 | std::optional<Rect> src_rect; |
| 344 | std::uint32_t mode = d3d12_resolve_mode::average; // colour: average only; stencil: minimum or maximum | ||
| 337 | }; | 345 | }; |
| 338 | 346 | ||
| 339 | // Without a region, both subresources have the same extent. A region with no source rectangle takes the | 347 | // Without a region, both subresources have the same extent. A region with no source rectangle takes the |
| @@ -599,6 +607,7 @@ public: | |||
| 599 | if (!resolve.dst || !resolve.src || resolve.dst == resolve.src) return false; | 607 | if (!resolve.dst || !resolve.src || resolve.dst == resolve.src) return false; |
| 600 | if (const auto& region = resolve.region) { | 608 | if (const auto& region = resolve.region) { |
| 601 | if (region->dst_x > INT32_MAX || region->dst_y > INT32_MAX) return false; | 609 | if (region->dst_x > INT32_MAX || region->dst_y > INT32_MAX) return false; |
| 610 | if (region->mode < d3d12_resolve_mode::minimum || region->mode > d3d12_resolve_mode::average) return false; | ||
| 602 | if (const auto& r = region->src_rect; | 611 | if (const auto& r = region->src_rect; |
| 603 | r && (r->left < 0 || r->top < 0 || r->right <= r->left || r->bottom <= r->top)) | 612 | r && (r->left < 0 || r->top < 0 || r->right <= r->left || r->bottom <= r->top)) |
| 604 | return false; | 613 | return false; |
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index 2a5e4533a..39f967460 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -614,9 +614,11 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler) { | |||
| 614 | 614 | ||
| 615 | // ---- V#: SQ_BUF_RSRC_WORD0..3 ---- | 615 | // ---- V#: SQ_BUF_RSRC_WORD0..3 ---- |
| 616 | 616 | ||
| 617 | // SQ_BUF_RSRC_WORD3.OOB_SELECT: the bounds check the hardware makes. The translator makes its own from the | 617 | // SQ_BUF_RSRC_WORD3.OOB_SELECT: the bounds check the hardware makes, and the one the translator makes too |
| 618 | // stride (tools/rdna2spirv.py, buffer_address): stride 0 checks the byte offset against num_records, otherwise | 618 | // (tools/rdna2spirv.py, buffer_address; docs/design.md, Buffer bounds checking): structured_with_offset is out of |
| 619 | // the index, or the offset against num_records * stride. | 619 | // range at index >= num_records or offset + 4 > stride, structured at index >= num_records, disabled only at |
| 620 | // num_records == 0, raw at offset + 4 > num_records (docs/buffer_bounds.md). A V# built here for a shader to read must say which: the default | ||
| 621 | // below makes every stride-0 access out of range. | ||
| 620 | enum class OobSelect : std::uint32_t { | 622 | enum class OobSelect : std::uint32_t { |
| 621 | structured_with_offset = 0, | 623 | structured_with_offset = 0, |
| 622 | structured = 1, | 624 | structured = 1, |
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index d865e4179..15a62d9b4 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -47,6 +47,11 @@ std::string read_string(const std::string& name, uint8_t* base, uint32_t image_s | |||
| 47 | return {s, end}; | 47 | return {s, end}; |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | // PE/COFF: NumberOfRvaAndSizes counts the data directories; entries past it are not directories, whatever they hold. | ||
| 51 | IMAGE_DATA_DIRECTORY directory(const IMAGE_NT_HEADERS64* nt, unsigned index) { | ||
| 52 | return index < nt->OptionalHeader.NumberOfRvaAndSizes ? nt->OptionalHeader.DataDirectory[index] : IMAGE_DATA_DIRECTORY{}; | ||
| 53 | } | ||
| 54 | |||
| 50 | // The TLS directory holds virtual addresses, which relocations have already moved to this mapping. | 55 | // The TLS directory holds virtual addresses, which relocations have already moved to this mapping. |
| 51 | uint64_t rva_in(const Module& m, uint64_t va, const char* what) { | 56 | uint64_t rva_in(const Module& m, uint64_t va, const char* what) { |
| 52 | const uint64_t base = reinterpret_cast<uint64_t>(m.base); | 57 | const uint64_t base = reinterpret_cast<uint64_t>(m.base); |
| @@ -161,6 +166,26 @@ Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) | |||
| 161 | } | 166 | } |
| 162 | 167 | ||
| 163 | Loader::~Loader() { | 168 | Loader::~Loader() { |
| 169 | // Importers must release their resources before their dependencies. Keep every mapping, unwind table and TLS | ||
| 170 | // block alive throughout the notifications: a detach handler can still call an imported function or free an | ||
| 171 | // FLS slot whose destructor lives in another mapped image. | ||
| 172 | for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) { | ||
| 173 | Module& m = **it; | ||
| 174 | if (!m.initialised) continue; // a map-only load never opts in to running image code | ||
| 175 | m.initialised = false; | ||
| 176 | try { | ||
| 177 | run_tls_callbacks(m, DLL_PROCESS_DETACH); | ||
| 178 | } catch (const std::exception& e) { | ||
| 179 | // A module may have changed its callback table since attach. A destructor cannot propagate the validation | ||
| 180 | // error; report it and still let DllMain release resources before the image is freed. | ||
| 181 | std::fprintf(stderr, "[rt] TLS process detach failed for %s: %s\n", m.name.c_str(), e.what()); | ||
| 182 | } | ||
| 183 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 184 | if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { | ||
| 185 | auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); | ||
| 186 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored | ||
| 187 | } | ||
| 188 | } | ||
| 164 | shims::remove_module_lookup(this); | 189 | shims::remove_module_lookup(this); |
| 165 | for (auto* m : order_) { | 190 | for (auto* m : order_) { |
| 166 | // TLS state must go away before the image and its TLS block are unmapped. | 191 | // TLS state must go away before the image and its TLS block are unmapped. |
| @@ -201,8 +226,7 @@ Module& Loader::load(const std::filesystem::path& image) { | |||
| 201 | // allowed. No entry in that set uses the indirect form (UnwindData bit 0). | 226 | // allowed. No entry in that set uses the indirect form (UnwindData bit 0). |
| 202 | void Loader::register_unwind(Module& m) { | 227 | void Loader::register_unwind(Module& m) { |
| 203 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | 228 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 204 | if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_EXCEPTION) return; | 229 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION); |
| 205 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; | ||
| 206 | // Like the system loader, a trailing partial entry is ignored. | 230 | // Like the system loader, a trailing partial entry is ignored. |
| 207 | const uint32_t count = dir.Size / sizeof(RUNTIME_FUNCTION); | 231 | const uint32_t count = dir.Size / sizeof(RUNTIME_FUNCTION); |
| 208 | if (!count) return; | 232 | if (!count) return; |
| @@ -287,7 +311,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 287 | m->base = static_cast<uint8_t*>( | 311 | m->base = static_cast<uint8_t*>( |
| 288 | VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 312 | VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 289 | if (!m->base) { | 313 | if (!m->base) { |
| 290 | auto& relocs = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | 314 | const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); |
| 291 | if (!relocs.Size) | 315 | if (!relocs.Size) |
| 292 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); | 316 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); |
| 293 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 317 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| @@ -308,7 +332,7 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 308 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); | 332 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); |
| 309 | if (delta) { | 333 | if (delta) { |
| 310 | m->relocated = true; | 334 | m->relocated = true; |
| 311 | auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | 335 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); |
| 312 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); | 336 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); |
| 313 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); | 337 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); |
| 314 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); | 338 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); |
| @@ -466,7 +490,7 @@ void Loader::run_tls_callbacks(Module& m, uint32_t reason) { | |||
| 466 | 490 | ||
| 467 | void Loader::parse_exports(Module& m) { | 491 | void Loader::parse_exports(Module& m) { |
| 468 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | 492 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 469 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; | 493 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); |
| 470 | if (!dir.Size) return; | 494 | if (!dir.Size) return; |
| 471 | require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); | 495 | require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); |
| 472 | auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress); | 496 | auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress); |
| @@ -520,8 +544,9 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d | |||
| 520 | uint32_t ordinal = 0; | 544 | uint32_t ordinal = 0; |
| 521 | if (by_ordinal) { | 545 | if (by_ordinal) { |
| 522 | for (size_t i = 1; i < symbol.size(); ++i) { | 546 | for (size_t i = 1; i < symbol.size(); ++i) { |
| 523 | if (symbol[i] < '0' || symbol[i] > '9' || ordinal > 0xFFFF) return nullptr; | 547 | if (symbol[i] < '0' || symbol[i] > '9') return nullptr; |
| 524 | ordinal = ordinal * 10 + static_cast<uint32_t>(symbol[i] - '0'); | 548 | ordinal = ordinal * 10 + static_cast<uint32_t>(symbol[i] - '0'); |
| 549 | if (ordinal > 0xFFFF) return nullptr; // checked after the digit, so "#65537" can't truncate to 1 | ||
| 525 | } | 550 | } |
| 526 | } | 551 | } |
| 527 | 552 | ||
| @@ -606,7 +631,7 @@ void Loader::bind_imports(Module& m) { | |||
| 606 | } | 631 | } |
| 607 | }; | 632 | }; |
| 608 | 633 | ||
| 609 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; | 634 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_IMPORT); |
| 610 | if (dir.Size) { | 635 | if (dir.Size) { |
| 611 | for (uint64_t i = 0;; ++i) { | 636 | for (uint64_t i = 0;; ++i) { |
| 612 | uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); | 637 | uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); |
| @@ -619,7 +644,7 @@ void Loader::bind_imports(Module& m) { | |||
| 619 | } | 644 | } |
| 620 | } | 645 | } |
| 621 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. | 646 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. |
| 622 | auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; | 647 | const auto ddir = directory(nt, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); |
| 623 | if (ddir.Size) { | 648 | if (ddir.Size) { |
| 624 | for (uint64_t i = 0;; ++i) { | 649 | for (uint64_t i = 0;; ++i) { |
| 625 | uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); | 650 | uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); |
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index ebcf411ec..6d6c94751 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h | |||
| @@ -1,8 +1,8 @@ | |||
| 1 | // Native PE mapper for Xbox Series (x86-64) images. | 1 | // Native PE mapper for Xbox Series (x86-64) images. |
| 2 | // Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and | 2 | // Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and |
| 3 | // installs static TLS for the calling thread. | 3 | // installs static TLS for the calling thread. |
| 4 | // Mapping never runs code from the image. Loader::initialise() is the one call that does: it sets up the module's TLS | 4 | // Mapping never runs code from the image. Loader::initialise() delivers process attach to TLS callbacks and DllMain; |
| 5 | // (slot, template and callbacks) and calls a DLL's entry point as DllMain. | 5 | // ~Loader() delivers process detach before unmapping initialised modules. The TLS slot and template are set up by load(). |
| 6 | // gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it. | 6 | // gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it. |
| 7 | #pragma once | 7 | #pragma once |
| 8 | #include <cstdint> | 8 | #include <cstdint> |
| @@ -65,8 +65,9 @@ public: | |||
| 65 | explicit Loader(std::filesystem::path game_dir); | 65 | explicit Loader(std::filesystem::path game_dir); |
| 66 | Loader(const Loader&) = delete; | 66 | Loader(const Loader&) = delete; |
| 67 | Loader& operator=(const Loader&) = delete; | 67 | Loader& operator=(const Loader&) = delete; |
| 68 | // Restores the TLS slot for the calling thread. Destroy the Loader on the thread | 68 | // Delivers process detach to initialised modules in reverse dependency order before freeing any mappings or TLS. |
| 69 | // that called load() while any mapped TLS module is still live. | 69 | // Restores the TLS slot for the calling thread. Destroy the Loader on the thread that called load() while any |
| 70 | // mapped TLS module is still live; all other threads executing mapped code must have finished first. | ||
| 70 | ~Loader(); | 71 | ~Loader(); |
| 71 | 72 | ||
| 72 | // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. | 73 | // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. |
| @@ -86,7 +87,7 @@ public: | |||
| 86 | void initialise(); | 87 | void initialise(); |
| 87 | 88 | ||
| 88 | // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in: | 89 | // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in: |
| 89 | // load() never runs image code, and initialise() is the only call inside the Loader that uses it. No-op for | 90 | // load() never runs image code; initialise() and ~Loader() use it for process attach/detach. No-op for |
| 90 | // images without TLS callbacks. The loader does not deliver thread attach/detach events: install the thread's | 91 | // images without TLS callbacks. The loader does not deliver thread attach/detach events: install the thread's |
| 91 | // TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and uninstall after the detach callbacks. | 92 | // TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and uninstall after the detach callbacks. |
| 92 | void run_tls_callbacks(Module& m, uint32_t reason); | 93 | void run_tls_callbacks(Module& m, uint32_t reason); |
diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h index 3a472d872..6bd890ae8 100644 --- a/runtime/src/resource_tiling.h +++ b/runtime/src/resource_tiling.h | |||
| @@ -76,6 +76,20 @@ constexpr TileShape element_tile_shape(bool volume, std::uint32_t element_bytes) | |||
| 76 | } | 76 | } |
| 77 | } | 77 | } |
| 78 | 78 | ||
| 79 | // The 4 KiB tile shape in elements the PC runtime counts to allow D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT (16 of | ||
| 80 | // them must cover a texture's top mip), or {} as above. Measured with GetResourceAllocationInfo on an RTX 5070 and | ||
| 81 | // WARP (d3d12_vulkan_device_test). | ||
| 82 | constexpr TileShape small_tile_shape(bool volume, std::uint32_t element_bytes) { | ||
| 83 | switch (element_bytes) { | ||
| 84 | case 1: return volume ? TileShape{16, 16, 16} : TileShape{64, 64, 1}; | ||
| 85 | case 2: return volume ? TileShape{16, 16, 8} : TileShape{64, 32, 1}; | ||
| 86 | case 4: return volume ? TileShape{16, 8, 8} : TileShape{32, 32, 1}; | ||
| 87 | case 8: return volume ? TileShape{8, 8, 8} : TileShape{32, 16, 1}; | ||
| 88 | case 16: return volume ? TileShape{8, 8, 4} : TileShape{16, 16, 1}; | ||
| 89 | default: return {}; | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 79 | // False when the resource cannot be tiled: an untileable element size, no mips, or more than 2^32 tiles. | 93 | // False when the resource cannot be tiled: an untileable element size, no mips, or more than 2^32 tiles. |
| 80 | inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) { | 94 | inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) { |
| 81 | out = {}; | 95 | out = {}; |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 2c6a8b7cc..1e4cd38d2 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -14,13 +14,18 @@ | |||
| 14 | #include "vulkan_replay.h" | 14 | #include "vulkan_replay.h" |
| 15 | 15 | ||
| 16 | #include <algorithm> | 16 | #include <algorithm> |
| 17 | #include <atomic> | ||
| 18 | #include <condition_variable> | ||
| 17 | #include <cstdint> | 19 | #include <cstdint> |
| 18 | #include <cstdio> | 20 | #include <cstdio> |
| 21 | #include <cstring> | ||
| 19 | #include <functional> | 22 | #include <functional> |
| 20 | #include <map> | 23 | #include <map> |
| 21 | #include <memory> | 24 | #include <memory> |
| 22 | #include <mutex> | 25 | #include <mutex> |
| 26 | #include <shared_mutex> | ||
| 23 | #include <span> | 27 | #include <span> |
| 28 | #include <thread> | ||
| 24 | #include <tuple> | 29 | #include <tuple> |
| 25 | #include <unordered_map> | 30 | #include <unordered_map> |
| 26 | #include <vector> | 31 | #include <vector> |
| @@ -287,7 +292,312 @@ private: | |||
| 287 | VkPipeline binary_pipeline_ = VK_NULL_HANDLE; | 292 | VkPipeline binary_pipeline_ = VK_NULL_HANDLE; |
| 288 | }; | 293 | }; |
| 289 | 294 | ||
| 295 | // Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. | ||
| 296 | class DeferredDeletionQueue { | ||
| 297 | public: | ||
| 298 | enum class Kind : std::uint8_t { | ||
| 299 | bindless_slot, | ||
| 300 | image_view, | ||
| 301 | image, | ||
| 302 | buffer, | ||
| 303 | device_memory, | ||
| 304 | acceleration_structure, | ||
| 305 | }; | ||
| 306 | |||
| 307 | struct Item { | ||
| 308 | std::uint64_t ticket = 0; | ||
| 309 | std::uint64_t handle = 0; // for bindless_slot: (uint64_t(dimension) << 32) | index | ||
| 310 | Kind kind = Kind::image_view; | ||
| 311 | }; | ||
| 312 | |||
| 313 | using BindlessReleaseFn = void (*)(void* user, std::uint32_t dimension, std::uint32_t index); | ||
| 314 | |||
| 315 | explicit DeferredDeletionQueue(std::size_t initial_capacity = 256) : pending_(next_pow2(initial_capacity)) {} | ||
| 316 | |||
| 317 | void set_bindless_release(BindlessReleaseFn fn, void* user) { | ||
| 318 | std::lock_guard lock(mutex_); | ||
| 319 | bindless_release_fn_ = fn; | ||
| 320 | bindless_release_user_ = user; | ||
| 321 | } | ||
| 322 | |||
| 323 | void push(std::uint64_t retire_ticket, Kind kind, std::uint64_t handle) { | ||
| 324 | if (!handle && kind != Kind::bindless_slot) return; | ||
| 325 | std::lock_guard lock(mutex_); | ||
| 326 | if (count_ == pending_.size()) { | ||
| 327 | const std::size_t old_cap = pending_.size(); | ||
| 328 | std::vector<Item> grown(old_cap * 2); | ||
| 329 | const std::size_t first = old_cap - head_; | ||
| 330 | std::memcpy(grown.data(), pending_.data() + head_, first * sizeof(Item)); | ||
| 331 | if (head_ > 0) std::memcpy(grown.data() + first, pending_.data(), head_ * sizeof(Item)); | ||
| 332 | pending_ = std::move(grown); | ||
| 333 | head_ = 0; | ||
| 334 | tail_ = count_; | ||
| 335 | } | ||
| 336 | pending_[tail_] = {retire_ticket, handle, kind}; | ||
| 337 | tail_ = (tail_ + 1) & (pending_.size() - 1); | ||
| 338 | ++count_; | ||
| 339 | } | ||
| 340 | |||
| 341 | // Drains all items with ticket <= current_ticket in O(k), invoking vkDestroy* outside the lock. | ||
| 342 | // Uses a stack-local batch vector so concurrent drain() calls from multiple queues never race. | ||
| 343 | void drain(std::uint64_t current_ticket, VkDevice device, const VulkanDeviceFunctions& vk) { | ||
| 344 | BindlessReleaseFn release_fn = nullptr; | ||
| 345 | void* release_user = nullptr; | ||
| 346 | std::vector<Item> to_destroy; | ||
| 347 | { | ||
| 348 | std::lock_guard lock(mutex_); | ||
| 349 | if (count_ == 0 || pending_[head_].ticket > current_ticket) return; | ||
| 350 | release_fn = bindless_release_fn_; | ||
| 351 | release_user = bindless_release_user_; | ||
| 352 | const std::size_t mask = pending_.size() - 1; | ||
| 353 | while (count_ > 0 && pending_[head_].ticket <= current_ticket) { | ||
| 354 | to_destroy.push_back(pending_[head_]); | ||
| 355 | head_ = (head_ + 1) & mask; | ||
| 356 | --count_; | ||
| 357 | } | ||
| 358 | if (count_ == 0) { | ||
| 359 | head_ = 0; | ||
| 360 | tail_ = 0; | ||
| 361 | } | ||
| 362 | } | ||
| 363 | |||
| 364 | for (const Item& item : to_destroy) { | ||
| 365 | switch (item.kind) { | ||
| 366 | case Kind::bindless_slot: | ||
| 367 | if (release_fn) { | ||
| 368 | release_fn(release_user, static_cast<std::uint32_t>(item.handle >> 32), | ||
| 369 | static_cast<std::uint32_t>(item.handle & 0xFFFFFFFFu)); | ||
| 370 | } | ||
| 371 | break; | ||
| 372 | case Kind::image_view: | ||
| 373 | vk.vkDestroyImageView(device, reinterpret_cast<VkImageView>(item.handle), nullptr); | ||
| 374 | break; | ||
| 375 | case Kind::image: | ||
| 376 | vk.vkDestroyImage(device, reinterpret_cast<VkImage>(item.handle), nullptr); | ||
| 377 | break; | ||
| 378 | case Kind::buffer: | ||
| 379 | vk.vkDestroyBuffer(device, reinterpret_cast<VkBuffer>(item.handle), nullptr); | ||
| 380 | break; | ||
| 381 | case Kind::device_memory: | ||
| 382 | vk.vkFreeMemory(device, reinterpret_cast<VkDeviceMemory>(item.handle), nullptr); | ||
| 383 | break; | ||
| 384 | case Kind::acceleration_structure: | ||
| 385 | if (vk.vkDestroyAccelerationStructureKHR) | ||
| 386 | vk.vkDestroyAccelerationStructureKHR( | ||
| 387 | device, reinterpret_cast<VkAccelerationStructureKHR>(item.handle), nullptr); | ||
| 388 | break; | ||
| 389 | } | ||
| 390 | } | ||
| 391 | } | ||
| 392 | |||
| 393 | private: | ||
| 394 | static std::size_t next_pow2(std::size_t n) { | ||
| 395 | std::size_t p = 16; | ||
| 396 | while (p < n) p <<= 1; | ||
| 397 | return p; | ||
| 398 | } | ||
| 399 | |||
| 400 | std::mutex mutex_; | ||
| 401 | std::vector<Item> pending_; | ||
| 402 | std::size_t head_ = 0; | ||
| 403 | std::size_t tail_ = 0; | ||
| 404 | std::size_t count_ = 0; | ||
| 405 | BindlessReleaseFn bindless_release_fn_ = nullptr; | ||
| 406 | void* bindless_release_user_ = nullptr; | ||
| 407 | }; | ||
| 408 | |||
| 409 | // Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT). | ||
| 410 | // Eliminates per-fence OS threads and 10ms polling: a synthetic timeline semaphore (wakeup_sem_) at index 0 | ||
| 411 | // wakes vkWaitSemaphores immediately whenever a new wait, a released fence, or shutdown arrives while waiting_ == true. | ||
| 412 | class FenceWaitDispatcher { | ||
| 413 | public: | ||
| 414 | struct Entry { | ||
| 415 | VkSemaphore semaphore = VK_NULL_HANDLE; | ||
| 416 | std::uint64_t value = 0; | ||
| 417 | void* event_handle = nullptr; | ||
| 418 | std::function<void()> callback; | ||
| 419 | }; | ||
| 420 | |||
| 421 | using SignalEventFn = void (*)(void* event_handle); | ||
| 422 | |||
| 423 | FenceWaitDispatcher(VkDevice device, const VulkanDeviceFunctions& vk, std::atomic<bool>& device_lost) | ||
| 424 | : device_(device), vk_(vk), device_lost_(device_lost) { | ||
| 425 | VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; | ||
| 426 | type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; | ||
| 427 | type.initialValue = 0; | ||
| 428 | VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; | ||
| 429 | if (vk_.vkCreateSemaphore(device_, &info, nullptr, &wakeup_sem_) != VK_SUCCESS) | ||
| 430 | wakeup_sem_ = VK_NULL_HANDLE; | ||
| 431 | semaphores_.reserve(64); | ||
| 432 | values_.reserve(64); | ||
| 433 | } | ||
| 434 | |||
| 435 | ~FenceWaitDispatcher() { | ||
| 436 | stop(); | ||
| 437 | if (wakeup_sem_) vk_.vkDestroySemaphore(device_, wakeup_sem_, nullptr); | ||
| 438 | } | ||
| 439 | |||
| 440 | FenceWaitDispatcher(const FenceWaitDispatcher&) = delete; | ||
| 441 | FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete; | ||
| 442 | |||
| 443 | void set_signal_event_fn(SignalEventFn fn) { | ||
| 444 | std::lock_guard lock(mutex_); | ||
| 445 | signal_event_ = fn; | ||
| 446 | } | ||
| 447 | |||
| 448 | void enqueue(VkSemaphore sem, std::uint64_t value, void* event_handle) { | ||
| 449 | if (!sem || !event_handle) return; | ||
| 450 | if (device_lost_.load(std::memory_order_acquire)) { | ||
| 451 | SignalEventFn fn = nullptr; | ||
| 452 | { | ||
| 453 | std::lock_guard lock(mutex_); | ||
| 454 | fn = signal_event_; | ||
| 455 | } | ||
| 456 | if (fn) fn(event_handle); | ||
| 457 | return; | ||
| 458 | } | ||
| 459 | { | ||
| 460 | std::lock_guard lock(mutex_); | ||
| 461 | pending_.push_back({sem, value, event_handle, {}}); | ||
| 462 | if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); | ||
| 463 | signal_wakeup_locked(); | ||
| 464 | } | ||
| 465 | cv_.notify_one(); | ||
| 466 | } | ||
| 467 | |||
| 468 | void enqueue_callback(VkSemaphore sem, std::uint64_t value, std::function<void()> cb) { | ||
| 469 | if (!sem || !cb) return; | ||
| 470 | if (device_lost_.load(std::memory_order_acquire)) { | ||
| 471 | cb(); | ||
| 472 | return; | ||
| 473 | } | ||
| 474 | { | ||
| 475 | std::lock_guard lock(mutex_); | ||
| 476 | pending_.push_back({sem, value, nullptr, std::move(cb)}); | ||
| 477 | if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); | ||
| 478 | signal_wakeup_locked(); | ||
| 479 | } | ||
| 480 | cv_.notify_one(); | ||
| 481 | } | ||
| 482 | |||
| 483 | // Completes the pending waits for `sem` (a released D3D12 fence counts as reached, as on the PC runtime) and | ||
| 484 | // blocks until any in-flight vkWaitSemaphores releases `sem` before the caller destroys the VkSemaphore. | ||
| 485 | void cancel(VkSemaphore sem) { | ||
| 486 | if (!sem) return; | ||
| 487 | std::unique_lock lock(mutex_); | ||
| 488 | std::erase_if(pending_, [this, sem](const Entry& e) { | ||
| 489 | if (e.semaphore != sem) return false; | ||
| 490 | if (e.callback) e.callback(); | ||
| 491 | else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); | ||
| 492 | return true; | ||
| 493 | }); | ||
| 494 | if (!thread_.joinable()) return; | ||
| 495 | if (waiting_) { | ||
| 496 | const std::uint64_t target_epoch = epoch_ + 1; | ||
| 497 | signal_wakeup_locked(); | ||
| 498 | epoch_cv_.wait(lock, [this, target_epoch] { return !waiting_ || epoch_ >= target_epoch; }); | ||
| 499 | } | ||
| 500 | } | ||
| 501 | |||
| 502 | void stop() { | ||
| 503 | { | ||
| 504 | std::lock_guard lock(mutex_); | ||
| 505 | if (stop_) return; | ||
| 506 | stop_ = true; | ||
| 507 | signal_wakeup_locked(); | ||
| 508 | } | ||
| 509 | cv_.notify_all(); | ||
| 510 | if (thread_.joinable()) thread_.join(); | ||
| 511 | } | ||
| 512 | |||
| 513 | private: | ||
| 514 | // Only signals wakeup_sem_ when run() is actively waiting (waiting_ == true) on wakeup_val_ + 1, | ||
| 515 | // eliminating any lost-wakeup race between snapshot construction and vkWaitSemaphores. | ||
| 516 | void signal_wakeup_locked() { | ||
| 517 | if (!waiting_ || !wakeup_sem_ || device_lost_.load(std::memory_order_relaxed)) return; | ||
| 518 | const std::uint64_t next = ++wakeup_val_; | ||
| 519 | VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; | ||
| 520 | si.semaphore = wakeup_sem_; | ||
| 521 | si.value = next; | ||
| 522 | vk_.vkSignalSemaphore(device_, &si); | ||
| 523 | } | ||
| 524 | |||
| 525 | void run() { | ||
| 526 | std::unique_lock lock(mutex_); | ||
| 527 | while (true) { | ||
| 528 | cv_.wait(lock, [this] { return stop_ || !pending_.empty(); }); | ||
| 529 | if (stop_) return; | ||
| 530 | |||
| 531 | semaphores_.clear(); | ||
| 532 | values_.clear(); | ||
| 533 | semaphores_.push_back(wakeup_sem_); | ||
| 534 | values_.push_back(wakeup_val_ + 1); | ||
| 535 | for (const Entry& e : pending_) { | ||
| 536 | semaphores_.push_back(e.semaphore); | ||
| 537 | values_.push_back(e.value); | ||
| 538 | } | ||
| 539 | |||
| 540 | waiting_ = true; | ||
| 541 | lock.unlock(); | ||
| 542 | |||
| 543 | VkSemaphoreWaitInfo wi{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; | ||
| 544 | wi.flags = VK_SEMAPHORE_WAIT_ANY_BIT; | ||
| 545 | wi.semaphoreCount = static_cast<std::uint32_t>(semaphores_.size()); | ||
| 546 | wi.pSemaphores = semaphores_.data(); | ||
| 547 | wi.pValues = values_.data(); | ||
| 548 | const VkResult res = vk_.vkWaitSemaphores(device_, &wi, UINT64_MAX); | ||
| 549 | |||
| 550 | lock.lock(); | ||
| 551 | waiting_ = false; | ||
| 552 | ++epoch_; | ||
| 553 | epoch_cv_.notify_all(); | ||
| 554 | |||
| 555 | if (res == VK_ERROR_DEVICE_LOST) { | ||
| 556 | device_lost_.store(true, std::memory_order_release); | ||
| 557 | for (const Entry& e : pending_) { | ||
| 558 | if (e.callback) e.callback(); | ||
| 559 | else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); | ||
| 560 | } | ||
| 561 | pending_.clear(); | ||
| 562 | return; | ||
| 563 | } | ||
| 564 | if (stop_) return; | ||
| 565 | |||
| 566 | std::erase_if(pending_, [this](const Entry& e) { | ||
| 567 | std::uint64_t done = 0; | ||
| 568 | if (vk_.vkGetSemaphoreCounterValue(device_, e.semaphore, &done) != VK_SUCCESS) return false; | ||
| 569 | if (done < e.value) return false; | ||
| 570 | if (e.callback) e.callback(); | ||
| 571 | else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); | ||
| 572 | return true; | ||
| 573 | }); | ||
| 574 | } | ||
| 575 | } | ||
| 576 | |||
| 577 | VkDevice device_; | ||
| 578 | const VulkanDeviceFunctions& vk_; | ||
| 579 | std::atomic<bool>& device_lost_; | ||
| 580 | SignalEventFn signal_event_ = nullptr; | ||
| 581 | VkSemaphore wakeup_sem_ = VK_NULL_HANDLE; | ||
| 582 | std::uint64_t wakeup_val_ = 0; | ||
| 583 | |||
| 584 | std::mutex mutex_; | ||
| 585 | std::condition_variable cv_; | ||
| 586 | std::condition_variable epoch_cv_; | ||
| 587 | std::vector<Entry> pending_; | ||
| 588 | std::vector<VkSemaphore> semaphores_; | ||
| 589 | std::vector<std::uint64_t> values_; | ||
| 590 | std::uint64_t epoch_ = 0; | ||
| 591 | bool waiting_ = false; | ||
| 592 | bool stop_ = false; | ||
| 593 | std::thread thread_; | ||
| 594 | }; | ||
| 595 | |||
| 290 | // Per device: what the queues share. Resources are registered by their stable ID (the COM resource pointer). | 596 | // Per device: what the queues share. Resources are registered by their stable ID (the COM resource pointer). |
| 597 | #ifdef _MSC_VER | ||
| 598 | #pragma warning(push) | ||
| 599 | #pragma warning(disable : 4324) // intentional alignas(64) cache-line padding to prevent false sharing | ||
| 600 | #endif | ||
| 291 | class VulkanContext { | 601 | class VulkanContext { |
| 292 | public: | 602 | public: |
| 293 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). | 603 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). |
| @@ -350,10 +660,22 @@ public: | |||
| 350 | return it == query_pools_.end() ? nullptr : &it->second; | 660 | return it == query_pools_.end() ? nullptr : &it->second; |
| 351 | }; | 661 | }; |
| 352 | replay_.separate_depth_stencil_layouts = separate_depth_stencil_layouts; | 662 | replay_.separate_depth_stencil_layouts = separate_depth_stencil_layouts; |
| 663 | if (loaded_) { | ||
| 664 | VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; | ||
| 665 | type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; | ||
| 666 | type.initialValue = 0; | ||
| 667 | VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; | ||
| 668 | if (vk.vkCreateSemaphore(device_, &info, nullptr, &retire_timeline_) != VK_SUCCESS) | ||
| 669 | retire_timeline_ = VK_NULL_HANDLE; | ||
| 670 | fence_dispatcher_ = std::make_unique<FenceWaitDispatcher>(device_, vk, device_lost_); | ||
| 671 | } | ||
| 353 | } | 672 | } |
| 354 | 673 | ||
| 355 | ~VulkanContext() { | 674 | ~VulkanContext() { |
| 675 | fence_dispatcher_.reset(); | ||
| 676 | deletion_queue_.drain(UINT64_MAX, device_, vk); | ||
| 356 | for (const auto& [key, view] : views_) vk.vkDestroyImageView(device_, view, nullptr); | 677 | for (const auto& [key, view] : views_) vk.vkDestroyImageView(device_, view, nullptr); |
| 678 | if (retire_timeline_) vk.vkDestroySemaphore(device_, retire_timeline_, nullptr); | ||
| 357 | } | 679 | } |
| 358 | 680 | ||
| 359 | VulkanContext(const VulkanContext&) = delete; | 681 | VulkanContext(const VulkanContext&) = delete; |
| @@ -376,41 +698,58 @@ public: | |||
| 376 | // Registers a resource in its D3D12 initial state (a legacy state; images get the matching layout). | 698 | // Registers a resource in its D3D12 initial state (a legacy state; images get the matching layout). |
| 377 | // The image must already be in that layout, e.g. transitioned from UNDEFINED at creation. | 699 | // The image must already be in that layout, e.g. transitioned from UNDEFINED at creation. |
| 378 | void add_resource(ResourceId id, const ResourceBinding& binding) { | 700 | void add_resource(ResourceId id, const ResourceBinding& binding) { |
| 379 | std::lock_guard lock(mutex_); | 701 | std::unique_lock lock(resource_mutex_); |
| 380 | resources_[id] = binding; | 702 | resources_[id] = binding; |
| 381 | } | 703 | } |
| 382 | void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { | 704 | void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { |
| 383 | std::lock_guard lock(mutex_); | 705 | std::unique_lock rlock(resource_mutex_); |
| 384 | resources_[id] = binding; | 706 | resources_[id] = binding; |
| 385 | if (binding.image) tracker_.track(id, binding, current_layout); | 707 | if (binding.image) { |
| 708 | std::lock_guard tlock(tracker_mutex_); | ||
| 709 | tracker_.track(id, binding, current_layout); | ||
| 710 | } | ||
| 386 | } | 711 | } |
| 387 | 712 | ||
| 388 | void remove_resource(ResourceId id) { | 713 | void remove_resource(ResourceId id) { |
| 389 | std::lock_guard lock(mutex_); | 714 | VkImage img = VK_NULL_HANDLE; |
| 390 | const auto it = resources_.find(id); | 715 | { |
| 391 | if (it == resources_.end()) return; | 716 | std::unique_lock rlock(resource_mutex_); |
| 392 | for (auto v = views_.begin(); v != views_.end();) { | 717 | const auto it = resources_.find(id); |
| 393 | if (std::get<0>(v->first) == it->second.image) { | 718 | if (it == resources_.end()) return; |
| 394 | vk.vkDestroyImageView(device_, v->second, nullptr); | 719 | img = it->second.image; |
| 395 | v = views_.erase(v); | 720 | resources_.erase(it); |
| 396 | } else { | 721 | } |
| 397 | ++v; | 722 | if (img) { |
| 723 | std::lock_guard vlock(views_mutex_); | ||
| 724 | for (auto v = views_.begin(); v != views_.end();) { | ||
| 725 | if (std::get<0>(v->first) == img) { | ||
| 726 | defer_destroy(DeferredDeletionQueue::Kind::image_view, v->second); | ||
| 727 | v = views_.erase(v); | ||
| 728 | } else { | ||
| 729 | ++v; | ||
| 730 | } | ||
| 398 | } | 731 | } |
| 399 | } | 732 | } |
| 733 | std::lock_guard tlock(tracker_mutex_); | ||
| 400 | tracker_.forget(id); | 734 | tracker_.forget(id); |
| 401 | resources_.erase(it); | ||
| 402 | } | 735 | } |
| 403 | 736 | ||
| 404 | // A query heap, by its stable ID (the COM query heap pointer). The pool stays the caller's to destroy, after | 737 | // A query heap, by its stable ID (the COM query heap pointer). The pool stays the caller's to destroy, after |
| 405 | // remove_query_pool. | 738 | // remove_query_pool. |
| 406 | void add_query_pool(QueryHeapId id, const QueryPool& pool) { | 739 | void add_query_pool(QueryHeapId id, const QueryPool& pool) { |
| 407 | std::lock_guard lock(mutex_); | 740 | std::unique_lock lock(resource_mutex_); |
| 408 | query_pools_[id] = pool; | 741 | query_pools_[id] = pool; |
| 409 | } | 742 | } |
| 410 | void remove_query_pool(QueryHeapId id) { | 743 | void remove_query_pool(QueryHeapId id) { |
| 411 | std::lock_guard lock(mutex_); | 744 | std::unique_lock lock(resource_mutex_); |
| 412 | query_pools_.erase(id); | 745 | query_pools_.erase(id); |
| 413 | } | 746 | } |
| 747 | // The heap's d3d12_query_heap type, or ~0u for a heap that is not registered. | ||
| 748 | std::uint32_t query_heap_type(QueryHeapId id) { | ||
| 749 | std::shared_lock lock(resource_mutex_); // query_pools_ is guarded by resource_mutex_, like add/remove | ||
| 750 | const auto it = query_pools_.find(id); | ||
| 751 | return it == query_pools_.end() ? ~0u : it->second.heap_type; | ||
| 752 | } | ||
| 414 | 753 | ||
| 415 | // VkPhysicalDeviceLimits::timestampPeriod (nanoseconds per tick), or 0 when the queue writes no timestamps | 754 | // VkPhysicalDeviceLimits::timestampPeriod (nanoseconds per tick), or 0 when the queue writes no timestamps |
| 416 | // (timestampValidBits 0). Set by the device before any queue uses it. | 755 | // (timestampValidBits 0). Set by the device before any queue uses it. |
| @@ -424,12 +763,12 @@ public: | |||
| 424 | 763 | ||
| 425 | // For tests and traces. | 764 | // For tests and traces. |
| 426 | VkImageLayout layout(ResourceId id, std::uint32_t subresource) { | 765 | VkImageLayout layout(ResourceId id, std::uint32_t subresource) { |
| 427 | std::lock_guard lock(mutex_); | 766 | std::lock_guard lock(tracker_mutex_); |
| 428 | return tracker_.layout(id, subresource); | 767 | return tracker_.layout(id, subresource); |
| 429 | } | 768 | } |
| 430 | 769 | ||
| 431 | bool has_resource(ResourceId id) { | 770 | bool has_resource(ResourceId id) { |
| 432 | std::lock_guard lock(mutex_); | 771 | std::shared_lock lock(resource_mutex_); |
| 433 | return resources_.find(id) != resources_.end(); | 772 | return resources_.find(id) != resources_.end(); |
| 434 | } | 773 | } |
| 435 | 774 | ||
| @@ -437,28 +776,27 @@ public: | |||
| 437 | 776 | ||
| 438 | void register_acceleration_structure(std::uint64_t va, VkAccelerationStructureKHR as) { | 777 | void register_acceleration_structure(std::uint64_t va, VkAccelerationStructureKHR as) { |
| 439 | if (!va || !as) return; | 778 | if (!va || !as) return; |
| 440 | std::lock_guard lock(mutex_); | 779 | std::unique_lock lock(resource_mutex_); |
| 441 | acceleration_structures_[va] = as; | 780 | acceleration_structures_[va] = as; |
| 442 | } | 781 | } |
| 443 | 782 | ||
| 444 | void unregister_acceleration_structure(std::uint64_t va) { | 783 | void unregister_acceleration_structure(std::uint64_t va) { |
| 445 | if (!va) return; | 784 | if (!va) return; |
| 446 | std::lock_guard lock(mutex_); | 785 | std::unique_lock lock(resource_mutex_); |
| 447 | acceleration_structures_.erase(va); | 786 | acceleration_structures_.erase(va); |
| 448 | } | 787 | } |
| 449 | 788 | ||
| 450 | VkAccelerationStructureKHR resolve_acceleration_structure(std::uint64_t va) { | 789 | VkAccelerationStructureKHR resolve_acceleration_structure(std::uint64_t va) { |
| 451 | std::lock_guard lock(mutex_); | 790 | std::shared_lock lock(resource_mutex_); |
| 452 | const auto it = acceleration_structures_.find(va); | 791 | const auto it = acceleration_structures_.find(va); |
| 453 | return it == acceleration_structures_.end() ? VK_NULL_HANDLE : it->second; | 792 | return it == acceleration_structures_.end() ? VK_NULL_HANDLE : it->second; |
| 454 | } | 793 | } |
| 455 | 794 | ||
| 456 | // `prepare` is called with the context locked, at the start of the command buffer of every | 795 | // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are |
| 457 | // ExecuteCommandLists, before the lists are written: the device brings the bindless set 0 of the translated | 796 | // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) |
| 458 | // shaders up to date there (vulkan_bindless.h) and records what the set needs first. When it fails, nothing | 797 | // and records what the set needs first. When it fails, nothing of that call is executed. |
| 459 | // of that call is executed. | ||
| 460 | void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { | 798 | void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { |
| 461 | std::lock_guard lock(mutex_); | 799 | std::unique_lock lock(resource_mutex_); |
| 462 | bindless_prepare_ = std::move(prepare); | 800 | bindless_prepare_ = std::move(prepare); |
| 463 | } | 801 | } |
| 464 | 802 | ||
| @@ -466,7 +804,7 @@ public: | |||
| 466 | // gives the scratch buffers device-local memory. Without this such a copy is refused as unsupported. | 804 | // gives the scratch buffers device-local memory. Without this such a copy is refused as unsupported. |
| 467 | void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, | 805 | void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, |
| 468 | std::uint64_t max_storage_range = 1u << 27) { | 806 | std::uint64_t max_storage_range = 1u << 27) { |
| 469 | std::lock_guard lock(mutex_); | 807 | std::unique_lock lock(resource_mutex_); |
| 470 | depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range); | 808 | depth24_ = std::make_unique<Depth24Converter>(get, device_, std::move(allocate), max_storage_range); |
| 471 | if (!depth24_->loaded()) { | 809 | if (!depth24_->loaded()) { |
| 472 | depth24_.reset(); | 810 | depth24_.reset(); |
| @@ -481,15 +819,65 @@ public: | |||
| 481 | // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The | 819 | // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The |
| 482 | // set keeps its upload pending in the second case, because the copy never reached the GPU. | 820 | // set keeps its upload pending in the second case, because the copy never reached the GPU. |
| 483 | void set_bindless_commit(std::function<void(bool)> commit) { | 821 | void set_bindless_commit(std::function<void(bool)> commit) { |
| 484 | std::lock_guard lock(mutex_); | 822 | std::unique_lock lock(resource_mutex_); |
| 485 | bindless_commit_ = std::move(commit); | 823 | bindless_commit_ = std::move(commit); |
| 486 | } | 824 | } |
| 487 | 825 | ||
| 826 | void set_bindless_release(DeferredDeletionQueue::BindlessReleaseFn fn, void* user) { | ||
| 827 | deletion_queue_.set_bindless_release(fn, user); | ||
| 828 | } | ||
| 829 | |||
| 830 | template<typename VkHandle> | ||
| 831 | void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { | ||
| 832 | const auto raw = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(handle)); | ||
| 833 | if (!raw) return; | ||
| 834 | const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; | ||
| 835 | deletion_queue_.push(safe_ticket, kind, raw); | ||
| 836 | } | ||
| 837 | |||
| 838 | void defer_destroy(DeferredDeletionQueue::Kind kind, std::uint64_t raw_handle) { | ||
| 839 | if (!raw_handle && kind != DeferredDeletionQueue::Kind::bindless_slot) return; | ||
| 840 | const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; | ||
| 841 | deletion_queue_.push(safe_ticket, kind, raw_handle); | ||
| 842 | } | ||
| 843 | |||
| 844 | std::uint64_t completed_retire_ticket() const { | ||
| 845 | if (!retire_timeline_) return submitted_ticket_.load(std::memory_order_acquire); | ||
| 846 | std::uint64_t done = 0; | ||
| 847 | vk.vkGetSemaphoreCounterValue(device_, retire_timeline_, &done); | ||
| 848 | return done; | ||
| 849 | } | ||
| 850 | |||
| 851 | void drain_deleted_resources(std::uint64_t current_ticket) { | ||
| 852 | deletion_queue_.drain(current_ticket, device_, vk); | ||
| 853 | } | ||
| 854 | |||
| 855 | VkSemaphore retire_timeline() const noexcept { return retire_timeline_; } | ||
| 856 | std::uint64_t advance_retire_ticket() noexcept { | ||
| 857 | return submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; | ||
| 858 | } | ||
| 859 | |||
| 488 | VulkanDeviceFunctions vk; | 860 | VulkanDeviceFunctions vk; |
| 489 | 861 | ||
| 490 | // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. | 862 | // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. |
| 491 | std::mutex& submit_mutex() { return submit_mutex_; } | 863 | std::mutex& submit_mutex() { return submit_mutex_; } |
| 492 | 864 | ||
| 865 | void mark_device_lost() noexcept { device_lost_.store(true, std::memory_order_release); } | ||
| 866 | bool is_device_lost() const noexcept { return device_lost_.load(std::memory_order_acquire); } | ||
| 867 | |||
| 868 | void set_signal_event_fn(FenceWaitDispatcher::SignalEventFn fn) { | ||
| 869 | if (fence_dispatcher_) fence_dispatcher_->set_signal_event_fn(fn); | ||
| 870 | } | ||
| 871 | void enqueue_fence_wait(VkSemaphore sem, std::uint64_t value, void* event_handle) { | ||
| 872 | if (fence_dispatcher_) fence_dispatcher_->enqueue(sem, value, event_handle); | ||
| 873 | } | ||
| 874 | void enqueue_fence_callback(VkSemaphore sem, std::uint64_t value, std::function<void()> cb) { | ||
| 875 | if (fence_dispatcher_) fence_dispatcher_->enqueue_callback(sem, value, std::move(cb)); | ||
| 876 | } | ||
| 877 | void cancel_fence_waits(VkSemaphore sem) { | ||
| 878 | if (fence_dispatcher_) fence_dispatcher_->cancel(sem); | ||
| 879 | } | ||
| 880 | |||
| 493 | private: | 881 | private: |
| 494 | friend class VulkanQueue; | 882 | friend class VulkanQueue; |
| 495 | 883 | ||
| @@ -498,8 +886,9 @@ private: | |||
| 498 | return it == resources_.end() ? nullptr : &it->second; | 886 | return it == resources_.end() ? nullptr : &it->second; |
| 499 | } | 887 | } |
| 500 | 888 | ||
| 501 | // Called with mutex_ held (from prepare). Views live until their image is removed. | 889 | // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. |
| 502 | VkImageView view(const ResourceBinding& r, const VkImageSubresourceRange& range) { | 890 | VkImageView view(const ResourceBinding& r, const VkImageSubresourceRange& range) { |
| 891 | std::lock_guard lock(views_mutex_); | ||
| 503 | const auto key = std::make_tuple(r.image, range.aspectMask, range.baseMipLevel, range.baseArrayLayer, | 892 | const auto key = std::make_tuple(r.image, range.aspectMask, range.baseMipLevel, range.baseArrayLayer, |
| 504 | range.layerCount, r.format); | 893 | range.layerCount, r.format); |
| 505 | if (const auto it = views_.find(key); it != views_.end()) return it->second; | 894 | if (const auto it = views_.find(key); it != views_.end()) return it->second; |
| @@ -522,8 +911,15 @@ private: | |||
| 522 | VkDevice device_; | 911 | VkDevice device_; |
| 523 | bool loaded_ = false; | 912 | bool loaded_ = false; |
| 524 | bool ray_tracing_ = false; | 913 | bool ray_tracing_ = false; |
| 525 | std::mutex mutex_; // resources, tracker and views; held while a queue prepares and emits | 914 | std::atomic<bool> device_lost_{false}; |
| 526 | std::mutex submit_mutex_; | 915 | alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove |
| 916 | alignas(64) std::mutex tracker_mutex_; | ||
| 917 | alignas(64) std::mutex views_mutex_; | ||
| 918 | alignas(64) std::mutex submit_mutex_; | ||
| 919 | VkSemaphore retire_timeline_ = VK_NULL_HANDLE; | ||
| 920 | std::atomic<std::uint64_t> submitted_ticket_{0}; | ||
| 921 | DeferredDeletionQueue deletion_queue_; | ||
| 922 | std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; | ||
| 527 | std::unordered_map<ResourceId, ResourceBinding> resources_; | 923 | std::unordered_map<ResourceId, ResourceBinding> resources_; |
| 528 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; | 924 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; |
| 529 | LayoutTracker tracker_; | 925 | LayoutTracker tracker_; |
| @@ -537,6 +933,9 @@ private: | |||
| 537 | ReplayFunctions replay_; | 933 | ReplayFunctions replay_; |
| 538 | DebugLabelFunctions labels_; | 934 | DebugLabelFunctions labels_; |
| 539 | }; | 935 | }; |
| 936 | #ifdef _MSC_VER | ||
| 937 | #pragma warning(pop) | ||
| 938 | #endif | ||
| 540 | 939 | ||
| 541 | // A Vulkan timeline semaphore with D3D12 fence semantics for the host side. | 940 | // A Vulkan timeline semaphore with D3D12 fence semantics for the host side. |
| 542 | class VulkanFence { | 941 | class VulkanFence { |
| @@ -591,7 +990,24 @@ private: | |||
| 591 | // per call, and the COM wrapper serialises its calls. | 990 | // per call, and the COM wrapper serialises its calls. |
| 592 | class VulkanQueue { | 991 | class VulkanQueue { |
| 593 | public: | 992 | public: |
| 594 | VulkanQueue(VulkanContext& context, VkQueue queue, std::uint32_t family) : context_(context), queue_(queue) { | 993 | enum class QueueKind : std::uint8_t { direct, compute, copy }; |
| 994 | |||
| 995 | static constexpr VkPipelineStageFlags2 queue_supported_stages(QueueKind kind) noexcept { | ||
| 996 | switch (kind) { | ||
| 997 | case QueueKind::copy: | ||
| 998 | return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 999 | case QueueKind::compute: | ||
| 1000 | return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | | ||
| 1001 | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; | ||
| 1002 | case QueueKind::direct: | ||
| 1003 | default: | ||
| 1004 | return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | | ||
| 1005 | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT; | ||
| 1006 | } | ||
| 1007 | } | ||
| 1008 | |||
| 1009 | VulkanQueue(VulkanContext& context, VkQueue queue, std::uint32_t family, QueueKind kind = QueueKind::direct) | ||
| 1010 | : context_(context), queue_(queue), kind_(kind) { | ||
| 595 | auto& vk = context.vk; | 1011 | auto& vk = context.vk; |
| 596 | VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; | 1012 | VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; |
| 597 | pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; | 1013 | pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; |
| @@ -611,7 +1027,7 @@ public: | |||
| 611 | vk.vkQueueWaitIdle(queue_); | 1027 | vk.vkQueueWaitIdle(queue_); |
| 612 | } | 1028 | } |
| 613 | if (progress_) { | 1029 | if (progress_) { |
| 614 | std::lock_guard lock(context_.mutex_); | 1030 | std::lock_guard lock(context_.tracker_mutex_); |
| 615 | if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now | 1031 | if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now |
| 616 | } | 1032 | } |
| 617 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); | 1033 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); |
| @@ -626,8 +1042,20 @@ public: | |||
| 626 | // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves | 1042 | // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves |
| 627 | // the layout tracker as it was. Pending Wait()s are attached to this submission. | 1043 | // the layout tracker as it was. Pending Wait()s are attached to this submission. |
| 628 | ReplayResult execute(std::span<const CommandList* const> lists) { | 1044 | ReplayResult execute(std::span<const CommandList* const> lists) { |
| 629 | std::lock_guard lock(context_.mutex_); | 1045 | if (context_.is_device_lost()) return ReplayResult::unsupported; |
| 630 | if (context_.depth24_) context_.depth24_->collect(); | 1046 | VkCommandBuffer command_buffer = VK_NULL_HANDLE; |
| 1047 | std::function<void(bool)> bindless_commit; | ||
| 1048 | // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. | ||
| 1049 | // Shared read-lock allows concurrent prepare() lookups; when depth24_ is active, tracker_mutex_ is also | ||
| 1050 | // acquired before prepare() so Depth24Converter::prepare/collect/retire stay serialized per execution. | ||
| 1051 | // Otherwise tracker_mutex_ is held from emit() through submit() so emit order == submit order across queues. | ||
| 1052 | std::shared_lock resource_lock(context_.resource_mutex_); | ||
| 1053 | std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); | ||
| 1054 | if (context_.depth24_) { | ||
| 1055 | tracker_lock.lock(); | ||
| 1056 | context_.depth24_->collect(); | ||
| 1057 | } | ||
| 1058 | bindless_commit = context_.bindless_commit_; | ||
| 631 | std::vector<PreparedList> prepared(lists.size()); | 1059 | std::vector<PreparedList> prepared(lists.size()); |
| 632 | ReplayFunctions replay = context_.replay_; | 1060 | ReplayFunctions replay = context_.replay_; |
| 633 | const auto& occlusion_memory = context_.occlusion_resolve_memory_; | 1061 | const auto& occlusion_memory = context_.occlusion_resolve_memory_; |
| @@ -682,7 +1110,7 @@ public: | |||
| 682 | 1110 | ||
| 683 | CommandSlot* slot = acquire(); | 1111 | CommandSlot* slot = acquire(); |
| 684 | if (!slot) return ReplayResult::unsupported; | 1112 | if (!slot) return ReplayResult::unsupported; |
| 685 | const auto command_buffer = slot->buffer; | 1113 | command_buffer = slot->buffer; |
| 686 | const auto discard = [&] { | 1114 | const auto discard = [&] { |
| 687 | if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; | 1115 | if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; |
| 688 | }; | 1116 | }; |
| @@ -693,25 +1121,57 @@ public: | |||
| 693 | return ReplayResult::unsupported; | 1121 | return ReplayResult::unsupported; |
| 694 | } | 1122 | } |
| 695 | if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { | 1123 | if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { |
| 696 | // The command buffer holds at most what the set recorded for itself; submit it so the buffer is reused. | 1124 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; |
| 697 | const bool submitted = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS && | 1125 | resource_lock.unlock(); |
| 698 | submit(command_buffer, VK_NULL_HANDLE, 0); | 1126 | if (tracker_lock.owns_lock()) tracker_lock.unlock(); |
| 1127 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); | ||
| 699 | if (!submitted) discard(); | 1128 | if (!submitted) discard(); |
| 700 | if (context_.bindless_commit_) context_.bindless_commit_(submitted); | 1129 | if (bindless_commit) bindless_commit(submitted); |
| 701 | return ReplayResult::unsupported; | 1130 | return ReplayResult::unsupported; |
| 702 | } | 1131 | } |
| 1132 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 1133 | bool wrote_readback = false; | ||
| 1134 | VkPipelineStageFlags2 readback_stages = 0; | ||
| 703 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists | 1135 | std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists |
| 704 | for (const auto& list : prepared) emit(list, command_buffer, replay, &context_.tracker_, &open_labels); | 1136 | for (const auto& list : prepared) { |
| 1137 | emit(list, command_buffer, replay, &context_.tracker_, &open_labels); | ||
| 1138 | wrote_readback |= list.wrote_readback; | ||
| 1139 | readback_stages |= list.readback_src_stages; | ||
| 1140 | } | ||
| 705 | close_labels(command_buffer, replay, open_labels); | 1141 | close_labels(command_buffer, replay, open_labels); |
| 706 | // A fence wait on the CPU makes GPU writes visible to the host only after a barrier to the host domain: | 1142 | // Only flush GPU writes to the host domain when this batch actually wrote to a readback buffer. |
| 707 | // readback buffers are read through Map once the application has waited. | 1143 | if (wrote_readback) { |
| 708 | VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 1144 | const VkPipelineStageFlags2 allowed = queue_supported_stages(kind_); |
| 709 | host.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | 1145 | VkPipelineStageFlags2 src_stages = readback_stages & allowed; |
| 710 | host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; | 1146 | if (!src_stages) src_stages = VK_PIPELINE_STAGE_2_TRANSFER_BIT; |
| 711 | context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, | 1147 | const bool copy_only = |
| 712 | 0, 1, &host, 0, nullptr, 0, nullptr); | 1148 | (src_stages & ~(VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT)) == 0; |
| 713 | const bool submitted = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS && | 1149 | const VkAccessFlags2 src_access = |
| 714 | submit(command_buffer, VK_NULL_HANDLE, 0); | 1150 | copy_only ? VK_ACCESS_2_TRANSFER_WRITE_BIT : VK_ACCESS_2_MEMORY_WRITE_BIT; |
| 1151 | |||
| 1152 | if (context_.vk.vkCmdPipelineBarrier2) { | ||
| 1153 | VkMemoryBarrier2 host{VK_STRUCTURE_TYPE_MEMORY_BARRIER_2}; | ||
| 1154 | host.srcStageMask = src_stages; | ||
| 1155 | host.srcAccessMask = src_access; | ||
| 1156 | host.dstStageMask = VK_PIPELINE_STAGE_2_HOST_BIT; | ||
| 1157 | host.dstAccessMask = VK_ACCESS_2_HOST_READ_BIT; | ||
| 1158 | VkDependencyInfo dep{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; | ||
| 1159 | dep.memoryBarrierCount = 1; | ||
| 1160 | dep.pMemoryBarriers = &host; | ||
| 1161 | context_.vk.vkCmdPipelineBarrier2(command_buffer, &dep); | ||
| 1162 | } else { | ||
| 1163 | const VkPipelineStageFlags legacy_src = | ||
| 1164 | copy_only ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; | ||
| 1165 | VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 1166 | host.srcAccessMask = copy_only ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 1167 | host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; | ||
| 1168 | context_.vk.vkCmdPipelineBarrier(command_buffer, legacy_src, VK_PIPELINE_STAGE_HOST_BIT, | ||
| 1169 | 0, 1, &host, 0, nullptr, 0, nullptr); | ||
| 1170 | } | ||
| 1171 | } | ||
| 1172 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; | ||
| 1173 | resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held | ||
| 1174 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); | ||
| 715 | if (submitted) { | 1175 | if (submitted) { |
| 716 | queries.commit(); | 1176 | queries.commit(); |
| 717 | slot->segments = std::move(queries.retained); | 1177 | slot->segments = std::move(queries.retained); |
| @@ -719,7 +1179,8 @@ public: | |||
| 719 | discard(); | 1179 | discard(); |
| 720 | } | 1180 | } |
| 721 | if (context_.depth24_) context_.depth24_->retire(progress_, submitted ? submitted_ : 0); | 1181 | if (context_.depth24_) context_.depth24_->retire(progress_, submitted ? submitted_ : 0); |
| 722 | if (context_.bindless_commit_) context_.bindless_commit_(submitted); | 1182 | tracker_lock.unlock(); |
| 1183 | if (bindless_commit) bindless_commit(submitted); | ||
| 723 | return submitted ? ReplayResult::success : ReplayResult::unsupported; | 1184 | return submitted ? ReplayResult::success : ReplayResult::unsupported; |
| 724 | } | 1185 | } |
| 725 | 1186 | ||
| @@ -766,6 +1227,8 @@ private: | |||
| 766 | }; | 1227 | }; |
| 767 | 1228 | ||
| 768 | CommandSlot* acquire() { | 1229 | CommandSlot* acquire() { |
| 1230 | if (context_.is_device_lost()) return nullptr; | ||
| 1231 | context_.drain_deleted_resources(context_.completed_retire_ticket()); | ||
| 769 | std::uint64_t done = 0; | 1232 | std::uint64_t done = 0; |
| 770 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); | 1233 | context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); |
| 771 | CommandSlot* reuse = nullptr; | 1234 | CommandSlot* reuse = nullptr; |
| @@ -791,32 +1254,47 @@ private: | |||
| 791 | } | 1254 | } |
| 792 | 1255 | ||
| 793 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { | 1256 | bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { |
| 1257 | if (context_.is_device_lost()) return false; | ||
| 794 | const std::uint64_t ticket = ++submitted_; | 1258 | const std::uint64_t ticket = ++submitted_; |
| 795 | std::vector<VkSemaphore> signals{progress_}; | ||
| 796 | std::vector<std::uint64_t> signal_values{ticket}; | ||
| 797 | if (fence) { | ||
| 798 | signals.push_back(fence); | ||
| 799 | signal_values.push_back(value); | ||
| 800 | } | ||
| 801 | const std::vector<VkPipelineStageFlags> stages(waits_.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | 1259 | const std::vector<VkPipelineStageFlags> stages(waits_.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); |
| 802 | VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; | 1260 | VkResult res = VK_SUCCESS; |
| 803 | timeline.waitSemaphoreValueCount = std::uint32_t(wait_values_.size()); | ||
| 804 | timeline.pWaitSemaphoreValues = wait_values_.data(); | ||
| 805 | timeline.signalSemaphoreValueCount = std::uint32_t(signal_values.size()); | ||
| 806 | timeline.pSignalSemaphoreValues = signal_values.data(); | ||
| 807 | VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; | ||
| 808 | submit.waitSemaphoreCount = std::uint32_t(waits_.size()); | ||
| 809 | submit.pWaitSemaphores = waits_.data(); | ||
| 810 | submit.pWaitDstStageMask = stages.data(); | ||
| 811 | submit.commandBufferCount = command_buffer ? 1 : 0; | ||
| 812 | submit.pCommandBuffers = &command_buffer; | ||
| 813 | submit.signalSemaphoreCount = std::uint32_t(signals.size()); | ||
| 814 | submit.pSignalSemaphores = signals.data(); | ||
| 815 | bool ok; | ||
| 816 | { | 1261 | { |
| 817 | std::lock_guard lock(context_.submit_mutex()); | 1262 | std::lock_guard lock(context_.submit_mutex()); |
| 818 | ok = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE) == VK_SUCCESS; | 1263 | VkSemaphore signals[3]{progress_, VK_NULL_HANDLE, VK_NULL_HANDLE}; |
| 1264 | std::uint64_t signal_values[3]{ticket, 0, 0}; | ||
| 1265 | std::uint32_t signal_count = 1; | ||
| 1266 | if (context_.retire_timeline()) { | ||
| 1267 | signals[signal_count] = context_.retire_timeline(); | ||
| 1268 | signal_values[signal_count] = context_.advance_retire_ticket(); | ||
| 1269 | ++signal_count; | ||
| 1270 | } | ||
| 1271 | if (fence) { | ||
| 1272 | signals[signal_count] = fence; | ||
| 1273 | signal_values[signal_count] = value; | ||
| 1274 | ++signal_count; | ||
| 1275 | } | ||
| 1276 | VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; | ||
| 1277 | timeline.waitSemaphoreValueCount = std::uint32_t(wait_values_.size()); | ||
| 1278 | timeline.pWaitSemaphoreValues = wait_values_.data(); | ||
| 1279 | timeline.signalSemaphoreValueCount = signal_count; | ||
| 1280 | timeline.pSignalSemaphoreValues = signal_values; | ||
| 1281 | VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; | ||
| 1282 | submit.waitSemaphoreCount = std::uint32_t(waits_.size()); | ||
| 1283 | submit.pWaitSemaphores = waits_.data(); | ||
| 1284 | submit.pWaitDstStageMask = stages.data(); | ||
| 1285 | submit.commandBufferCount = command_buffer ? 1 : 0; | ||
| 1286 | submit.pCommandBuffers = &command_buffer; | ||
| 1287 | submit.signalSemaphoreCount = signal_count; | ||
| 1288 | submit.pSignalSemaphores = signals; | ||
| 1289 | res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); | ||
| 1290 | } | ||
| 1291 | if (res == VK_ERROR_DEVICE_LOST) { | ||
| 1292 | context_.mark_device_lost(); | ||
| 1293 | waits_.clear(); | ||
| 1294 | wait_values_.clear(); | ||
| 1295 | return false; | ||
| 819 | } | 1296 | } |
| 1297 | const bool ok = (res == VK_SUCCESS); | ||
| 820 | waits_.clear(); | 1298 | waits_.clear(); |
| 821 | wait_values_.clear(); | 1299 | wait_values_.clear(); |
| 822 | for (auto& slot : buffers_) | 1300 | for (auto& slot : buffers_) |
| @@ -826,6 +1304,7 @@ private: | |||
| 826 | 1304 | ||
| 827 | VulkanContext& context_; | 1305 | VulkanContext& context_; |
| 828 | VkQueue queue_; | 1306 | VkQueue queue_; |
| 1307 | QueueKind kind_ = QueueKind::direct; | ||
| 829 | VkCommandPool pool_ = VK_NULL_HANDLE; | 1308 | VkCommandPool pool_ = VK_NULL_HANDLE; |
| 830 | VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done | 1309 | VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done |
| 831 | std::uint64_t submitted_ = 0; | 1310 | std::uint64_t submitted_ = 0; |
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index f68b6f292..3bf07fa5d 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h | |||
| @@ -11,14 +11,17 @@ | |||
| 11 | // dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. | 11 | // dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. |
| 12 | // bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). | 12 | // bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). |
| 13 | // bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. | 13 | // bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. |
| 14 | // These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays | ||
| 15 | // from the device's limits instead; the shaders declare runtime arrays, so any count works for them. | ||
| 14 | // | 16 | // |
| 15 | // A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in | 17 | // A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in |
| 16 | // whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage | 18 | // whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage |
| 17 | // arrays. So an image has one index, the same in every binding of its dimension, and each dimension has its own | 19 | // arrays. So an image has one index, the same in every binding of its dimension, and each dimension has its own |
| 18 | // index space. The storage arrays hold 256, so an image with storage views gets an index below 256; one without | 20 | // index space. The storage arrays are shorter (storage_capacity()), so an image with storage views gets an index |
| 19 | // takes a higher index while there is one. Index 0 of every array is a fallback, because a miss gives 0: a 1x1 | 21 | // they hold; one without takes a higher index while there is one. Index 0 of every array is a fallback, because a |
| 20 | // image of zeros, a nearest clamping sampler, and 1x1 storage images. The caller owns the views and samplers it | 22 | // miss gives 0: a 1x1 image of zeros, a nearest clamping sampler, and 1x1 storage images. The caller owns the views |
| 21 | // adds and keeps them alive while they are in the set; this class owns only the fallbacks and the table's buffer. | 23 | // and samplers it adds and keeps them alive while they are in the set; this class owns only the fallbacks and the |
| 24 | // table's buffer. | ||
| 22 | // | 25 | // |
| 23 | // Device features: runtimeDescriptorArray for the shaders. With BindlessFeatures::update_after_bind | 26 | // Device features: runtimeDescriptorArray for the shaders. With BindlessFeatures::update_after_bind |
| 24 | // (descriptorBindingSampledImageUpdateAfterBind, ...StorageImage..., ...StorageBuffer...) flush() may run while | 27 | // (descriptorBindingSampledImageUpdateAfterBind, ...StorageImage..., ...StorageBuffer...) flush() may run while |
| @@ -62,12 +65,19 @@ struct StorageViews { | |||
| 62 | VkImageView r32ui = VK_NULL_HANDLE; | 65 | VkImageView r32ui = VK_NULL_HANDLE; |
| 63 | }; | 66 | }; |
| 64 | 67 | ||
| 68 | namespace bindless { | ||
| 69 | inline constexpr std::uint32_t binding_count = 26; | ||
| 70 | constexpr std::array<std::uint32_t, binding_count> default_counts(); | ||
| 71 | } // namespace bindless | ||
| 72 | |||
| 65 | struct BindlessFeatures { | 73 | struct BindlessFeatures { |
| 66 | bool update_after_bind = false; | 74 | bool update_after_bind = false; |
| 67 | bool partially_bound = false; | 75 | bool partially_bound = false; |
| 68 | // Fallback sample counts for RGBA8_UNORM, R32_UINT, R32_SINT. A single sample omits that class's MS bindings. | 76 | // Fallback sample counts for RGBA8_UNORM, R32_UINT, R32_SINT. A single sample omits that class's MS bindings. |
| 69 | std::array<VkSampleCountFlagBits, 3> ms_samples{ | 77 | std::array<VkSampleCountFlagBits, 3> ms_samples{ |
| 70 | VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}; | 78 | VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}; |
| 79 | // Descriptors in each binding, by binding number: bindless::bindings by default, or what size_bindings() chose. | ||
| 80 | std::array<std::uint32_t, bindless::binding_count> counts = bindless::default_counts(); | ||
| 71 | }; | 81 | }; |
| 72 | 82 | ||
| 73 | namespace bindless { | 83 | namespace bindless { |
| @@ -79,7 +89,6 @@ struct Binding { | |||
| 79 | 89 | ||
| 80 | inline constexpr std::uint32_t table_binding = 2; | 90 | inline constexpr std::uint32_t table_binding = 2; |
| 81 | inline constexpr std::uint32_t sampler_binding = 1; | 91 | inline constexpr std::uint32_t sampler_binding = 1; |
| 82 | inline constexpr std::uint32_t storage_indices = 256; // what every storage array of bindings 8-19 holds | ||
| 83 | inline constexpr std::uint32_t first_ms_binding = 20; | 92 | inline constexpr std::uint32_t first_ms_binding = 20; |
| 84 | inline constexpr std::uint32_t no_binding = 0xffffffffu; | 93 | inline constexpr std::uint32_t no_binding = 0xffffffffu; |
| 85 | 94 | ||
| @@ -100,6 +109,14 @@ inline constexpr std::array<Binding, 26> bindings = {{ | |||
| 100 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, | 109 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, |
| 101 | }}; | 110 | }}; |
| 102 | 111 | ||
| 112 | static_assert(bindings.size() == binding_count); | ||
| 113 | |||
| 114 | constexpr std::array<std::uint32_t, binding_count> default_counts() { | ||
| 115 | std::array<std::uint32_t, binding_count> counts{}; | ||
| 116 | for (std::uint32_t b = 0; b < binding_count; ++b) counts[b] = bindings[b].count; | ||
| 117 | return counts; | ||
| 118 | } | ||
| 119 | |||
| 103 | constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { | 120 | constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { |
| 104 | return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; | 121 | return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; |
| 105 | } | 122 | } |
| @@ -108,15 +125,16 @@ constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& fe | |||
| 108 | // per-stage or per-set limits have no room for additional pairs of MS arrays. | 125 | // per-stage or per-set limits have no room for additional pairs of MS arrays. |
| 109 | constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampled_limit, | 126 | constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampled_limit, |
| 110 | std::uint32_t resource_limit) { | 127 | std::uint32_t resource_limit) { |
| 128 | const auto& counts = features.counts; | ||
| 111 | std::uint32_t sampled = 0, total = 0; | 129 | std::uint32_t sampled = 0, total = 0; |
| 112 | for (std::uint32_t b = 0; b < first_ms_binding; ++b) { | 130 | for (std::uint32_t b = 0; b < first_ms_binding; ++b) { |
| 113 | if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += bindings[b].count; | 131 | if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; |
| 114 | if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += bindings[b].count; | 132 | if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; |
| 115 | } | 133 | } |
| 116 | for (std::uint32_t c = 0; c < features.ms_samples.size(); ++c) { | 134 | for (std::uint32_t c = 0; c < features.ms_samples.size(); ++c) { |
| 117 | if (features.ms_samples[c] == VK_SAMPLE_COUNT_1_BIT) continue; | 135 | if (features.ms_samples[c] == VK_SAMPLE_COUNT_1_BIT) continue; |
| 118 | const auto b = first_ms_binding + 2 * c; | 136 | const auto b = first_ms_binding + 2 * c; |
| 119 | const auto pair = bindings[b].count + bindings[b + 1].count; | 137 | const auto pair = counts[b] + counts[b + 1]; |
| 120 | if (sampled + pair > sampled_limit || total + pair > resource_limit) { | 138 | if (sampled + pair > sampled_limit || total + pair > resource_limit) { |
| 121 | features.ms_samples[c] = VK_SAMPLE_COUNT_1_BIT; | 139 | features.ms_samples[c] = VK_SAMPLE_COUNT_1_BIT; |
| 122 | } else { | 140 | } else { |
| @@ -126,23 +144,6 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl | |||
| 126 | } | 144 | } |
| 127 | } | 145 | } |
| 128 | 146 | ||
| 129 | inline void limit_ms_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits, | ||
| 130 | const VkPhysicalDeviceVulkan12Properties& indexed) { | ||
| 131 | const auto sampled = features.update_after_bind | ||
| 132 | ? std::min(indexed.maxPerStageDescriptorUpdateAfterBindSampledImages, | ||
| 133 | indexed.maxDescriptorSetUpdateAfterBindSampledImages) | ||
| 134 | : std::min(limits.maxPerStageDescriptorSampledImages, limits.maxDescriptorSetSampledImages); | ||
| 135 | auto resources = features.update_after_bind ? indexed.maxPerStageUpdateAfterBindResources : limits.maxPerStageResources; | ||
| 136 | // Fragment outputs count as stage resources. D3D12 allows up to eight render targets. | ||
| 137 | resources -= std::min(resources, std::min(limits.maxColorAttachments, 8u)); | ||
| 138 | if (features.update_after_bind) { | ||
| 139 | // Standalone samplers count in the pool, but do not count against the per-stage resource limit. | ||
| 140 | const auto pool = indexed.maxUpdateAfterBindDescriptorsInAllPools; | ||
| 141 | resources = std::min(resources, pool - std::min(pool, bindings[sampler_binding].count)); | ||
| 142 | } | ||
| 143 | limit_ms_bindings(features, sampled, resources); | ||
| 144 | } | ||
| 145 | |||
| 146 | constexpr bool multisampled(ImageDimension dimension) { | 147 | constexpr bool multisampled(ImageDimension dimension) { |
| 147 | return dimension == ImageDimension::dim_2d_ms || dimension == ImageDimension::dim_2d_ms_array; | 148 | return dimension == ImageDimension::dim_2d_ms || dimension == ImageDimension::dim_2d_ms_array; |
| 148 | } | 149 | } |
| @@ -161,8 +162,114 @@ constexpr std::uint32_t r32ui_binding(ImageDimension dimension) { | |||
| 161 | return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding; | 162 | return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding; |
| 162 | } | 163 | } |
| 163 | 164 | ||
| 164 | // How many images of a dimension the set holds, the fallback included. | 165 | // What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then |
| 165 | constexpr std::uint32_t image_capacity(ImageDimension dimension) { return bindings[sampled_binding(dimension)].count; } | 166 | // 3-6 MiB (93793 descriptors on an RTX 5070). |
| 167 | inline constexpr std::uint32_t max_2d_images = 65536; | ||
| 168 | inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images | ||
| 169 | // A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can | ||
| 170 | // create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. | ||
| 171 | inline constexpr std::uint32_t max_samplers = 4096; | ||
| 172 | inline constexpr std::uint32_t reserved_samplers = 64; | ||
| 173 | // Growth leaves this many descriptors of each limit to the other sets of a pipeline layout. | ||
| 174 | inline constexpr std::uint32_t growth_headroom = 64; | ||
| 175 | |||
| 176 | // Sizes the 2D image, sampler and storage arrays from the device's limits: the update-after-bind ones with | ||
| 177 | // features.update_after_bind, the plain ones otherwise. Every binding is visible to every stage, so the per-stage | ||
| 178 | // limits apply to the whole set; fragment outputs count as stage resources (D3D12 allows eight render targets) and | ||
| 179 | // standalone samplers do not, though they count in an update-after-bind pool. | ||
| 180 | // 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images. | ||
| 181 | // 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). | ||
| 182 | // 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says | ||
| 183 | // what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. | ||
| 184 | // A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a | ||
| 185 | // storage view an index past the sampled array. The other bindings keep their default counts. | ||
| 186 | // Sets features.counts; returns false when a count is below its default because the device's limits are. | ||
| 187 | inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits, | ||
| 188 | const VkPhysicalDeviceVulkan11Properties& v11, | ||
| 189 | const VkPhysicalDeviceVulkan12Properties& v12) { | ||
| 190 | const bool uab = features.update_after_bind; | ||
| 191 | const std::uint32_t sampled_limit = | ||
| 192 | uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages, | ||
| 193 | v12.maxDescriptorSetUpdateAfterBindSampledImages) | ||
| 194 | : std::min(limits.maxPerStageDescriptorSampledImages, limits.maxDescriptorSetSampledImages); | ||
| 195 | const std::uint32_t sampler_limit = | ||
| 196 | uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSamplers, v12.maxDescriptorSetUpdateAfterBindSamplers) | ||
| 197 | : std::min(limits.maxPerStageDescriptorSamplers, limits.maxDescriptorSetSamplers); | ||
| 198 | const std::uint32_t storage_limit = | ||
| 199 | uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindStorageImages, | ||
| 200 | v12.maxDescriptorSetUpdateAfterBindStorageImages) | ||
| 201 | : std::min(limits.maxPerStageDescriptorStorageImages, limits.maxDescriptorSetStorageImages); | ||
| 202 | std::uint32_t resource_limit = uab ? v12.maxPerStageUpdateAfterBindResources : limits.maxPerStageResources; | ||
| 203 | resource_limit -= std::min(resource_limit, std::min(limits.maxColorAttachments, 8u)); | ||
| 204 | const std::uint32_t pool_limit = uab ? v12.maxUpdateAfterBindDescriptorsInAllPools : 0xffffffffu; | ||
| 205 | |||
| 206 | auto& counts = features.counts; | ||
| 207 | counts = default_counts(); | ||
| 208 | std::uint32_t images = 1, samplers = 1, storage = 1; | ||
| 209 | // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only | ||
| 210 | // take descriptors away. | ||
| 211 | const auto apply = [&](bool final) { | ||
| 212 | counts[sampled_binding(ImageDimension::dim_2d)] = images; | ||
| 213 | counts[sampler_binding] = samplers; | ||
| 214 | for (std::uint32_t d = 0; d < 4; ++d) { | ||
| 215 | const auto dimension = ImageDimension(d); | ||
| 216 | const bool capped = final || dimension != ImageDimension::dim_2d; | ||
| 217 | const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; | ||
| 218 | for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; | ||
| 219 | if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; | ||
| 220 | } | ||
| 221 | }; | ||
| 222 | const auto fits = [&](std::uint32_t headroom, std::uint64_t set_limit) { | ||
| 223 | apply(false); | ||
| 224 | std::uint64_t sampled = 0, sampler = 0, stored = 0, buffers = 0; | ||
| 225 | for (std::uint32_t b = 0; b < binding_count; ++b) { | ||
| 226 | if (!binding_enabled(b, features)) continue; | ||
| 227 | const auto type = bindings[b].type; | ||
| 228 | (type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ? sampled | ||
| 229 | : type == VK_DESCRIPTOR_TYPE_SAMPLER ? sampler | ||
| 230 | : type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE ? stored | ||
| 231 | : buffers) += counts[b]; | ||
| 232 | } | ||
| 233 | const auto within = [&](std::uint64_t n, std::uint32_t limit) { return n + headroom <= limit; }; | ||
| 234 | const std::uint64_t all = sampled + sampler + stored + buffers; | ||
| 235 | return within(sampled, sampled_limit) && within(sampler, sampler_limit) && within(stored, storage_limit) && | ||
| 236 | within(sampled + stored + buffers, resource_limit) && all <= pool_limit && all <= set_limit; | ||
| 237 | }; | ||
| 238 | // Raises n to the largest value up to `high` that fits; leaves it where it is when none does. | ||
| 239 | const auto grow = [&](std::uint32_t& n, std::uint32_t high, std::uint32_t headroom, std::uint64_t set_limit) { | ||
| 240 | std::uint32_t low = n; | ||
| 241 | while (low < high) { | ||
| 242 | n = low + (high - low + 1) / 2; | ||
| 243 | if (fits(headroom, set_limit)) low = n; | ||
| 244 | else high = n - 1; | ||
| 245 | } | ||
| 246 | n = low; | ||
| 247 | }; | ||
| 248 | |||
| 249 | constexpr std::uint64_t no_limit = ~0ull; | ||
| 250 | const auto ms_samples = features.ms_samples; | ||
| 251 | features.ms_samples.fill(VK_SAMPLE_COUNT_1_BIT); | ||
| 252 | grow(samplers, bindings[sampler_binding].count, 0, no_limit); | ||
| 253 | grow(storage, bindings[storage_binding(ImageDimension::dim_2d, 0)].count, 0, no_limit); | ||
| 254 | grow(images, bindings[sampled_binding(ImageDimension::dim_2d)].count, 0, no_limit); | ||
| 255 | apply(false); | ||
| 256 | const bool full = images == bindings[0].count && samplers == bindings[sampler_binding].count && | ||
| 257 | storage == bindings[storage_binding(ImageDimension::dim_2d, 0)].count; | ||
| 258 | features.ms_samples = ms_samples; | ||
| 259 | limit_ms_bindings(features, sampled_limit, std::min(resource_limit, pool_limit - std::min(pool_limit, samplers))); | ||
| 260 | |||
| 261 | std::uint64_t set_limit = 0; | ||
| 262 | for (std::uint32_t b = 0; b < binding_count; ++b) | ||
| 263 | if (binding_enabled(b, features)) set_limit += counts[b]; | ||
| 264 | set_limit = std::max(set_limit, std::uint64_t(v11.maxPerSetDescriptors)); | ||
| 265 | const std::uint32_t creatable = | ||
| 266 | limits.maxSamplerAllocationCount - std::min(limits.maxSamplerAllocationCount, reserved_samplers); | ||
| 267 | grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); | ||
| 268 | grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); | ||
| 269 | grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); | ||
| 270 | apply(true); | ||
| 271 | return full; | ||
| 272 | } | ||
| 166 | 273 | ||
| 167 | } // namespace bindless | 274 | } // namespace bindless |
| 168 | 275 | ||
| @@ -194,6 +301,15 @@ public: | |||
| 194 | bool supports_ms_class(std::uint32_t component_class) const { | 301 | bool supports_ms_class(std::uint32_t component_class) const { |
| 195 | return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT; | 302 | return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT; |
| 196 | } | 303 | } |
| 304 | // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those | ||
| 305 | // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. | ||
| 306 | std::uint32_t image_capacity(ImageDimension dimension) const { | ||
| 307 | return features_.counts[bindless::sampled_binding(dimension)]; | ||
| 308 | } | ||
| 309 | std::uint32_t storage_capacity(ImageDimension dimension) const { | ||
| 310 | return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; | ||
| 311 | } | ||
| 312 | std::uint32_t sampler_capacity() const { return features_.counts[bindless::sampler_binding]; } | ||
| 197 | // Set 0 of every pipeline layout made for translated shaders. | 313 | // Set 0 of every pipeline layout made for translated shaders. |
| 198 | VkDescriptorSetLayout layout() const { return layout_; } | 314 | VkDescriptorSetLayout layout() const { return layout_; } |
| 199 | // Bound at set 0. The same set for the life of this object: flush() updates it in place. | 315 | // Bound at set 0. The same set for the life of this object: flush() updates it in place. |
| @@ -239,7 +355,7 @@ public: | |||
| 239 | const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; | 355 | const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; |
| 240 | if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; | 356 | if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; |
| 241 | auto& used = image_used_[std::uint32_t(dimension)]; | 357 | auto& used = image_used_[std::uint32_t(dimension)]; |
| 242 | const std::uint32_t low_end = std::min(std::uint32_t(used.size()), bindless::storage_indices); | 358 | const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); |
| 243 | std::uint32_t index = stores ? 0 : allocate(used, low_end, std::uint32_t(used.size())); | 359 | std::uint32_t index = stores ? 0 : allocate(used, low_end, std::uint32_t(used.size())); |
| 244 | if (!index) index = allocate(used, 1, low_end); | 360 | if (!index) index = allocate(used, 1, low_end); |
| 245 | if (index) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); | 361 | if (index) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); |
| @@ -422,10 +538,10 @@ private: | |||
| 422 | std::uint32_t count = 0; | 538 | std::uint32_t count = 0; |
| 423 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { | 539 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { |
| 424 | if (!bindless::binding_enabled(b, features_)) continue; | 540 | if (!bindless::binding_enabled(b, features_)) continue; |
| 425 | entries[count] = {b, bindless::bindings[b].type, bindless::bindings[b].count, VK_SHADER_STAGE_ALL, nullptr}; | 541 | entries[count] = {b, bindless::bindings[b].type, features_.counts[b], VK_SHADER_STAGE_ALL, nullptr}; |
| 426 | flags[count] = (features_.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) | | 542 | flags[count] = (features_.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) | |
| 427 | (features_.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0); | 543 | (features_.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0); |
| 428 | sizes[count] = {bindless::bindings[b].type, bindless::bindings[b].count}; | 544 | sizes[count] = {bindless::bindings[b].type, features_.counts[b]}; |
| 429 | ++count; | 545 | ++count; |
| 430 | } | 546 | } |
| 431 | VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{ | 547 | VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{ |
| @@ -451,10 +567,10 @@ private: | |||
| 451 | if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set_) != VK_SUCCESS) return false; | 567 | if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set_) != VK_SUCCESS) return false; |
| 452 | 568 | ||
| 453 | for (std::uint32_t d = 0; d < dimensions; ++d) { | 569 | for (std::uint32_t d = 0; d < dimensions; ++d) { |
| 454 | image_used_[d].assign(bindless::image_capacity(ImageDimension(d)), 0); | 570 | image_used_[d].assign(image_capacity(ImageDimension(d)), 0); |
| 455 | image_used_[d][0] = 1; | 571 | image_used_[d][0] = 1; |
| 456 | } | 572 | } |
| 457 | sampler_used_.assign(bindless::bindings[bindless::sampler_binding].count, 0); | 573 | sampler_used_.assign(sampler_capacity(), 0); |
| 458 | sampler_used_[0] = 1; | 574 | sampler_used_[0] = 1; |
| 459 | return true; | 575 | return true; |
| 460 | } | 576 | } |
| @@ -716,7 +832,7 @@ private: | |||
| 716 | infos.reserve(bindless::bindings.size()); | 832 | infos.reserve(bindless::bindings.size()); |
| 717 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { | 833 | for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { |
| 718 | if (b == bindless::table_binding || !bindless::binding_enabled(b, features_)) continue; | 834 | if (b == bindless::table_binding || !bindless::binding_enabled(b, features_)) continue; |
| 719 | const std::uint32_t count = features_.partially_bound ? 1 : bindless::bindings[b].count; | 835 | const std::uint32_t count = features_.partially_bound ? 1 : features_.counts[b]; |
| 720 | infos.emplace_back(count, fallback_info(b)); | 836 | infos.emplace_back(count, fallback_info(b)); |
| 721 | VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; | 837 | VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; |
| 722 | write.dstSet = set_; | 838 | write.dstSet = set_; |
| @@ -762,7 +878,7 @@ private: | |||
| 762 | queue(sampled_at, index, | 878 | queue(sampled_at, index, |
| 763 | sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); | 879 | sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); |
| 764 | const auto store = [&](std::uint32_t binding, VkImageView view) { | 880 | const auto store = [&](std::uint32_t binding, VkImageView view) { |
| 765 | if (binding == bindless::no_binding || index >= bindless::bindings[binding].count) return; | 881 | if (binding == bindless::no_binding || index >= features_.counts[binding]) return; |
| 766 | queue(binding, index, | 882 | queue(binding, index, |
| 767 | view ? VkDescriptorImageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL} : fallback_info(binding)); | 883 | view ? VkDescriptorImageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL} : fallback_info(binding)); |
| 768 | }; | 884 | }; |
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 36761356a..8ec2ccc76 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -76,6 +76,7 @@ struct ResourceBinding { | |||
| 76 | bool depth24_as_float = false; | 76 | bool depth24_as_float = false; |
| 77 | bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first | 77 | bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first |
| 78 | bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it | 78 | bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it |
| 79 | bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush | ||
| 79 | }; | 80 | }; |
| 80 | 81 | ||
| 81 | struct VulkanAccess { | 82 | struct VulkanAccess { |
| @@ -731,6 +732,9 @@ struct Prepared { | |||
| 731 | std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image | 732 | std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image |
| 732 | std::vector<VkImageCopy> image_copies; | 733 | std::vector<VkImageCopy> image_copies; |
| 733 | VkImageResolve resolve{}; // resolves | 734 | VkImageResolve resolve{}; // resolves |
| 735 | // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). | ||
| 736 | VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; | ||
| 737 | VkImageView resolve_view = VK_NULL_HANDLE; | ||
| 734 | bool has_depth24 = false; // a depth plane copy of a depth24_as_float texture: convert through depth24 | 738 | bool has_depth24 = false; // a depth plane copy of a depth24_as_float texture: convert through depth24 |
| 735 | Depth24Job depth24; // the whole copy: where its scratch floats are | 739 | Depth24Job depth24; // the whole copy: where its scratch floats are |
| 736 | std::vector<Depth24Job> depth24_parts; // the dispatches that convert it | 740 | std::vector<Depth24Job> depth24_parts; // the dispatches that convert it |
| @@ -1037,6 +1041,33 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1037 | const auto padded = [block](std::uint32_t size) { return (size + block - 1) / block * block; }; | 1041 | const auto padded = [block](std::uint32_t size) { return (size + block - 1) / block * block; }; |
| 1038 | if (box.right > padded(from.width) || box.bottom > padded(from.height) || box.back > from_depth) | 1042 | if (box.right > padded(from.width) || box.bottom > padded(from.height) || box.back > from_depth) |
| 1039 | return ReplayResult::invalid_copy; | 1043 | return ReplayResult::invalid_copy; |
| 1044 | if (const std::uint32_t dst_block = block_format(p.binding.format, dst.aspectMask).block; dst_block != block) { | ||
| 1045 | // A BC format and its uncompressed equivalent ("Format Conversion using Direct3D 10.1"): one texel of the | ||
| 1046 | // uncompressed side is one block of the other. The box is in source texels, the offset in destination | ||
| 1047 | // texels, and Vulkan takes the extent in source texels, cut at the source's mip edge. | ||
| 1048 | const auto blocks = [](std::uint32_t size, std::uint32_t b) { return (size + b - 1) / b; }; | ||
| 1049 | const bool same_bytes = | ||
| 1050 | block_format(p.binding.format, dst.aspectMask).bytes == block_format(p.source.format, src.aspectMask).bytes; | ||
| 1051 | if (!same_bytes || (box.left | box.top) % block || (copy.x | copy.y) % dst_block || box.left >= from.width || | ||
| 1052 | box.top >= from.height || !within(copy.z, box.back - box.front, to_depth) || | ||
| 1053 | copy.x / dst_block + blocks(box.right - box.left, block) > blocks(to.width, dst_block) || | ||
| 1054 | copy.y / dst_block + blocks(box.bottom - box.top, block) > blocks(to.height, dst_block)) | ||
| 1055 | return ReplayResult::invalid_copy; | ||
| 1056 | const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); | ||
| 1057 | const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); | ||
| 1058 | // shortcut: into a BC mip whose edge block is partial, Vulkan's extent cannot reach the padded edge; such | ||
| 1059 | // a copy is refused until it is staged through a buffer. | ||
| 1060 | if (dst_block > 1 && (copy.x + w * dst_block > to.width || copy.y + h * dst_block > to.height)) | ||
| 1061 | return ReplayResult::invalid_copy; | ||
| 1062 | p.image_copies.push_back({{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, | ||
| 1063 | {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, | ||
| 1064 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, | ||
| 1065 | {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, | ||
| 1066 | {w, h, box.back - box.front}}); | ||
| 1067 | p.range = dst; | ||
| 1068 | p.source_range = src; | ||
| 1069 | return ReplayResult::success; | ||
| 1070 | } | ||
| 1040 | std::uint32_t w = box.right - box.left, h = box.bottom - box.top; | 1071 | std::uint32_t w = box.right - box.left, h = box.bottom - box.top; |
| 1041 | const std::uint32_t d = box.back - box.front; | 1072 | const std::uint32_t d = box.back - box.front; |
| 1042 | if (block > 1) { | 1073 | if (block > 1) { |
| @@ -1138,7 +1169,15 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { | |||
| 1138 | return ReplayResult::success; | 1169 | return ReplayResult::success; |
| 1139 | } | 1170 | } |
| 1140 | const ResourceBinding &dst = p.binding, &src = p.source; | 1171 | const ResourceBinding &dst = p.binding, &src = p.source; |
| 1141 | if (!dst.image || !src.image || dst.width != src.width || dst.height != src.height || | 1172 | // A BC texture and one of its uncompressed equivalent match block for texel ("Format Conversion using |
| 1173 | // Direct3D 10.1"); the Vulkan extent is in source texels. | ||
| 1174 | const std::uint32_t sb = block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).block; | ||
| 1175 | const std::uint32_t db = block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).block; | ||
| 1176 | const auto blocks = [](std::uint32_t size, std::uint32_t b) { return (size + b - 1) / b; }; | ||
| 1177 | const bool same_shape = sb == db ? dst.width == src.width && dst.height == src.height | ||
| 1178 | : blocks(dst.width, db) == blocks(src.width, sb) && | ||
| 1179 | blocks(dst.height, db) == blocks(src.height, sb); | ||
| 1180 | if (!dst.image || !src.image || !same_shape || | ||
| 1142 | dst.depth != src.depth || dst.volume != src.volume || dst.mip_levels != src.mip_levels || | 1181 | dst.depth != src.depth || dst.volume != src.volume || dst.mip_levels != src.mip_levels || |
| 1143 | dst.array_layers != src.array_layers || dst.aspects != src.aspects || dst.samples != src.samples || | 1182 | dst.array_layers != src.array_layers || dst.aspects != src.aspects || dst.samples != src.samples || |
| 1144 | block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes != block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes) | 1183 | block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes != block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes) |
| @@ -1146,7 +1185,13 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { | |||
| 1146 | for (const VkImageAspectFlags aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) { | 1185 | for (const VkImageAspectFlags aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) { |
| 1147 | if (!(dst.aspects & aspect)) continue; | 1186 | if (!(dst.aspects & aspect)) continue; |
| 1148 | for (std::uint32_t mip = 0; mip < dst.mip_levels; ++mip) { | 1187 | for (std::uint32_t mip = 0; mip < dst.mip_levels; ++mip) { |
| 1149 | const VkExtent2D extent = mip_extent(dst, mip); | 1188 | const VkExtent2D extent = mip_extent(src, mip), to = mip_extent(dst, mip); |
| 1189 | // Lower mips can differ in blocks (BC 12x8 mip 1 is 2x1 blocks, R32G32 3x2 mip 1 is 1x1): more source | ||
| 1190 | // blocks than the destination holds is refused, as by WARP. shortcut: a BC destination mip with a partial | ||
| 1191 | // edge block cannot take a whole uncompressed texel per block in one vkCmdCopyImage; refused until such | ||
| 1192 | // a copy is staged through a buffer. | ||
| 1193 | if (sb != db && (blocks(extent.width, sb) * db > to.width || blocks(extent.height, sb) * db > to.height)) | ||
| 1194 | return ReplayResult::invalid_copy; | ||
| 1150 | p.image_copies.push_back({{aspect, mip, 0, dst.array_layers}, {0, 0, 0}, {aspect, mip, 0, dst.array_layers}, | 1195 | p.image_copies.push_back({{aspect, mip, 0, dst.array_layers}, {0, 0, 0}, {aspect, mip, 0, dst.array_layers}, |
| 1151 | {0, 0, 0}, {extent.width, extent.height, std::max(1u, src.depth >> mip)}}); | 1196 | {0, 0, 0}, {extent.width, extent.height, std::max(1u, src.depth >> mip)}}); |
| 1152 | } | 1197 | } |
| @@ -1156,7 +1201,8 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { | |||
| 1156 | return ReplayResult::success; | 1201 | return ReplayResult::success; |
| 1157 | } | 1202 | } |
| 1158 | 1203 | ||
| 1159 | // Resolve a multisampled colour image into a single-sampled image of the same format. | 1204 | // Resolve a multisampled colour image into a single-sampled image of the same format, or (a region) one plane of a |
| 1205 | // depth/stencil image into the same plane of another: MIN or MAX, or AVERAGE of depth. | ||
| 1160 | inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& p) { | 1206 | inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& p) { |
| 1161 | VkImageSubresourceRange dst{}, src{}; | 1207 | VkImageSubresourceRange dst{}, src{}; |
| 1162 | if (!copy_subresource(p.binding, resolve.dst_subresource, dst) || | 1208 | if (!copy_subresource(p.binding, resolve.dst_subresource, dst) || |
| @@ -1179,9 +1225,19 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& | |||
| 1179 | } else if (from.width != to.width || from.height != to.height) { | 1225 | } else if (from.width != to.width || from.height != to.height) { |
| 1180 | return ReplayResult::invalid_copy; | 1226 | return ReplayResult::invalid_copy; |
| 1181 | } | 1227 | } |
| 1182 | if (src.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || dst.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || | 1228 | if (src.aspectMask != dst.aspectMask || p.source.format != p.binding.format) return ReplayResult::unsupported; |
| 1183 | p.source.format != p.binding.format) | 1229 | const auto& region = resolve.region; |
| 1184 | return ReplayResult::unsupported; | 1230 | if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) { |
| 1231 | if (region && region->mode != d3d12_resolve_mode::average) return ReplayResult::unsupported; | ||
| 1232 | } else { | ||
| 1233 | // A rendering scope resolves each pixel in place, so the destination offset must be the source's. | ||
| 1234 | if (!region || dst_offset.x != src_offset.x || dst_offset.y != src_offset.y || | ||
| 1235 | (region->mode == d3d12_resolve_mode::average && src.aspectMask != VK_IMAGE_ASPECT_DEPTH_BIT)) | ||
| 1236 | return ReplayResult::unsupported; | ||
| 1237 | p.resolve_mode = region->mode == d3d12_resolve_mode::minimum ? VK_RESOLVE_MODE_MIN_BIT | ||
| 1238 | : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT | ||
| 1239 | : VK_RESOLVE_MODE_AVERAGE_BIT; | ||
| 1240 | } | ||
| 1185 | p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, src_offset, | 1241 | p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, src_offset, |
| 1186 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, dst_offset, extent}; | 1242 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, dst_offset, extent}; |
| 1187 | p.range = dst; | 1243 | p.range = dst; |
| @@ -1289,6 +1345,9 @@ public: | |||
| 1289 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run | 1345 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run |
| 1290 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. | 1346 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. |
| 1291 | std::size_t unpredicated_copies = 0; | 1347 | std::size_t unpredicated_copies = 0; |
| 1348 | // Set when any command writes to a host_readable (READBACK) buffer so VulkanQueue only flushes to HOST_BIT when needed. | ||
| 1349 | bool wrote_readback = false; | ||
| 1350 | VkPipelineStageFlags2 readback_src_stages = 0; | ||
| 1292 | }; | 1351 | }; |
| 1293 | 1352 | ||
| 1294 | inline ReplayResult plan_occlusion_segments(PreparedList& out) { | 1353 | inline ReplayResult plan_occlusion_segments(PreparedList& out) { |
| @@ -1397,6 +1456,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1397 | // Vulkan allows one active query per type. Only ordinary occlusion uses virtual segments. | 1456 | // Vulkan allows one active query per type. Only ordinary occlusion uses virtual segments. |
| 1398 | std::size_t ordinary_active = 0; | 1457 | std::size_t ordinary_active = 0; |
| 1399 | bool overlaps = false, binary_active = false, statistics_active = false; | 1458 | bool overlaps = false, binary_active = false, statistics_active = false; |
| 1459 | out.wrote_readback = false; | ||
| 1460 | out.readback_src_stages = 0; | ||
| 1400 | 1461 | ||
| 1401 | for (std::size_t i = 0; i < commands.size(); ++i) { | 1462 | for (std::size_t i = 0; i < commands.size(); ++i) { |
| 1402 | const auto& command = commands[i]; | 1463 | const auto& command = commands[i]; |
| @@ -1515,6 +1576,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1515 | const auto [dst_id, src_id] = copy_ids(command); | 1576 | const auto [dst_id, src_id] = copy_ids(command); |
| 1516 | const ResourceBinding* source = resolve(src_id); | 1577 | const ResourceBinding* source = resolve(src_id); |
| 1517 | if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; | 1578 | if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; |
| 1579 | if (p.binding.host_readable) { | ||
| 1580 | out.wrote_readback = true; | ||
| 1581 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT; | ||
| 1582 | } | ||
| 1518 | p.source = *source; | 1583 | p.source = *source; |
| 1519 | ReplayResult result = ReplayResult::success; | 1584 | ReplayResult result = ReplayResult::success; |
| 1520 | if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { | 1585 | if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { |
| @@ -1557,6 +1622,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1557 | p.source = *source; | 1622 | p.source = *source; |
| 1558 | if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) | 1623 | if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) |
| 1559 | return result; | 1624 | return result; |
| 1625 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { | ||
| 1626 | if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return ReplayResult::unsupported; | ||
| 1627 | p.view = vk.image_view(p.source, p.source_range); | ||
| 1628 | p.resolve_view = vk.image_view(p.binding, p.range); | ||
| 1629 | if (!p.view || !p.resolve_view) return ReplayResult::unsupported; | ||
| 1630 | } | ||
| 1560 | } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { | 1631 | } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { |
| 1561 | // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. | 1632 | // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. |
| 1562 | if (!bind(discard->resource)) return ReplayResult::unresolved_resource; | 1633 | if (!bind(discard->resource)) return ReplayResult::unresolved_resource; |
| @@ -1579,6 +1650,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1579 | if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; | 1650 | if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; |
| 1580 | if (!vk.buffer_at(write->address, 4, p.write_buffer, p.write_offset)) return ReplayResult::unresolved_resource; | 1651 | if (!vk.buffer_at(write->address, 4, p.write_buffer, p.write_offset)) return ReplayResult::unresolved_resource; |
| 1581 | if (p.write_offset % 4) return ReplayResult::invalid_copy; | 1652 | if (p.write_offset % 4) return ReplayResult::invalid_copy; |
| 1653 | // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. | ||
| 1654 | out.wrote_readback = true; | ||
| 1655 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 1582 | } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) { | 1656 | } else if (const auto* atomic = std::get_if<AtomicCopyBuffer>(&command)) { |
| 1583 | if (!vk.copy_buffer) return ReplayResult::unsupported; | 1657 | if (!vk.copy_buffer) return ReplayResult::unsupported; |
| 1584 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies | 1658 | if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies |
| @@ -1596,6 +1670,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1596 | } | 1670 | } |
| 1597 | p.buffer_copies.push_back({p.source.buffer_offset + atomic->src_offset, | 1671 | p.buffer_copies.push_back({p.source.buffer_offset + atomic->src_offset, |
| 1598 | p.binding.buffer_offset + atomic->dst_offset, atomic->bytes}); | 1672 | p.binding.buffer_offset + atomic->dst_offset, atomic->bytes}); |
| 1673 | if (p.binding.host_readable) { | ||
| 1674 | out.wrote_readback = true; | ||
| 1675 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 1676 | } | ||
| 1599 | } else if (const auto* predication = std::get_if<Predication>(&command)) { | 1677 | } else if (const auto* predication = std::get_if<Predication>(&command)) { |
| 1600 | predicated = predication->buffer != 0; | 1678 | predicated = predication->buffer != 0; |
| 1601 | if (!predicated) continue; | 1679 | if (!predicated) continue; |
| @@ -1642,6 +1720,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 1642 | // The internal dispatch would otherwise count towards the application's CSInvocations. | 1720 | // The internal dispatch would otherwise count towards the application's CSInvocations. |
| 1643 | if (!vk.resolve_binary_occlusion || statistics_active) return ReplayResult::unsupported; | 1721 | if (!vk.resolve_binary_occlusion || statistics_active) return ReplayResult::unsupported; |
| 1644 | } | 1722 | } |
| 1723 | if (p.binding.host_readable) { | ||
| 1724 | out.wrote_readback = true; | ||
| 1725 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | ||
| 1726 | } | ||
| 1645 | } | 1727 | } |
| 1646 | out.queries.push_back({i, heap, statistics_active}); | 1728 | out.queries.push_back({i, heap, statistics_active}); |
| 1647 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { | 1729 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { |
| @@ -2156,6 +2238,55 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 2156 | } else if (std::holds_alternative<ResolveSubresource>(command)) { | 2238 | } else if (std::holds_alternative<ResolveSubresource>(command)) { |
| 2157 | // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. | 2239 | // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. |
| 2158 | const auto [dst_id, src_id] = copy_ids(command); | 2240 | const auto [dst_id, src_id] = copy_ids(command); |
| 2241 | if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { | ||
| 2242 | // A rendering scope of its own, with no draws: the source plane as the attachment, the destination | ||
| 2243 | // as its resolve target. Both go to the attachment layout and back. Resolves run in the colour | ||
| 2244 | // attachment output stage with colour attachment accesses, depth and stencil ones included. | ||
| 2245 | constexpr VkAccessFlags attachment_access = | ||
| 2246 | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | | ||
| 2247 | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; | ||
| 2248 | constexpr VkPipelineStageFlags attachment_stages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | | ||
| 2249 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | | ||
| 2250 | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; | ||
| 2251 | const VulkanAccess source_state = vulkan_access(d3d12_state::resolve_source, false); | ||
| 2252 | const VulkanAccess dest_state = vulkan_access(d3d12_state::resolve_dest, false); | ||
| 2253 | const VkImageLayout source_layout = image_layout(p.source, source_state.layout); | ||
| 2254 | const VkImageLayout dest_layout = image_layout(p.binding, dest_state.layout); | ||
| 2255 | auto source_pieces = detail::current( | ||
| 2256 | tracker, src_id, detail::planes_for_layout(p.source, p.source_range, separate), source_layout); | ||
| 2257 | detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker); | ||
| 2258 | auto dest_pieces = detail::current( | ||
| 2259 | tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); | ||
| 2260 | detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker); | ||
| 2261 | const VkImageLayout source_attachment = | ||
| 2262 | image_layout(p.source, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); | ||
| 2263 | const VkImageLayout dest_attachment = | ||
| 2264 | image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); | ||
| 2265 | detail::round_trip(vk, command_buffer, p.source, source_pieces, source_attachment, source_state, | ||
| 2266 | attachment_access, attachment_stages, [&] { | ||
| 2267 | detail::round_trip(vk, command_buffer, p.binding, dest_pieces, dest_attachment, dest_state, | ||
| 2268 | attachment_access, attachment_stages, [&] { | ||
| 2269 | VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; | ||
| 2270 | info.imageView = p.view; | ||
| 2271 | info.imageLayout = source_attachment; | ||
| 2272 | info.resolveMode = p.resolve_mode; | ||
| 2273 | info.resolveImageView = p.resolve_view; | ||
| 2274 | info.resolveImageLayout = dest_attachment; | ||
| 2275 | info.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; | ||
| 2276 | info.storeOp = VK_ATTACHMENT_STORE_OP_NONE; // the source is only read | ||
| 2277 | VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; | ||
| 2278 | rendering.renderArea = {{p.resolve.srcOffset.x, p.resolve.srcOffset.y}, | ||
| 2279 | {p.resolve.extent.width, p.resolve.extent.height}}; | ||
| 2280 | rendering.layerCount = 1; | ||
| 2281 | // One plane only, so independentResolve(None) never applies. | ||
| 2282 | if (p.range.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT) rendering.pDepthAttachment = &info; | ||
| 2283 | else rendering.pStencilAttachment = &info; | ||
| 2284 | vk.begin_rendering(command_buffer, &rendering); | ||
| 2285 | vk.end_rendering(command_buffer); | ||
| 2286 | }); | ||
| 2287 | }); | ||
| 2288 | continue; | ||
| 2289 | } | ||
| 2159 | const VkImageLayout src_layout = detail::copy_layout( | 2290 | const VkImageLayout src_layout = detail::copy_layout( |
| 2160 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), | 2291 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), |
| 2161 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); | 2292 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); |