upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorTomgamer <tomanhorak22@gmail.com>2026-11-22 17:59:04 +0100
committerTomgamer <tomanhorak22@gmail.com>2026-11-22 17:59:04 +0100
commit9d731bc11e2c063965ab3f3fe0882f4822b2fa08 (patch)
tree08cdf6b9d197238ed5269bc5a09ec875a1e5c362 /runtime/src
parentce7a34850e5e69bbb86f5955b37356d92d4bd90c (diff)
parent49475796c226c8511b9470bf97a4daf57b8af323 (diff)
Merge origin/main into shader-309-wave64-lds-limit
Conflict in tools/rdna2spirv.py: both sides added a module function before cs_dispatch_state (ds_const_extent, check_printed_encodings); both kept. main's new ds_mskor path now goes through lds_access, so it is bounds-checked like the other LDS accesses (test added), and the mock Gen in main's new test_lds_atomic_minmax/xchg tests gains lds_bound/lds_access/lds_atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/base_reservation.h5
-rw-r--r--runtime/src/command_list.h8
-rw-r--r--runtime/src/gfx10_descriptors.h6
-rw-r--r--runtime/src/main.cpp23
-rw-r--r--runtime/src/pe_loader.cpp134
-rw-r--r--runtime/src/pe_loader.h8
-rw-r--r--runtime/src/resource_tiling.h61
-rw-r--r--runtime/src/shader_library.h192
-rw-r--r--runtime/src/subgroup_size.h14
-rw-r--r--runtime/src/uav_clear.h2
-rw-r--r--runtime/src/vulkan13_features.h44
-rw-r--r--runtime/src/vulkan_backend.h418
-rw-r--r--runtime/src/vulkan_device_filter.h24
-rw-r--r--runtime/src/vulkan_present.h13
-rw-r--r--runtime/src/vulkan_replay.h244
15 files changed, 1029 insertions, 167 deletions
diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h
index bf4946895..b76c28c70 100644
--- a/runtime/src/base_reservation.h
+++ b/runtime/src/base_reservation.h
@@ -41,8 +41,9 @@ inline std::optional<Range> inherited() {
41 const DWORD length = GetEnvironmentVariableW(kVariable, value, 64); 41 const DWORD length = GetEnvironmentVariableW(kVariable, value, 64);
42 if (!length || length >= 64) return std::nullopt; 42 if (!length || length >= 64) return std::nullopt;
43 Range r{}; 43 Range r{};
44 if (std::swscanf(value, L"%llx:%llx", reinterpret_cast<unsigned long long*>(&r.base), 44 // swscanf_s, not swscanf (MSVC's C4996): integer conversions take no buffer sizes, so the parse is the same.
45 reinterpret_cast<unsigned long long*>(&r.size)) != 2 || 45 if (swscanf_s(value, L"%llx:%llx", reinterpret_cast<unsigned long long*>(&r.base),
46 reinterpret_cast<unsigned long long*>(&r.size)) != 2 ||
46 !r.size) 47 !r.size)
47 return std::nullopt; 48 return std::nullopt;
48 return r; 49 return r;
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 07520c2e3..47a0561b3 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -8,6 +8,7 @@
8 8
9#include <algorithm> 9#include <algorithm>
10#include <array> 10#include <array>
11#include <utility>
11#include <cstdint> 12#include <cstdint>
12#include <optional> 13#include <optional>
13#include <span> 14#include <span>
@@ -288,6 +289,7 @@ struct CopyBuffer {
288 ResourceId src; 289 ResourceId src;
289 std::uint64_t src_offset; 290 std::uint64_t src_offset;
290 std::uint64_t size; 291 std::uint64_t size;
292 ResourceId tiled_resource = 0; // CopyTiles uses the padded size of the sparse side
291}; 293};
292 294
293// D3D12_TEXTURE_COPY_LOCATION: a texture subresource, or a placed footprint in a buffer. The footprint's format is 295// D3D12_TEXTURE_COPY_LOCATION: a texture subresource, or a placed footprint in a buffer. The footprint's format is
@@ -882,6 +884,12 @@ private:
882 commands_.push_back(command); 884 commands_.push_back(command);
883 return true; 885 return true;
884 } 886 }
887 // The recording calls pass a temporary: moved, so a command's rectangles are not copied a second time.
888 bool append(Command&& command) {
889 if (closed_) return false;
890 commands_.push_back(std::move(command));
891 return true;
892 }
885 893
886 std::vector<BeginQuery>::iterator find_active(QueryHeapId heap, std::uint32_t index) { 894 std::vector<BeginQuery>::iterator find_active(QueryHeapId heap, std::uint32_t index) {
887 return std::find_if(active_.begin(), active_.end(), 895 return std::find_if(active_.begin(), active_.end(),
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index 498a8f392..91826fbea 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -223,6 +223,7 @@ inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one};
223inline constexpr Swizzle channels_rgba = identity_swizzle; 223inline constexpr Swizzle channels_rgba = identity_swizzle;
224inline constexpr Swizzle channels_bgr{select_z, select_y, select_x, select_one}; 224inline constexpr Swizzle channels_bgr{select_z, select_y, select_x, select_one};
225inline constexpr Swizzle channels_bgra{select_z, select_y, select_x, select_w}; 225inline constexpr Swizzle channels_bgra{select_z, select_y, select_x, select_w};
226inline constexpr Swizzle channels_abgr{select_w, select_z, select_y, select_x};
226 227
227inline constexpr FormatRow format_table[] = { 228inline constexpr FormatRow format_table[] = {
228 {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM 229 {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM
@@ -299,6 +300,7 @@ inline constexpr FormatRow format_table[] = {
299 {134, VK_FORMAT_A1R5G5B5_UNORM_PACK16, channels_bgra}, // GFX10_FORMAT_1_5_5_5_UNORM 300 {134, VK_FORMAT_A1R5G5B5_UNORM_PACK16, channels_bgra}, // GFX10_FORMAT_1_5_5_5_UNORM
300 {136, VK_FORMAT_A4B4G4R4_UNORM_PACK16, channels_rgba}, // GFX10_FORMAT_4_4_4_4_UNORM 301 {136, VK_FORMAT_A4B4G4R4_UNORM_PACK16, channels_rgba}, // GFX10_FORMAT_4_4_4_4_UNORM
301 {136, VK_FORMAT_A4R4G4B4_UNORM_PACK16, channels_bgra}, // GFX10_FORMAT_4_4_4_4_UNORM 302 {136, VK_FORMAT_A4R4G4B4_UNORM_PACK16, channels_bgra}, // GFX10_FORMAT_4_4_4_4_UNORM
303 {136, VK_FORMAT_R4G4B4A4_UNORM_PACK16, channels_abgr}, // GFX10_FORMAT_4_4_4_4_UNORM
302 {141, VK_FORMAT_D24_UNORM_S8_UINT, channels_r}, // GFX10_FORMAT_8_24_UNORM 304 {141, VK_FORMAT_D24_UNORM_S8_UINT, channels_r}, // GFX10_FORMAT_8_24_UNORM
303 {141, VK_FORMAT_X8_D24_UNORM_PACK32, channels_r}, // GFX10_FORMAT_8_24_UNORM 305 {141, VK_FORMAT_X8_D24_UNORM_PACK32, channels_r}, // GFX10_FORMAT_8_24_UNORM
304 {146, VK_FORMAT_D32_SFLOAT_S8_UINT, channels_r}, // GFX10_FORMAT_X24_8_32_FLOAT 306 {146, VK_FORMAT_D32_SFLOAT_S8_UINT, channels_r}, // GFX10_FORMAT_X24_8_32_FLOAT
@@ -596,8 +598,8 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_
596 info.maxLod = 0.25f; 598 info.maxLod = 0.25f;
597 } 599 }
598 // An integer image sampled with a FLOAT border colour reads it as 0 on NVIDIA (Vonsek, #538), so the type follows 600 // An integer image sampled with a FLOAT border colour reads it as 0 on NVIDIA (Vonsek, #538), so the type follows
599 // integer_border. A table colour is not kept yet: transparent black. 601 // integer_border. A table colour falls back to transparent black matching integer_border.
600 const bool integer = sampler.integer_border && sampler.border_color != BorderColor::table; 602 const bool integer = sampler.integer_border;
601 switch (sampler.border_color) { 603 switch (sampler.border_color) {
602 case BorderColor::opaque_black: 604 case BorderColor::opaque_black:
603 info.borderColor = integer ? VK_BORDER_COLOR_INT_OPAQUE_BLACK : VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; 605 info.borderColor = integer ? VK_BORDER_COLOR_INT_OPAQUE_BLACK : VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK;
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 560f68349..06baae387 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -9,7 +9,7 @@
9// gta6rt --init <image> [--game-dir DIR] [--overlay DIR] 9// gta6rt --init <image> [--game-dir DIR] [--overlay DIR]
10// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. 10// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run.
11// 11//
12// gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [-- game arguments...] 12// gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...]
13// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and 13// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and
14// command line are <exe name> plus the arguments after "--"; exit/ExitProcess from the game end the run 14// command line are <exe name> plus the arguments after "--"; exit/ExitProcess from the game end the run
15// (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code. 15// (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code.
@@ -29,6 +29,7 @@
29#include "../shims/file_system.h" 29#include "../shims/file_system.h"
30#include "../shims/process_shim.h" 30#include "../shims/process_shim.h"
31#include "../shims/shims.h" 31#include "../shims/shims.h"
32#include "../shims/startup_trace.h"
32 33
33namespace { 34namespace {
34 35
@@ -43,9 +44,9 @@ const char* binding_name(rt::Binding b) {
43 44
44int usage() { 45int usage() {
45 std::fprintf(stderr, 46 std::fprintf(stderr,
46 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR]\n" 47 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n"
47 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--trace-d3d12]\n" 48 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE]\n"
48 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [-- game arguments...]\n"); 49 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n");
49 return 2; 50 return 2;
50} 51}
51 52
@@ -55,6 +56,7 @@ int wmain(int argc, wchar_t** argv) {
55 std::filesystem::path image, game_dir, overlay_dir; 56 std::filesystem::path image, game_dir, overlay_dir;
56 bool dry_run = false, init = false, run = false, trace_d3d12 = false; 57 bool dry_run = false, init = false, run = false, trace_d3d12 = false;
57 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84) 58 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84)
59 std::wstring trace_file;
58 for (int i = 1; i < argc; ++i) { 60 for (int i = 1; i < argc; ++i) {
59 std::wstring a = argv[i]; 61 std::wstring a = argv[i];
60 if (a == L"--") { 62 if (a == L"--") {
@@ -65,6 +67,7 @@ int wmain(int argc, wchar_t** argv) {
65 else if (a == L"--init") init = true; 67 else if (a == L"--init") init = true;
66 else if (a == L"--run") run = true; 68 else if (a == L"--run") run = true;
67 else if (a == L"--trace-d3d12") trace_d3d12 = true; 69 else if (a == L"--trace-d3d12") trace_d3d12 = true;
70 else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i];
68 else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; 71 else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i];
69 else if (a == L"--overlay" && i + 1 < argc) overlay_dir = argv[++i]; 72 else if (a == L"--overlay" && i + 1 < argc) overlay_dir = argv[++i];
70 else if (image.empty()) image = a; 73 else if (image.empty()) image = a;
@@ -82,6 +85,11 @@ int wmain(int argc, wchar_t** argv) {
82 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; 85 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay";
83 rt::fs::configure(game_dir, overlay_dir); 86 rt::fs::configure(game_dir, overlay_dir);
84 rt::d3d12_trace::set_enabled(trace_d3d12); 87 rt::d3d12_trace::set_enabled(trace_d3d12);
88 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) {
89 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n"
90 : "error: cannot create the trace file\n");
91 return 2;
92 }
85 93
86 try { 94 try {
87 rt::Loader loader(game_dir); 95 rt::Loader loader(game_dir);
@@ -112,7 +120,10 @@ int wmain(int argc, wchar_t** argv) {
112 std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); 120 std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented);
113 std::printf("unimplemented by return policy: hresult=%d other=%d\n", unimplemented_hresult, 121 std::printf("unimplemented by return policy: hresult=%d other=%d\n", unimplemented_hresult,
114 unimplemented - unimplemented_hresult); 122 unimplemented - unimplemented_hresult);
115 if (!run) return 0; 123 if (!run) {
124 rt::startup_trace::event("exit", "\"code\":0");
125 return 0;
126 }
116 if (!main_module.entry_rva) { 127 if (!main_module.entry_rva) {
117 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); 128 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
118 return 1; 129 return 1;
@@ -125,6 +136,7 @@ int wmain(int argc, wchar_t** argv) {
125 std::fflush(stdout); 136 std::fflush(stdout);
126 std::printf("game exited with code %d\n", code); 137 std::printf("game exited with code %d\n", code);
127 rt::shims::report_called_unimplemented(); 138 rt::shims::report_called_unimplemented();
139 rt::startup_trace::event("exit", "\"code\":" + std::to_string(code));
128 std::fflush(stdout); 140 std::fflush(stdout);
129 std::fflush(stderr); 141 std::fflush(stderr);
130 // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its 142 // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its
@@ -132,6 +144,7 @@ int wmain(int argc, wchar_t** argv) {
132 ExitProcess(static_cast<UINT>(code)); 144 ExitProcess(static_cast<UINT>(code));
133 } catch (const std::exception& e) { 145 } catch (const std::exception& e) {
134 std::fprintf(stderr, "error: %s\n", e.what()); 146 std::fprintf(stderr, "error: %s\n", e.what());
147 rt::startup_trace::event("error", "\"what\":" + rt::startup_trace::quote(e.what()));
135 return 1; 148 return 1;
136 } 149 }
137} 150}
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 387051756..bdb3df6f5 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -14,6 +14,7 @@
14#include <vector> 14#include <vector>
15 15
16#include "../shims/shims.h" 16#include "../shims/shims.h"
17#include "../shims/startup_trace.h"
17#include "base_reservation.h" 18#include "base_reservation.h"
18 19
19namespace rt { 20namespace rt {
@@ -214,7 +215,9 @@ void uninstall_thread_block(Module& m) {
214 release_thread_block(); 215 release_thread_block();
215} 216}
216 217
217void run_callbacks(Module& m, uint32_t reason) { 218// `trace`: record each callback in the startup trace. Only the Loader's own calls (process attach and detach) pass
219// true; the thread events run under the Windows loader lock and stay out of the trace.
220void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
218 auto* tls = tls_directory(m); 221 auto* tls = tls_directory(m);
219 if (!tls || !tls->AddressOfCallBacks) return; 222 if (!tls || !tls->AddressOfCallBacks) return;
220 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table"); 223 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
@@ -226,6 +229,10 @@ void run_callbacks(Module& m, uint32_t reason) {
226 if (!fn) break; 229 if (!fn) break;
227 auto callback = 230 auto callback =
228 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback")); 231 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
232 if (trace && startup_trace::enabled())
233 startup_trace::event("tls_callback", "\"module\":" + startup_trace::quote(m.name) + ",\"at\":" +
234 startup_trace::quote(startup_trace::where(reinterpret_cast<uint64_t>(callback))) +
235 ",\"reason\":" + std::to_string(reason));
229 callback(m.base, static_cast<DWORD>(reason), nullptr); 236 callback(m.base, static_cast<DWORD>(reason), nullptr);
230 } 237 }
231} 238}
@@ -345,10 +352,34 @@ bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t
345 } 352 }
346 return false; 353 return false;
347} 354}
355
356void* bundled_find_loaded(void* ctx, const std::string& dll_lower) {
357 return static_cast<Loader*>(ctx)->find_loaded_module(dll_lower);
358}
359
360void* bundled_load(void* ctx, const std::string& dll_lower, bool& handled) {
361 return static_cast<Loader*>(ctx)->load_runtime_module(dll_lower, handled);
362}
363
364void* bundled_get_proc(void* ctx, void* module, const std::string& sym, bool& owns_handle) {
365 return static_cast<Loader*>(ctx)->resolve_module_export(module, sym, owns_handle);
366}
367
368bool bundled_owns_handle(void* ctx, void* module) {
369 return static_cast<Loader*>(ctx)->owns_module_handle(module);
370}
371
372const shims::BundledModuleOps kBundledOps{
373 &bundled_find_loaded,
374 &bundled_load,
375 &bundled_get_proc,
376 &bundled_owns_handle,
377};
348} // namespace 378} // namespace
349 379
350Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 380Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
351 shims::add_module_lookup(this, &lookup_in_loader); 381 shims::add_module_lookup(this, &lookup_in_loader);
382 shims::add_bundled_loader(this, &kBundledOps);
352} 383}
353 384
354Loader::~Loader() { 385Loader::~Loader() {
@@ -372,6 +403,7 @@ Loader::~Loader() {
372 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored 403 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored
373 } 404 }
374 } 405 }
406 shims::remove_bundled_loader(this);
375 shims::remove_module_lookup(this); 407 shims::remove_module_lookup(this);
376 for (auto* m : order_) { 408 for (auto* m : order_) {
377 // TLS state must go away before the image and its TLS block are unmapped. 409 // TLS state must go away before the image and its TLS block are unmapped.
@@ -394,6 +426,7 @@ Loader::~Loader() {
394} 426}
395 427
396Module& Loader::load(const std::filesystem::path& image) { 428Module& Loader::load(const std::filesystem::path& image) {
429 std::lock_guard lock(mutex_);
397 std::string key = lower(image.filename().string()); 430 std::string key = lower(image.filename().string());
398 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 431 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
399 Module& m = map_image(image); 432 Module& m = map_image(image);
@@ -401,9 +434,94 @@ Module& Loader::load(const std::filesystem::path& image) {
401 protect_sections(m); 434 protect_sections(m);
402 register_unwind(m); 435 register_unwind(m);
403 init_order_.push_back(&m); 436 init_order_.push_back(&m);
437 if (startup_trace::enabled())
438 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) +
439 ",\"base\":" + startup_trace::quote(startup_trace::hex(reinterpret_cast<uint64_t>(m.base))) +
440 ",\"size\":" + startup_trace::quote(startup_trace::hex(m.size)) +
441 ",\"relocated\":" + (m.relocated ? "true" : "false"));
404 return m; 442 return m;
405} 443}
406 444
445void* Loader::find_loaded_module(const std::string& dll_lower) const {
446 std::lock_guard lock(mutex_);
447 auto it = by_name_.find(dll_lower);
448 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base);
449}
450
451void* Loader::load_runtime_module(const std::string& dll_lower, bool& handled) {
452 handled = false;
453 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
454
455 std::lock_guard lock(mutex_);
456 if (auto it = by_name_.find(dll_lower); it != by_name_.end()) {
457 handled = true;
458 try {
459 initialise();
460 return static_cast<void*>(it->second->base);
461 } catch (const std::exception& e) {
462 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what());
463 SetLastError(ERROR_DLL_INIT_FAILED);
464 return nullptr;
465 }
466 }
467
468 const std::filesystem::path candidate = game_dir_ / dll_lower;
469 std::error_code ec;
470 if (!std::filesystem::is_regular_file(candidate, ec)) return nullptr;
471
472 handled = true;
473 try {
474 Module& m = load(candidate);
475 initialise();
476 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
477 return static_cast<void*>(m.base);
478 } catch (const std::exception& e) {
479 // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not
480 // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_.
481 by_name_.erase(dll_lower);
482 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
483 SetLastError(ERROR_DLL_INIT_FAILED);
484 return nullptr;
485 }
486}
487
488void* Loader::resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle) {
489 owns_handle = false;
490 if (!module_handle) return nullptr;
491 std::lock_guard lock(mutex_);
492 Module* target = nullptr;
493 for (Module* m : order_) {
494 if (m->base == module_handle) {
495 target = m;
496 break;
497 }
498 }
499 if (!target) return nullptr;
500 owns_handle = true;
501 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second;
502 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
503 try {
504 Binding binding = Binding::Unimplemented;
505 void* fn = resolve_forwarder(it->second, binding, 0);
506 if (binding == Binding::Module) initialise();
507 return fn;
508 } catch (const std::exception& e) {
509 std::fprintf(stderr, "[rt] loader: forwarder %s from %s failed: %s\n", it->second.c_str(),
510 target->name.c_str(), e.what());
511 return nullptr;
512 }
513 }
514 return nullptr;
515}
516
517bool Loader::owns_module_handle(void* module_handle) const {
518 if (!module_handle) return false;
519 std::lock_guard lock(mutex_);
520 for (const Module* m : order_)
521 if (m->base == module_handle) return true;
522 return false;
523}
524
407// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing 525// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing
408// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps 526// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps
409// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. 527// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables.
@@ -458,7 +576,11 @@ void Loader::initialise(Module& m) {
458 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 576 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
459 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); 577 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
460 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 578 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
461 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) { 579 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr);
580 if (startup_trace::enabled())
581 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
582 ",\"result\":" + std::to_string(ok));
583 if (!ok) {
462 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong 584 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong
463 throw std::runtime_error(m.name + ": DllMain returned FALSE"); 585 throw std::runtime_error(m.name + ": DllMain returned FALSE");
464 } 586 }
@@ -645,7 +767,7 @@ void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }
645 767
646void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); } 768void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); }
647 769
648void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason); } 770void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason, /*trace=*/true); }
649 771
650void Loader::parse_exports(Module& m) { 772void Loader::parse_exports(Module& m) {
651 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 773 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
@@ -669,6 +791,8 @@ void Loader::parse_exports(Module& m) {
669 auto add_export = [&](const std::string& key, uint32_t rva) { 791 auto add_export = [&](const std::string& key, uint32_t rva) {
670 if (rva >= dir_begin && rva < dir_end) 792 if (rva >= dir_begin && rva < dir_end)
671 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); 793 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export");
794 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there
795 throw std::runtime_error(m.name + ": export " + key + " points outside the image");
672 else 796 else
673 m.exports[key] = m.base + rva; 797 m.exports[key] = m.base + rva;
674 }; 798 };
@@ -709,10 +833,12 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
709 } 833 }
710 } 834 }
711 835
836 // shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host
837 // CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does.
712 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")}; 838 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")};
713 for (const auto& candidate : candidates) { 839 for (const auto& candidate : candidates) {
714 std::error_code ec; 840 std::error_code ec;
715 if (prefer_host_copy(lower(module)) || !std::filesystem::exists(candidate, ec)) continue; 841 if (prefer_host_copy(shim_key) || !std::filesystem::exists(candidate, ec)) continue;
716 Module& dep = load(candidate); 842 Module& dep = load(candidate);
717 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) { 843 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) {
718 binding = Binding::Module; 844 binding = Binding::Module;
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index 1303cdff9..d9f89f542 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -8,6 +8,7 @@
8#include <cstdint> 8#include <cstdint>
9#include <filesystem> 9#include <filesystem>
10#include <map> 10#include <map>
11#include <mutex>
11#include <string> 12#include <string>
12#include <vector> 13#include <vector>
13 14
@@ -103,6 +104,12 @@ public:
103 void install_tls_for_thread(Module& m); 104 void install_tls_for_thread(Module& m);
104 void uninstall_tls_for_thread(Module& m); 105 void uninstall_tls_for_thread(Module& m);
105 106
107 // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs.
108 void* find_loaded_module(const std::string& dll_lower) const;
109 void* load_runtime_module(const std::string& dll_lower, bool& handled);
110 void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle);
111 bool owns_module_handle(void* module_handle) const;
112
106private: 113private:
107 void initialise(Module& m); 114 void initialise(Module& m);
108 static void set_initialised(Module& m, bool value); 115 static void set_initialised(Module& m, bool value);
@@ -115,6 +122,7 @@ private:
115 void protect_sections(Module& m); 122 void protect_sections(Module& m);
116 void register_unwind(Module& m); 123 void register_unwind(Module& m);
117 124
125 mutable std::recursive_mutex mutex_;
118 std::filesystem::path game_dir_; 126 std::filesystem::path game_dir_;
119 std::map<std::string, Module*> by_name_; // lower-case file name 127 std::map<std::string, Module*> by_name_; // lower-case file name
120 std::vector<Module*> order_; // mapping order; owns the modules 128 std::vector<Module*> order_; // mapping order; owns the modules
diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h
index a9d95ae9f..e63f7ff45 100644
--- a/runtime/src/resource_tiling.h
+++ b/runtime/src/resource_tiling.h
@@ -15,10 +15,11 @@
15// GPU packs from the first mip smaller than a tile on any axis and WARP packs nothing; the test accepts all of 15// GPU packs from the first mip smaller than a tile on any axis and WARP packs nothing; the test accepts all of
16// them. The packed size is their tight 16// them. The packed size is their tight
17// linear size rounded up to whole tiles (at least one); NVIDIA sometimes reports one more. Applications read the 17// linear size rounded up to whole tiles (at least one); NVIDIA sometimes reports one more. Applications read the
18// numbers rather than assume them, and this layer backs every reserved resource fully, so any split is consistent. 18// numbers rather than assume them, and this layer backs reserved textures fully, so any split is consistent.
19 19
20#include <algorithm> 20#include <algorithm>
21#include <cstdint> 21#include <cstdint>
22#include <utility>
22#include <vector> 23#include <vector>
23 24
24namespace leonida { 25namespace leonida {
@@ -107,10 +108,14 @@ constexpr TileShape small_tile_shape(bool volume, std::uint32_t element_bytes) {
107// False when the resource cannot be tiled: an untileable element size, no mips, or more than 2^32 tiles. 108// False when the resource cannot be tiled: an untileable element size, no mips, or more than 2^32 tiles.
108inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) { 109inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
109 out = {}; 110 out = {};
110 const auto up = [](std::uint64_t value, std::uint64_t by) { return (value + by - 1) / by; }; 111 constexpr std::uint64_t max_tiles = 0xffffffffu;
112 constexpr std::uint64_t max_packed_bytes = max_tiles * tile_size_in_bytes;
113 const auto up = [](std::uint64_t value, std::uint64_t by) -> std::uint64_t {
114 return value ? 1 + (value - 1) / by : 0;
115 };
111 if (desc.kind == TiledKind::buffer) { 116 if (desc.kind == TiledKind::buffer) {
112 const std::uint64_t tiles = up(desc.width, tile_size_in_bytes); 117 const std::uint64_t tiles = up(desc.width, tile_size_in_bytes);
113 if (!tiles || tiles > 0xffffffffu) return false; 118 if (!tiles || tiles > max_tiles) return false;
114 out.total_tiles = std::uint32_t(tiles); 119 out.total_tiles = std::uint32_t(tiles);
115 out.shape = {tile_size_in_bytes, 1, 1}; 120 out.shape = {tile_size_in_bytes, 1, 1};
116 out.subresources = {{out.total_tiles, 1, 1, 0}}; 121 out.subresources = {{out.total_tiles, 1, 1, 0}};
@@ -121,7 +126,11 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
121 const TileShape elements = element_tile_shape(volume, desc.element_bytes, desc.samples); 126 const TileShape elements = element_tile_shape(volume, desc.element_bytes, desc.samples);
122 if (!elements.width || !desc.mips || !desc.block || !desc.width || !desc.height || !desc.depth_or_layers) 127 if (!elements.width || !desc.mips || !desc.block || !desc.width || !desc.height || !desc.depth_or_layers)
123 return false; 128 return false;
124 out.shape = {elements.width * desc.block, elements.height * desc.block, elements.depth}; 129 const std::uint64_t shape_w = std::uint64_t(elements.width) * desc.block;
130 const std::uint64_t shape_h = std::uint64_t(elements.height) * desc.block;
131 if (shape_w > 0xffffffffu || shape_h > 0xffffffffu) return false;
132 ResourceTiling result;
133 result.shape = {std::uint32_t(shape_w), std::uint32_t(shape_h), elements.depth};
125 const std::uint32_t layers = volume ? 1 : desc.depth_or_layers; 134 const std::uint32_t layers = volume ? 1 : desc.depth_or_layers;
126 const std::uint32_t depth = volume ? desc.depth_or_layers : 1; 135 const std::uint32_t depth = volume ? desc.depth_or_layers : 1;
127 136
@@ -129,32 +138,46 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
129 std::vector<SubresourceTiling> slice(desc.mips); 138 std::vector<SubresourceTiling> slice(desc.mips);
130 std::uint64_t standard_tiles = 0, packed_bytes = 0; 139 std::uint64_t standard_tiles = 0, packed_bytes = 0;
131 for (std::uint32_t mip = 0; mip < desc.mips; ++mip) { 140 for (std::uint32_t mip = 0; mip < desc.mips; ++mip) {
132 const std::uint64_t w = std::max<std::uint64_t>(1, desc.width >> mip); 141 const std::uint64_t w = mip >= 64 ? 1 : std::max<std::uint64_t>(1, desc.width >> mip);
133 const std::uint32_t h = std::max(1u, desc.height >> mip), d = std::max(1u, depth >> mip); 142 const std::uint32_t h = mip >= 32 ? 1u : std::max(1u, desc.height >> mip);
134 const bool standard = out.packed_mips == 0 && (w > out.shape.width / 2 || h > out.shape.height); 143 const std::uint32_t d = mip >= 32 ? 1u : std::max(1u, depth >> mip);
144 const bool standard = result.packed_mips == 0 && (w > result.shape.width / 2 || h > result.shape.height);
135 if (standard) { 145 if (standard) {
136 const std::uint64_t tw = up(w, out.shape.width), th = up(h, out.shape.height), td = up(d, out.shape.depth); 146 const std::uint64_t tw = up(w, result.shape.width);
147 const std::uint64_t th = up(h, result.shape.height);
148 const std::uint64_t td = up(d, result.shape.depth);
149 if (tw > max_tiles || th > max_tiles || td > max_tiles) return false;
150 const std::uint64_t xy = tw * th;
151 if (xy > max_tiles || xy > max_tiles / td) return false;
152 const std::uint64_t mip_tiles = xy * td;
153 if (mip_tiles > max_tiles - standard_tiles) return false;
137 slice[mip] = {std::uint32_t(tw), std::uint32_t(th), std::uint32_t(td), std::uint32_t(standard_tiles)}; 154 slice[mip] = {std::uint32_t(tw), std::uint32_t(th), std::uint32_t(td), std::uint32_t(standard_tiles)};
138 standard_tiles += tw * th * td; 155 standard_tiles += mip_tiles;
139 ++out.standard_mips; 156 ++result.standard_mips;
140 } else { 157 } else {
141 slice[mip] = {0, 0, 0, packed_tile}; 158 slice[mip] = {0, 0, 0, packed_tile};
142 packed_bytes += up(w, desc.block) * up(h, desc.block) * d * desc.element_bytes * desc.samples; 159 const std::uint64_t row_slice_bytes =
143 ++out.packed_mips; 160 up(w, desc.block) * up(h, desc.block) * desc.element_bytes * desc.samples;
161 if (d > (max_packed_bytes - packed_bytes) / row_slice_bytes) return false;
162 packed_bytes += row_slice_bytes * d;
163 ++result.packed_mips;
144 } 164 }
145 } 165 }
146 const std::uint64_t packed_tiles = out.packed_mips ? std::max<std::uint64_t>(1, up(packed_bytes, tile_size_in_bytes)) : 0; 166 const std::uint64_t packed_tiles =
167 result.packed_mips ? std::max<std::uint64_t>(1, up(packed_bytes, tile_size_in_bytes)) : 0;
168 if (packed_tiles > max_tiles - standard_tiles) return false;
147 const std::uint64_t per_slice = standard_tiles + packed_tiles; 169 const std::uint64_t per_slice = standard_tiles + packed_tiles;
148 if (per_slice * layers > 0xffffffffu) return false; 170 if (per_slice > max_tiles / layers) return false;
149 out.packed_tiles = std::uint32_t(packed_tiles); 171 result.packed_tiles = std::uint32_t(packed_tiles);
150 out.packed_start = out.packed_mips ? std::uint32_t(standard_tiles) : 0; 172 result.packed_start = result.packed_mips ? std::uint32_t(standard_tiles) : 0;
151 out.total_tiles = std::uint32_t(per_slice * layers); 173 result.total_tiles = std::uint32_t(per_slice * layers);
152 out.subresources.reserve(std::size_t(desc.mips) * layers); 174 result.subresources.reserve(std::size_t(desc.mips) * layers);
153 for (std::uint32_t layer = 0; layer < layers; ++layer) 175 for (std::uint32_t layer = 0; layer < layers; ++layer)
154 for (SubresourceTiling s : slice) { 176 for (SubresourceTiling s : slice) {
155 if (s.start != packed_tile) s.start += std::uint32_t(per_slice * layer); 177 if (s.start != packed_tile) s.start += std::uint32_t(per_slice * layer);
156 out.subresources.push_back(s); 178 result.subresources.push_back(s);
157 } 179 }
180 out = std::move(result);
158 return true; 181 return true;
159} 182}
160 183
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index b16bb072d..c8c994451 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -8,6 +8,7 @@
8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code: 8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code:
9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader. 9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader.
10 10
11#include <algorithm>
11#include <array> 12#include <array>
12#include <cerrno> 13#include <cerrno>
13#include <cstdint> 14#include <cstdint>
@@ -511,6 +512,96 @@ inline std::vector<std::uint8_t> fssm_program(std::span<const std::uint8_t> byte
511} 512}
512 513
513// --------------------------------------------------------------------------------------------------------------- 514// ---------------------------------------------------------------------------------------------------------------
515// FSPX payloads: the FidelityFX DLL's compute programs (docs/fspx.md)
516
517// The two entries of an FSPX payload the runtime reads: kind 0 (dispatch state) and kind 6 (the program).
518struct FspxParts {
519 std::span<const std::uint8_t> state, code;
520};
521
522// Kinds 0 and 6 of an FSPX payload, both empty when the payload is not one the DLL's reader accepts. Same rules as
523// that reader and tools/fspx_unpack.py's parse_fspx: the total is clamped to the buffer, the directory must fit it,
524// an entry whose range starts inside the directory or ends past the total is skipped, the last entry of a kind wins,
525// and kind 0 and kind 6 must both be there and non-empty.
526inline FspxParts fspx_parts(std::span<const std::uint8_t> payload) {
527 const auto u32 = [&](std::size_t at) {
528 std::uint32_t v;
529 std::memcpy(&v, payload.data() + at, 4);
530 return v;
531 };
532 if (payload.size() < 16 || std::memcmp(payload.data(), "FSPX", 4) != 0) return {};
533 const std::uint64_t total = std::min<std::uint64_t>(u32(12), payload.size());
534 const std::uint64_t end_dir = 16 + 16 * std::uint64_t(u32(8));
535 if (total < end_dir) return {};
536 std::uint64_t code_offset = 0, code_size = 0, state_offset = 0, state_size = 0;
537 for (std::uint64_t at = 16; at < end_dir; at += 16) {
538 const std::uint32_t kind = u32(std::size_t(at)), offset = u32(std::size_t(at) + 4),
539 size = u32(std::size_t(at) + 8);
540 if (offset < end_dir || std::uint64_t(offset) + size > total) continue; // the DLL skips it too
541 if (kind == 6) code_offset = offset, code_size = size;
542 if (kind == 0) state_offset = offset, state_size = size;
543 }
544 if (!state_size || !code_size) return {};
545 return {payload.subspan(std::size_t(state_offset), std::size_t(state_size)),
546 payload.subspan(std::size_t(code_offset), std::size_t(code_size))};
547}
548
549// The kind-6 program of an FSPX payload, or an empty span (fspx_parts).
550inline std::span<const std::uint8_t> fspx_program(std::span<const std::uint8_t> payload) {
551 return fspx_parts(payload).code;
552}
553
554// Whether `code` looks like a bare kind-6 program: the 36-byte prologue of three VOP3 words with opcode 0x180
555// (bits 31..16 = 0xD580) at words 0, 3 and 6, which all 29 programs of the 1.0.2.1 DLL have (docs/fspx.md).
556inline bool fspx_bare_program(std::span<const std::uint8_t> code) {
557 if (code.size() < 36 || code.size() % 4) return false;
558 for (const std::size_t word : {0u, 3u, 6u}) {
559 std::uint32_t v;
560 std::memcpy(&v, code.data() + 4 * word, 4);
561 if (v >> 16 != 0xD580) return false;
562 }
563 return true;
564}
565
566// What a compute shader's bytecode is looked up by in the translator's index.
567struct ComputeProgram {
568 enum class Kind { none, fssm, fspx } kind = Kind::none;
569 // The bytes whose SHA-256 is the index key (fssm_sha256 or fspx_code_sha256), and which the pipeline copies to
570 // the GPU address arena as its code base: the program's code offsets are into them.
571 std::vector<std::uint8_t> bytes;
572 // An FSPX program from a container or a bare payload: its kind-0 entry, whose SHA-256 (fspx_state_sha256) picks
573 // among translations of the same kind-6 bytes. Empty for a bare kind-6 program, which comes without it.
574 std::vector<std::uint8_t> state;
575};
576
577// The program in a compute shader's bytecode:
578// - an FSSM blob, bare or in a DXBC container's DXIL part (fssm_program), the game's own shaders;
579// - the kind-6 program of an FSPX payload in a DXBC container's ACCC part, what the FidelityFX DLL passes to device
580// slot 62, or of a bare FSPX payload;
581// - a bare kind-6 program, what the DLL passes in its slot-67 description at +0x28 (with its exact size at +0x30).
582// A DXBC container whose ACCC part is not a usable FSPX payload, and anything else, gives Kind::none.
583inline ComputeProgram compute_program(std::span<const std::uint8_t> bytecode) {
584 ComputeProgram out;
585 out.bytes = fssm_program(bytecode);
586 if (!out.bytes.empty()) {
587 out.kind = ComputeProgram::Kind::fssm;
588 return out;
589 }
590 FspxParts parts;
591 if (bytecode.size() >= 4 && std::memcmp(bytecode.data(), "DXBC", 4) == 0)
592 parts = fspx_parts(dxbc_part(bytecode, "ACCC"));
593 else if (bytecode.size() >= 4 && std::memcmp(bytecode.data(), "FSPX", 4) == 0)
594 parts = fspx_parts(bytecode);
595 else if (fspx_bare_program(bytecode))
596 parts.code = bytecode;
597 if (parts.code.empty()) return out;
598 out.kind = ComputeProgram::Kind::fspx;
599 out.bytes.assign(parts.code.begin(), parts.code.end());
600 out.state.assign(parts.state.begin(), parts.state.end());
601 return out;
602}
603
604// ---------------------------------------------------------------------------------------------------------------
514// The translator's spirv/index.json 605// The translator's spirv/index.json
515 606
516// One element of a shader's DXBC input signature (ISG1), as tools/shader_meta.py records it. For a vertex shader 607// One element of a shader's DXBC input signature (ISG1), as tools/shader_meta.py records it. For a vertex shader
@@ -527,6 +618,8 @@ struct ShaderEntry {
527 std::string name; 618 std::string name;
528 std::string stage; // "vs", "ps", "cs", "ms", "gs" 619 std::string stage; // "vs", "ps", "cs", "ms", "gs"
529 std::string fssm_sha256; 620 std::string fssm_sha256;
621 std::string fspx_code_sha256; // an FSPX program (docs/fspx.md): the SHA-256 of its kind-6 bytes
622 std::string fspx_state_sha256; // and of its kind-0 entry (dispatch state)
530 std::size_t binding_count = 0; // set-0 bindings the module declares 623 std::size_t binding_count = 0; // set-0 bindings the module declares
531 std::uint32_t push_constant_bytes = 0; 624 std::uint32_t push_constant_bytes = 0;
532 std::array<std::uint32_t, 3> local_size{1, 1, 1}; 625 std::array<std::uint32_t, 3> local_size{1, 1, 1};
@@ -548,7 +641,10 @@ struct ShaderEntry {
548 641
549class ShaderLibrary { 642class ShaderLibrary {
550public: 643public:
551 // Reads <dir>/index.json. Entries without fssm_sha256 cannot be found by content and are skipped. 644 // Reads <dir>/index.json, then <dir>/fspx/index.json when it is there (make_game.py translates the FidelityFX
645 // DLL's FSPX programs into that folder; their entries are named "fspx/<name>"). Entries with neither
646 // fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The fspx folder is optional: a
647 // missing or unreadable index there leaves the main one loaded.
552 bool load(const std::string& dir, std::string* error = nullptr) { 648 bool load(const std::string& dir, std::string* error = nullptr) {
553 const auto fail = [&](const std::string& why) { 649 const auto fail = [&](const std::string& why) {
554 if (error) *error = why; 650 if (error) *error = why;
@@ -556,10 +652,16 @@ public:
556 }; 652 };
557 // Nothing here may throw into the D3D12 shim (only allocation can, and that is caught too). 653 // Nothing here may throw into the D3D12 shim (only allocation can, and that is caught too).
558 try { 654 try {
559 return load_index(dir, fail); 655 if (!load_index(dir, "", fail)) return false;
560 } catch (...) { 656 } catch (...) {
561 return fail("index.json could not be read"); 657 return fail("index.json could not be read");
562 } 658 }
659 try {
660 const auto ignore = [](const std::string&) { return false; };
661 if (std::ifstream(dir + "/fspx/index.json", std::ios::binary)) load_index(dir + "/fspx", "fspx/", ignore);
662 } catch (...) {
663 }
664 return true;
563 } 665 }
564 666
565 bool loaded() const { return !dir_.empty(); } 667 bool loaded() const { return !dir_.empty(); }
@@ -573,11 +675,44 @@ public:
573 } 675 }
574 676
575 std::vector<const ShaderEntry*> candidates(std::string_view stage, std::string_view fssm_sha256) const { 677 std::vector<const ShaderEntry*> candidates(std::string_view stage, std::string_view fssm_sha256) const {
576 std::vector<const ShaderEntry*> out; 678 return lookup(entries_, stage, fssm_sha256);
577 const auto it = entries_.find({std::string(stage), std::string(fssm_sha256)}); 679 }
578 if (it != entries_.end()) 680
579 for (const ShaderEntry& e : it->second) out.push_back(&e); 681 // The entries of an FSPX program, by the SHA-256 of its kind-6 bytes (fspx_code_sha256).
580 return out; 682 std::vector<const ShaderEntry*> fspx_candidates(std::string_view stage, std::string_view fspx_code_sha256) const {
683 return lookup(fspx_entries_, stage, fspx_code_sha256);
684 }
685
686 // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time
687 // lookup"):
688 // - FSSM: by fssm_sha256, as before;
689 // - FSPX with its kind-0 entry (a container or a bare payload): by fspx_code_sha256, then only the entries
690 // whose fspx_state_sha256 is the SHA-256 of that kind-0 entry;
691 // - a bare kind-6 program, which comes without kind 0: by fspx_code_sha256 when all those entries have the
692 // same module; when their modules differ the program is ambiguous, the result is empty and `ambiguous` is
693 // set, instead of picking one of them.
694 std::vector<const ShaderEntry*> program_candidates(std::string_view stage, const ComputeProgram& program,
695 bool* ambiguous = nullptr) const {
696 if (ambiguous) *ambiguous = false;
697 if (program.kind == ComputeProgram::Kind::none) return {};
698 const std::string hash = sha256_hex(program.bytes);
699 if (program.kind == ComputeProgram::Kind::fssm) return candidates(stage, hash);
700 auto all = fspx_candidates(stage, hash);
701 if (!program.state.empty()) {
702 const std::string state = sha256_hex(program.state);
703 std::erase_if(all, [&](const ShaderEntry* e) { return e->fspx_state_sha256 != state; });
704 return all;
705 }
706 if (all.size() > 1) {
707 const auto first = spirv(*all.front());
708 for (std::size_t i = 1; i < all.size(); ++i) {
709 if (first.empty() || spirv(*all[i]) != first) {
710 if (ambiguous) *ambiguous = true;
711 return {};
712 }
713 }
714 }
715 return all;
581 } 716 }
582 717
583 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. 718 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V.
@@ -599,24 +734,45 @@ private:
599 return n >= 0 && n <= 4294967295.0 ? std::uint32_t(n) : 0; 734 return n >= 0 && n <= 4294967295.0 ? std::uint32_t(n) : 0;
600 } 735 }
601 736
737 using Entries = std::map<std::pair<std::string, std::string>, std::vector<ShaderEntry>>;
738
739 static std::vector<const ShaderEntry*> lookup(const Entries& entries, std::string_view stage, std::string_view key) {
740 std::vector<const ShaderEntry*> out;
741 const auto it = entries.find({std::string(stage), std::string(key)});
742 if (it != entries.end())
743 for (const ShaderEntry& e : it->second) out.push_back(&e);
744 return out;
745 }
746
747 // Reads <dir>/index.json. With an empty prefix it replaces what was loaded (the main index); with a prefix it
748 // adds its entries under "<prefix><name>", the path of their modules relative to the main folder.
602 template<typename Fail> 749 template<typename Fail>
603 bool load_index(const std::string& dir, Fail&& fail) { 750 bool load_index(const std::string& dir, const std::string& prefix, Fail&& fail) {
604 std::ifstream file(dir + "/index.json", std::ios::binary); 751 std::ifstream file(dir + "/index.json", std::ios::binary);
605 if (!file) return fail("cannot open " + dir + "/index.json"); 752 if (!file) return fail("cannot open " + dir + "/index.json");
606 const std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); 753 const std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
607 Json root; 754 Json root;
608 if (!JsonReader(text).parse(root) || root.kind != Json::Kind::object) return fail("index.json is not a JSON object"); 755 if (!JsonReader(text).parse(root) || root.kind != Json::Kind::object) return fail("index.json is not a JSON object");
609 dir_ = dir; 756 if (prefix.empty()) {
610 entries_.clear(); 757 dir_ = dir;
611 count_ = 0; 758 entries_.clear();
759 fspx_entries_.clear();
760 count_ = 0;
761 }
612 for (const auto& [name, meta] : root.object) { 762 for (const auto& [name, meta] : root.object) {
613 const Json* hash = meta.find("fssm_sha256"); 763 const Json* hash = meta.find("fssm_sha256");
764 const Json* code_hash = meta.find("fspx_code_sha256");
614 const Json* stage = meta.find("stage"); 765 const Json* stage = meta.find("stage");
615 if (!hash || hash->kind != Json::Kind::string || !stage || stage->kind != Json::Kind::string) continue; 766 const bool by_fssm = hash && hash->kind == Json::Kind::string;
767 const bool by_fspx = code_hash && code_hash->kind == Json::Kind::string;
768 if ((!by_fssm && !by_fspx) || !stage || stage->kind != Json::Kind::string) continue;
616 ShaderEntry e; 769 ShaderEntry e;
617 e.name = name; 770 e.name = prefix + name;
618 e.stage = stage->string; 771 e.stage = stage->string;
619 e.fssm_sha256 = hash->string; 772 if (by_fssm) e.fssm_sha256 = hash->string;
773 if (by_fspx) e.fspx_code_sha256 = code_hash->string;
774 if (const Json* s = meta.find("fspx_state_sha256"); s && s->kind == Json::Kind::string)
775 e.fspx_state_sha256 = s->string;
620 if (const Json* b = meta.find("bindings"); b && b->kind == Json::Kind::array) e.binding_count = b->array.size(); 776 if (const Json* b = meta.find("bindings"); b && b->kind == Json::Kind::array) e.binding_count = b->array.size();
621 e.push_constant_bytes = u32(meta.find("push_constant_bytes")); 777 e.push_constant_bytes = u32(meta.find("push_constant_bytes"));
622 e.lds_bytes = u32(meta.find("lds_bytes")); 778 e.lds_bytes = u32(meta.find("lds_bytes"));
@@ -642,7 +798,8 @@ private:
642 } 798 }
643 if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array) 799 if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array)
644 for (const Json& item : o->array) e.outputs.push_back(u32(&item)); 800 for (const Json& item : o->array) e.outputs.push_back(u32(&item));
645 entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 801 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
802 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
646 ++count_; 803 ++count_;
647 } 804 }
648 return true; 805 return true;
@@ -650,8 +807,9 @@ private:
650 807
651 std::string dir_; 808 std::string dir_;
652 std::size_t count_ = 0; 809 std::size_t count_ = 0;
653 // Entries by (stage, fssm_sha256), in index order. 810 // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order.
654 std::map<std::pair<std::string, std::string>, std::vector<ShaderEntry>> entries_; 811 Entries entries_;
812 Entries fspx_entries_;
655}; 813};
656 814
657} // namespace leonida 815} // namespace leonida
diff --git a/runtime/src/subgroup_size.h b/runtime/src/subgroup_size.h
index 2df643fdf..c391b7e63 100644
--- a/runtime/src/subgroup_size.h
+++ b/runtime/src/subgroup_size.h
@@ -81,6 +81,13 @@ struct SubgroupRequest {
81 81
82inline bool subgroup_is_power_of_two(std::uint32_t v) { return v && !(v & (v - 1)); } 82inline bool subgroup_is_power_of_two(std::uint32_t v) { return v && !(v & (v - 1)); }
83 83
84// Overflow-safe check of local_size[0] * local_size[1] * local_size[2] <= max_invocations.
85inline bool subgroup_workgroup_fits(const std::array<std::uint32_t, 3>& local_size, std::uint64_t max_invocations) {
86 const std::uint64_t xy = std::uint64_t(local_size[0]) * local_size[1];
87 if (local_size[2] == 0) return true;
88 return xy <= max_invocations / local_size[2];
89}
90
84// What to ask for one stage of a pipeline made from `entry`. 91// What to ask for one stage of a pipeline made from `entry`.
85// - Emulated (`wave64_exchange` present): nothing. 92// - Emulated (`wave64_exchange` present): nothing.
86// - Otherwise the wanted size is the entry's `subgroup_size`, or 64 for a wave64 entry without one and 32 for the 93// - Otherwise the wanted size is the entry's `subgroup_size`, or 64 for a wave64 entry without one and 32 for the
@@ -112,20 +119,19 @@ inline SubgroupRequest decide_subgroup_size(const ShaderEntry& entry, const Subg
112 } 119 }
113 120
114 const bool compute_like = r.stage == VK_SHADER_STAGE_COMPUTE_BIT || r.stage == VK_SHADER_STAGE_MESH_BIT_EXT; 121 const bool compute_like = r.stage == VK_SHADER_STAGE_COMPUTE_BIT || r.stage == VK_SHADER_STAGE_MESH_BIT_EXT;
115 const std::uint64_t invocations = 122 const std::uint64_t max_invocations = std::uint64_t(r.wanted) * caps.max_compute_workgroup_subgroups;
116 std::uint64_t(entry.local_size[0]) * entry.local_size[1] * entry.local_size[2];
117 const bool fixed = caps.min_size && caps.min_size == caps.max_size && caps.min_size == r.wanted; 123 const bool fixed = caps.min_size && caps.min_size == caps.max_size && caps.min_size == r.wanted;
118 const bool requirable = 124 const bool requirable =
119 caps.subgroup_size_control && (caps.required_stages & r.stage) && subgroup_is_power_of_two(r.wanted) && 125 caps.subgroup_size_control && (caps.required_stages & r.stage) && subgroup_is_power_of_two(r.wanted) &&
120 r.wanted >= caps.min_size && r.wanted <= caps.max_size && 126 r.wanted >= caps.min_size && r.wanted <= caps.max_size &&
121 (!compute_like || invocations <= std::uint64_t(r.wanted) * caps.max_compute_workgroup_subgroups); 127 (!compute_like || subgroup_workgroup_fits(entry.local_size, max_invocations));
122 128
123 if (fixed) { 129 if (fixed) {
124 r.outcome = SubgroupOutcome::device_fixed; 130 r.outcome = SubgroupOutcome::device_fixed;
125 } else if (requirable) { 131 } else if (requirable) {
126 r.outcome = SubgroupOutcome::required; 132 r.outcome = SubgroupOutcome::required;
127 r.size = r.wanted; 133 r.size = r.wanted;
128 if (r.stage == VK_SHADER_STAGE_COMPUTE_BIT && caps.compute_full_subgroups && 134 if (r.stage == VK_SHADER_STAGE_COMPUTE_BIT && caps.compute_full_subgroups && entry.local_size[0] != 0 &&
129 entry.local_size[0] % r.wanted == 0) 135 entry.local_size[0] % r.wanted == 0)
130 r.flags |= VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT; 136 r.flags |= VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT;
131 } else if (caps.default_size == r.wanted) { 137 } else if (caps.default_size == r.wanted) {
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h
index a27da8d7a..226868475 100644
--- a/runtime/src/uav_clear.h
+++ b/runtime/src/uav_clear.h
@@ -89,6 +89,8 @@ inline constexpr Layout layouts[] = {
89 {VK_FORMAT_R8G8_SINT, Kind::sint, 2, {{{0, 8}, {8, 8}, {}, {}}}}, 89 {VK_FORMAT_R8G8_SINT, Kind::sint, 2, {{{0, 8}, {8, 8}, {}, {}}}},
90 {VK_FORMAT_R16_SFLOAT, Kind::sfloat, 2, {{{0, 16}, {}, {}, {}}}}, 90 {VK_FORMAT_R16_SFLOAT, Kind::sfloat, 2, {{{0, 16}, {}, {}, {}}}},
91 {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, 91 {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}},
92 // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't).
93 {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}},
92 {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, 94 {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}},
93 {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, 95 {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}},
94 {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, 96 {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}},
diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h
index 2057d953b..e86ec02a2 100644
--- a/runtime/src/vulkan13_features.h
+++ b/runtime/src/vulkan13_features.h
@@ -4,6 +4,9 @@
4// or on a Vulkan 1.2 device through VK_KHR_dynamic_rendering and VK_KHR_synchronization2. CrossOver's MoltenVK on 4// or on a Vulkan 1.2 device through VK_KHR_dynamic_rendering and VK_KHR_synchronization2. CrossOver's MoltenVK on
5// macOS is such a 1.2 device (1.2.10: Vulkan 1.2 with both extensions); the extension structs, functions and 5// macOS is such a 1.2 device (1.2.10: Vulkan 1.2 with both extensions); the extension structs, functions and
6// behaviour are the core ones under another name, so the rest of the layer does not see the difference. 6// behaviour are the core ones under another name, so the rest of the layer does not see the difference.
7// Graphics pipelines also use the 1.3 core dynamic states (primitive topology, primitive restart, vertex binding
8// stride); a 1.2 device gives them through VK_EXT_extended_dynamic_state and VK_EXT_extended_dynamic_state2, enabled
9// where the device has both (extended_dynamic_state). Without them the device still works for compute.
7// 10//
8// leonida::Vulkan13Features v13; 11// leonida::Vulkan13Features v13;
9// v13.query(physical, props.apiVersion, get_features2, enumerate_extensions); // per candidate 12// v13.query(physical, props.apiVersion, get_features2, enumerate_extensions); // per candidate
@@ -34,6 +37,7 @@ public:
34 // Optional 1.3 core features, enabled where supported; on a 1.2 device they stay off (no required subgroup size). 37 // Optional 1.3 core features, enabled where supported; on a 1.2 device they stay off (no required subgroup size).
35 bool subgroup_size_control = false; 38 bool subgroup_size_control = false;
36 bool compute_full_subgroups = false; 39 bool compute_full_subgroups = false;
40 bool extended_dynamic_state = false; // core on 1.3; on 1.2 both VK_EXT_extended_dynamic_state(2) extensions
37 41
38 bool usable() const { return dynamic_rendering && synchronization2; } 42 bool usable() const { return dynamic_rendering && synchronization2; }
39 43
@@ -42,6 +46,7 @@ public:
42 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { 46 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) {
43 core = api_version >= VK_API_VERSION_1_3; 47 core = api_version >= VK_API_VERSION_1_3;
44 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; 48 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false;
49 extended_dynamic_state = false;
45 if (!features2) return; 50 if (!features2) return;
46 if (core) { 51 if (core) {
47 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 52 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
@@ -51,6 +56,7 @@ public:
51 synchronization2 = f13.synchronization2 == VK_TRUE; 56 synchronization2 = f13.synchronization2 == VK_TRUE;
52 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; 57 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE;
53 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; 58 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE;
59 extended_dynamic_state = true; // core in 1.3, no feature bit
54 return; 60 return;
55 } 61 }
56 if (api_version < VK_API_VERSION_1_2 || !enumerate_extensions) return; 62 if (api_version < VK_API_VERSION_1_2 || !enumerate_extensions) return;
@@ -58,19 +64,28 @@ public:
58 enumerate_extensions(physical, nullptr, &count, nullptr); 64 enumerate_extensions(physical, nullptr, &count, nullptr);
59 std::vector<VkExtensionProperties> extensions(count); 65 std::vector<VkExtensionProperties> extensions(count);
60 enumerate_extensions(physical, nullptr, &count, extensions.data()); 66 enumerate_extensions(physical, nullptr, &count, extensions.data());
61 bool has_dynamic_rendering = false, has_synchronization2 = false; 67 bool has_dynamic_rendering = false, has_synchronization2 = false, has_eds = false, has_eds2 = false;
62 for (const auto& e : extensions) { 68 for (const auto& e : extensions) {
63 has_dynamic_rendering |= std::strcmp(e.extensionName, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0; 69 has_dynamic_rendering |= std::strcmp(e.extensionName, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0;
64 has_synchronization2 |= std::strcmp(e.extensionName, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0; 70 has_synchronization2 |= std::strcmp(e.extensionName, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0;
71 has_eds |= std::strcmp(e.extensionName, VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) == 0;
72 has_eds2 |= std::strcmp(e.extensionName, VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0;
65 } 73 }
66 if (!has_dynamic_rendering || !has_synchronization2) return; 74 if (!has_dynamic_rendering || !has_synchronization2) return;
67 VkPhysicalDeviceSynchronization2FeaturesKHR sync2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR}; 75 VkPhysicalDeviceExtendedDynamicState2FeaturesEXT eds2{
76 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT};
77 VkPhysicalDeviceExtendedDynamicStateFeaturesEXT eds{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT,
78 has_eds2 ? &eds2 : nullptr};
79 VkPhysicalDeviceSynchronization2FeaturesKHR sync2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR,
80 has_eds ? &eds : nullptr};
68 VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering{ 81 VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering{
69 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR, &sync2}; 82 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR, &sync2};
70 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &rendering}; 83 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &rendering};
71 features2(physical, &query); 84 features2(physical, &query);
72 dynamic_rendering = rendering.dynamicRendering == VK_TRUE; 85 dynamic_rendering = rendering.dynamicRendering == VK_TRUE;
73 synchronization2 = sync2.synchronization2 == VK_TRUE; 86 synchronization2 = sync2.synchronization2 == VK_TRUE;
87 extended_dynamic_state = has_eds && has_eds2 && eds.extendedDynamicState == VK_TRUE &&
88 eds2.extendedDynamicState2 == VK_TRUE;
74 } 89 }
75 90
76 // Copies the flags of the device query() chose (a later query() for another candidate overwrites them). 91 // Copies the flags of the device query() chose (a later query() for another candidate overwrites them).
@@ -80,6 +95,7 @@ public:
80 synchronization2 = from.synchronization2; 95 synchronization2 = from.synchronization2;
81 subgroup_size_control = from.subgroup_size_control; 96 subgroup_size_control = from.subgroup_size_control;
82 compute_full_subgroups = from.compute_full_subgroups; 97 compute_full_subgroups = from.compute_full_subgroups;
98 extended_dynamic_state = from.extended_dynamic_state;
83 } 99 }
84 100
85 // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features' 101 // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features'
@@ -95,33 +111,47 @@ public:
95 } 111 }
96 sync2_.pNext = chain; 112 sync2_.pNext = chain;
97 sync2_.synchronization2 = VK_TRUE; 113 sync2_.synchronization2 = VK_TRUE;
114 if (extended_dynamic_state) {
115 eds2_.pNext = chain;
116 eds2_.extendedDynamicState2 = VK_TRUE;
117 eds_.pNext = &eds2_;
118 eds_.extendedDynamicState = VK_TRUE;
119 sync2_.pNext = &eds_;
120 }
98 rendering_.pNext = &sync2_; 121 rendering_.pNext = &sync2_;
99 rendering_.dynamicRendering = VK_TRUE; 122 rendering_.dynamicRendering = VK_TRUE;
100 return &rendering_; 123 return &rendering_;
101 } 124 }
102 125
103 // Where a feature struct goes to follow these: insert with `s.pNext = *next(); *next() = &s;`. 126 // Where a feature struct goes to follow these: insert with `s.pNext = *next(); *next() = &s;`.
104 void** next() { return core ? &enable13_.pNext : &sync2_.pNext; } 127 void** next() { return core ? &enable13_.pNext : extended_dynamic_state ? &eds2_.pNext : &sync2_.pNext; }
105 128
106 // The device extensions a 1.2 device needs for both features; none on 1.3. 129 // The device extensions a 1.2 device needs for both features; none on 1.3.
107 void add_extensions(std::vector<const char*>& extensions) const { 130 void add_extensions(std::vector<const char*>& extensions) const {
108 if (core) return; 131 if (core) return;
109 extensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME); 132 extensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME);
110 extensions.push_back(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME); 133 extensions.push_back(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME);
134 if (!extended_dynamic_state) return;
135 extensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME);
136 extensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME);
111 } 137 }
112 138
113private: 139private:
114 VkPhysicalDeviceVulkan13Features enable13_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 140 VkPhysicalDeviceVulkan13Features enable13_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
115 VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR}; 141 VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR};
116 VkPhysicalDeviceSynchronization2FeaturesKHR sync2_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR}; 142 VkPhysicalDeviceSynchronization2FeaturesKHR sync2_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR};
143 VkPhysicalDeviceExtendedDynamicStateFeaturesEXT eds_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT};
144 VkPhysicalDeviceExtendedDynamicState2FeaturesEXT eds2_{
145 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT};
117}; 146};
118 147
119// A device function by its core name, or by its KHR name where the core one is null: a Vulkan 1.2 device returns 148// A device function by its core name, or else by its KHR or EXT name: a Vulkan 1.2 device returns null for Vulkan
120// null for Vulkan 1.3 core names (vkCmdPipelineBarrier2, vkCmdBeginRendering, ...) and serves the enabled 149// 1.3 core names (vkCmdPipelineBarrier2, vkCmdBeginRendering, vkCmdSetPrimitiveTopology, ...) and serves the enabled
121// extension's vkCmdPipelineBarrier2KHR and the like, which have the same signatures. 150// extension's vkCmdPipelineBarrier2KHR, vkCmdSetPrimitiveTopologyEXT and the like, which have the same signatures.
122inline PFN_vkVoidFunction device_proc_or_khr(PFN_vkGetDeviceProcAddr get, VkDevice device, const char* name) { 151inline PFN_vkVoidFunction device_proc_or_khr(PFN_vkGetDeviceProcAddr get, VkDevice device, const char* name) {
123 if (const PFN_vkVoidFunction function = get(device, name)) return function; 152 if (const PFN_vkVoidFunction function = get(device, name)) return function;
124 return get(device, (std::string(name) + "KHR").c_str()); 153 if (const PFN_vkVoidFunction function = get(device, (std::string(name) + "KHR").c_str())) return function;
154 return get(device, (std::string(name) + "EXT").c_str());
125} 155}
126 156
127} // namespace leonida 157} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 8683ae2de..93d7e5259 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -17,6 +17,7 @@
17#include "vulkan_depth24.h" 17#include "vulkan_depth24.h"
18#include "vulkan_scratch.h" 18#include "vulkan_scratch.h"
19#include "vulkan_replay.h" 19#include "vulkan_replay.h"
20#include "resource_tiling.h"
20#include "xdxr_build.h" 21#include "xdxr_build.h"
21 22
22#include <algorithm> 23#include <algorithm>
@@ -25,6 +26,7 @@
25#include <cstdint> 26#include <cstdint>
26#include <cstdio> 27#include <cstdio>
27#include <cstring> 28#include <cstring>
29#include <deque>
28#include <functional> 30#include <functional>
29#include <map> 31#include <map>
30#include <memory> 32#include <memory>
@@ -78,7 +80,7 @@ struct VulkanDeviceFunctions {
78 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 80 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
79 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 81 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
80 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 82 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
81 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) 83 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse)
82#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 84#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
83 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 85 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
84#undef LEONIDA_VK_MEMBER 86#undef LEONIDA_VK_MEMBER
@@ -498,56 +500,79 @@ public:
498 500
499 void enqueue(VkSemaphore sem, std::uint64_t value, void* event_handle) { 501 void enqueue(VkSemaphore sem, std::uint64_t value, void* event_handle) {
500 if (!sem || !event_handle) return; 502 if (!sem || !event_handle) return;
501 if (device_lost_.load(std::memory_order_acquire)) { 503 SignalEventFn immediate_fn = nullptr;
502 SignalEventFn fn = nullptr;
503 {
504 std::lock_guard lock(mutex_);
505 fn = signal_event_;
506 }
507 if (fn) fn(event_handle);
508 return;
509 }
510 { 504 {
511 std::lock_guard lock(mutex_); 505 std::lock_guard lock(mutex_);
512 pending_.push_back({sem, value, event_handle, {}}); 506 if (stop_ || device_lost_.load(std::memory_order_acquire)) {
513 if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); 507 immediate_fn = signal_event_;
514 signal_wakeup_locked(); 508 } else {
509 pending_.push_back({sem, value, event_handle, {}});
510 if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); });
511 signal_wakeup_locked();
512 }
513 }
514 if (immediate_fn) {
515 immediate_fn(event_handle);
516 return;
515 } 517 }
516 cv_.notify_one(); 518 cv_.notify_one();
517 } 519 }
518 520
519 void enqueue_callback(VkSemaphore sem, std::uint64_t value, std::function<void()> cb) { 521 void enqueue_callback(VkSemaphore sem, std::uint64_t value, std::function<void()> cb) {
520 if (!sem || !cb) return; 522 if (!sem || !cb) return;
521 if (device_lost_.load(std::memory_order_acquire)) { 523 std::function<void()> immediate_cb;
522 cb(); 524 {
525 std::lock_guard lock(mutex_);
526 if (stop_ || device_lost_.load(std::memory_order_acquire)) {
527 immediate_cb = std::move(cb);
528 } else {
529 pending_.push_back({sem, value, nullptr, std::move(cb)});
530 if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); });
531 signal_wakeup_locked();
532 }
533 }
534 if (immediate_cb) {
535 immediate_cb();
523 return; 536 return;
524 } 537 }
538 cv_.notify_one();
539 }
540
541 // Wakes run() when another path marks the device lost so pending waits complete and stop()/cancel() never hang.
542 void notify_device_lost() {
525 { 543 {
526 std::lock_guard lock(mutex_); 544 std::lock_guard lock(mutex_);
527 pending_.push_back({sem, value, nullptr, std::move(cb)});
528 if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); });
529 signal_wakeup_locked(); 545 signal_wakeup_locked();
530 } 546 }
531 cv_.notify_one(); 547 cv_.notify_all();
532 } 548 }
533 549
534 // Completes the pending waits for `sem` (a released D3D12 fence counts as reached, as on the PC runtime) and 550 // Completes the pending waits for `sem` (a released D3D12 fence counts as reached, as on the PC runtime) and
535 // blocks until any in-flight vkWaitSemaphores releases `sem` before the caller destroys the VkSemaphore. 551 // blocks until any in-flight vkWaitSemaphores releases `sem` before the caller destroys the VkSemaphore.
536 void cancel(VkSemaphore sem) { 552 void cancel(VkSemaphore sem) {
537 if (!sem) return; 553 if (!sem) return;
538 std::unique_lock lock(mutex_); 554 std::vector<Entry> cancelled;
539 std::erase_if(pending_, [this, sem](const Entry& e) { 555 SignalEventFn fn = nullptr;
540 if (e.semaphore != sem) return false; 556 {
541 if (e.callback) e.callback(); 557 std::unique_lock lock(mutex_);
542 else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); 558 fn = signal_event_;
543 return true; 559 std::size_t write = 0;
544 }); 560 for (std::size_t i = 0; i < pending_.size(); ++i) {
545 if (!thread_.joinable()) return; 561 if (pending_[i].semaphore == sem) {
546 if (waiting_) { 562 cancelled.push_back(std::move(pending_[i]));
547 const std::uint64_t target_epoch = epoch_ + 1; 563 } else {
548 signal_wakeup_locked(); 564 if (write != i) pending_[write] = std::move(pending_[i]);
549 epoch_cv_.wait(lock, [this, target_epoch] { return !waiting_ || epoch_ >= target_epoch; }); 565 ++write;
566 }
567 }
568 pending_.resize(write);
569 if (thread_.joinable() && waiting_) {
570 const std::uint64_t target_epoch = epoch_ + 1;
571 signal_wakeup_locked();
572 epoch_cv_.wait(lock, [this, target_epoch] { return !waiting_ || epoch_ >= target_epoch; });
573 }
550 } 574 }
575 dispatch_entries(cancelled, fn);
551 } 576 }
552 577
553 void stop() { 578 void stop() {
@@ -562,10 +587,18 @@ public:
562 } 587 }
563 588
564private: 589private:
590 static void dispatch_entries(std::vector<Entry>& entries, SignalEventFn signal_event) {
591 for (Entry& e : entries) {
592 if (e.callback) e.callback();
593 else if (signal_event && e.event_handle) signal_event(e.event_handle);
594 }
595 }
596
565 // Only signals wakeup_sem_ when run() is actively waiting (waiting_ == true) on wakeup_val_ + 1, 597 // Only signals wakeup_sem_ when run() is actively waiting (waiting_ == true) on wakeup_val_ + 1,
566 // eliminating any lost-wakeup race between snapshot construction and vkWaitSemaphores. 598 // eliminating any lost-wakeup race between snapshot construction and vkWaitSemaphores. Keep signaling even if
599 // device_lost_ is already set so a blocked vkWaitSemaphores wakes cleanly for cancel()/stop().
567 void signal_wakeup_locked() { 600 void signal_wakeup_locked() {
568 if (!waiting_ || !wakeup_sem_ || device_lost_.load(std::memory_order_relaxed)) return; 601 if (!waiting_ || !wakeup_sem_) return;
569 const std::uint64_t next = ++wakeup_val_; 602 const std::uint64_t next = ++wakeup_val_;
570 VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; 603 VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
571 si.semaphore = wakeup_sem_; 604 si.semaphore = wakeup_sem_;
@@ -576,7 +609,15 @@ private:
576 void run() { 609 void run() {
577 std::unique_lock lock(mutex_); 610 std::unique_lock lock(mutex_);
578 while (true) { 611 while (true) {
579 cv_.wait(lock, [this] { return stop_ || !pending_.empty(); }); 612 cv_.wait(lock, [this] { return stop_ || !pending_.empty() || device_lost_.load(std::memory_order_acquire); });
613 if (device_lost_.load(std::memory_order_acquire)) {
614 std::vector<Entry> drained = std::move(pending_);
615 pending_.clear();
616 const SignalEventFn fn = signal_event_;
617 lock.unlock();
618 dispatch_entries(drained, fn);
619 return;
620 }
580 if (stop_) return; 621 if (stop_) return;
581 622
582 semaphores_.clear(); 623 semaphores_.clear();
@@ -603,25 +644,53 @@ private:
603 ++epoch_; 644 ++epoch_;
604 epoch_cv_.notify_all(); 645 epoch_cv_.notify_all();
605 646
606 if (res == VK_ERROR_DEVICE_LOST) { 647 if (res == VK_ERROR_DEVICE_LOST || device_lost_.load(std::memory_order_acquire)) {
607 device_lost_.store(true, std::memory_order_release); 648 device_lost_.store(true, std::memory_order_release);
608 for (const Entry& e : pending_) { 649 std::vector<Entry> drained = std::move(pending_);
609 if (e.callback) e.callback();
610 else if (signal_event_ && e.event_handle) signal_event_(e.event_handle);
611 }
612 pending_.clear(); 650 pending_.clear();
651 const SignalEventFn fn = signal_event_;
652 lock.unlock();
653 dispatch_entries(drained, fn);
613 return; 654 return;
614 } 655 }
615 if (stop_) return; 656 if (stop_) return;
616 657
617 std::erase_if(pending_, [this](const Entry& e) { 658 std::vector<Entry> ready;
659 bool lost = false;
660 std::size_t write = 0;
661 for (std::size_t i = 0; i < pending_.size(); ++i) {
618 std::uint64_t done = 0; 662 std::uint64_t done = 0;
619 if (vk_.vkGetSemaphoreCounterValue(device_, e.semaphore, &done) != VK_SUCCESS) return false; 663 const VkResult cr = vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done);
620 if (done < e.value) return false; 664 if (cr == VK_ERROR_DEVICE_LOST) {
621 if (e.callback) e.callback(); 665 lost = true;
622 else if (signal_event_ && e.event_handle) signal_event_(e.event_handle); 666 for (std::size_t j = i; j < pending_.size(); ++j) ready.push_back(std::move(pending_[j]));
623 return true; 667 break;
624 }); 668 }
669 if (cr == VK_SUCCESS && done >= pending_[i].value) {
670 ready.push_back(std::move(pending_[i]));
671 } else {
672 if (write != i) pending_[write] = std::move(pending_[i]);
673 ++write;
674 }
675 }
676 if (lost) {
677 pending_.resize(write);
678 for (Entry& e : pending_) ready.push_back(std::move(e));
679 pending_.clear();
680 device_lost_.store(true, std::memory_order_release);
681 const SignalEventFn fn = signal_event_;
682 lock.unlock();
683 dispatch_entries(ready, fn);
684 return;
685 }
686 pending_.resize(write);
687 if (!ready.empty()) {
688 const SignalEventFn fn = signal_event_;
689 lock.unlock();
690 dispatch_entries(ready, fn);
691 lock.lock();
692 if (stop_) return;
693 }
625 } 694 }
626 } 695 }
627 696
@@ -644,6 +713,47 @@ private:
644 std::thread thread_; 713 std::thread thread_;
645}; 714};
646 715
716// A range of a D3D12 heap allocation. Mappings and in-flight unbinds keep the arena range alive.
717struct TileHeapAllocation {
718 VkDeviceMemory memory = VK_NULL_HANDLE;
719 VkDeviceSize offset = 0;
720 VkDeviceSize size = 0;
721 std::uint32_t memory_type = 0;
722};
723
724struct BufferTile {
725 std::shared_ptr<const TileHeapAllocation> heap;
726 VkDeviceSize offset = 0;
727 bool operator==(const BufferTile&) const = default;
728};
729
730struct SparseBuffer {
731 SparseBuffer(VkDevice device, PFN_vkDestroyBuffer destroy) : device(device), destroy(destroy) {}
732 SparseBuffer(const SparseBuffer&) = delete;
733 SparseBuffer& operator=(const SparseBuffer&) = delete;
734 ~SparseBuffer() { if (buffer) destroy(device, buffer, nullptr); }
735
736 VkDevice device;
737 PFN_vkDestroyBuffer destroy;
738 VkBuffer buffer = VK_NULL_HANDLE;
739 std::uint64_t tile_count = 0;
740 std::uint32_t memory_types = 0;
741 std::map<std::uint64_t, BufferTile> mapped;
742};
743
744struct BufferTileRegion {
745 std::uint64_t first = 0;
746 std::uint64_t count = 0;
747};
748
749enum class TileRangeMode { sequential, unmap, skip, reuse };
750
751struct BufferTileRange {
752 TileRangeMode mode;
753 std::uint64_t first;
754 std::uint64_t count;
755};
756
647// Per device: what the queues share. Resources are registered by their stable ID (the COM resource pointer). 757// Per device: what the queues share. Resources are registered by their stable ID (the COM resource pointer).
648#ifdef _MSC_VER 758#ifdef _MSC_VER
649#pragma warning(push) 759#pragma warning(push)
@@ -837,6 +947,12 @@ public:
837 storage_pending_.insert(id); 947 storage_pending_.insert(id);
838 } 948 }
839 949
950 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) {
951 std::unique_lock lock(resource_mutex_);
952 resources_[id] = binding;
953 sparse_buffers_.emplace(id, std::move(buffer));
954 }
955
840 void remove_resource(ResourceId id) { 956 void remove_resource(ResourceId id) {
841 VkImage img = VK_NULL_HANDLE; 957 VkImage img = VK_NULL_HANDLE;
842 { 958 {
@@ -845,6 +961,7 @@ public:
845 if (it == resources_.end()) return; 961 if (it == resources_.end()) return;
846 img = it->second.image; 962 img = it->second.image;
847 resources_.erase(it); 963 resources_.erase(it);
964 sparse_buffers_.erase(id);
848 } 965 }
849 if (img) { 966 if (img) {
850 std::lock_guard vlock(views_mutex_); 967 std::lock_guard vlock(views_mutex_);
@@ -1076,7 +1193,15 @@ public:
1076 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. 1193 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
1077 std::mutex& submit_mutex() { return submit_mutex_; } 1194 std::mutex& submit_mutex() { return submit_mutex_; }
1078 1195
1079 void mark_device_lost() noexcept { device_lost_.store(true, std::memory_order_release); } 1196 void mark_device_lost() noexcept {
1197 device_lost_.store(true, std::memory_order_release);
1198 if (fence_dispatcher_) {
1199 try {
1200 fence_dispatcher_->notify_device_lost();
1201 } catch (...) {
1202 }
1203 }
1204 }
1080 bool is_device_lost() const noexcept { return device_lost_.load(std::memory_order_acquire); } 1205 bool is_device_lost() const noexcept { return device_lost_.load(std::memory_order_acquire); }
1081 1206
1082 void set_signal_event_fn(FenceWaitDispatcher::SignalEventFn fn) { 1207 void set_signal_event_fn(FenceWaitDispatcher::SignalEventFn fn) {
@@ -1138,6 +1263,7 @@ private:
1138 DeferredDeletionQueue deletion_queue_; 1263 DeferredDeletionQueue deletion_queue_;
1139 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_; 1264 std::unique_ptr<FenceWaitDispatcher> fence_dispatcher_;
1140 std::unordered_map<ResourceId, ResourceBinding> resources_; 1265 std::unordered_map<ResourceId, ResourceBinding> resources_;
1266 std::unordered_map<ResourceId, std::shared_ptr<SparseBuffer>> sparse_buffers_;
1141 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 1267 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
1142 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 1268 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
1143 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 1269 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
@@ -1276,6 +1402,68 @@ public:
1276 1402
1277 bool ok() const { return ok_; } 1403 bool ok() const { return ok_; }
1278 1404
1405 template<typename GetHeap>
1406 bool update_tiles(ResourceId id, std::span<const BufferTileRegion> regions,
1407 std::span<const BufferTileRange> ranges, GetHeap&& get_heap) {
1408 std::unique_lock lock(context_.resource_mutex_);
1409 const auto it = context_.sparse_buffers_.find(id);
1410 if (it == context_.sparse_buffers_.end()) return false;
1411 const auto& buffer = it->second;
1412 for (const auto& region : regions)
1413 if (!valid_tiles(*buffer, region)) return false;
1414 const auto heap = get_heap();
1415
1416 std::map<std::uint64_t, BufferTile> changes;
1417 std::size_t region_index = 0;
1418 std::uint64_t consumed = 0;
1419 for (const auto& range : ranges) {
1420 const bool backed = range.mode == TileRangeMode::sequential || range.mode == TileRangeMode::reuse;
1421 const std::uint64_t heap_count = heap ? heap->size / tile_size_in_bytes : 0;
1422 const std::uint64_t required = range.mode == TileRangeMode::reuse ? 1 : range.count;
1423 if (backed && (!heap || range.first > heap_count || required > heap_count - range.first)) return false;
1424 for (std::uint64_t i = 0; i < range.count;) {
1425 if (region_index == regions.size()) return false;
1426 const auto& region = regions[region_index];
1427 const auto count = std::min(range.count - i, region.count - consumed);
1428 const auto first = region.first + consumed;
1429 if (range.mode == TileRangeMode::unmap) {
1430 const auto end = first + count;
1431 for (auto old = buffer->mapped.lower_bound(first); old != buffer->mapped.end() && old->first < end; ++old)
1432 changes[old->first] = {};
1433 for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change)
1434 change->second = {};
1435 } else if (backed) {
1436 for (std::uint64_t j = 0; j < count; ++j) {
1437 const auto page = range.first + (range.mode == TileRangeMode::sequential ? i + j : 0);
1438 changes[first + j] = {heap, heap->offset + page * tile_size_in_bytes};
1439 }
1440 }
1441 i += count;
1442 consumed += count;
1443 if (consumed == region.count) {
1444 ++region_index;
1445 consumed = 0;
1446 }
1447 }
1448 }
1449 return region_index == regions.size() && bind_tiles(buffer, changes);
1450 }
1451
1452 bool copy_tile_mappings(ResourceId dst, std::uint64_t dst_first, ResourceId src, BufferTileRegion src_region) {
1453 std::unique_lock lock(context_.resource_mutex_);
1454 const auto source = context_.sparse_buffers_.find(src), target = context_.sparse_buffers_.find(dst);
1455 if (source == context_.sparse_buffers_.end() || target == context_.sparse_buffers_.end() ||
1456 !valid_tiles(*source->second, src_region) ||
1457 !valid_tiles(*target->second, {dst_first, src_region.count})) return false;
1458 // Read the complete source mapping before changing any destination slot, including copies within one buffer.
1459 std::map<std::uint64_t, BufferTile> changes;
1460 for (std::uint64_t i = 0; i < src_region.count; ++i) {
1461 const auto page = source->second->mapped.find(src_region.first + i);
1462 changes.emplace(dst_first + i, page == source->second->mapped.end() ? BufferTile{} : page->second);
1463 }
1464 return bind_tiles(target->second, changes);
1465 }
1466
1279 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves 1467 // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves
1280 // the layout tracker as it was. Pending Wait()s are attached to this submission. 1468 // the layout tracker as it was. Pending Wait()s are attached to this submission.
1281 ReplayResult execute(std::span<const CommandList* const> lists) { 1469 ReplayResult execute(std::span<const CommandList* const> lists) {
@@ -1307,7 +1495,10 @@ public:
1307 } 1495 }
1308 } scratch_guard{context_.scratch_.get(), progress_, false}; 1496 } scratch_guard{context_.scratch_.get(), progress_, false};
1309 bindless_commit = context_.bindless_commit_; 1497 bindless_commit = context_.bindless_commit_;
1310 std::vector<PreparedList> prepared(lists.size()); 1498 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
1499 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
1500 auto& prepared = prepared_;
1501 prepared.resize(lists.size());
1311 ReplayFunctions replay = context_.replay_; 1502 ReplayFunctions replay = context_.replay_;
1312 std::uint64_t captures = 0; 1503 std::uint64_t captures = 0;
1313 for (const auto* list : lists) 1504 for (const auto* list : lists)
@@ -1383,7 +1574,7 @@ public:
1383 std::uint32_t segments = 0, statistics_segments = 0; 1574 std::uint32_t segments = 0, statistics_segments = 0;
1384 bool has_queries = false; 1575 bool has_queries = false;
1385 for (std::size_t i = 0; i < lists.size(); ++i) { 1576 for (std::size_t i = 0; i < lists.size(); ++i) {
1386 const auto result = prepare(*lists[i], resolve, replay, prepared[i]); 1577 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
1387 if (result != ReplayResult::success) return result; 1578 if (result != ReplayResult::success) return result;
1388 if (prepared[i].segment_count > UINT32_MAX - segments || 1579 if (prepared[i].segment_count > UINT32_MAX - segments ||
1389 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 1580 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
@@ -1611,11 +1802,107 @@ private:
1611 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 1802 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
1612 }; 1803 };
1613 1804
1805 struct PendingBindings {
1806 std::uint64_t ticket = 0;
1807 // Vulkan needs the buffer until the bind completes and the previous allocation until it is unmapped.
1808 std::vector<std::shared_ptr<const TileHeapAllocation>> old_heaps;
1809 std::shared_ptr<SparseBuffer> buffer;
1810 };
1811
1812 static bool valid_tiles(const SparseBuffer& buffer, BufferTileRegion region) {
1813 return region.count && region.first < buffer.tile_count && region.count <= buffer.tile_count - region.first;
1814 }
1815
1816 bool bind_tiles(const std::shared_ptr<SparseBuffer>& buffer,
1817 std::map<std::uint64_t, BufferTile>& changes) {
1818 auto& vk = context_.vk;
1819 if (!vk.vkQueueBindSparse || context_.is_device_lost()) return false;
1820 const auto ticket = submitted_ + 1;
1821 PendingBindings pending{ticket, {}, buffer};
1822 std::vector<VkSparseMemoryBind> binds;
1823 for (const auto& [index, page] : changes) {
1824 const auto old = buffer->mapped.find(index);
1825 if (old != buffer->mapped.end()) {
1826 if (old->second == page) continue;
1827 pending.old_heaps.push_back(old->second.heap);
1828 } else if (!page.heap) {
1829 continue;
1830 }
1831 if (page.heap && !(buffer->memory_types & (1u << page.heap->memory_type))) return false;
1832 const VkDeviceMemory memory = page.heap ? page.heap->memory : VK_NULL_HANDLE;
1833 const VkDeviceSize resource_offset = index * tile_size_in_bytes;
1834 if (!binds.empty()) {
1835 auto& previous = binds.back();
1836 if (previous.resourceOffset + previous.size == resource_offset && previous.memory == memory &&
1837 (!memory || previous.memoryOffset + previous.size == page.offset)) {
1838 previous.size += tile_size_in_bytes;
1839 continue;
1840 }
1841 }
1842 binds.push_back({resource_offset, tile_size_in_bytes, memory, page.offset, 0});
1843 }
1844 if (binds.empty()) return true;
1845 collect_bindings(completed());
1846 auto semaphores = waits_;
1847 auto values = wait_values_;
1848 // Sparse binds are not ordered against work on the same Vulkan queue by submission order alone.
1849 if (submitted_) {
1850 semaphores.push_back(progress_);
1851 values.push_back(submitted_);
1852 }
1853 VkTimelineSemaphoreSubmitInfo tickets{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO};
1854 tickets.waitSemaphoreValueCount = std::uint32_t(values.size());
1855 tickets.pWaitSemaphoreValues = values.data();
1856 tickets.signalSemaphoreValueCount = 1;
1857 tickets.pSignalSemaphoreValues = &ticket;
1858 const VkSparseBufferMemoryBindInfo buffer_bind{buffer->buffer, std::uint32_t(binds.size()), binds.data()};
1859 VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &tickets};
1860 info.waitSemaphoreCount = std::uint32_t(semaphores.size());
1861 info.pWaitSemaphores = semaphores.data();
1862 info.bufferBindCount = 1;
1863 info.pBufferBinds = &buffer_bind;
1864 info.signalSemaphoreCount = 1;
1865 info.pSignalSemaphores = &progress_;
1866 pending_bindings_.push_back(std::move(pending));
1867 {
1868 std::lock_guard lock(context_.submit_mutex());
1869 const auto result = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE);
1870 if (result != VK_SUCCESS) {
1871 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
1872 pending_bindings_.pop_back();
1873 return false;
1874 }
1875 context_.record_submit_locked(progress_, ticket);
1876 }
1877 submitted_ = last_sparse_ = ticket;
1878 waits_.clear();
1879 wait_values_.clear();
1880 for (auto it = changes.begin(); it != changes.end();) {
1881 buffer->mapped.erase(it->first);
1882 if (it->second.heap) ++it;
1883 else it = changes.erase(it);
1884 }
1885 buffer->mapped.merge(changes);
1886 return true;
1887 }
1888
1889 std::uint64_t completed() const {
1890 std::uint64_t done = 0;
1891 context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done);
1892 return done;
1893 }
1894
1895 void collect_bindings(std::uint64_t done) {
1896 while (!pending_bindings_.empty() && pending_bindings_.front().ticket <= done)
1897 pending_bindings_.pop_front();
1898 if (last_sparse_ <= done) last_sparse_ = 0;
1899 }
1900
1614 CommandSlot* acquire() { 1901 CommandSlot* acquire() {
1615 if (context_.is_device_lost()) return nullptr; 1902 if (context_.is_device_lost()) return nullptr;
1616 context_.drain_deleted_resources(context_.completed_retire_ticket()); 1903 context_.drain_deleted_resources(context_.completed_retire_ticket());
1617 std::uint64_t done = 0; 1904 const auto done = completed();
1618 context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); 1905 collect_bindings(done);
1619 CommandSlot* reuse = nullptr; 1906 CommandSlot* reuse = nullptr;
1620 for (auto& slot : buffers_) { 1907 for (auto& slot : buffers_) {
1621 if (slot.ticket > done) continue; 1908 if (slot.ticket > done) continue;
@@ -1642,8 +1929,21 @@ private:
1642 1929
1643 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { 1930 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) {
1644 if (context_.is_device_lost()) return false; 1931 if (context_.is_device_lost()) return false;
1645 const std::uint64_t ticket = ++submitted_; 1932 const std::uint64_t ticket = submitted_ + 1;
1646 const std::vector<VkPipelineStageFlags> stages(waits_.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 1933 if (last_sparse_) collect_bindings(completed());
1934 std::span<const VkSemaphore> semaphores = waits_;
1935 std::span<const std::uint64_t> values = wait_values_;
1936 std::vector<VkSemaphore> sparse_waits;
1937 std::vector<std::uint64_t> sparse_values;
1938 if (last_sparse_) {
1939 sparse_waits = waits_;
1940 sparse_values = wait_values_;
1941 sparse_waits.push_back(progress_);
1942 sparse_values.push_back(last_sparse_);
1943 semaphores = sparse_waits;
1944 values = sparse_values;
1945 }
1946 const std::vector<VkPipelineStageFlags> stages(semaphores.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1647 VkResult res = VK_SUCCESS; 1947 VkResult res = VK_SUCCESS;
1648 { 1948 {
1649 std::lock_guard lock(context_.submit_mutex()); 1949 std::lock_guard lock(context_.submit_mutex());
@@ -1656,13 +1956,13 @@ private:
1656 ++signal_count; 1956 ++signal_count;
1657 } 1957 }
1658 VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; 1958 VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO};
1659 timeline.waitSemaphoreValueCount = std::uint32_t(wait_values_.size()); 1959 timeline.waitSemaphoreValueCount = std::uint32_t(values.size());
1660 timeline.pWaitSemaphoreValues = wait_values_.data(); 1960 timeline.pWaitSemaphoreValues = values.data();
1661 timeline.signalSemaphoreValueCount = signal_count; 1961 timeline.signalSemaphoreValueCount = signal_count;
1662 timeline.pSignalSemaphoreValues = signal_values; 1962 timeline.pSignalSemaphoreValues = signal_values;
1663 VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; 1963 VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline};
1664 submit.waitSemaphoreCount = std::uint32_t(waits_.size()); 1964 submit.waitSemaphoreCount = std::uint32_t(semaphores.size());
1665 submit.pWaitSemaphores = waits_.data(); 1965 submit.pWaitSemaphores = semaphores.data();
1666 submit.pWaitDstStageMask = stages.data(); 1966 submit.pWaitDstStageMask = stages.data();
1667 submit.commandBufferCount = command_buffer ? 1 : 0; 1967 submit.commandBufferCount = command_buffer ? 1 : 0;
1668 submit.pCommandBuffers = &command_buffer; 1968 submit.pCommandBuffers = &command_buffer;
@@ -1679,6 +1979,7 @@ private:
1679 } 1979 }
1680 const bool ok = (res == VK_SUCCESS); 1980 const bool ok = (res == VK_SUCCESS);
1681 if (ok) { 1981 if (ok) {
1982 submitted_ = ticket;
1682 waits_.clear(); 1983 waits_.clear();
1683 wait_values_.clear(); 1984 wait_values_.clear();
1684 for (auto& slot : buffers_) 1985 for (auto& slot : buffers_)
@@ -1697,8 +1998,13 @@ private:
1697 std::vector<CommandSlot> buffers_; 1998 std::vector<CommandSlot> buffers_;
1698 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 1999 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
1699 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for 2000 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
2001 std::uint64_t last_sparse_ = 0;
2002 std::deque<PendingBindings> pending_bindings_;
1700 std::vector<VkSemaphore> waits_; 2003 std::vector<VkSemaphore> waits_;
1701 std::vector<std::uint64_t> wait_values_; 2004 std::vector<std::uint64_t> wait_values_;
2005 // execute's working storage. Per queue like buffers_: one execute at a time on a queue, as acquire() and
2006 // submit() already assume; other queues prepare concurrently with their own.
2007 std::vector<PreparedList> prepared_;
1702 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 2008 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
1703 bool ok_ = false; 2009 bool ok_ = false;
1704}; 2010};
diff --git a/runtime/src/vulkan_device_filter.h b/runtime/src/vulkan_device_filter.h
index 1e7a12e37..87b02424b 100644
--- a/runtime/src/vulkan_device_filter.h
+++ b/runtime/src/vulkan_device_filter.h
@@ -2,11 +2,12 @@
2 2
3// LEONIDA_VK_DEVICE: which Vulkan GPU the runtime and its tests take on a machine with more than one. The value is 3// LEONIDA_VK_DEVICE: which Vulkan GPU the runtime and its tests take on a machine with more than one. The value is
4// part of the device name, compared without case ("5070", "radeon"); unset or empty takes every device, and the 4// part of the device name, compared without case ("5070", "radeon"); unset or empty takes every device, and the
5// caller then picks as before (the last discrete GPU, else the first that fits). Several GPUs of one vendor share 5// caller then picks by vulkan_device_rank (below) among the devices it can use. Several GPUs of one vendor share
6// one driver, so the loader's own driver filters cannot tell them apart. A value that matches no device must fail 6// one driver, so the loader's own driver filters cannot tell them apart. A value that matches no device must fail
7// the caller, not fall back, so a typo cannot silently test another GPU (as LEONIDA_HOST_ADAPTER does). 7// the caller, not fall back, so a typo cannot silently test another GPU (as LEONIDA_HOST_ADAPTER does).
8 8
9#include <cctype> 9#include <cctype>
10#include <cstdint>
10#include <cstdlib> 11#include <cstdlib>
11#include <string> 12#include <string>
12 13
@@ -36,4 +37,25 @@ inline bool vulkan_device_wanted(const char* device_name) {
36 return name.find(filter) != std::string::npos; 37 return name.find(filter) != std::string::npos;
37} 38}
38 39
40// Microsoft is the vendor of the D3D12 translation layers Windows adds next to the real GPU (Mesa's Dozen from the
41// "OpenCL, OpenGL and Vulkan Compatibility Pack", and the Basic Render Driver); no native GPU driver uses it. Dozen
42// reports a discrete GPU, so "the last discrete device wins" took the wrapper over the native driver (#915).
43inline constexpr std::uint32_t microsoft_vulkan_vendor_id = 0x1414;
44
45// How much a device is wanted, higher first: a native driver over Microsoft's layers, then discrete > integrated >
46// virtual > CPU > other. `device_type` is VkPhysicalDeviceType (OTHER 0, INTEGRATED 1, DISCRETE 2, VIRTUAL 3, CPU 4;
47// as an int so this header needs no Vulkan headers). The runtime and every test harness pick the first device with
48// the highest rank among those they can use, so on a PC with two usable GPUs they take the same one.
49inline int vulkan_device_rank(int device_type, std::uint32_t vendor_id) {
50 int type_rank = 0;
51 switch (device_type) {
52 case 2: type_rank = 4; break; // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
53 case 1: type_rank = 3; break; // VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU
54 case 3: type_rank = 2; break; // VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU
55 case 4: type_rank = 1; break; // VK_PHYSICAL_DEVICE_TYPE_CPU
56 default: type_rank = 0; break;
57 }
58 return (vendor_id == microsoft_vulkan_vendor_id ? 0 : 10) + type_rank;
59}
60
39} // namespace leonida 61} // namespace leonida
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index d9f53baa5..15a706668 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -22,9 +22,8 @@
22 22
23#include "vulkan_backend.h" 23#include "vulkan_backend.h"
24 24
25// Both extension names share the structures (the KHR one was promoted from the EXT one); headers older than the 25// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
26// promotion do not have the KHR types, and the presenter then never tears. 26#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
27#if defined(VK_KHR_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_KHR_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
28#define LEONIDA_SWAPCHAIN_MAINTENANCE1 1 27#define LEONIDA_SWAPCHAIN_MAINTENANCE1 1
29#endif 28#endif
30 29
@@ -315,7 +314,7 @@ public:
315 present.pImageIndices = &image; 314 present.pImageIndices = &image;
316#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 315#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1
317 // The swapchain was created with FIFO and tear_mode_ (both come from the same recreate). 316 // The swapchain was created with FIFO and tear_mode_ (both come from the same recreate).
318 VkSwapchainPresentModeInfoKHR present_mode{VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_KHR}; 317 VkSwapchainPresentModeInfoEXT present_mode{VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT};
319 const bool tearing = tear && vsync_ && tear_supported(); 318 const bool tearing = tear && vsync_ && tear_supported();
320 if (tearing) { 319 if (tearing) {
321 present_mode.swapchainCount = 1; 320 present_mode.swapchainCount = 1;
@@ -694,7 +693,7 @@ private:
694 info.presentMode = mode; 693 info.presentMode = mode;
695#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 694#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1
696 // A vsync swapchain that can also be presented in IMMEDIATE (or FIFO_RELAXED), switched per present. 695 // A vsync swapchain that can also be presented in IMMEDIATE (or FIFO_RELAXED), switched per present.
697 VkSwapchainPresentModesCreateInfoKHR switchable{VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODES_CREATE_INFO_KHR}; 696 VkSwapchainPresentModesCreateInfoEXT switchable{VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODES_CREATE_INFO_EXT};
698 std::array<VkPresentModeKHR, 2> switchable_modes{VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_MAX_ENUM_KHR}; 697 std::array<VkPresentModeKHR, 2> switchable_modes{VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_MAX_ENUM_KHR};
699 VkPresentModeKHR tear = VK_PRESENT_MODE_MAX_ENUM_KHR; 698 VkPresentModeKHR tear = VK_PRESENT_MODE_MAX_ENUM_KHR;
700 if (vsync && mode == VK_PRESENT_MODE_FIFO_KHR) tear = find_tear_mode(modes, info.minImageCount, info.imageUsage, info.imageExtent); 699 if (vsync && mode == VK_PRESENT_MODE_FIFO_KHR) tear = find_tear_mode(modes, info.minImageCount, info.imageUsage, info.imageExtent);
@@ -762,11 +761,11 @@ private:
762 // The capabilities of the surface for one present mode, and the modes it can switch to from there. 761 // The capabilities of the surface for one present mode, and the modes it can switch to from there.
763 const auto ask = [&](VkPresentModeKHR asked, VkSurfaceCapabilitiesKHR& caps, 762 const auto ask = [&](VkPresentModeKHR asked, VkSurfaceCapabilitiesKHR& caps,
764 std::array<VkPresentModeKHR, 16>* compatible, std::uint32_t* compatible_count) { 763 std::array<VkPresentModeKHR, 16>* compatible, std::uint32_t* compatible_count) {
765 VkSurfacePresentModeKHR for_mode{VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_KHR}; 764 VkSurfacePresentModeEXT for_mode{VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT};
766 for_mode.presentMode = asked; 765 for_mode.presentMode = asked;
767 VkPhysicalDeviceSurfaceInfo2KHR surface_info{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR, &for_mode}; 766 VkPhysicalDeviceSurfaceInfo2KHR surface_info{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR, &for_mode};
768 surface_info.surface = surface_; 767 surface_info.surface = surface_;
769 VkSurfacePresentModeCompatibilityKHR compat{VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_KHR}; 768 VkSurfacePresentModeCompatibilityEXT compat{VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT};
770 if (compatible) { 769 if (compatible) {
771 compat.presentModeCount = std::uint32_t(compatible->size()); 770 compat.presentModeCount = std::uint32_t(compatible->size());
772 compat.pPresentModes = compatible->data(); 771 compat.pPresentModes = compatible->data();
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 2a37f58f5..8ece08d1e 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -1,5 +1,7 @@
1#pragma once 1#pragma once
2 2
3#include "resource_tiling.h"
4
3// Replays a closed CommandList (command_list.h) into a Vulkan command buffer. 5// Replays a closed CommandList (command_list.h) into a Vulkan command buffer.
4// 6//
5// Layouts. With a LayoutTracker, every image's current Vulkan layout is known per subresource, and barriers and 7// Layouts. With a LayoutTracker, every image's current Vulkan layout is known per subresource, and barriers and
@@ -86,6 +88,7 @@ struct ResourceBinding {
86 bool rgb96 = false; 88 bool rgb96 = false;
87 bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it 89 bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it
88 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush 90 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush
91 bool sparse_buffer = false;
89}; 92};
90 93
91struct VulkanAccess { 94struct VulkanAccess {
@@ -410,6 +413,7 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) {
410 case VK_FORMAT_R32G32B32A32_SINT: return {16, 1}; 413 case VK_FORMAT_R32G32B32A32_SINT: return {16, 1};
411 case VK_FORMAT_R16G16B16A16_SFLOAT: 414 case VK_FORMAT_R16G16B16A16_SFLOAT:
412 case VK_FORMAT_R16G16B16A16_UNORM: 415 case VK_FORMAT_R16G16B16A16_UNORM:
416 case VK_FORMAT_R16G16B16A16_SNORM:
413 case VK_FORMAT_R16G16B16A16_UINT: 417 case VK_FORMAT_R16G16B16A16_UINT:
414 case VK_FORMAT_R16G16B16A16_SINT: 418 case VK_FORMAT_R16G16B16A16_SINT:
415 case VK_FORMAT_R32G32_SFLOAT: 419 case VK_FORMAT_R32G32_SFLOAT:
@@ -427,6 +431,8 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) {
427 case VK_FORMAT_B8G8R8A8_UNORM: 431 case VK_FORMAT_B8G8R8A8_UNORM:
428 case VK_FORMAT_B8G8R8A8_SRGB: 432 case VK_FORMAT_B8G8R8A8_SRGB:
429 case VK_FORMAT_R16G16_SFLOAT: 433 case VK_FORMAT_R16G16_SFLOAT:
434 case VK_FORMAT_R16G16_UNORM:
435 case VK_FORMAT_R16G16_SNORM:
430 case VK_FORMAT_R16G16_UINT: 436 case VK_FORMAT_R16G16_UINT:
431 case VK_FORMAT_R16G16_SINT: 437 case VK_FORMAT_R16G16_SINT:
432 case VK_FORMAT_R32_SFLOAT: 438 case VK_FORMAT_R32_SFLOAT:
@@ -443,9 +449,16 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) {
443 case VK_FORMAT_R8G8_SINT: 449 case VK_FORMAT_R8G8_SINT:
444 case VK_FORMAT_R16_SFLOAT: 450 case VK_FORMAT_R16_SFLOAT:
445 case VK_FORMAT_R16_UNORM: 451 case VK_FORMAT_R16_UNORM:
452 case VK_FORMAT_R16_SNORM:
453 case VK_FORMAT_R16_UINT:
454 case VK_FORMAT_R16_SINT:
446 case VK_FORMAT_A4R4G4B4_UNORM_PACK16: 455 case VK_FORMAT_A4R4G4B4_UNORM_PACK16:
456 case VK_FORMAT_R4G4B4A4_UNORM_PACK16:
447 case VK_FORMAT_D16_UNORM: return {2, 1}; 457 case VK_FORMAT_D16_UNORM: return {2, 1};
448 case VK_FORMAT_R8_UNORM: return {1, 1}; 458 case VK_FORMAT_R8_UNORM:
459 case VK_FORMAT_R8_SNORM:
460 case VK_FORMAT_R8_UINT:
461 case VK_FORMAT_R8_SINT: return {1, 1};
449 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: 462 case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
450 case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: 463 case VK_FORMAT_BC1_RGBA_SRGB_BLOCK:
451 case VK_FORMAT_BC4_UNORM_BLOCK: 464 case VK_FORMAT_BC4_UNORM_BLOCK:
@@ -477,8 +490,7 @@ inline bool two_planes(const ResourceBinding& resource) {
477} 490}
478 491
479// D3D12 copies between a depth format and a colour format of the same typeless family, bit for bit: D32_FLOAT with 492// D3D12 copies between a depth format and a colour format of the same typeless family, bit for bit: D32_FLOAT with
480// R32_FLOAT/UINT/SINT (R32_TYPELESS) and D16_UNORM with R16_FLOAT/UNORM (R16_TYPELESS; the other R16 formats have no 493// R32_FLOAT/UINT/SINT (R32_TYPELESS) and D16_UNORM with R16_FLOAT/UNORM/SNORM/UINT/SINT (R16_TYPELESS). Single-sampled, single-plane depth only: D24 and D32 with stencil have two planes, and a D24
481// copy layout here yet). Single-sampled, single-plane depth only: D24 and D32 with stencil have two planes, and a D24
482// stored as D32 would need the depth24 conversion. Vulkan's vkCmdCopyImage refuses mismatched aspects, so the replay 494// stored as D32 would need the depth24 conversion. Vulkan's vkCmdCopyImage refuses mismatched aspects, so the replay
483// stages these through a buffer. 495// stages these through a buffer.
484inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { 496inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) {
@@ -490,7 +502,10 @@ inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b
490 case VK_FORMAT_R32_SINT: return 32; 502 case VK_FORMAT_R32_SINT: return 32;
491 case VK_FORMAT_D16_UNORM: 503 case VK_FORMAT_D16_UNORM:
492 case VK_FORMAT_R16_SFLOAT: 504 case VK_FORMAT_R16_SFLOAT:
493 case VK_FORMAT_R16_UNORM: return 16; 505 case VK_FORMAT_R16_UNORM:
506 case VK_FORMAT_R16_SNORM:
507 case VK_FORMAT_R16_UINT:
508 case VK_FORMAT_R16_SINT: return 16;
494 default: return 0; 509 default: return 0;
495 } 510 }
496 }; 511 };
@@ -551,6 +566,42 @@ struct LayoutPiece {
551 VkImageLayout layout; 566 VkImageLayout layout;
552}; 567};
553 568
569// The layout pieces of one range: nearly always one (the tracked layouts agree over the range) or two (depth and
570// stencil apart), so those live inline and a barrier or clear makes no heap allocation; more spill to the heap.
571class LayoutPieces {
572public:
573 LayoutPiece* begin() { return data(); }
574 LayoutPiece* end() { return data() + size_; }
575 const LayoutPiece* begin() const { return data(); }
576 const LayoutPiece* end() const { return data() + size_; }
577 std::size_t size() const { return size_; }
578 bool empty() const { return size_ == 0; }
579 LayoutPiece& operator[](std::size_t i) { return data()[i]; }
580 const LayoutPiece& operator[](std::size_t i) const { return data()[i]; }
581
582 void clear() {
583 size_ = 0;
584 heap_.clear();
585 }
586 void push_back(const LayoutPiece& piece) {
587 if (heap_.empty() && size_ < inline_.size()) {
588 inline_[size_++] = piece;
589 return;
590 }
591 if (heap_.empty()) heap_.assign(inline_.begin(), inline_.begin() + size_);
592 heap_.push_back(piece);
593 ++size_;
594 }
595
596private:
597 LayoutPiece* data() { return heap_.empty() ? inline_.data() : heap_.data(); }
598 const LayoutPiece* data() const { return heap_.empty() ? inline_.data() : heap_.data(); }
599
600 std::array<LayoutPiece, 2> inline_{};
601 std::vector<LayoutPiece> heap_;
602 std::size_t size_ = 0;
603};
604
554// The current Vulkan layout of every tracked image subresource. Shared by all queues of a device; lists are 605// The current Vulkan layout of every tracked image subresource. Shared by all queues of a device; lists are
555// emitted in submission order. Images are tracked from creation (their initial state) until destruction. 606// emitted in submission order. Images are tracked from creation (their initial state) until destruction.
556class LayoutTracker { 607class LayoutTracker {
@@ -582,7 +633,9 @@ public:
582 } 633 }
583 634
584 // The current layouts over a range: one piece when they all agree, else one per subresource. 635 // The current layouts over a range: one piece when they all agree, else one per subresource.
585 bool pieces(ResourceId id, const VkImageSubresourceRange& range, std::vector<LayoutPiece>& out) const { 636 // Out is LayoutPieces or std::vector<LayoutPiece>.
637 template<typename Out>
638 bool pieces(ResourceId id, const VkImageSubresourceRange& range, Out& out) const {
586 const auto it = entries_.find(id); 639 const auto it = entries_.find(id);
587 if (it == entries_.end()) return false; 640 if (it == entries_.end()) return false;
588 const Entry& e = it->second; 641 const Entry& e = it->second;
@@ -703,6 +756,7 @@ struct GraphicsPipeline {
703 // and stencil. Null when it cannot be built. 756 // and stencil. Null when it cannot be built.
704 static constexpr std::uint32_t unbound_depth = 1u << 8; 757 static constexpr std::uint32_t unbound_depth = 1u << 8;
705 std::function<VkPipeline(std::uint32_t unbound)> variant; 758 std::function<VkPipeline(std::uint32_t unbound)> variant;
759 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count
706}; 760};
707 761
708// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. 762// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base.
@@ -845,7 +899,7 @@ struct PreparedQuery {
845 std::uint32_t end_segment = no_segment; 899 std::uint32_t end_segment = no_segment;
846 std::uint32_t first_result = 0; 900 std::uint32_t first_result = 0;
847 std::uint32_t result_count = 0; 901 std::uint32_t result_count = 0;
848 // A pipeline-statistics query split around the resolves it contains (plan_statistics_segments): the physical 902 // A pipeline-statistics query split around the helpers it contains (plan_statistics_segments): the physical
849 // statistics segment this command ends or begins, and for its EndQuery the segments that hold its result. 903 // statistics segment this command ends or begins, and for its EndQuery the segments that hold its result.
850 std::uint32_t statistics_end = no_segment; 904 std::uint32_t statistics_end = no_segment;
851 std::uint32_t statistics_begin = no_segment; 905 std::uint32_t statistics_begin = no_segment;
@@ -855,6 +909,9 @@ struct PreparedQuery {
855}; 909};
856 910
857struct Prepared { 911struct Prepared {
912 // Helper commands split the active statistics query just like query resolves.
913 std::uint32_t statistics_end = PreparedQuery::no_segment;
914 std::uint32_t statistics_begin = PreparedQuery::no_segment;
858 PredicateCapture predicate; 915 PredicateCapture predicate;
859 std::vector<PredicatedCopyDispatch> predicated_copy; 916 std::vector<PredicatedCopyDispatch> predicated_copy;
860 ResourceBinding binding; 917 ResourceBinding binding;
@@ -1010,8 +1067,9 @@ inline VkExtent2D mip_extent(const ResourceBinding& resource, std::uint32_t mip)
1010 return {std::max(1u, resource.width >> mip), std::max(1u, resource.height >> mip)}; 1067 return {std::max(1u, resource.width >> mip), std::max(1u, resource.height >> mip)};
1011} 1068}
1012 1069
1013inline std::vector<VkClearRect> clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t layers) { 1070// Into `out`, replacing what it held: a kept PreparedList entry reuses the vector's storage.
1014 std::vector<VkClearRect> out; 1071inline void clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t layers, std::vector<VkClearRect>& out) {
1072 out.clear();
1015 for (const Rect& r : rects) { 1073 for (const Rect& r : rects) {
1016 const std::int64_t left = std::max<std::int64_t>(r.left, 0), top = std::max<std::int64_t>(r.top, 0); 1074 const std::int64_t left = std::max<std::int64_t>(r.left, 0), top = std::max<std::int64_t>(r.top, 0);
1017 const std::int64_t right = std::min<std::int64_t>(r.right, extent.width); 1075 const std::int64_t right = std::min<std::int64_t>(r.right, extent.width);
@@ -1020,7 +1078,6 @@ inline std::vector<VkClearRect> clip(std::span<const Rect> rects, VkExtent2D ext
1020 out.push_back({{{std::int32_t(left), std::int32_t(top)}, {std::uint32_t(right - left), std::uint32_t(bottom - top)}}, 1078 out.push_back({{{std::int32_t(left), std::int32_t(top)}, {std::uint32_t(right - left), std::uint32_t(bottom - top)}},
1021 0, layers}); 1079 0, layers});
1022 } 1080 }
1023 return out;
1024} 1081}
1025 1082
1026// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9. 1083// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9.
@@ -1056,10 +1113,13 @@ inline void memory_barrier(const ReplayFunctions& vk, VkCommandBuffer command_bu
1056} 1113}
1057 1114
1058// The current layouts of a range: from the tracker, or `assumed` for an untracked image. 1115// The current layouts of a range: from the tracker, or `assumed` for an untracked image.
1059inline std::vector<LayoutPiece> current(const LayoutTracker* tracker, ResourceId id, const VkImageSubresourceRange& range, 1116inline LayoutPieces current(const LayoutTracker* tracker, ResourceId id, const VkImageSubresourceRange& range,
1060 VkImageLayout assumed) { 1117 VkImageLayout assumed) {
1061 std::vector<LayoutPiece> out; 1118 LayoutPieces out;
1062 if (!tracker || !tracker->pieces(id, range, out)) out = {{range, assumed}}; 1119 if (!tracker || !tracker->pieces(id, range, out)) {
1120 out.clear();
1121 out.push_back({range, assumed});
1122 }
1063 return out; 1123 return out;
1064} 1124}
1065 1125
@@ -1210,7 +1270,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1210// when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run 1270// when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run
1211// expects; with not_zeroed, it is only moved. The tracker records it. 1271// expects; with not_zeroed, it is only moved. The tracker records it.
1212inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, 1272inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource,
1213 ResourceId id, std::vector<LayoutPiece>& pieces, VkImageLayout layout, LayoutTracker* tracker) { 1273 ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker) {
1214 constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; 1274 constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1215 for (auto& piece : pieces) { 1275 for (auto& piece : pieces) {
1216 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; 1276 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue;
@@ -1614,6 +1674,43 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared&
1614 return ReplayResult::success; 1674 return ReplayResult::success;
1615} 1675}
1616 1676
1677// A depth or stencil resolve of a rectangle runs in a rendering scope whose render area is the rectangle, and Vulkan
1678// resolves only inside it. MoltenVK resolves the whole destination subresource instead: the resolve is Metal's
1679// store action, which has no render area (measured on MoltenVK 1.4.2 and 1.4.3, docs/d3d12_vulkan.md). No Vulkan
1680// property tells, so on every GPU the texels around the rectangle go into `staged` before the resolve and come back
1681// after it, in up to four bands (`staged_reads`, one region per band, used in both directions).
1682inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p) {
1683 const VkExtent2D to = mip_extent(p.binding, p.range.baseMipLevel);
1684 const auto x0 = std::uint32_t(p.resolve.dstOffset.x), y0 = std::uint32_t(p.resolve.dstOffset.y);
1685 const std::uint32_t x1 = x0 + p.resolve.extent.width, y1 = y0 + p.resolve.extent.height;
1686 const VkRect2D bands[4] = {
1687 {{0, 0}, {to.width, y0}}, // above
1688 {{0, std::int32_t(y1)}, {to.width, to.height - y1}}, // below
1689 {{0, std::int32_t(y0)}, {x0, y1 - y0}}, // left
1690 {{std::int32_t(x1), std::int32_t(y0)}, {to.width - x1, y1 - y0}}, // right
1691 };
1692 // Depth aspects want 4-byte buffer offsets; 16 covers every texel size here.
1693 const std::uint32_t texel = block_format(p.binding.format, p.range.aspectMask).bytes;
1694 VkDeviceSize total = 0;
1695 for (const VkRect2D& band : bands) {
1696 if (!band.extent.width || !band.extent.height) continue;
1697 VkBufferImageCopy region{};
1698 region.bufferOffset = total;
1699 region.imageSubresource = p.resolve.dstSubresource;
1700 region.imageOffset = {band.offset.x, band.offset.y, 0};
1701 region.imageExtent = {band.extent.width, band.extent.height, 1};
1702 p.staged_reads.push_back(region);
1703 total += (VkDeviceSize(band.extent.width) * band.extent.height * texel + 15) / 16 * 16;
1704 }
1705 if (p.staged_reads.empty()) return ReplayResult::success; // the rectangle is the whole subresource
1706 VkDeviceSize base = 0;
1707 if (!texel || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch ||
1708 !vk.copy_scratch(total, p.staged, base))
1709 return ReplayResult::unsupported;
1710 for (VkBufferImageCopy& region : p.staged_reads) region.bufferOffset += base;
1711 return ReplayResult::success;
1712}
1713
1617// The layout a copy uses for a range: D3D12 requires copy_dest/copy_source, or common (GENERAL), where an implicit 1714// The layout a copy uses for a range: D3D12 requires copy_dest/copy_source, or common (GENERAL), where an implicit
1618// promotion lets the copy run in place. Anything else is moved to `wanted` and tracked. 1715// promotion lets the copy run in place. Anything else is moved to `wanted` and tracked.
1619inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer command_buffer, 1716inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer command_buffer,
@@ -1653,7 +1750,7 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm
1653// back to where they were. Pieces already in `target` need no transition. 1750// back to where they were. Pieces already in `target` need no transition.
1654template<typename Body> 1751template<typename Body>
1655void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, 1752void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource,
1656 const std::vector<LayoutPiece>& pieces, VkImageLayout target, const VulkanAccess& state, 1753 const LayoutPieces& pieces, VkImageLayout target, const VulkanAccess& state,
1657 VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) { 1754 VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) {
1658 for (const auto& piece : pieces) { 1755 for (const auto& piece : pieces) {
1659 if (piece.layout == target) { 1756 if (piece.layout == target) {
@@ -1710,6 +1807,9 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
1710 a.binding = *binding; 1807 a.binding = *binding;
1711 a.id = target.resource; 1808 a.id = target.resource;
1712 if (!a.binding.image || a.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; 1809 if (!a.binding.image || a.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear;
1810 // D3D12 requires the PSO's SampleDesc on every bound target (a mismatch is undefined); Vulkan's dynamic
1811 // rendering requires the counts to agree, so the list fails here instead of in the driver.
1812 if (a.binding.samples != pipeline->samples) return ReplayResult::invalid_subresource;
1713 if (!view_range(a.binding, target, VK_IMAGE_ASPECT_COLOR_BIT, a.range)) return ReplayResult::invalid_subresource; 1813 if (!view_range(a.binding, target, VK_IMAGE_ASPECT_COLOR_BIT, a.range)) return ReplayResult::invalid_subresource;
1714 ResourceBinding viewed = a.binding; 1814 ResourceBinding viewed = a.binding;
1715 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot]; 1815 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot];
@@ -1724,6 +1824,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
1724 a.binding = *binding; 1824 a.binding = *binding;
1725 a.id = draw.depth.resource; 1825 a.id = draw.depth.resource;
1726 if (!a.binding.image || !(a.binding.aspects & depth_stencil_aspects)) return ReplayResult::invalid_clear; 1826 if (!a.binding.image || !(a.binding.aspects & depth_stencil_aspects)) return ReplayResult::invalid_clear;
1827 if (a.binding.samples != pipeline->samples) return ReplayResult::invalid_subresource;
1727 if (!view_range(a.binding, draw.depth, a.binding.aspects, a.range)) return ReplayResult::invalid_subresource; 1828 if (!view_range(a.binding, draw.depth, a.binding.aspects, a.range)) return ReplayResult::invalid_subresource;
1728 ResourceBinding viewed = a.binding; 1829 ResourceBinding viewed = a.binding;
1729 viewed.format = pipeline->depth_format; 1830 viewed.format = pipeline->depth_format;
@@ -1907,20 +2008,25 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
1907 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; 2008 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query;
1908} 2009}
1909 2010
1910// A resolve inside a pipeline-statistics query can record a helper dispatch (the binary-occlusion normalisation, an 2011// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and
1911// occlusion or a statistics sum), and Vulkan would count its invocations in the application's CSInvocations. Such a 2012// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements
1912// query is therefore split: its counters go to physical segments that end before each resolve inside it and begin 2013// depend on heap state at planning time, so every non-timestamp resolve splits conservatively.
1913// again after it, and its result is the sum of those segments (D3D-162). Whether a resolve dispatches is only known
1914// when the list is planned against the heaps' state, so every resolve except a timestamp copy splits the query.
1915// A BeginQuery without its EndQuery in the list is left as it was.
1916inline void plan_statistics_segments(PreparedList& out) { 2014inline void plan_statistics_segments(PreparedList& out) {
1917 detail::PreparedQuery* begin = nullptr; 2015 detail::PreparedQuery* begin = nullptr;
1918 std::vector<detail::PreparedQuery*> inner; 2016 struct Split { std::uint32_t* end; std::uint32_t* begin; };
1919 for (auto& query : out.queries) { 2017 std::vector<Split> inner;
1920 const Command& command = out.list->commands()[query.command]; 2018 std::size_t next_query = 0;
2019 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2020 auto& p = out.commands[i];
2021 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24))
2022 inner.push_back({&p.statistics_end, &p.statistics_begin});
2023 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue;
2024 auto& query = out.queries[next_query++];
2025 const Command& command = out.list->commands()[i];
1921 const auto range = query_range(command); 2026 const auto range = query_range(command);
1922 if (std::holds_alternative<ResolveQueries>(command)) { 2027 if (std::holds_alternative<ResolveQueries>(command)) {
1923 if (begin && range.type != d3d12_query::timestamp) inner.push_back(&query); 2028 if (begin && range.type != d3d12_query::timestamp)
2029 inner.push_back({&query.statistics_end, &query.statistics_begin});
1924 } else if (range.type == d3d12_query::pipeline_statistics) { 2030 } else if (range.type == d3d12_query::pipeline_statistics) {
1925 if (std::holds_alternative<BeginQuery>(command)) { 2031 if (std::holds_alternative<BeginQuery>(command)) {
1926 begin = &query; 2032 begin = &query;
@@ -1929,9 +2035,9 @@ inline void plan_statistics_segments(PreparedList& out) {
1929 if (!inner.empty()) { 2035 if (!inner.empty()) {
1930 const std::uint32_t first = out.statistics_segment_count; 2036 const std::uint32_t first = out.statistics_segment_count;
1931 begin->statistics_begin = out.statistics_segment_count++; 2037 begin->statistics_begin = out.statistics_segment_count++;
1932 for (auto* resolve : inner) { 2038 for (auto split : inner) {
1933 resolve->statistics_end = out.statistics_segment_count - 1; 2039 *split.end = out.statistics_segment_count - 1;
1934 resolve->statistics_begin = out.statistics_segment_count++; 2040 *split.begin = out.statistics_segment_count++;
1935 } 2041 }
1936 query.statistics_end = out.statistics_segment_count - 1; 2042 query.statistics_end = out.statistics_segment_count - 1;
1937 query.statistics_first = first; 2043 query.statistics_first = first;
@@ -1994,8 +2100,11 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun
1994 2100
1995// Resolves and checks every command. Nothing is written to a command buffer. 2101// Resolves and checks every command. Nothing is written to a command buffer.
1996// Resolve maps a ResourceId to a const ResourceBinding* (nullptr: unknown). 2102// Resolve maps a ResourceId to a const ResourceBinding* (nullptr: unknown).
2103// statistics_helpers promises a statistics segment pool at QueryReplay::plan(). Keep the default for replay()
2104// and callers without a summation helper: reject before allocating any helper scratch.
1997template<typename Resolve> 2105template<typename Resolve>
1998ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFunctions& vk, PreparedList& out) { 2106ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFunctions& vk, PreparedList& out,
2107 bool statistics_helpers = false) {
1999 if (!list.closed()) return ReplayResult::list_open; 2108 if (!list.closed()) return ReplayResult::list_open;
2000 if (list.queries_open()) return ReplayResult::invalid_query; // a Vulkan query must end in its command buffer 2109 if (list.queries_open()) return ReplayResult::invalid_query; // a Vulkan query must end in its command buffer
2001 const auto commands = list.commands(); 2110 const auto commands = list.commands();
@@ -2037,7 +2146,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2037 const auto rect_view = [&](std::span<const Rect> rects, const TargetView& target, VkImageAspectFlags view_aspects) { 2146 const auto rect_view = [&](std::span<const Rect> rects, const TargetView& target, VkImageAspectFlags view_aspects) {
2038 if (rects.empty()) return ReplayResult::success; 2147 if (rects.empty()) return ReplayResult::success;
2039 if (!rendering) return ReplayResult::unsupported; 2148 if (!rendering) return ReplayResult::unsupported;
2040 p.rects = detail::clip(rects, detail::mip_extent(p.binding, target.mip), target.layer_count); 2149 detail::clip(rects, detail::mip_extent(p.binding, target.mip), target.layer_count, p.rects);
2041 if (p.rects.empty()) { 2150 if (p.rects.empty()) {
2042 p.skip = true; 2151 p.skip = true;
2043 return ReplayResult::success; 2152 return ReplayResult::success;
@@ -2150,9 +2259,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2150 p.source = *source; 2259 p.source = *source;
2151 ReplayResult result = ReplayResult::success; 2260 ReplayResult result = ReplayResult::success;
2152 if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) { 2261 if (const auto* buffer_copy = std::get_if<CopyBuffer>(&command)) {
2262 const auto size = [&](const ResourceBinding& binding, ResourceId id) {
2263 if (buffer_copy->tiled_resource != id) return binding.size;
2264 if (!binding.sparse_buffer) return VkDeviceSize(0);
2265 return (binding.size + tile_size_in_bytes - 1) / tile_size_in_bytes * tile_size_in_bytes;
2266 };
2153 if (!p.binding.buffer || !p.source.buffer || 2267 if (!p.binding.buffer || !p.source.buffer ||
2154 !detail::within(buffer_copy->dst_offset, buffer_copy->size, p.binding.size) || 2268 !detail::within(buffer_copy->dst_offset, buffer_copy->size, size(p.binding, dst_id)) ||
2155 !detail::within(buffer_copy->src_offset, buffer_copy->size, p.source.size)) 2269 !detail::within(buffer_copy->src_offset, buffer_copy->size, size(p.source, src_id)))
2156 return ReplayResult::invalid_copy; 2270 return ReplayResult::invalid_copy;
2157 if (buffer_copy->src_offset > UINT64_MAX - p.source.buffer_offset || 2271 if (buffer_copy->src_offset > UINT64_MAX - p.source.buffer_offset ||
2158 buffer_copy->dst_offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_copy; 2272 buffer_copy->dst_offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_copy;
@@ -2163,7 +2277,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2163 if (p.source.buffer == p.binding.buffer && src < dst + buffer_copy->size && dst < src + buffer_copy->size) 2277 if (p.source.buffer == p.binding.buffer && src < dst + buffer_copy->size && dst < src + buffer_copy->size)
2164 return ReplayResult::invalid_copy; 2278 return ReplayResult::invalid_copy;
2165 if (predicated) { 2279 if (predicated) {
2166 if (statistics_active || !vk.prepare_predicated_copy || !vk.emit_predicated_copy || 2280 if ((statistics_active && !statistics_helpers) || !vk.prepare_predicated_copy || !vk.emit_predicated_copy ||
2167 !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy)) 2281 !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy))
2168 return ReplayResult::unsupported; 2282 return ReplayResult::unsupported;
2169 } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); 2283 } else p.buffer_copies.push_back({src, dst, buffer_copy->size});
@@ -2177,9 +2291,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2177 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; 2291 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
2178 const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 && 2292 const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 &&
2179 !p.buffer_image_copies.empty(); 2293 !p.buffer_image_copies.empty();
2180 // These footprint conversions emit compute dispatches in emit(). Refuse them before allocating their 2294 // Without a segment pool, refuse before allocating conversion scratch/descriptors.
2181 // conversion scratch/descriptors because an active statistics query would include their CSInvocations. 2295 if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported;
2182 if (statistics_active && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported;
2183 if (depth24_footprint) { 2296 if (depth24_footprint) {
2184 const VkBufferImageCopy& region = p.buffer_image_copies[0]; 2297 const VkBufferImageCopy& region = p.buffer_image_copies[0];
2185 const ResourceBinding& buffer = upload ? p.source : p.binding; 2298 const ResourceBinding& buffer = upload ? p.source : p.binding;
@@ -2267,6 +2380,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2267 p.view = vk.image_view(p.source, p.source_range); 2380 p.view = vk.image_view(p.source, p.source_range);
2268 p.resolve_view = vk.image_view(p.binding, p.range); 2381 p.resolve_view = vk.image_view(p.binding, p.range);
2269 if (!p.view || !p.resolve_view) return ReplayResult::unsupported; 2382 if (!p.view || !p.resolve_view) return ReplayResult::unsupported;
2383 if (const auto result = detail::keep_around_resolve(vk, p); result != ReplayResult::success)
2384 return result;
2270 } 2385 }
2271 } else if (const auto* discard = std::get_if<DiscardResource>(&command)) { 2386 } else if (const auto* discard = std::get_if<DiscardResource>(&command)) {
2272 // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. 2387 // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows.
@@ -2320,9 +2435,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2320 predicated = predication->buffer != 0; 2435 predicated = predication->buffer != 0;
2321 if (!predicated) continue; 2436 if (!predicated) continue;
2322 if (!conditional) return ReplayResult::unsupported; 2437 if (!conditional) return ReplayResult::unsupported;
2323 // The internal dispatch must not appear in the application's pipeline-statistics result. Virtualising 2438 // Without physical segments the capture dispatch would pollute CSInvocations.
2324 // that query is separate work; reject the combination before emitting any commands instead of lying. 2439 if (statistics_active && !statistics_helpers) return ReplayResult::unsupported;
2325 if (statistics_active) return ReplayResult::unsupported;
2326 if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; 2440 if (!bind(predication->buffer)) return ReplayResult::unresolved_resource;
2327 if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || 2441 if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) ||
2328 predication->offset > UINT64_MAX - p.binding.buffer_offset) 2442 predication->offset > UINT64_MAX - p.binding.buffer_offset)
@@ -2466,7 +2580,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2466class QueryReplay { 2580class QueryReplay {
2467public: 2581public:
2468 // `statistics_pool` holds the list's pipeline-statistics segments (plan_statistics_segments). Without one, the 2582 // `statistics_pool` holds the list's pipeline-statistics segments (plan_statistics_segments). Without one, the
2469 // list's statistics queries are not split, and a resolve inside one that needs a helper dispatch is refused. 2583 // list's statistics queries are not split: ordinary helper commands are refused, as are resolves that dispatch.
2470 ReplayResult plan(PreparedList& list, const std::shared_ptr<const OcclusionSegmentPool>& pool = {}, 2584 ReplayResult plan(PreparedList& list, const std::shared_ptr<const OcclusionSegmentPool>& pool = {},
2471 std::uint32_t base = 0, bool can_sum = false, 2585 std::uint32_t base = 0, bool can_sum = false,
2472 const std::shared_ptr<const OcclusionSegmentPool>& statistics_pool = {}, 2586 const std::shared_ptr<const OcclusionSegmentPool>& statistics_pool = {},
@@ -2483,6 +2597,9 @@ public:
2483 list.statistics_pool = statistics_pool->pool; 2597 list.statistics_pool = statistics_pool->pool;
2484 list.statistics_base = statistics_base; 2598 list.statistics_base = statistics_base;
2485 } else { 2599 } else {
2600 for (const auto& command : list.commands)
2601 if (command.statistics_end != detail::PreparedQuery::no_segment)
2602 return ReplayResult::unsupported;
2486 for (auto& query : list.queries) { 2603 for (auto& query : list.queries) {
2487 query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment; 2604 query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment;
2488 query.statistics_count = 0; 2605 query.statistics_count = 0;
@@ -2681,12 +2798,25 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2681 emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); 2798 emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate);
2682 continue; 2799 continue;
2683 } 2800 }
2801 // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too.
2802 const auto end_statistics = [&] {
2803 if (p.statistics_end != detail::PreparedQuery::no_segment)
2804 vk.end_query(command_buffer, prepared.statistics_pool, prepared.statistics_base + p.statistics_end);
2805 };
2806 const auto begin_statistics = [&] {
2807 if (p.statistics_begin == detail::PreparedQuery::no_segment) return;
2808 const auto index = prepared.statistics_base + p.statistics_begin;
2809 vk.reset_query_pool(command_buffer, prepared.statistics_pool, index, 1);
2810 vk.begin_query(command_buffer, prepared.statistics_pool, index, 0);
2811 };
2684 if (const auto* predication = std::get_if<Predication>(&command)) { 2812 if (const auto* predication = std::get_if<Predication>(&command)) {
2685 // Conditional rendering cannot nest, so a new predicate ends the previous one first. 2813 // Conditional rendering cannot nest, so a new predicate ends the previous one first.
2686 if (predicate.buffer) vk.end_conditional_rendering(command_buffer); 2814 if (predicate.buffer) vk.end_conditional_rendering(command_buffer);
2687 predicate.buffer = predication->buffer ? p.predicate.scratch : VK_NULL_HANDLE; 2815 predicate.buffer = predication->buffer ? p.predicate.scratch : VK_NULL_HANDLE;
2688 if (predicate.buffer) { 2816 if (predicate.buffer) {
2817 end_statistics();
2689 vk.capture_predicate(command_buffer, p.predicate); 2818 vk.capture_predicate(command_buffer, p.predicate);
2819 begin_statistics();
2690 predicate.offset = p.predicate.offset + 8; 2820 predicate.offset = p.predicate.offset + 8;
2691 // Vulkan discards the commands when the word is 0, which is EQUAL_ZERO; INVERTED gives NOT_EQUAL_ZERO. 2821 // Vulkan discards the commands when the word is 0, which is EQUAL_ZERO; INVERTED gives NOT_EQUAL_ZERO.
2692 predicate.flags = predication->op == d3d12_predication::not_equal_zero 2822 predicate.flags = predication->op == d3d12_predication::not_equal_zero
@@ -2767,9 +2897,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2767 texture->layout_before == d3d12_layout::undefined; 2897 texture->layout_before == d3d12_layout::undefined;
2768 const VkImageLayout new_layout = 2898 const VkImageLayout new_layout =
2769 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); 2899 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable));
2770 std::vector<LayoutPiece> pieces; 2900 LayoutPieces pieces;
2771 if (discard) 2901 if (discard)
2772 pieces = {{range, VK_IMAGE_LAYOUT_UNDEFINED}}; 2902 pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED});
2773 else { 2903 else {
2774 const VkImageLayout before = 2904 const VkImageLayout before =
2775 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); 2905 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable));
@@ -2924,7 +3054,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2924 std::holds_alternative<CopyResource>(command)) { 3054 std::holds_alternative<CopyResource>(command)) {
2925 const auto [dst_id, src_id] = copy_ids(command); 3055 const auto [dst_id, src_id] = copy_ids(command);
2926 if (!p.predicated_copy.empty()) { 3056 if (!p.predicated_copy.empty()) {
3057 end_statistics();
2927 vk.emit_predicated_copy(command_buffer, p.predicated_copy); 3058 vk.emit_predicated_copy(command_buffer, p.predicated_copy);
3059 begin_statistics();
2928 } else if (!p.buffer_copies.empty()) { 3060 } else if (!p.buffer_copies.empty()) {
2929 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), 3061 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()),
2930 p.buffer_copies.data()); 3062 p.buffer_copies.data());
@@ -2979,7 +3111,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2979 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 3111 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
2980 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, 3112 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
2981 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); 3113 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
3114 end_statistics();
2982 for (const auto& part : p.depth24_parts) run_depth24(part); 3115 for (const auto& part : p.depth24_parts) run_depth24(part);
3116 begin_statistics();
2983 detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 3117 detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
2984 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); 3118 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
2985 converted = p.buffer_image_copies; 3119 converted = p.buffer_image_copies;
@@ -3011,7 +3145,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3011 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 3145 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
3012 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, 3146 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
3013 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); 3147 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
3148 end_statistics();
3014 for (const auto& part : p.depth24_parts) run_depth24(part); 3149 for (const auto& part : p.depth24_parts) run_depth24(part);
3150 begin_statistics();
3015 detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 3151 detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
3016 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, 3152 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
3017 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 3153 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
@@ -3040,6 +3176,22 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3040 auto dest_pieces = detail::current( 3176 auto dest_pieces = detail::current(
3041 tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); 3177 tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout);
3042 detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker); 3178 detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker);
3179 // The texels around the rectangle, kept in `staged` across the resolve (keep_around_resolve).
3180 const auto keep = [&](VkImageLayout wanted, VkAccessFlags access, auto&& copy) {
3181 const VkImageLayout layout = image_layout(p.binding, wanted);
3182 detail::round_trip(vk, command_buffer, p.binding, dest_pieces, layout, dest_state, access,
3183 VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); });
3184 };
3185 const auto bands = std::uint32_t(p.staged_reads.size());
3186 if (p.staged) {
3187 keep(VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, [&](VkImageLayout layout) {
3188 vk.copy_image_to_buffer(command_buffer, p.binding.image, layout, p.staged, bands,
3189 p.staged_reads.data());
3190 });
3191 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT,
3192 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT,
3193 VK_PIPELINE_STAGE_TRANSFER_BIT);
3194 }
3043 const VkImageLayout source_attachment = 3195 const VkImageLayout source_attachment =
3044 image_layout(p.source, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); 3196 image_layout(p.source, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
3045 const VkImageLayout dest_attachment = 3197 const VkImageLayout dest_attachment =
@@ -3067,6 +3219,12 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3067 vk.end_rendering(command_buffer); 3219 vk.end_rendering(command_buffer);
3068 }); 3220 });
3069 }); 3221 });
3222 if (p.staged) {
3223 keep(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, [&](VkImageLayout layout) {
3224 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, bands,
3225 p.staged_reads.data());
3226 });
3227 }
3070 continue; 3228 continue;
3071 } 3229 }
3072 const VkImageLayout src_layout = detail::copy_layout( 3230 const VkImageLayout src_layout = detail::copy_layout(
@@ -3098,7 +3256,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3098 for (const auto& range : p.discards) { 3256 for (const auto& range : p.discards) {
3099 if (!tracker || detail::planes_for_layout(p.binding, range, separate).aspectMask != range.aspectMask) 3257 if (!tracker || detail::planes_for_layout(p.binding, range, separate).aspectMask != range.aspectMask)
3100 continue; 3258 continue;
3101 std::vector<LayoutPiece> pieces; 3259 LayoutPieces pieces;
3102 if (!tracker->pieces(id, range, pieces)) continue; 3260 if (!tracker->pieces(id, range, pieces)) continue;
3103 for (const auto& piece : pieces) 3261 for (const auto& piece : pieces)
3104 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) 3262 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED)