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:
authorTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 16:10:41 +0000
committerTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 16:10:41 +0000
commitfc7d1f514d9d73c7366336c1e7adbdf5c689dfa0 (patch)
treee46dc95057c9b935804d172c132e5ea4976a373d /runtime/src
parent279898ee6ce736d77e03ca81eeeacde31f4f4f9f (diff)
parent8575d36edc479218972497a7bded8651a42856c0 (diff)
Merge origin/main into test/877b-shader-programs-validation
Conflicts in vk_store_test.cpp and vk_texture_test.cpp: both new includes (vk_validation.h and spirv_capability.h) are kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/command_list.h28
-rw-r--r--runtime/src/crt_timed_wait.cpp74
-rw-r--r--runtime/src/main.cpp15
-rw-r--r--runtime/src/mods.h23
-rw-r--r--runtime/src/pe_loader.cpp70
-rw-r--r--runtime/src/pe_loader.h8
-rw-r--r--runtime/src/queue_families.h28
-rw-r--r--runtime/src/shader_library.h6
-rw-r--r--runtime/src/statistics_sum.comp11
-rw-r--r--runtime/src/statistics_sum_spirv.h86
-rw-r--r--runtime/src/vulkan_backend.h75
-rw-r--r--runtime/src/vulkan_present.h51
-rw-r--r--runtime/src/vulkan_replay.h214
13 files changed, 548 insertions, 141 deletions
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 5c36d44e3..4b384bdc1 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -414,9 +414,11 @@ struct DrawViews {
414 std::uint32_t render_target_count = 8; 414 std::uint32_t render_target_count = 8;
415}; 415};
416 416
417// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads 417// DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded:
418// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at 418// D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the
419// the draw. resource 0 marks an unbound render-target slot or no depth buffer. 419// list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw
420// (DispatchMesh) takes its thread-group counts in count (x), instances (y) and first (z), and ignores the vertex
421// and index buffers and the topology.
420// Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations 422// Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations
421// during command list recording (D3D-289). 423// during command list recording (D3D-289).
422struct Draw { 424struct Draw {
@@ -437,6 +439,7 @@ struct Draw {
437 std::uint32_t first = 0; // first vertex or first index 439 std::uint32_t first = 0; // first vertex or first index
438 std::int32_t base_vertex = 0; 440 std::int32_t base_vertex = 0;
439 std::uint32_t first_instance = 0; 441 std::uint32_t first_instance = 0;
442 bool mesh = false;
440}; 443};
441 444
442// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. 445// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.
@@ -738,10 +741,11 @@ public:
738 return append(dispatch); 741 return append(dispatch);
739 } 742 }
740 743
741 // A draw with no vertices or instances does nothing in D3D12, and is not recorded. 744 // A draw with no vertices or instances, or a mesh draw with no thread groups, does nothing in D3D12, and is
745 // not recorded.
742 bool draw(const Draw& draw) { 746 bool draw(const Draw& draw) {
743 if (!draw.pipeline) return false; 747 if (!draw.pipeline) return false;
744 if (!draw.count || !draw.instances) return !closed_; 748 if (!draw.count || !draw.instances || (draw.mesh && !draw.first)) return !closed_;
745 return append(draw); 749 return append(draw);
746 } 750 }
747 bool draw(Draw&& draw) { 751 bool draw(Draw&& draw) {
@@ -866,22 +870,26 @@ public:
866 } 870 }
867 871
868 bool execute_indirect(const ExecuteIndirect& indirect) { 872 bool execute_indirect(const ExecuteIndirect& indirect) {
869 if (!indirect.argument_buffer || !indirect.stride) return false; 873 if (!indirect.argument_buffer || !indirect.stride || indirect.stride % 4) return false;
874 if (indirect.argument_offset % 4) return false;
875 if (!indirect.count_buffer && indirect.count_offset) return false;
876 if (indirect.count_buffer && indirect.count_offset % 4) return false;
870 if (!indirect.max_count) return !closed_; // the PC runtime takes MaxCommandCount 0 as a no-op 877 if (!indirect.max_count) return !closed_; // the PC runtime takes MaxCommandCount 0 as a no-op
871 return append(indirect); 878 return append(indirect);
872 } 879 }
873 880
881 // D3D12: acceleration structures and build scratch are 256-byte aligned; postbuild destinations 8-byte aligned.
874 bool build_acceleration_structure(BuildAccelerationStructure build) { 882 bool build_acceleration_structure(BuildAccelerationStructure build) {
875 if (!build.dst_va || !build.scratch_va) return false; 883 if (!build.dst_va || build.dst_va % 256 || !build.scratch_va || build.scratch_va % 256) return false;
884 if (build.update && (!build.src_va || build.src_va % 256)) return false;
876 return append(std::move(build)); 885 return append(std::move(build));
877 } 886 }
878 // D3D12: acceleration structures are 256-byte aligned, postbuild destinations 8-byte aligned.
879 bool copy_acceleration_structure(CopyAccelerationStructure copy) { 887 bool copy_acceleration_structure(CopyAccelerationStructure copy) {
880 if (!copy.dst_va || !copy.src_va || copy.dst_va % 256 || copy.src_va % 256) return false; 888 if (!copy.dst_va || !copy.src_va || copy.dst_va % 256 || copy.src_va % 256 || copy.mode > 4) return false;
881 return append(copy); 889 return append(copy);
882 } 890 }
883 bool acceleration_structure_postbuild(AccelerationStructurePostbuild info) { 891 bool acceleration_structure_postbuild(AccelerationStructurePostbuild info) {
884 if (!info.dest_va || info.dest_va % 8 || info.sources.empty()) return false; 892 if (!info.dest_va || info.dest_va % 8 || info.type > 3 || info.sources.empty()) return false;
885 for (const auto va : info.sources) 893 for (const auto va : info.sources)
886 if (!va || va % 256) return false; 894 if (!va || va % 256) return false;
887 return append(std::move(info)); 895 return append(std::move(info));
diff --git a/runtime/src/crt_timed_wait.cpp b/runtime/src/crt_timed_wait.cpp
new file mode 100644
index 000000000..6441f2868
--- /dev/null
+++ b/runtime/src/crt_timed_wait.cpp
@@ -0,0 +1,74 @@
1// The timed condition-variable wait of every runtime binary built against the dynamic CRT (/MD), routed through
2// msvcp140.dll so it uses the same _Mtx_t layout as the mutex it unlocks.
3//
4// In the 14.4x STL, condition_variable::wait_for/wait_until call _Cnd_timedwait_for_unchecked. <xthreads.h> declares
5// it without _CRTIMP2_PURE, so it is not imported: it is linked statically from msvcprt.lib (its sharedmutex.obj),
6// and it unlocks the mutex by reaching into Windows' _Mtx_t layout for its SRW lock. _Mtx_lock/_Mtx_unlock are
7// imported from msvcp140.dll. Wine's builtin msvcp140 laid _Mtx_t out differently until wine-10.1 ("msvcp140: Fix
8// field order in _Mtx_t", 757bd7909fda), so on Wine 9.0 (Ubuntu 24.04's wine) a timed wait released nothing and
9// kept the mutex for its whole timeout: the thread that would set the predicate could not take the lock, and every
10// wait_for timed out instead of being woken (issue #3796, measured 2000 ms vs 0.3 ms for a 2 s wait).
11//
12// Defining the public symbols of that msvcprt.lib member here keeps it out of the link. The timed wait then goes
13// through msvcp140's exported _Cnd_timedwait, which locks and waits on its own layout, whatever DLL provides it
14// (Windows, any Wine). The other definitions are the ones the member would bring in, with the same behaviour:
15// std::shared_mutex on an SRW lock, and this_thread::sleep_for. Only /MD targets get this file (CMakeLists.txt);
16// a /MT target links the whole STL statically, so its mutex and wait already agree. No game files.
17#include <windows.h>
18
19#include <time.h>
20#include <xthreads.h>
21
22extern "C" {
23
24// Exported by every msvcp140.dll, Windows' and Wine's; no longer declared by the 14.4x headers. The deadline is
25// absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout).
26__declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept;
27
28_Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept {
29 _timespec64 deadline{};
30 if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {};
31 deadline.tv_sec += ms / 1000;
32 deadline.tv_nsec += static_cast<long>(ms % 1000) * 1000000L;
33 if (deadline.tv_nsec >= 1000000000L) {
34 deadline.tv_sec += 1;
35 deadline.tv_nsec -= 1000000000L;
36 }
37 // A spurious or early return is allowed ("unchecked"): the STL's callers check the clock themselves.
38 return static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline));
39}
40
41// Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too.
42_Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept {
43 return _Cnd_timedwait_for_unchecked(cond, mtx, ms);
44}
45
46void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept {
47 AcquireSRWLockExclusive(reinterpret_cast<PSRWLOCK>(lock));
48}
49
50void __cdecl _Smtx_lock_shared(_Smtx_t* lock) noexcept {
51 AcquireSRWLockShared(reinterpret_cast<PSRWLOCK>(lock));
52}
53
54int __cdecl _Smtx_try_lock_exclusive(_Smtx_t* lock) noexcept {
55 return TryAcquireSRWLockExclusive(reinterpret_cast<PSRWLOCK>(lock));
56}
57
58int __cdecl _Smtx_try_lock_shared(_Smtx_t* lock) noexcept {
59 return TryAcquireSRWLockShared(reinterpret_cast<PSRWLOCK>(lock));
60}
61
62void __cdecl _Smtx_unlock_exclusive(_Smtx_t* lock) noexcept {
63 ReleaseSRWLockExclusive(reinterpret_cast<PSRWLOCK>(lock));
64}
65
66void __cdecl _Smtx_unlock_shared(_Smtx_t* lock) noexcept {
67 ReleaseSRWLockShared(reinterpret_cast<PSRWLOCK>(lock));
68}
69
70void __stdcall _Thrd_sleep_for(unsigned long ms) noexcept {
71 Sleep(ms);
72}
73
74} // extern "C"
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index b75baf15f..71a5b44e1 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -20,6 +20,7 @@
20 20
21#include <cstdio> 21#include <cstdio>
22#include <cstdlib> 22#include <cstdlib>
23#include <exception>
23#include <filesystem> 24#include <filesystem>
24#include <map> 25#include <map>
25#include <string> 26#include <string>
@@ -179,9 +180,15 @@ int wmain(int argc, wchar_t** argv) {
179 r.error); 180 r.error);
180 } 181 }
181 if (run) rt::process::set_command_line(image.filename().wstring(), game_args); 182 if (run) rt::process::set_command_line(image.filename().wstring(), game_args);
183 std::exception_ptr init_failure;
182 if (init || run) { 184 if (init || run) {
183 loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs 185 try {
184 std::printf("%zu module(s) initialised\n", loader.modules().size()); 186 loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs
187 std::printf("%zu module(s) initialised\n", loader.modules().size());
188 } catch (const std::exception&) {
189 // Keep the mapped modules available for the binding report on an attach failure.
190 init_failure = std::current_exception();
191 }
185 } 192 }
186 int unimplemented = 0, unimplemented_hresult = 0; 193 int unimplemented = 0, unimplemented_hresult = 0;
187 for (auto* m : loader.modules()) { 194 for (auto* m : loader.modules()) {
@@ -205,6 +212,10 @@ int wmain(int argc, wchar_t** argv) {
205 std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); 212 std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented);
206 std::printf("unimplemented by return policy: hresult=%d other=%d\n", unimplemented_hresult, 213 std::printf("unimplemented by return policy: hresult=%d other=%d\n", unimplemented_hresult,
207 unimplemented - unimplemented_hresult); 214 unimplemented - unimplemented_hresult);
215 if (init_failure) {
216 std::fflush(stdout);
217 std::rethrow_exception(init_failure);
218 }
208 if (!run) { 219 if (!run) {
209 rt::startup_trace::event("exit", "\"code\":0"); 220 rt::startup_trace::event("exit", "\"code\":0");
210 return 0; 221 return 0;
diff --git a/runtime/src/mods.h b/runtime/src/mods.h
index c308ed7db..10155bf19 100644
--- a/runtime/src/mods.h
+++ b/runtime/src/mods.h
@@ -15,6 +15,7 @@
15#pragma once 15#pragma once
16 16
17#include <algorithm> 17#include <algorithm>
18#include <cmath>
18#include <cstdint> 19#include <cstdint>
19#include <filesystem> 20#include <filesystem>
20#include <fstream> 21#include <fstream>
@@ -94,8 +95,24 @@ inline bool parse_model_id(const std::string& text, uint32_t& out) {
94 return true; 95 return true;
95} 96}
96 97
98// A JSON number that is a whole value in [0, max]. Checked before any integer cast: converting a double outside the
99// target type's range is undefined, so `v != static_cast<int>(v)` cannot be the test for a value past INT_MAX.
100inline bool whole_number(double v, double max) { return v >= 0 && v <= max && v == std::floor(v); }
101
97// Parses one mod.json's text. On failure returns false with `error` set; `mod` is then not to be used. 102// Parses one mod.json's text. On failure returns false with `error` set; `mod` is then not to be used.
98inline bool parse_mod(std::string_view text, const std::string& folder, Mod& mod, std::string& error) { 103inline bool parse_mod(std::string_view text, const std::string& folder, Mod& mod, std::string& error) {
104 // Windows editors and shells mark the encoding. Notepad's "UTF-8 with BOM" and Windows PowerShell 5.1's
105 // `-Encoding utf8` put EF BB BF in front of the same JSON, so it is skipped. PowerShell 5.1's `>` writes UTF-16,
106 // which is not readable as bytes: say so, instead of blaming the JSON. A NUL in the first two bytes is UTF-16
107 // without a mark; no UTF-8 JSON text starts that way.
108 if (text.substr(0, 3) == std::string_view("\xEF\xBB\xBF", 3)) {
109 text.remove_prefix(3);
110 } else if (text.size() >= 2 && (text.substr(0, 2) == std::string_view("\xFF\xFE", 2) ||
111 text.substr(0, 2) == std::string_view("\xFE\xFF", 2) || text[0] == '\0' ||
112 text[1] == '\0')) {
113 error = "mod.json is UTF-16; save it as UTF-8";
114 return false;
115 }
99 Json root; 116 Json root;
100 if (!JsonReader(text).parse(root) || root.kind != Json::Kind::object) { 117 if (!JsonReader(text).parse(root) || root.kind != Json::Kind::object) {
101 error = "mod.json is not a JSON object"; 118 error = "mod.json is not a JSON object";
@@ -161,7 +178,7 @@ inline bool parse_mod(std::string_view text, const std::string& folder, Mod& mod
161 } 178 }
162 mod.camera.first_person = view->string == "first_person"; 179 mod.camera.first_person = view->string == "first_person";
163 if (const Json* v = cam->find("first_person_value")) { 180 if (const Json* v = cam->find("first_person_value")) {
164 if (v->kind != Json::Kind::number || v->number < 0 || v->number > 255 || v->number != static_cast<int>(v->number)) { 181 if (v->kind != Json::Kind::number || !whole_number(v->number, 255)) {
165 error = "\"camera\": \"first_person_value\" must be a whole number 0-255"; 182 error = "\"camera\": \"first_person_value\" must be a whole number 0-255";
166 return false; 183 return false;
167 } 184 }
@@ -173,8 +190,8 @@ inline bool parse_mod(std::string_view text, const std::string& folder, Mod& mod
173 return false; 190 return false;
174 } 191 }
175 for (const Json& x : c->array) { 192 for (const Json& x : c->array) {
176 if (x.kind != Json::Kind::number || x.number < 0 || x.number != static_cast<int>(x.number)) { 193 if (x.kind != Json::Kind::number || !whole_number(x.number, 4294967295.0)) {
177 error = "\"camera\": \"contexts\" must be a list of whole numbers"; 194 error = "\"camera\": \"contexts\" must be a list of whole numbers from 0 to 4294967295";
178 return false; 195 return false;
179 } 196 }
180 mod.camera.contexts.push_back(static_cast<uint32_t>(x.number)); 197 mod.camera.contexts.push_back(static_cast<uint32_t>(x.number));
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index e8c504f0f..bfeab4c7f 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -13,6 +13,7 @@
13#include <fstream> 13#include <fstream>
14#include <mutex> 14#include <mutex>
15#include <stdexcept> 15#include <stdexcept>
16#include <system_error>
16#include <vector> 17#include <vector>
17 18
18#include "../shims/shims.h" 19#include "../shims/shims.h"
@@ -28,9 +29,36 @@ std::string lower(std::string s) {
28 29
29namespace { 30namespace {
30 31
32std::filesystem::path::string_type module_key(const std::filesystem::path& path) {
33 // Keep identity in the platform's native path representation. Only the existing ASCII case folding is
34 // applied here; representable names also retain their old narrow-byte alias below.
35 auto key = path.filename().native();
36 for (auto& c : key)
37 if (c >= 'A' && c <= 'Z') c = static_cast<std::filesystem::path::value_type>(c + ('a' - 'A'));
38 return key;
39}
40
41std::string narrow_module_key(const std::filesystem::path& path) {
42 const auto filename = path.filename();
43 try {
44 const auto narrow = filename.string();
45 // A lossy/default-character alias must not collapse two distinct Unicode basenames.
46 if (std::filesystem::path(narrow).native() == filename.native()) return lower(narrow);
47 } catch (const std::system_error&) {
48 // Some Windows standard libraries throw when a basename is outside the current narrow code page.
49 // It still has a native identity; it simply has no alias in the existing narrow lookup API.
50 }
51 return {};
52}
53
54std::string path_utf8(const std::filesystem::path& path) {
55 const auto bytes = path.u8string();
56 return {reinterpret_cast<const char*>(bytes.data()), bytes.size()};
57}
58
31std::vector<uint8_t> read_file(const std::filesystem::path& p) { 59std::vector<uint8_t> read_file(const std::filesystem::path& p) {
32 std::ifstream f(p, std::ios::binary); 60 std::ifstream f(p, std::ios::binary);
33 if (!f) throw std::runtime_error("cannot open " + p.string()); 61 if (!f) throw std::runtime_error("cannot open " + path_utf8(p));
34 return {std::istreambuf_iterator<char>(f), {}}; 62 return {std::istreambuf_iterator<char>(f), {}};
35} 63}
36 64
@@ -930,11 +958,13 @@ Loader::~Loader() {
930 958
931Module& Loader::load(const std::filesystem::path& image) { 959Module& Loader::load(const std::filesystem::path& image) {
932 std::lock_guard lock(mutex_); 960 std::lock_guard lock(mutex_);
933 std::string key = lower(image.filename().string()); 961 const auto key = module_key(image);
934 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 962 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
963 const auto narrow_key = narrow_module_key(image);
964 if (Module* existing = find_narrow_module(narrow_key)) return *existing;
935 Module* mapped = nullptr; 965 Module* mapped = nullptr;
936 try { 966 try {
937 mapped = &map_image(image); 967 mapped = &map_image(image, narrow_key);
938 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m 968 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m
939 protect_sections(*mapped); 969 protect_sections(*mapped);
940 register_unwind(*mapped); 970 register_unwind(*mapped);
@@ -954,10 +984,19 @@ Module& Loader::load(const std::filesystem::path& image) {
954 return m; 984 return m;
955} 985}
956 986
987Module* Loader::find_narrow_module(const std::string& dll_lower) const {
988 if (dll_lower.empty()) return nullptr;
989 // library_loader and PE import names keep their existing narrow-byte contract. Do not reinterpret them
990 // as UTF-8 or widen already-folded bytes (which could be part of a multibyte code-page character).
991 for (const auto& entry : by_name_)
992 if (entry.second->narrow_key == dll_lower) return entry.second;
993 return nullptr;
994}
995
957void* Loader::find_loaded_module(const std::string& dll_lower) const { 996void* Loader::find_loaded_module(const std::string& dll_lower) const {
958 std::lock_guard lock(mutex_); 997 std::lock_guard lock(mutex_);
959 auto it = by_name_.find(dll_lower); 998 Module* m = find_narrow_module(dll_lower);
960 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base); 999 return m ? static_cast<void*>(m->base) : nullptr;
961} 1000}
962 1001
963void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { 1002void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) {
@@ -965,10 +1004,10 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
965 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; 1004 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
966 1005
967 std::lock_guard lock(mutex_); 1006 std::lock_guard lock(mutex_);
968 const auto existing = by_name_.find(dll_lower); 1007 Module* existing = find_narrow_module(dll_lower);
969 const std::filesystem::path candidate = game_dir_ / dll_lower; 1008 const std::filesystem::path candidate = game_dir_ / dll_lower;
970 std::error_code ec; 1009 std::error_code ec;
971 const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec); 1010 const bool is_bundled = existing || std::filesystem::is_regular_file(candidate, ec);
972 if (!is_bundled) return nullptr; 1011 if (!is_bundled) return nullptr;
973 1012
974 handled = true; 1013 handled = true;
@@ -982,10 +1021,10 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
982 return nullptr; 1021 return nullptr;
983 } 1022 }
984 1023
985 if (existing != by_name_.end()) { 1024 if (existing) {
986 try { 1025 try {
987 initialise(); 1026 initialise();
988 return static_cast<void*>(existing->second->base); 1027 return static_cast<void*>(existing->base);
989 } catch (const std::exception& e) { 1028 } catch (const std::exception& e) {
990 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what()); 1029 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what());
991 SetLastError(ERROR_DLL_INIT_FAILED); 1030 SetLastError(ERROR_DLL_INIT_FAILED);
@@ -993,15 +1032,17 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
993 } 1032 }
994 } 1033 }
995 1034
1035 Module* mapped = nullptr;
996 try { 1036 try {
997 Module& m = load(candidate); 1037 Module& m = load(candidate);
1038 mapped = &m;
998 initialise(); 1039 initialise();
999 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); 1040 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
1000 return static_cast<void*>(m.base); 1041 return static_cast<void*>(m.base);
1001 } catch (const std::exception& e) { 1042 } catch (const std::exception& e) {
1002 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose 1043 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose
1003 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. 1044 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_.
1004 by_name_.erase(dll_lower); 1045 by_name_.erase(module_key(mapped ? mapped->path : candidate));
1005 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); 1046 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
1006 SetLastError(ERROR_DLL_INIT_FAILED); 1047 SetLastError(ERROR_DLL_INIT_FAILED);
1007 return nullptr; 1048 return nullptr;
@@ -1129,12 +1170,12 @@ void Loader::set_initialised(Module& m, bool value) {
1129 m.initialised = value; 1170 m.initialised = value;
1130} 1171}
1131 1172
1132Module& Loader::map_image(const std::filesystem::path& path) { 1173Module& Loader::map_image(const std::filesystem::path& path, const std::string& narrow_key) {
1133 auto file = read_file(path); 1174 auto file = read_file(path);
1134 const std::string name = path.filename().string(); 1175 const std::string name = path_utf8(path.filename());
1135 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); 1176 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data());
1136 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) 1177 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE)
1137 throw std::runtime_error(path.string() + ": not an MZ image"); 1178 throw std::runtime_error(path_utf8(path) + ": not an MZ image");
1138 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) 1179 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
1139 throw std::runtime_error(name + ": the NT headers are outside the file"); 1180 throw std::runtime_error(name + ": the NT headers are outside the file");
1140 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); 1181 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
@@ -1158,11 +1199,12 @@ Module& Loader::map_image(const std::filesystem::path& path) {
1158 1199
1159 auto* m = new Module; 1200 auto* m = new Module;
1160 m->name = name; 1201 m->name = name;
1202 m->narrow_key = narrow_key;
1161 m->path = path; 1203 m->path = path;
1162 m->preferred_base = oh.ImageBase; 1204 m->preferred_base = oh.ImageBase;
1163 m->size = oh.SizeOfImage; 1205 m->size = oh.SizeOfImage;
1164 m->entry_rva = oh.AddressOfEntryPoint; 1206 m->entry_rva = oh.AddressOfEntryPoint;
1165 by_name_[lower(m->name)] = m; 1207 by_name_[module_key(path)] = m;
1166 order_.push_back(m); 1208 order_.push_back(m);
1167 1209
1168 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. 1210 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual.
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index 82f05de12..812b7316f 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -27,7 +27,8 @@ struct ImportRecord {
27}; 27};
28 28
29struct Module { 29struct Module {
30 std::string name; 30 std::string name; // UTF-8 basename for diagnostics and traces, not a lookup key
31 std::string narrow_key; // legacy lower-case narrow basename; empty when it cannot round-trip
31 std::filesystem::path path; 32 std::filesystem::path path;
32 uint8_t* base = nullptr; 33 uint8_t* base = nullptr;
33 uint64_t preferred_base = 0; 34 uint64_t preferred_base = 0;
@@ -122,7 +123,8 @@ public:
122private: 123private:
123 void initialise(Module& m); 124 void initialise(Module& m);
124 static void set_initialised(Module& m, bool value); 125 static void set_initialised(Module& m, bool value);
125 Module& map_image(const std::filesystem::path& path); 126 Module* find_narrow_module(const std::string& dll_lower) const; // caller holds mutex_
127 Module& map_image(const std::filesystem::path& path, const std::string& narrow_key);
126 void initialize_tls(Module& m); 128 void initialize_tls(Module& m);
127 void bind_imports(Module& m); 129 void bind_imports(Module& m);
128 void* resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal); 130 void* resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal);
@@ -133,7 +135,7 @@ private:
133 135
134 mutable std::recursive_mutex mutex_; 136 mutable std::recursive_mutex mutex_;
135 std::filesystem::path game_dir_; 137 std::filesystem::path game_dir_;
136 std::map<std::string, Module*> by_name_; // lower-case file name 138 std::map<std::filesystem::path::string_type, Module*> by_name_; // native basename, ASCII case folded
137 std::vector<Module*> order_; // mapping order; owns the modules 139 std::vector<Module*> order_; // mapping order; owns the modules
138 std::vector<Module*> init_order_; // dependencies first, see initialisation_order() 140 std::vector<Module*> init_order_; // dependencies first, see initialisation_order()
139 141
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h
index e7dd50fe6..3148d0ad1 100644
--- a/runtime/src/queue_families.h
+++ b/runtime/src/queue_families.h
@@ -5,7 +5,9 @@
5 5
6#include <vulkan/vulkan.h> 6#include <vulkan/vulkan.h>
7 7
8#include <cstddef>
8#include <cstdint> 9#include <cstdint>
10#include <initializer_list>
9#include <span> 11#include <span>
10 12
11namespace leonida { 13namespace leonida {
@@ -65,4 +67,30 @@ inline QueueFamilies sparse_capable_queue_families(std::span<const VkQueueFamily
65 return chosen; 67 return chosen;
66} 68}
67 69
70// Which VkQueue a new D3D12 queue runs on. `pools` are its candidate VkQueues in order of preference (a COMPUTE or
71// COPY queue's own family first, then the graphics family); each entry counts the live D3D12 queues on that VkQueue.
72// An unused VkQueue comes first, in pool order, so a GPU with enough queues keeps one VkQueue per live D3D12 queue
73// (D3D-97). With none unused, the VkQueue with the fewest D3D12 queues is shared, the earliest on a tie: the D3D12
74// queues on it then run one after the other, in the order their batches reach it (docs/d3d12_vulkan.md 4.4).
75// `pool` is SIZE_MAX when every pool is empty.
76struct QueueSlot {
77 std::size_t pool = SIZE_MAX;
78 std::size_t index = 0;
79};
80
81inline QueueSlot pick_queue_slot(std::initializer_list<std::span<const std::uint32_t>> pools) {
82 QueueSlot chosen; // the first VkQueue with the fewest users: an unused one whenever there is one
83 std::uint32_t fewest = UINT32_MAX;
84 std::size_t p = 0;
85 for (const auto users : pools) {
86 for (std::size_t i = 0; i < users.size(); ++i)
87 if (users[i] < fewest) {
88 fewest = users[i];
89 chosen = {p, i};
90 }
91 ++p;
92 }
93 return chosen;
94}
95
68} // namespace leonida 96} // namespace leonida
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 4cc35d58a..c4cba63af 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -714,6 +714,10 @@ struct ShaderEntry {
714 // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a 714 // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a
715 // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). 715 // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers).
716 std::vector<std::array<std::uint32_t, 4>> literal_samplers; 716 std::vector<std::array<std::uint32_t, 4>> literal_samplers;
717 // Mesh shaders: the output array sizes the SPIR-V declares (OutputVertices / OutputPrimitivesEXT), checked
718 // against the device's maxMeshOutputVertices / maxMeshOutputPrimitives when a pipeline is created. 0: not given.
719 std::uint32_t max_vertices = 0;
720 std::uint32_t max_primitives = 0;
717}; 721};
718 722
719class ShaderLibrary { 723class ShaderLibrary {
@@ -907,6 +911,8 @@ private:
907 e.literal_samplers.push_back(words); 911 e.literal_samplers.push_back(words);
908 } 912 }
909 } 913 }
914 e.max_vertices = u32(meta.find("max_vertices"));
915 e.max_primitives = u32(meta.find("max_primitives"));
910 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 916 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
911 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 917 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
912 if (by_fspx && prefix == "fspx/") ++fspx_count_; 918 if (by_fspx && prefix == "fspx/") ++fspx_count_;
diff --git a/runtime/src/statistics_sum.comp b/runtime/src/statistics_sum.comp
index e4e2ce13c..c4960347c 100644
--- a/runtime/src/statistics_sum.comp
+++ b/runtime/src/statistics_sum.comp
@@ -2,18 +2,23 @@
2 2
3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one 3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one
4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. 4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order.
5// `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only clipping, fragment and
6// compute: they are copied to counters 5..8 of their record, so CSInvocations sits at 8 and the input-assembly,
7// vertex, geometry and tessellation counters (0..4, 8 and 9 of the D3D12 order) add nothing.
5layout(local_size_x = 11) in; 8layout(local_size_x = 11) in;
6layout(set = 0, binding = 0, std430) buffer QueryResults { 9layout(set = 0, binding = 0, std430) buffer QueryResults {
7 uvec2 total[11]; 10 uvec2 total[11];
8 uvec2 segments[]; // `count` results of 11 counters each 11 uvec2 segments[]; // `count` results of 11 counters each
9}; 12};
10layout(push_constant) uniform ResolveRange { uint count; }; 13layout(push_constant) uniform ResolveRange { uint count; uint mesh; };
11 14
12void main() { 15void main() {
13 const uint counter = gl_LocalInvocationID.x; 16 const uint counter = gl_LocalInvocationID.x;
14 uvec2 sum = total[counter]; 17 uvec2 sum = total[counter];
15 for (uint i = 0; i < count; ++i) { 18 const bool counted = mesh == 0u || (counter >= 5u && counter <= 7u) || counter == 10u;
16 uvec2 segment = segments[i * 11 + counter]; 19 const uint source = mesh != 0u && counter == 10u ? 8u : counter;
20 for (uint i = 0; counted && i < count; ++i) {
21 uvec2 segment = segments[i * 11 + source];
17 uint low = sum.x + segment.x; 22 uint low = sum.x + segment.x;
18 sum.y += segment.y + uint(low < sum.x); 23 sum.y += segment.y + uint(low < sum.x);
19 sum.x = low; 24 sum.x = low;
diff --git a/runtime/src/statistics_sum_spirv.h b/runtime/src/statistics_sum_spirv.h
index d3c0709a5..9c67f0429 100644
--- a/runtime/src/statistics_sum_spirv.h
+++ b/runtime/src/statistics_sum_spirv.h
@@ -7,47 +7,63 @@ namespace leonida {
7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, 7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0,
8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. 8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time.
9inline constexpr std::uint32_t statistics_sum_spirv[] = { 9inline constexpr std::uint32_t statistics_sum_spirv[] = {
10 0x07230203, 0x00010000, 0x0008000b, 0x0000005e, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 10 0x07230203, 0x00010000, 0x0008000b, 0x00000080, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, 12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004,
13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, 13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b,
14 0x00040047, 0x00000014, 0x00000006, 0x00000008, 0x00040047, 0x00000015, 0x00000006, 0x00000008, 14 0x00040047, 0x00000014, 0x00000006, 0x00000008, 0x00040047, 0x00000015, 0x00000006, 0x00000008,
15 0x00030047, 0x00000016, 0x00000003, 0x00050048, 0x00000016, 0x00000000, 0x00000023, 0x00000000, 15 0x00030047, 0x00000016, 0x00000003, 0x00050048, 0x00000016, 0x00000000, 0x00000023, 0x00000000,
16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, 16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021,
17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000026, 0x00000002, 17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002,
18 0x00050048, 0x00000026, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000050, 0x0000000b, 18 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001,
19 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 19 0x00000023, 0x00000004, 0x00040047, 0x00000072, 0x0000000b, 0x00000019, 0x00020013, 0x00000002,
20 0x00000020, 0x00000000, 0x00040017, 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 20 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017,
21 0x00000001, 0x00000009, 0x0004003b, 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 21 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b,
22 0x0000000c, 0x00000000, 0x00040020, 0x0000000d, 0x00000001, 0x00000006, 0x00040017, 0x00000010, 22 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020,
23 0x00000006, 0x00000002, 0x0004002b, 0x00000006, 0x00000013, 0x0000000b, 0x0004001c, 0x00000014, 23 0x0000000d, 0x00000001, 0x00000006, 0x00040017, 0x00000010, 0x00000006, 0x00000002, 0x0004002b,
24 0x00000010, 0x00000013, 0x0003001d, 0x00000015, 0x00000010, 0x0004001e, 0x00000016, 0x00000014, 24 0x00000006, 0x00000013, 0x0000000b, 0x0004001c, 0x00000014, 0x00000010, 0x00000013, 0x0003001d,
25 0x00000015, 0x00040020, 0x00000017, 0x00000002, 0x00000016, 0x0004003b, 0x00000017, 0x00000018, 25 0x00000015, 0x00000010, 0x0004001e, 0x00000016, 0x00000014, 0x00000015, 0x00040020, 0x00000017,
26 0x00000002, 0x00040015, 0x00000019, 0x00000020, 0x00000001, 0x0004002b, 0x00000019, 0x0000001a, 26 0x00000002, 0x00000016, 0x0004003b, 0x00000017, 0x00000018, 0x00000002, 0x00040015, 0x00000019,
27 0x00000000, 0x00040020, 0x0000001c, 0x00000002, 0x00000010, 0x0003001e, 0x00000026, 0x00000006, 27 0x00000020, 0x00000001, 0x0004002b, 0x00000019, 0x0000001a, 0x00000000, 0x00040020, 0x0000001c,
28 0x00040020, 0x00000027, 0x00000009, 0x00000026, 0x0004003b, 0x00000027, 0x00000028, 0x00000009, 28 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006,
29 0x00040020, 0x00000029, 0x00000009, 0x00000006, 0x00020014, 0x0000002c, 0x0004002b, 0x00000019, 29 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009,
30 0x0000002f, 0x00000001, 0x0004002b, 0x00000006, 0x0000003c, 0x00000001, 0x0006002c, 0x00000009, 30 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006,
31 0x00000050, 0x00000013, 0x0000003c, 0x0000003c, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 31 0x0004002b, 0x00000006, 0x0000002e, 0x00000005, 0x0004002b, 0x00000006, 0x00000031, 0x00000007,
32 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 32 0x0004002b, 0x00000006, 0x00000036, 0x0000000a, 0x0004002b, 0x00000006, 0x00000040, 0x00000008,
33 0x0004003d, 0x00000006, 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 33 0x0004002b, 0x00000006, 0x0000005e, 0x00000001, 0x0006002c, 0x00000009, 0x00000072, 0x00000013,
34 0x0000001a, 0x0000000f, 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x000200f9, 0x00000020, 34 0x0000005e, 0x0000005e, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8,
35 0x000200f8, 0x00000020, 0x000700f5, 0x00000010, 0x0000005c, 0x0000001e, 0x00000005, 0x0000005d, 35 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006,
36 0x00000021, 0x000700f5, 0x00000006, 0x00000051, 0x0000000c, 0x00000005, 0x0000004c, 0x00000021, 36 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f,
37 0x00050041, 0x00000029, 0x0000002a, 0x00000028, 0x0000001a, 0x0004003d, 0x00000006, 0x0000002b, 37 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024,
38 0x0000002a, 0x000500b0, 0x0000002c, 0x0000002d, 0x00000051, 0x0000002b, 0x000400f6, 0x00000022, 38 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029,
39 0x00000021, 0x00000000, 0x000400fa, 0x0000002d, 0x00000021, 0x00000022, 0x000200f8, 0x00000021, 39 0x00000028, 0x0000000c, 0x000400a8, 0x0000001f, 0x0000002a, 0x00000029, 0x000300f7, 0x0000002c,
40 0x00050084, 0x00000006, 0x00000031, 0x00000051, 0x00000013, 0x00050080, 0x00000006, 0x00000033, 40 0x00000000, 0x000400fa, 0x0000002a, 0x0000002b, 0x0000002c, 0x000200f8, 0x0000002b, 0x000500ae,
41 0x00000031, 0x0000000f, 0x00060041, 0x0000001c, 0x00000034, 0x00000018, 0x0000002f, 0x00000033, 41 0x0000001f, 0x0000002f, 0x0000000f, 0x0000002e, 0x000500b2, 0x0000001f, 0x00000032, 0x0000000f,
42 0x0004003d, 0x00000010, 0x00000035, 0x00000034, 0x00050051, 0x00000006, 0x00000038, 0x0000005c, 42 0x00000031, 0x000500a7, 0x0000001f, 0x00000033, 0x0000002f, 0x00000032, 0x000200f9, 0x0000002c,
43 0x00000000, 0x00050051, 0x00000006, 0x0000003a, 0x00000035, 0x00000000, 0x00050080, 0x00000006, 43 0x000200f8, 0x0000002c, 0x000700f5, 0x0000001f, 0x00000034, 0x00000029, 0x00000005, 0x00000033,
44 0x0000003b, 0x00000038, 0x0000003a, 0x00050051, 0x00000006, 0x0000003e, 0x00000035, 0x00000001, 44 0x0000002b, 0x000500aa, 0x0000001f, 0x00000037, 0x0000000f, 0x00000036, 0x000500a6, 0x0000001f,
45 0x000500b0, 0x0000002c, 0x00000042, 0x0000003b, 0x00000038, 0x000600a9, 0x00000006, 0x00000043, 45 0x00000038, 0x00000034, 0x00000037, 0x000500ab, 0x0000001f, 0x0000003c, 0x00000028, 0x0000000c,
46 0x00000042, 0x0000003c, 0x0000000c, 0x00050080, 0x00000006, 0x00000044, 0x0000003e, 0x00000043, 46 0x000500a7, 0x0000001f, 0x0000003f, 0x0000003c, 0x00000037, 0x000600a9, 0x00000006, 0x00000042,
47 0x00050051, 0x00000006, 0x00000046, 0x0000005c, 0x00000001, 0x00050080, 0x00000006, 0x00000047, 47 0x0000003f, 0x00000040, 0x0000000f, 0x000200f9, 0x00000044, 0x000200f8, 0x00000044, 0x000700f5,
48 0x00000046, 0x00000044, 0x00050050, 0x00000010, 0x0000005d, 0x0000003b, 0x00000047, 0x00050080, 48 0x00000010, 0x0000007f, 0x0000001e, 0x0000002c, 0x0000007c, 0x00000045, 0x000700f5, 0x00000006,
49 0x00000006, 0x0000004c, 0x00000051, 0x0000002f, 0x000200f9, 0x00000020, 0x000200f8, 0x00000022, 49 0x0000007d, 0x0000000c, 0x0000002c, 0x0000006e, 0x00000045, 0x000400f6, 0x00000046, 0x00000045,
50 0x0003003e, 0x0000001d, 0x0000005c, 0x000100fd, 0x00010038, 50 0x00000000, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000300f7, 0x0000004b, 0x00000000,
51 0x000400fa, 0x00000038, 0x0000004a, 0x0000004b, 0x000200f8, 0x0000004a, 0x00050041, 0x00000026,
52 0x0000004d, 0x00000024, 0x0000001a, 0x0004003d, 0x00000006, 0x0000004e, 0x0000004d, 0x000500b0,
53 0x0000001f, 0x0000004f, 0x0000007d, 0x0000004e, 0x000200f9, 0x0000004b, 0x000200f8, 0x0000004b,
54 0x000700f5, 0x0000001f, 0x00000050, 0x00000038, 0x00000048, 0x0000004f, 0x0000004a, 0x000400fa,
55 0x00000050, 0x00000045, 0x00000046, 0x000200f8, 0x00000045, 0x00050084, 0x00000006, 0x00000053,
56 0x0000007d, 0x00000013, 0x00050080, 0x00000006, 0x00000055, 0x00000053, 0x00000042, 0x00060041,
57 0x0000001c, 0x00000056, 0x00000018, 0x00000025, 0x00000055, 0x0004003d, 0x00000010, 0x00000057,
58 0x00000056, 0x00050051, 0x00000006, 0x0000005a, 0x0000007f, 0x00000000, 0x00050051, 0x00000006,
59 0x0000005c, 0x00000057, 0x00000000, 0x00050080, 0x00000006, 0x0000005d, 0x0000005a, 0x0000005c,
60 0x00050051, 0x00000006, 0x00000060, 0x00000057, 0x00000001, 0x000500b0, 0x0000001f, 0x00000064,
61 0x0000005d, 0x0000005a, 0x000600a9, 0x00000006, 0x00000065, 0x00000064, 0x0000005e, 0x0000000c,
62 0x00050080, 0x00000006, 0x00000066, 0x00000060, 0x00000065, 0x00050051, 0x00000006, 0x00000068,
63 0x0000007f, 0x00000001, 0x00050080, 0x00000006, 0x00000069, 0x00000068, 0x00000066, 0x00050050,
64 0x00000010, 0x0000007c, 0x0000005d, 0x00000069, 0x00050080, 0x00000006, 0x0000006e, 0x0000007d,
65 0x00000025, 0x000200f9, 0x00000044, 0x000200f8, 0x00000046, 0x0003003e, 0x0000001d, 0x0000007f,
66 0x000100fd, 0x00010038,
51}; 67};
52 68
53} // namespace leonida 69} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index dc042bf73..e659a762d 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -96,16 +96,17 @@ struct VulkanDeviceFunctions {
96 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 96 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
97 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 97 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
98 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ 98 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \
99 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) \ 99 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \
100 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 100 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
101 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 101 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)
102#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 102#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
103 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 103 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
104#undef LEONIDA_VK_MEMBER 104#undef LEONIDA_VK_MEMBER
105 105
106 // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering) when the 106 // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering, mesh
107 // extension is not enabled, and the query functions are optional (a list that uses queries without them is 107 // shaders) when the extension is not enabled, and the query functions are optional (a list that uses queries
108 // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results. 108 // without them is unsupported). The compute and descriptor functions are needed for normalized or summed
109 // occlusion results.
109 bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { 110 bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) {
110#define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(leonida::device_proc_or_khr(get, device, #name)); 111#define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(leonida::device_proc_or_khr(get, device, #name));
111 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) 112 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD)
@@ -211,7 +212,8 @@ public:
211 write.pBufferInfo = &storage; 212 write.pBufferInfo = &storage;
212 vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr); 213 vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr);
213 214
214 const VkPushConstantRange count{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(std::uint32_t)}; 215 // The count, and for statistics_sum.comp whether the segments are mesh-pool results.
216 const VkPushConstantRange count{VK_SHADER_STAGE_COMPUTE_BIT, 0, 2 * sizeof(std::uint32_t)};
215 VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 217 VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
216 layout.setLayoutCount = 1; 218 layout.setLayoutCount = 1;
217 layout.pSetLayouts = &set_layout_; 219 layout.pSetLayouts = &set_layout_;
@@ -231,21 +233,28 @@ public:
231 create_pipeline(statistics_sum_spirv, statistics_pipeline_)); 233 create_pipeline(statistics_sum_spirv, statistics_pipeline_));
232 } 234 }
233 235
234 // Adds `count` pipeline-statistics results (11 counters each) into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at 236 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the
235 // dst + offset: the segments of a statistics query that was split around helper dispatches (D3D-162). 237 // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291).
236 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, 238 // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see
237 VkBuffer dst, VkDeviceSize offset) const { 239 // statistics_sum.comp), otherwise in `queries` (all eleven).
240 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh,
241 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const {
238 constexpr VkDeviceSize result = statistics_counters * word_size; 242 constexpr VkDeviceSize result = statistics_counters * word_size;
243 constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes
239 begin_scratch_write(cb); 244 begin_scratch_write(cb);
240 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); 245 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0);
241 bind(cb, statistics_pipeline_); 246 bind(cb, statistics_pipeline_);
242 while (count) { 247 while (count) {
243 const auto chunk = std::min(count, statistics_capacity); 248 const bool in_mesh = mesh && mesh[first];
244 vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, result, result, 249 std::uint32_t chunk = 1;
250 while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh)
251 ++chunk;
252 vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_,
253 result + (in_mesh ? mesh_slot : 0), result,
245 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); 254 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
246 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, 255 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT,
247 shader_access); 256 shader_access);
248 dispatch(cb, chunk, 1); 257 dispatch(cb, chunk, 1, in_mesh);
249 first += chunk; 258 first += chunk;
250 count -= chunk; 259 count -= chunk;
251 if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); 260 if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT);
@@ -339,8 +348,9 @@ private:
339 vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr); 348 vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr);
340 } 349 }
341 350
342 void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups) const { 351 void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups, bool mesh = false) const {
343 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(chunk), &chunk); 352 const std::uint32_t range[2] = {chunk, mesh ? 1u : 0u};
353 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(range), range);
344 vk_.vkCmdDispatch(cb, groups, 1, 1); 354 vk_.vkCmdDispatch(cb, groups, 1, 1);
345 } 355 }
346 356
@@ -956,6 +966,7 @@ public:
956 replay_.set_stencil_reference = vk.vkCmdSetStencilReference; 966 replay_.set_stencil_reference = vk.vkCmdSetStencilReference;
957 replay_.set_blend_constants = vk.vkCmdSetBlendConstants; 967 replay_.set_blend_constants = vk.vkCmdSetBlendConstants;
958 replay_.draw = vk.vkCmdDraw; 968 replay_.draw = vk.vkCmdDraw;
969 replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled
959 replay_.draw_indexed = vk.vkCmdDrawIndexed; 970 replay_.draw_indexed = vk.vkCmdDrawIndexed;
960 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { 971 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* {
961 const auto it = graphics_pipelines_.find(id); 972 const auto it = graphics_pipelines_.find(id);
@@ -2276,9 +2287,10 @@ private:
2276 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2287 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
2277 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 2288 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
2278 }; 2289 };
2279 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 2290 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
2280 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2291 const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count,
2281 occlusion_resolve_->sum_statistics(cb, pool, first, count, dst, offset); 2292 VkBuffer dst, VkDeviceSize offset) {
2293 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset);
2282 }; 2294 };
2283 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 2295 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
2284 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2296 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
@@ -2314,10 +2326,31 @@ private:
2314 }; 2326 };
2315 std::shared_ptr<OcclusionSegmentPool> physical, statistics; 2327 std::shared_ptr<OcclusionSegmentPool> physical, statistics;
2316 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; 2328 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported;
2317 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before. 2329 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before
2318 if (statistics_segments && can_resolve_occlusion && 2330 // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then).
2319 !segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) 2331 if (statistics_segments && can_resolve_occlusion) {
2320 return ReplayResult::unsupported; 2332 if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics))
2333 return ReplayResult::unsupported;
2334 for (const auto& list : prepared)
2335 statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(),
2336 list.statistics_mesh.end());
2337 if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) {
2338 statistics->mesh.clear();
2339 } else {
2340 // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping
2341 // invocations and primitives, fragment and compute invocations (D3D-291).
2342 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
2343 info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS;
2344 info.queryCount = statistics_segments;
2345 info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT |
2346 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
2347 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
2348 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
2349 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) !=
2350 VK_SUCCESS)
2351 return ReplayResult::unsupported;
2352 }
2353 }
2321 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after 2354 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after
2322 // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues 2355 // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues
2323 // see submission-order query state and remove_query_pool() waits until commit finishes. 2356 // see submission-order query state and remove_query_pool() waits until commit finishes.
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index b2f5894de..8644346c5 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -109,9 +109,11 @@ public:
109 VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance, 109 VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance,
110 VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface, 110 VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface,
111 bool swapchain_maintenance1 = false, 111 bool swapchain_maintenance1 = false,
112 std::function<VkExtent2D()> extent_fn = nullptr) 112 std::function<VkExtent2D()> extent_fn = nullptr,
113 std::function<VkSurfaceKHR()> recreate_surface_fn = nullptr)
113 : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface), 114 : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface),
114 maintenance1_(swapchain_maintenance1), extent_fn_(std::move(extent_fn)) { 115 maintenance1_(swapchain_maintenance1), extent_fn_(std::move(extent_fn)),
116 recreate_surface_fn_(std::move(recreate_surface_fn)) {
115#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast<PFN_##name>(get_instance(instance, #name)); 117#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast<PFN_##name>(get_instance(instance, #name));
116 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR) 118 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR)
117 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) 119 LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)
@@ -421,6 +423,18 @@ private:
421 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { 423 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
422 last_tore_ = false; 424 last_tore_ = false;
423 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 425 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
426 if (surface_lost_) { // the window's display went away under a presented swapchain
427 // Try to make a new surface for the same window (the hwnd is retained by the factory's callback).
428 // Until that succeeds, vkd3d's precedent keeps rendering to nothing: the frame is not shown, but
429 // the run continues instead of wedging on a sticky E_FAIL.
430 surface_ = recreate_surface_fn_ ? recreate_surface_fn_() : VK_NULL_HANDLE;
431 if (!surface_) {
432 captured_ = false; // nothing was shown: read_back() must not hand out the frame
433 return VK_SUCCESS;
434 }
435 surface_lost_ = false;
436 stale_ = true; // the old swapchain is gone: rebuild on the new surface below
437 }
424 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank 438 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank
425 // frame keeps whatever the swapchain has (black is black), except that a blit needs the SDR one. 439 // frame keeps whatever the swapchain has (black is black), except that a blit needs the SDR one.
426 bool want_hdr = swapchain_hdr_req_; 440 bool want_hdr = swapchain_hdr_req_;
@@ -458,6 +472,11 @@ private:
458 } 472 }
459 acquired = acquire(frame.acquired, &image); 473 acquired = acquire(frame.acquired, &image);
460 } 474 }
475 if (acquired == VK_ERROR_SURFACE_LOST_KHR) {
476 captured_ = false; // nothing was acquired, nothing was shown
477 mark_surface_lost();
478 return VK_SUCCESS;
479 }
461 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired 480 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired
462 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; 481 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true;
463 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it. 482 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it.
@@ -576,6 +595,13 @@ private:
576 captured_extent_ = extent_; 595 captured_extent_ = extent_;
577 captured_format_ = format_; 596 captured_format_ = format_;
578 } 597 }
598 if (result == VK_ERROR_SURFACE_LOST_KHR) {
599 // The surface was lost during the present (display disconnected, a driver reset of the window's
600 // plane): vkd3d keeps rendering to nothing, and the next present recreates surface and swapchain.
601 captured_ = false;
602 mark_surface_lost();
603 result = VK_SUCCESS;
604 }
579 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { 605 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) {
580 stale_ = true; 606 stale_ = true;
581 result = VK_SUCCESS; 607 result = VK_SUCCESS;
@@ -635,6 +661,25 @@ private:
635 return failure; 661 return failure;
636 } 662 }
637 663
664 // The window's surface is dead (VK_ERROR_SURFACE_LOST_KHR): the swapchain that presented into it is retired
665 // and the surface destroyed. The next submit_now() first tries the factory's recreate-surface callback; until
666 // it succeeds the presenter keeps the vkd3d "render to nothing" behaviour, not a sticky failure.
667 void mark_surface_lost() {
668 auto& vk = context_.vk;
669 const VkDevice device = context_.device();
670 {
671 std::lock_guard lock(context_.submit_mutex());
672 vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use
673 release(swapchain_);
674 }
675 swapchain_ = VK_NULL_HANDLE;
676 if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr);
677 surface_ = VK_NULL_HANDLE;
678 surface_lost_ = true;
679 stale_ = true;
680 captured_ = false;
681 }
682
638 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image, 683 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image,
639 const PresentRect* source_rect) { 684 const PresentRect* source_rect) {
640 auto& vk = context_.vk; 685 auto& vk = context_.vk;
@@ -1250,6 +1295,8 @@ private:
1250 std::unique_ptr<PresentComposer> composer_; 1295 std::unique_ptr<PresentComposer> composer_;
1251 std::function<bool()> abort_; 1296 std::function<bool()> abort_;
1252 std::function<VkExtent2D()> extent_fn_; 1297 std::function<VkExtent2D()> extent_fn_;
1298 std::function<VkSurfaceKHR()> recreate_surface_fn_; // makes a new Win32 surface for the same window
1299 bool surface_lost_ = false; // set by mark_surface_lost(); cleared once a new surface was created
1253 std::map<VkFormat, VkFormatFeatureFlags> features_; 1300 std::map<VkFormat, VkFormatFeatureFlags> features_;
1254 bool warned_srgb_ = false; 1301 bool warned_srgb_ = false;
1255 bool capture_ = false; 1302 bool capture_ = false;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 49efd399d..1e0e598c7 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -709,11 +709,18 @@ struct OcclusionSegmentPool {
709 VkDevice device = VK_NULL_HANDLE; 709 VkDevice device = VK_NULL_HANDLE;
710 PFN_vkDestroyQueryPool destroy = nullptr; 710 PFN_vkDestroyQueryPool destroy = nullptr;
711 VkQueryPool pool = VK_NULL_HANDLE; 711 VkQueryPool pool = VK_NULL_HANDLE;
712 // Pipeline-statistics segments only: a second pool with the counters a mesh draw allows (D3D-291), and for each
713 // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw.
714 VkQueryPool mesh_pool = VK_NULL_HANDLE;
715 std::vector<std::uint8_t> mesh;
712 716
713 OcclusionSegmentPool() = default; 717 OcclusionSegmentPool() = default;
714 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; 718 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete;
715 OcclusionSegmentPool& operator=(const OcclusionSegmentPool&) = delete; 719 OcclusionSegmentPool& operator=(const OcclusionSegmentPool&) = delete;
716 ~OcclusionSegmentPool() { if (pool) destroy(device, pool, nullptr); } 720 ~OcclusionSegmentPool() {
721 if (pool) destroy(device, pool, nullptr);
722 if (mesh_pool) destroy(device, mesh_pool, nullptr);
723 }
717}; 724};
718 725
719struct OcclusionResult { 726struct OcclusionResult {
@@ -758,6 +765,7 @@ struct GraphicsPipeline {
758 std::uint32_t vertex_slots = 0; // bit per input slot the input layout uses 765 std::uint32_t vertex_slots = 0; // bit per input slot the input layout uses
759 std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time 766 std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time
760 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) 767 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF)
768 bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only
761 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots 769 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots
762 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth 770 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth
763 // and stencil. Null when it cannot be built. 771 // and stencil. Null when it cannot be built.
@@ -788,6 +796,7 @@ enum class ReplayResult {
788 invalid_predication, 796 invalid_predication,
789 invalid_query, 797 invalid_query,
790 invalid_indirect_arguments, 798 invalid_indirect_arguments,
799 invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has
791 unsupported 800 unsupported
792}; 801};
793 802
@@ -843,6 +852,7 @@ struct ReplayFunctions {
843 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; 852 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr;
844 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; 853 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr;
845 PFN_vkCmdDraw draw = nullptr; 854 PFN_vkCmdDraw draw = nullptr;
855 PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported
846 PFN_vkCmdDrawIndexed draw_indexed = nullptr; 856 PFN_vkCmdDrawIndexed draw_indexed = nullptr;
847 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline; 857 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline;
848 // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is 858 // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is
@@ -861,9 +871,11 @@ struct ReplayFunctions {
861 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 871 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
862 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; 872 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion;
863 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional 873 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional
864 // rendering: the segments of a statistics query split around resolves (D3D-162). 874 // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291).
865 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 875 // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is).
866 VkBuffer dst, VkDeviceSize offset)> sum_statistics; 876 std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, const std::uint8_t* mesh,
877 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset)>
878 sum_statistics;
867 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional 879 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional
868 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). 880 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252).
869 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 881 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
@@ -937,6 +949,9 @@ struct QueryResolveRun {
937 std::uint32_t count = 0; 949 std::uint32_t count = 0;
938 VkDeviceSize offset = 0; 950 VkDeviceSize offset = 0;
939 bool sum = false; 951 bool sum = false;
952 // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh).
953 VkQueryPool mesh_pool = VK_NULL_HANDLE;
954 const std::uint8_t* mesh = nullptr;
940}; 955};
941 956
942struct PreparedQuery { 957struct PreparedQuery {
@@ -958,7 +973,8 @@ struct PreparedQuery {
958}; 973};
959 974
960struct Prepared { 975struct Prepared {
961 // Helper commands split the active statistics query just like query resolves. 976 // Helper commands split the active statistics query just like query resolves, and so does a draw whose kind (mesh
977 // or vertex) differs from the draws before it in the current segment (plan_statistics_segments, D3D-291).
962 std::uint32_t statistics_end = PreparedQuery::no_segment; 978 std::uint32_t statistics_end = PreparedQuery::no_segment;
963 std::uint32_t statistics_begin = PreparedQuery::no_segment; 979 std::uint32_t statistics_begin = PreparedQuery::no_segment;
964 PredicateCapture predicate; 980 PredicateCapture predicate;
@@ -2068,6 +2084,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2068 return ReplayResult::unsupported; 2084 return ReplayResult::unsupported;
2069 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); 2085 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline);
2070 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 2086 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource;
2087 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw;
2088 if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported;
2071 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 2089 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
2072 if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; 2090 if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported;
2073 p.graphics = pipeline; 2091 p.graphics = pipeline;
@@ -2262,6 +2280,9 @@ public:
2262 // The list's statistics queries overlap (D3D-252): without a statistics pool they cannot run whole, because 2280 // The list's statistics queries overlap (D3D-252): without a statistics pool they cannot run whole, because
2263 // two Vulkan queries of one type may not be active at once; QueryReplay::plan refuses such a list. 2281 // two Vulkan queries of one type may not be active at once; QueryReplay::plan refuses such a list.
2264 bool statistics_overlaps = false; 2282 bool statistics_overlaps = false;
2283 // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291).
2284 std::vector<std::uint8_t> statistics_mesh;
2285 VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE;
2265 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them 2286 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them
2266 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run 2287 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run
2267 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. 2288 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it.
@@ -2305,37 +2326,74 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
2305// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and 2326// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and
2306// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements 2327// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements
2307// depend on heap state at planning time, so every non-timestamp resolve splits conservatively. 2328// depend on heap state at planning time, so every non-timestamp resolve splits conservatively.
2329// A mesh draw cannot run while a query with the input-assembly, vertex, geometry or tessellation counters is active
2330// (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as 0. A query
2331// that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in the full pool
2332// or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of its own kind.
2333// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw
2334// has its own rendering scope, so a split before one stays outside rendering, as a helper's does.
2308inline void plan_statistics_segments(PreparedList& out) { 2335inline void plan_statistics_segments(PreparedList& out) {
2309 detail::PreparedQuery* begin = nullptr; 2336 detail::PreparedQuery* begin = nullptr;
2310 struct Split { std::uint32_t* end; std::uint32_t* begin; }; 2337 // A split point (a helper or a resolve), or a draw: kind 0 vertex, 1 mesh.
2311 std::vector<Split> inner; 2338 struct Event { std::uint32_t* end; std::uint32_t* begin; int kind; };
2339 std::vector<Event> inner;
2340 bool splits = false, mesh = false;
2312 std::size_t next_query = 0; 2341 std::size_t next_query = 0;
2342 const auto commands = out.list->commands();
2313 for (std::size_t i = 0; i < out.commands.size(); ++i) { 2343 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2314 auto& p = out.commands[i]; 2344 auto& p = out.commands[i];
2315 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || 2345 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2316 p.counted_dispatch.indirect)) 2346 p.counted_dispatch.indirect)) {
2317 inner.push_back({&p.statistics_end, &p.statistics_begin}); 2347 inner.push_back({&p.statistics_end, &p.statistics_begin, -1});
2348 splits = true;
2349 }
2350 if (begin) {
2351 int kind = -1;
2352 if (const auto* draw = std::get_if<Draw>(&commands[i])) kind = draw->mesh ? 1 : 0;
2353 else if (const auto* indirect = std::get_if<ExecuteIndirect>(&commands[i]))
2354 kind = indirect->kind == IndirectKind::dispatch ? -1 : 0;
2355 if (kind >= 0) inner.push_back({&p.statistics_end, &p.statistics_begin, kind});
2356 mesh |= kind == 1;
2357 }
2318 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; 2358 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue;
2319 auto& query = out.queries[next_query++]; 2359 auto& query = out.queries[next_query++];
2320 const Command& command = out.list->commands()[i]; 2360 const Command& command = commands[i];
2321 const auto range = query_range(command); 2361 const auto range = query_range(command);
2322 if (std::holds_alternative<ResolveQueries>(command)) { 2362 if (std::holds_alternative<ResolveQueries>(command)) {
2323 // A stream-output resolve only fills zeros (no dispatch), so it needs no split. 2363 // A stream-output resolve only fills zeros (no dispatch), so it needs no split.
2324 if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type)) 2364 if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type)) {
2325 inner.push_back({&query.statistics_end, &query.statistics_begin}); 2365 inner.push_back({&query.statistics_end, &query.statistics_begin, -1});
2366 splits = true;
2367 }
2326 } else if (range.type == d3d12_query::pipeline_statistics) { 2368 } else if (range.type == d3d12_query::pipeline_statistics) {
2327 if (std::holds_alternative<BeginQuery>(command)) { 2369 if (std::holds_alternative<BeginQuery>(command)) {
2328 begin = &query; 2370 begin = &query;
2329 inner.clear(); 2371 inner.clear();
2372 splits = mesh = false;
2330 } else if (begin) { 2373 } else if (begin) {
2331 if (!inner.empty()) { 2374 if (splits || mesh) {
2332 const std::uint32_t first = out.statistics_segment_count; 2375 const std::uint32_t first = out.statistics_segment_count;
2333 begin->statistics_begin = out.statistics_segment_count++; 2376 const auto open = [&] {
2334 for (auto split : inner) { 2377 out.statistics_mesh.push_back(0);
2335 *split.end = out.statistics_segment_count - 1; 2378 return out.statistics_segment_count++;
2336 *split.begin = out.statistics_segment_count++; 2379 };
2380 std::uint32_t current = begin->statistics_begin = open();
2381 int kind = -1; // of the current segment's draws, -1 before its first
2382 for (const auto& event : inner) {
2383 if (event.kind < 0) {
2384 *event.end = current;
2385 current = *event.begin = open();
2386 kind = -1;
2387 continue;
2388 }
2389 if (kind >= 0 && event.kind != kind) {
2390 *event.end = current;
2391 current = *event.begin = open();
2392 }
2393 kind = event.kind;
2394 out.statistics_mesh[current] = std::uint8_t(kind);
2337 } 2395 }
2338 query.statistics_end = out.statistics_segment_count - 1; 2396 query.statistics_end = current;
2339 query.statistics_first = first; 2397 query.statistics_first = first;
2340 query.statistics_count = out.statistics_segment_count - first; 2398 query.statistics_count = out.statistics_segment_count - first;
2341 } 2399 }
@@ -2355,6 +2413,14 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2355 std::map<std::pair<QueryHeapId, std::uint32_t>, std::uint32_t> active; 2413 std::map<std::pair<QueryHeapId, std::uint32_t>, std::uint32_t> active;
2356 std::uint32_t current = detail::PreparedQuery::no_segment; 2414 std::uint32_t current = detail::PreparedQuery::no_segment;
2357 std::size_t next_query = 0; 2415 std::size_t next_query = 0;
2416 // Each physical segment's draw kind (D3D-291): -1 before its first draw, 0 vertex, 1 mesh.
2417 int kind = -1;
2418 const auto open = [&] {
2419 out.statistics_mesh.push_back(0);
2420 kind = -1;
2421 return out.statistics_segment_count++;
2422 };
2423 const auto commands = out.list->commands();
2358 for (std::size_t i = 0; i < out.commands.size(); ++i) { 2424 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2359 auto& p = out.commands[i]; 2425 auto& p = out.commands[i];
2360 detail::PreparedQuery* query = nullptr; 2426 detail::PreparedQuery* query = nullptr;
@@ -2366,8 +2432,23 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2366 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || 2432 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2367 p.counted_dispatch.indirect)) { 2433 p.counted_dispatch.indirect)) {
2368 p.statistics_end = current; 2434 p.statistics_end = current;
2369 current = out.statistics_segment_count++; 2435 current = open();
2370 p.statistics_begin = current; 2436 p.statistics_begin = current;
2437 continue;
2438 }
2439 // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291).
2440 int draw = -1;
2441 if (const auto* d = std::get_if<Draw>(&commands[i])) draw = d->mesh ? 1 : 0;
2442 else if (const auto* indirect = std::get_if<ExecuteIndirect>(&commands[i]))
2443 draw = indirect->kind == IndirectKind::dispatch ? -1 : 0;
2444 if (!active.empty() && draw >= 0) {
2445 if (kind >= 0 && draw != kind) {
2446 p.statistics_end = current;
2447 current = open();
2448 p.statistics_begin = current;
2449 }
2450 kind = draw;
2451 out.statistics_mesh[current] = std::uint8_t(draw);
2371 } 2452 }
2372 continue; 2453 continue;
2373 } 2454 }
@@ -2391,11 +2472,11 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2391 } else { 2472 } else {
2392 if (current == detail::PreparedQuery::no_segment || range.type == d3d12_query::timestamp) continue; 2473 if (current == detail::PreparedQuery::no_segment || range.type == d3d12_query::timestamp) continue;
2393 query->statistics_end = current; 2474 query->statistics_end = current;
2394 current = out.statistics_segment_count++; 2475 current = open();
2395 query->statistics_begin = current; 2476 query->statistics_begin = current;
2396 continue; 2477 continue;
2397 } 2478 }
2398 current = active.empty() ? detail::PreparedQuery::no_segment : out.statistics_segment_count++; 2479 current = active.empty() ? detail::PreparedQuery::no_segment : open();
2399 query->statistics_begin = current; 2480 query->statistics_begin = current;
2400 } 2481 }
2401 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; 2482 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query;
@@ -2466,8 +2547,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2466 out.segment_pool = VK_NULL_HANDLE; 2547 out.segment_pool = VK_NULL_HANDLE;
2467 out.segment_base = out.segment_count = 0; 2548 out.segment_base = out.segment_count = 0;
2468 out.precise_segments = false; 2549 out.precise_segments = false;
2469 out.statistics_pool = VK_NULL_HANDLE; 2550 out.statistics_pool = out.statistics_mesh_pool = VK_NULL_HANDLE;
2470 out.statistics_base = out.statistics_segment_count = 0; 2551 out.statistics_base = out.statistics_segment_count = 0;
2552 out.statistics_mesh.clear();
2471 const bool rendering = vk.begin_rendering && vk.end_rendering && vk.clear_attachments && vk.image_view; 2553 const bool rendering = vk.begin_rendering && vk.end_rendering && vk.clear_attachments && vk.image_view;
2472 const bool copies = vk.copy_buffer && vk.copy_buffer_to_image && vk.copy_image_to_buffer && vk.copy_image; 2554 const bool copies = vk.copy_buffer && vk.copy_buffer_to_image && vk.copy_image_to_buffer && vk.copy_image;
2473 const bool conditional = vk.begin_conditional_rendering && vk.end_conditional_rendering; 2555 const bool conditional = vk.begin_conditional_rendering && vk.end_conditional_rendering;
@@ -3037,10 +3119,16 @@ public:
3037 list.segment_base = base; 3119 list.segment_base = base;
3038 } 3120 }
3039 if (list.statistics_segment_count) { 3121 if (list.statistics_segment_count) {
3040 if (statistics_pool) { 3122 const bool mesh = std::find(list.statistics_mesh.begin(), list.statistics_mesh.end(), 1) !=
3123 list.statistics_mesh.end();
3124 if (statistics_pool && (!mesh || statistics_pool->mesh_pool)) {
3041 retain(statistics_pool); 3125 retain(statistics_pool);
3042 list.statistics_pool = statistics_pool->pool; 3126 list.statistics_pool = statistics_pool->pool;
3127 list.statistics_mesh_pool = statistics_pool->mesh_pool;
3043 list.statistics_base = statistics_base; 3128 list.statistics_base = statistics_base;
3129 } else if (mesh) {
3130 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there.
3131 return ReplayResult::unsupported;
3044 } else if (list.statistics_overlaps) { 3132 } else if (list.statistics_overlaps) {
3045 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once. 3133 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once.
3046 return ReplayResult::unsupported; 3134 return ReplayResult::unsupported;
@@ -3087,7 +3175,14 @@ public:
3087 if (resolve.type != d3d12_query::occlusion && !binary && !statistics) 3175 if (resolve.type != d3d12_query::occlusion && !binary && !statistics)
3088 return ReplayResult::invalid_query; 3176 return ReplayResult::invalid_query;
3089 const auto& saved = value.occlusion; 3177 const auto& saved = value.occlusion;
3090 run = {saved.segments->pool, saved.first, saved.count, run.offset, saved.count > 1}; 3178 const std::uint8_t* kinds = saved.segments->mesh.empty() ? nullptr
3179 : saved.segments->mesh.data();
3180 // A mesh segment's four counters go through the sum to land in their D3D12 fields.
3181 const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count,
3182 std::uint8_t(1)) != kinds + saved.first + saved.count;
3183 run = {saved.segments->pool, saved.first, saved.count, run.offset,
3184 saved.count > 1 || any_mesh, saved.segments->mesh_pool, kinds};
3185 if (any_mesh && !statistics) return ReplayResult::invalid_query;
3091 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; 3186 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported;
3092 if (statistics) needs_statistics_sum |= run.sum; 3187 if (statistics) needs_statistics_sum |= run.sum;
3093 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true; 3188 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true;
@@ -3142,6 +3237,29 @@ private:
3142 std::map<std::pair<QueryPool*, std::uint32_t>, Value> pending_; 3237 std::map<std::pair<QueryPool*, std::uint32_t>, Value> pending_;
3143}; 3238};
3144 3239
3240namespace detail {
3241
3242// A physical pipeline-statistics segment (plan_statistics_segments), in the pool its kind needs.
3243inline VkQueryPool statistics_segment_pool(const PreparedList& list, std::uint32_t segment) {
3244 return list.statistics_mesh[segment] ? list.statistics_mesh_pool : list.statistics_pool;
3245}
3246
3247inline void end_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb,
3248 const ReplayFunctions& vk) {
3249 if (segment == PreparedQuery::no_segment) return;
3250 vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment);
3251}
3252
3253inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb,
3254 const ReplayFunctions& vk) {
3255 if (segment == PreparedQuery::no_segment) return;
3256 const auto pool = statistics_segment_pool(list, segment);
3257 vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1);
3258 vk.begin_query(cb, pool, list.statistics_base + segment, 0);
3259}
3260
3261} // namespace detail
3262
3145inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, 3263inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb,
3146 const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { 3264 const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) {
3147 constexpr auto none = detail::PreparedQuery::no_segment; 3265 constexpr auto none = detail::PreparedQuery::no_segment;
@@ -3155,16 +3273,8 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
3155 return; 3273 return;
3156 } 3274 }
3157 // A split pipeline-statistics query (plan_statistics_segments): its counters run in the physical segments. 3275 // A split pipeline-statistics query (plan_statistics_segments): its counters run in the physical segments.
3158 const auto end_statistics = [&] { 3276 const auto end_statistics = [&] { detail::end_statistics_segment(list, query.statistics_end, cb, vk); };
3159 if (query.statistics_end != none) 3277 const auto begin_statistics = [&] { detail::begin_statistics_segment(list, query.statistics_begin, cb, vk); };
3160 vk.end_query(cb, list.statistics_pool, list.statistics_base + query.statistics_end);
3161 };
3162 const auto begin_statistics = [&] {
3163 if (query.statistics_begin == none) return;
3164 const auto index = list.statistics_base + query.statistics_begin;
3165 vk.reset_query_pool(cb, list.statistics_pool, index, 1);
3166 vk.begin_query(cb, list.statistics_pool, index, 0);
3167 };
3168 const auto& command = list.list->commands()[query.command]; 3278 const auto& command = list.list->commands()[query.command];
3169 const QueryPool& heap = *query.heap; 3279 const QueryPool& heap = *query.heap;
3170 if (!std::holds_alternative<ResolveQueries>(command) && 3280 if (!std::holds_alternative<ResolveQueries>(command) &&
@@ -3206,7 +3316,7 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
3206 if (!run.pool) { 3316 if (!run.pool) {
3207 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); 3317 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0);
3208 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { 3318 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) {
3209 vk.sum_statistics(cb, run.pool, run.first, run.count, dst, run.offset); 3319 vk.sum_statistics(cb, run.pool, run.mesh_pool, run.mesh, run.first, run.count, dst, run.offset);
3210 } else if (run.sum && binary) { 3320 } else if (run.sum && binary) {
3211 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); 3321 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
3212 } else if (run.sum || binary) { 3322 } else if (run.sum || binary) {
@@ -3260,15 +3370,17 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3260 } 3370 }
3261 // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too. 3371 // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too.
3262 const auto end_statistics = [&] { 3372 const auto end_statistics = [&] {
3263 if (p.statistics_end != detail::PreparedQuery::no_segment) 3373 detail::end_statistics_segment(prepared, p.statistics_end, command_buffer, vk);
3264 vk.end_query(command_buffer, prepared.statistics_pool, prepared.statistics_base + p.statistics_end);
3265 }; 3374 };
3266 const auto begin_statistics = [&] { 3375 const auto begin_statistics = [&] {
3267 if (p.statistics_begin == detail::PreparedQuery::no_segment) return; 3376 detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk);
3268 const auto index = prepared.statistics_base + p.statistics_begin;
3269 vk.reset_query_pool(command_buffer, prepared.statistics_pool, index, 1);
3270 vk.begin_query(command_buffer, prepared.statistics_pool, index, 0);
3271 }; 3377 };
3378 // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the
3379 // draw's own rendering scope begins.
3380 if (std::holds_alternative<Draw>(command) || std::holds_alternative<ExecuteIndirect>(command)) {
3381 end_statistics();
3382 begin_statistics();
3383 }
3272 if (const auto* predication = std::get_if<Predication>(&command)) { 3384 if (const auto* predication = std::get_if<Predication>(&command)) {
3273 // Conditional rendering cannot nest, so a new predicate ends the previous one first. 3385 // Conditional rendering cannot nest, so a new predicate ends the previous one first.
3274 if (predicate.buffer) vk.end_conditional_rendering(command_buffer); 3386 if (predicate.buffer) vk.end_conditional_rendering(command_buffer);
@@ -3974,12 +4086,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3974 {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), 4086 {std::uint32_t(std::max(0, s.right - std::max(0, s.left))),
3975 std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; 4087 std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}};
3976 vk.set_scissor(command_buffer, 0, 1, &scissor); 4088 vk.set_scissor(command_buffer, 0, 1, &scissor);
3977 const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); 4089 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology
3978 vk.set_primitive_topology(command_buffer, topology); 4090 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065).
3979 const bool restart = draw->indexed && detail::strip_topology(topology) && 4091 if (!draw->mesh) {
3980 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || 4092 const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology);
3981 (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); 4093 vk.set_primitive_topology(command_buffer, topology);
3982 vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); 4094 const bool restart = draw->indexed && detail::strip_topology(topology) &&
4095 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) ||
4096 (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32));
4097 vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE);
4098 }
3983 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); 4099 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front);
3984 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); 4100 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back);
3985 vk.set_blend_constants(command_buffer, draw->blend_factor.data()); 4101 vk.set_blend_constants(command_buffer, draw->blend_factor.data());
@@ -3988,7 +4104,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3988 vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], 4104 vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot],
3989 &d.vertex_sizes[slot], &d.vertex_strides[slot]); 4105 &d.vertex_sizes[slot], &d.vertex_strides[slot]);
3990 } 4106 }
3991 if (draw->indexed) { 4107 if (draw->mesh) {
4108 vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first);
4109 } else if (draw->indexed) {
3992 vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); 4110 vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type);
3993 vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, 4111 vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex,
3994 draw->first_instance); 4112 draw->first_instance);