upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/test
diff options
context:
space:
mode:
authorNolan Cotter <186326284+NolanCotter@users.noreply.github.com>2026-11-22 20:39:59 -0700
committerNolan Cotter <186326284+NolanCotter@users.noreply.github.com>2026-11-22 20:39:59 -0700
commitfa5f26db8eafd2cc27f627b68c0a5a5949bcf2ff (patch)
treefc57e238be829295fc216dff89a6d93e64c16b50 /runtime/test
parent9b693ecd8a2f90799f6c47f8f06cf062feb9820c (diff)
parent7b7d73f890f9fbbf5967bbb694390bbc99e33ba6 (diff)
Merge origin/main: DXGI device fields coexist with the console-ABI device state
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/active_input_test.cpp236
-rw-r--r--runtime/test/buffer_va_index_test.cpp36
-rw-r--r--runtime/test/bvh_builder_test.cpp22
-rw-r--r--runtime/test/check_atexit.cmake71
-rw-r--r--runtime/test/check_sparse_queue_family.py117
-rw-r--r--runtime/test/check_tiny_frame.py124
-rw-r--r--runtime/test/command_list_test.cpp2
-rw-r--r--runtime/test/cpp_unwind_test.cpp31
-rw-r--r--runtime/test/cs_wave_probe_spv.h63
-rw-r--r--runtime/test/d3d12_buffer_tiles_test.cpp42
-rw-r--r--runtime/test/d3d12_bundle_test.cpp17
-rw-r--r--runtime/test/d3d12_com_test.cpp6
-rw-r--r--runtime/test/d3d12_compute_test.cpp18
-rw-r--r--runtime/test/d3d12_copy_xfmt_test.cpp61
-rw-r--r--runtime/test/d3d12_depth24_draw_test.cpp464
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp119
-rw-r--r--runtime/test/d3d12_draw_test.cpp17
-rw-r--r--runtime/test/d3d12_fspx_compute_test.cpp15
-rw-r--r--runtime/test/d3d12_geometry_test.cpp4
-rw-r--r--runtime/test/d3d12_heap_properties_test.cpp284
-rw-r--r--runtime/test/d3d12_indirect_dispatch_count_test.cpp231
-rw-r--r--runtime/test/d3d12_m2_textured_test.cpp100
-rw-r--r--runtime/test/d3d12_method_variants_test.cpp311
-rw-r--r--runtime/test/d3d12_msaa_draw_test.cpp10
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp14
-rw-r--r--runtime/test/d3d12_placed_dimensions_test.cpp347
-rw-r--r--runtime/test/d3d12_present_test.cpp55
-rw-r--r--runtime/test/d3d12_residency_test.cpp421
-rw-r--r--runtime/test/d3d12_set0_compute_test.cpp10
-rw-r--r--runtime/test/d3d12_shader_cache_test.cpp26
-rw-r--r--runtime/test/d3d12_sparse_queue_family_test.cpp175
-rw-r--r--runtime/test/d3d12_state_map_test.cpp15
-rw-r--r--runtime/test/d3d12_subgroup_test.cpp5
-rw-r--r--runtime/test/d3d12_typeless_families_test.cpp13
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp342
-rw-r--r--runtime/test/dxgi_device_test.cpp349
-rw-r--r--runtime/test/dxgi_swapchain_count_test.cpp354
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp240
-rw-r--r--runtime/test/file_system_test.cpp46
-rw-r--r--runtime/test/fixtures/d3d12_xs_stub.cpp10
-rw-r--r--runtime/test/fixtures/d3d12_xs_stub.def3
-rw-r--r--runtime/test/fixtures/dll_thread_calls.cpp9
-rw-r--r--runtime/test/fixtures/gameinput_host.cpp43
-rw-r--r--runtime/test/fixtures/tiny_atexit.cpp92
-rw-r--r--runtime/test/fixtures/tiny_frame.cpp166
-rw-r--r--runtime/test/fixtures/tiny_gdk_load.cpp5
-rw-r--r--runtime/test/fixtures/tiny_tls_cb_only.cpp9
-rw-r--r--runtime/test/gameinput_host_test.cpp90
-rw-r--r--runtime/test/gameinput_test.cpp154
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp9
-rw-r--r--runtime/test/glsl/cs_indirect_dispatch_count.comp17
-rw-r--r--runtime/test/glsl/cs_wave_probe.comp31
-rw-r--r--runtime/test/glsl/gs_depth.geom15
-rw-r--r--runtime/test/glsl/ps_depth_empty.frag11
-rw-r--r--runtime/test/glsl/ps_depth_write.frag13
-rw-r--r--runtime/test/glsl/vs_depth.vert16
-rw-r--r--runtime/test/large_module_gate.h179
-rw-r--r--runtime/test/large_module_gate_test.cpp159
-rw-r--r--runtime/test/loader_test.cpp55
-rw-r--r--runtime/test/queue_proxy_test.cpp15
-rw-r--r--runtime/test/replay_cpu_bench.cpp13
-rw-r--r--runtime/test/replay_query_predication_test.cpp50
-rw-r--r--runtime/test/root_signature_oracle_test.cpp366
-rw-r--r--runtime/test/shader_library_test.cpp4
-rw-r--r--runtime/test/shaders/build.py7
-rw-r--r--runtime/test/shaders/check.py38
-rw-r--r--runtime/test/shaders/cs_bvh.asm6
-rw-r--r--runtime/test/shaders/cs_bvh32.asm12
-rw-r--r--runtime/test/shaders/cs_smem_sconst_off.asm47
-rw-r--r--runtime/test/shaders/ps_far_branch.asm321
-rw-r--r--runtime/test/shaders/ps_m2_literal.asm21
-rw-r--r--runtime/test/shaders/ps_sample_c.asm25
-rw-r--r--runtime/test/shaders/ps_sample_c_b.asm25
-rw-r--r--runtime/test/shaders/ps_texture_b_cl.asm23
-rw-r--r--runtime/test/shaders/ps_texture_cl.asm23
-rw-r--r--runtime/test/shaders/ps_w64_a_discard.asm65
-rw-r--r--runtime/test/shaders/w64_graphics.py11
-rw-r--r--runtime/test/test_runtime_types.cpp15
-rw-r--r--runtime/test/test_temp_dir.h67
-rw-r--r--runtime/test/vk_command_replay_test.cpp81
-rw-r--r--runtime/test/vk_compute_test.cpp157
-rw-r--r--runtime/test/vk_pipeline_check.cpp164
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp86
-rw-r--r--runtime/test/vk_queue_test.cpp28
-rw-r--r--runtime/test/vk_sandbox.cpp734
-rw-r--r--runtime/test/vk_texture_test.cpp39
-rw-r--r--runtime/test/vulkan13_features_test.cpp61
-rw-r--r--runtime/test/winhttp_offline_test.cpp75
-rw-r--r--runtime/test/xbox_present_test.cpp60
-rw-r--r--runtime/test/xgameruntime_test.cpp189
-rw-r--r--runtime/test/xgameruntime_user_test.cpp227
-rw-r--r--runtime/test/xmem_test.cpp63
92 files changed, 8706 insertions, 311 deletions
diff --git a/runtime/test/active_input_test.cpp b/runtime/test/active_input_test.cpp
new file mode 100644
index 000000000..11c628320
--- /dev/null
+++ b/runtime/test/active_input_test.cpp
@@ -0,0 +1,236 @@
1// ActiveInputTracker (src/active_input.h) on synthetic samples with its own clock: what counts as deliberate input
2// (edges only, thresholds, baselines), the minimum time between changes, several devices of one family, a device that
3// goes and comes back, and a forced family. No SDL, no controller, no GPU.
4#include "../src/active_input.h"
5
6#include <cstdio>
7#include <iterator>
8#include <string_view>
9
10using namespace leonida;
11
12#define EXPECT(condition) do { \
13 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
14} while (0)
15
16namespace {
17
18constexpr std::uint64_t ms = 1000; // the tracker's clock is in microseconds
19
20InputSample rest() { return {}; }
21
22InputSample button(std::uint32_t bits) {
23 InputSample s;
24 s.buttons = bits;
25 return s;
26}
27
28InputSample left_stick(float x, float y) {
29 InputSample s;
30 s.left_x = x;
31 s.left_y = y;
32 return s;
33}
34
35InputSample right_stick(float x, float y) {
36 InputSample s;
37 s.right_x = x;
38 s.right_y = y;
39 return s;
40}
41
42InputSample triggers(float left, float right) {
43 InputSample s;
44 s.left_trigger = left;
45 s.right_trigger = right;
46 return s;
47}
48
49// Device keys and families used below.
50constexpr std::uint64_t xbox = 1, dualsense = 2, ds4 = 3, keyboard = 4, xbox2 = 5, switch_pro = 6;
51
52int test_start_and_baseline() {
53 ActiveInputTracker t;
54 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0 && !t.forced());
55
56 // A first sample is a baseline, whatever it holds: a pad connecting with a button down changes nothing.
57 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 0) == InputEdge::None);
58 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0);
59 // Still held: no edge.
60 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::None);
61 // Released, then pressed again: that press is the first deliberate input, and the first change needs no wait.
62 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 20 * ms) == InputEdge::None);
63 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 30 * ms) == InputEdge::Button);
64 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
65 return 0;
66}
67
68int test_drift_and_thresholds() {
69 ActiveInputTracker t;
70 EXPECT(t.observe(xbox, InputFamily::Xbox, rest(), 0) == InputEdge::None);
71 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 0) == InputEdge::None);
72
73 // A worn stick drifting around inside the radius never counts, however long it wanders.
74 for (int i = 0; i < 200; ++i) {
75 const float d = 0.05f + 0.25f * static_cast<float>(i % 7) / 6.0f; // 0.05 .. 0.30
76 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(d, -d * 0.5f), (1 + i) * ms) ==
77 InputEdge::None);
78 }
79 // Just inside the radius (0.35 along a diagonal is 0.247 per axis): nothing.
80 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.24f, 0.24f), 300 * ms) == InputEdge::None);
81 // Leaving it is an edge.
82 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.3f, 0.3f), 310 * ms) == InputEdge::Stick);
83 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
84 // Held over the radius: no further edge from the same stick.
85 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(1.0f, 0.0f), 320 * ms) == InputEdge::None);
86
87 // Triggers: resting at 0.29 is not a pull; rising past 0.3 is.
88 EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.29f, 0.0f), 700 * ms) == InputEdge::None);
89 EXPECT(t.active() == InputFamily::PlayStation5);
90 EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.31f, 0.0f), 710 * ms) == InputEdge::Trigger);
91 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2);
92 // A trigger held further down does not count again.
93 EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.9f, 0.0f), 720 * ms) == InputEdge::None);
94 return 0;
95}
96
97int test_min_switch_time() {
98 ActiveInputTracker t;
99 t.observe(xbox, InputFamily::Xbox, rest(), 0);
100 t.observe(dualsense, InputFamily::PlayStation5, rest(), 0);
101
102 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2), 1000 * ms) == InputEdge::Button);
103 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
104 // 100 ms later the Xbox pad's press is inside the window: ignored, and not remembered for later.
105 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1100 * ms) == InputEdge::None);
106 EXPECT(t.active() == InputFamily::PlayStation5);
107 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1400 * ms) == InputEdge::None); // still held: no edge
108 EXPECT(t.active() == InputFamily::PlayStation5);
109 // Released and pressed again after the window: that one counts.
110 t.observe(xbox, InputFamily::Xbox, rest(), 1500 * ms);
111 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1600 * ms) == InputEdge::Button);
112 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2);
113 // Exactly at the window's end counts (the window is "less than min_switch_us").
114 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2 | 4), 1900 * ms) == InputEdge::Button);
115 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 3);
116
117 // A zero window lets every deliberate input switch at once.
118 ActiveInputTracker fast(InputFamily::Xbox, {0.35f, 0.3f, 0});
119 fast.observe(xbox, InputFamily::Xbox, rest(), 0);
120 fast.observe(keyboard, InputFamily::Keyboard, rest(), 0);
121 EXPECT(fast.observe(keyboard, InputFamily::Keyboard, button(8), 1) == InputEdge::Button);
122 EXPECT(fast.observe(xbox, InputFamily::Xbox, button(8), 2) == InputEdge::Button);
123 EXPECT(fast.active() == InputFamily::Xbox && fast.generation() == 2);
124 return 0;
125}
126
127int test_same_family_and_holds() {
128 ActiveInputTracker t;
129 for (std::uint64_t d : {xbox, xbox2}) t.observe(d, InputFamily::Xbox, rest(), 0);
130 t.observe(keyboard, InputFamily::Keyboard, rest(), 0);
131
132 // Input from a second pad of the family already in use changes nothing.
133 EXPECT(t.observe(xbox2, InputFamily::Xbox, button(1), 10 * ms) == InputEdge::None);
134 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0);
135
136 // The keyboard pad: W held pushes the left stick to full. The first push is the edge; holding it is not.
137 EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), 20 * ms) == InputEdge::Stick);
138 EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 1);
139 // The player picks up the Xbox pad while W is still held down: the pad takes over after the window and the held
140 // key does not take it back.
141 EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 400 * ms) == InputEdge::Button);
142 for (int i = 0; i < 50; ++i)
143 EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), (410 + 10 * i) * ms) ==
144 InputEdge::None);
145 EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2);
146
147 // The mouse moves the keyboard pad's right stick: a small jitter stays inside the radius, a real movement
148 // leaves it.
149 t.observe(keyboard, InputFamily::Keyboard, rest(), 1000 * ms);
150 EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.03f, 0.0f), 1010 * ms) == InputEdge::None);
151 EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.5f, -0.1f), 1020 * ms) == InputEdge::Stick);
152 EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 3);
153 return 0;
154}
155
156int test_reconnect() {
157 ActiveInputTracker t;
158 t.observe(ds4, InputFamily::PlayStation4, rest(), 0);
159 EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 10 * ms) == InputEdge::Button);
160 EXPECT(t.active() == InputFamily::PlayStation4);
161
162 // Unplugged while the button was down; it comes back with the button still down. The new first sample is a
163 // baseline, so there is no edge to count, and no stale state from before.
164 t.forget(ds4);
165 t.observe(switch_pro, InputFamily::Nintendo, rest(), 0);
166 EXPECT(t.observe(switch_pro, InputFamily::Nintendo, button(1), 500 * ms) == InputEdge::Button);
167 EXPECT(t.active() == InputFamily::Nintendo);
168 EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 900 * ms) == InputEdge::None);
169 EXPECT(t.active() == InputFamily::Nintendo);
170 t.observe(ds4, InputFamily::PlayStation4, rest(), 910 * ms);
171 EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 920 * ms) == InputEdge::Button);
172 EXPECT(t.active() == InputFamily::PlayStation4 && t.generation() == 3);
173 return 0;
174}
175
176int test_forced() {
177 ActiveInputTracker t;
178 t.observe(dualsense, InputFamily::PlayStation5, rest(), 0);
179 t.observe(keyboard, InputFamily::Keyboard, rest(), 0);
180
181 t.force(InputFamily::Keyboard);
182 EXPECT(t.forced() && t.active() == InputFamily::Keyboard && t.generation() == 1);
183 // Forcing the same family again changes nothing.
184 t.force(InputFamily::Keyboard);
185 EXPECT(t.generation() == 1);
186
187 // Tracking still runs underneath: the DualSense becomes the tracked family, but the answer stays forced and the
188 // generation does not move.
189 EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::Button);
190 EXPECT(t.tracked() == InputFamily::PlayStation5 && t.active() == InputFamily::Keyboard && t.generation() == 1);
191
192 // Clearing the force goes straight back to the device in use.
193 t.force(std::nullopt);
194 EXPECT(!t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2);
195
196 // Forcing the family that is already tracked does not change the answer, so no new generation.
197 t.force(InputFamily::PlayStation5);
198 EXPECT(t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2);
199 t.force(std::nullopt);
200 EXPECT(t.generation() == 2);
201 return 0;
202}
203
204int test_names() {
205 EXPECT(std::string_view(input_family_name(InputFamily::PlayStation5)) == "PlayStation 5");
206 EXPECT(std::string_view(input_family_name(InputFamily::Keyboard)) == "keyboard and mouse");
207 EXPECT(std::string_view(input_edge_name(InputEdge::Stick)) == "stick movement");
208 return 0;
209}
210
211} // namespace
212
213int main() {
214 struct Case {
215 const char* name;
216 int (*run)();
217 };
218 const Case cases[] = {
219 {"start and baseline", test_start_and_baseline},
220 {"drift and thresholds", test_drift_and_thresholds},
221 {"minimum time between changes", test_min_switch_time},
222 {"one family, held input", test_same_family_and_holds},
223 {"reconnect", test_reconnect},
224 {"forced family", test_forced},
225 {"names", test_names},
226 };
227 int failures = 0;
228 for (const Case& c : cases) {
229 const int r = c.run();
230 std::printf("%s: %s\n", c.name, r ? "FAIL" : "ok");
231 failures += r;
232 }
233 const int total = static_cast<int>(std::size(cases));
234 std::printf("active input: %d of %d cases pass\n", total - failures, total);
235 return failures ? 1 : 0;
236}
diff --git a/runtime/test/buffer_va_index_test.cpp b/runtime/test/buffer_va_index_test.cpp
index 3368e8b8b..b5b5e997f 100644
--- a/runtime/test/buffer_va_index_test.cpp
+++ b/runtime/test/buffer_va_index_test.cpp
@@ -27,10 +27,10 @@ void check(bool ok, const char* what) {
27 ++failures; 27 ++failures;
28} 28}
29 29
30// The id that holds `va`, 0 for none. 30// The id that holds `va` (preferring one that holds `bytes` from it), 0 for none.
31std::uintptr_t at(const Index& index, std::uint64_t va) { 31std::uintptr_t at(const Index& index, std::uint64_t va, std::uint64_t bytes = 1) {
32 Index::Hit hit{}; 32 Index::Hit hit{};
33 return index.find(va, hit) ? hit.id : 0; 33 return index.find(va, hit, bytes) ? hit.id : 0;
34} 34}
35 35
36void fixed_cases() { 36void fixed_cases() {
@@ -64,6 +64,13 @@ void fixed_cases() {
64 check(at(alias, 0x1f000) == 10, "past every short buffer"); 64 check(at(alias, 0x1f000) == 10, "past every short buffer");
65 check(at(alias, 0x20000) == 0, "past the long buffer"); 65 check(at(alias, 0x20000) == 0, "past the long buffer");
66 66
67 // A view that starts in a short buffer and runs past its end: the long buffer around it holds all of it.
68 check(at(alias, 0x11080, 0x80) == 11, "a view that fits in the short buffer stays in it");
69 check(at(alias, 0x11080, 0x81) == 10, "a view past the short buffer's end goes to the long one around it");
70 check(at(alias, 0x1ff00, 0x200) == 10, "a view no range holds: the closest that holds its start");
71 check(at(alias, 0x11080, 0x10000) == 11, "a view past the long buffer too: the closest start, as without a size");
72 check(at(alias, 0x11080, 0) == 11, "a size of 0 counts as one byte");
73
67 // Two resources placed at the same offset: the larger ID, either way they were added. 74 // Two resources placed at the same offset: the larger ID, either way they were added.
68 alias.insert(0x30000, 0x100, 21); 75 alias.insert(0x30000, 0x100, 21);
69 alias.insert(0x30000, 0x200, 20); 76 alias.insert(0x30000, 0x200, 20);
@@ -100,19 +107,25 @@ void fixed_cases() {
100 check(bound.longest() == 0 && bound.size() == 0, "an empty index has no bound"); 107 check(bound.longest() == 0 && bound.size() == 0, "an empty index has no bound");
101} 108}
102 109
103// The rule BufferVaIndex follows, by a scan: among the ranges that hold va, the greatest (start, id). 110// The rule BufferVaIndex follows, by a scan: among the ranges that hold all of [va, va + bytes), the greatest
111// (start, id); when none does, the greatest among those that hold va.
104struct Range { 112struct Range {
105 std::uint64_t start, size; 113 std::uint64_t start, size;
106 std::uintptr_t id; 114 std::uintptr_t id;
107}; 115};
108 116
109std::uintptr_t scan(const std::vector<Range>& ranges, std::uint64_t va) { 117std::uintptr_t scan(const std::vector<Range>& ranges, std::uint64_t va, std::uint64_t bytes = 1) {
110 const Range* best = nullptr; 118 const Range* best = nullptr;
119 const Range* whole = nullptr;
120 const auto greater = [](const Range& a, const Range* b) {
121 return !b || a.start > b->start || (a.start == b->start && a.id > b->id);
122 };
111 for (const Range& r : ranges) { 123 for (const Range& r : ranges) {
112 if (va < r.start || va - r.start >= r.size) continue; 124 if (va < r.start || va - r.start >= r.size) continue;
113 if (!best || r.start > best->start || (r.start == best->start && r.id > best->id)) best = &r; 125 if (greater(r, best)) best = &r;
126 if (bytes <= r.size - (va - r.start) && greater(r, whole)) whole = &r;
114 } 127 }
115 return best ? best->id : 0; 128 return whole ? whole->id : best ? best->id : 0;
116} 129}
117 130
118void random_tables() { 131void random_tables() {
@@ -148,9 +161,12 @@ void random_tables() {
148 } 161 }
149 for (int q = 0; q < 2000; ++q) { 162 for (int q = 0; q < 2000; ++q) {
150 const std::uint64_t va = 0x8000 + rng() % (next + 0x20000); 163 const std::uint64_t va = 0x8000 + rng() % (next + 0x20000);
151 if (at(index, va) != scan(ranges, va)) { 164 // A quarter of the lookups name one byte, the rest a view of up to twice the largest buffer.
152 std::printf("FAIL: round %d va 0x%llx: index %llu, scan %llu\n", round, (unsigned long long)va, 165 const std::uint64_t bytes = q % 4 ? 1 + rng() % 0x8000 : 1;
153 (unsigned long long)at(index, va), (unsigned long long)scan(ranges, va)); 166 if (at(index, va, bytes) != scan(ranges, va, bytes)) {
167 std::printf("FAIL: round %d va 0x%llx bytes 0x%llx: index %llu, scan %llu\n", round,
168 (unsigned long long)va, (unsigned long long)bytes,
169 (unsigned long long)at(index, va, bytes), (unsigned long long)scan(ranges, va, bytes));
154 ++failures; 170 ++failures;
155 return; 171 return;
156 } 172 }
diff --git a/runtime/test/bvh_builder_test.cpp b/runtime/test/bvh_builder_test.cpp
index 16e5db4d8..2635711c9 100644
--- a/runtime/test/bvh_builder_test.cpp
+++ b/runtime/test/bvh_builder_test.cpp
@@ -8,7 +8,8 @@
8// LEONIDA_BVH_FLAG=1 (optional: pass true as the constructor's bool argument) 8// LEONIDA_BVH_FLAG=1 (optional: pass true as the constructor's bool argument)
9// LEONIDA_BVH_WARP=1 (optional: use the WARP adapter; the default on an NVIDIA adapter, RT-54) 9// LEONIDA_BVH_WARP=1 (optional: use the WARP adapter; the default on an NVIDIA adapter, RT-54)
10// LEONIDA_BVH_HARDWARE=1 (optional: keep an NVIDIA adapter instead of switching to WARP) 10// LEONIDA_BVH_HARDWARE=1 (optional: keep an NVIDIA adapter instead of switching to WARP)
11// LEONIDA_BVH_RECORD62=1 (optional: print each CreateComputePipelineState's container shape) 11// LEONIDA_BVH_RECORD62=1 (optional: print each CreateComputePipelineState's container shape, its ILDN
12// module name and digest)
12// LEONIDA_BVH_DXIL=1 (optional, with RECORD62: dx.op counts and validator error kinds, needs 13// LEONIDA_BVH_DXIL=1 (optional, with RECORD62: dx.op counts and validator error kinds, needs
13// dxcompiler.dll and dxil.dll on PATH) 14// dxcompiler.dll and dxil.dll on PATH)
14// LEONIDA_BVH_DEVICE=vulkan (optional: the Vulkan-backed ID3D12Device from #119 instead of a PC device) 15// LEONIDA_BVH_DEVICE=vulkan (optional: the Vulkan-backed ID3D12Device from #119 instead of a PC device)
@@ -309,7 +310,8 @@ bool looks_like_iid(uint64_t p, const IID& iid) {
309uint64_t g_slot62_ok = 0, g_slot62_failed = 0; 310uint64_t g_slot62_ok = 0, g_slot62_failed = 0;
310 311
311// The shape of a DXBC container, for the record: its parts (four-character code and size), the DXIL part's shader 312// The shape of a DXBC container, for the record: its parts (four-character code and size), the DXIL part's shader
312// model and DXIL version, the SFI0 feature flags, and whether the hash is zero (unsigned). Counts and flags only. 313// model and DXIL version, the SFI0 feature flags, whether the hash is zero (unsigned), the ILDN module name and the
314// first four bytes of the digest. Counts, flags and names only.
313std::string container_shape(const void* bytecode, size_t length) { 315std::string container_shape(const void* bytecode, size_t length) {
314 const auto* b = static_cast<const uint8_t*>(bytecode); 316 const auto* b = static_cast<const uint8_t*>(bytecode);
315 auto u32 = [&](size_t o) { 317 auto u32 = [&](size_t o) {
@@ -340,9 +342,23 @@ std::string container_shape(const void* bytecode, size_t length) {
340 std::snprintf(item, sizeof(item), "(flags %#llx)", 342 std::snprintf(item, sizeof(item), "(flags %#llx)",
341 static_cast<unsigned long long>(u32(data) | (uint64_t(u32(data + 4)) << 32))); 343 static_cast<unsigned long long>(u32(data) | (uint64_t(u32(data + 4)) << 32)));
342 out += item; 344 out += item;
345 } else if (!std::strcmp(fourcc, "ILDN") && size >= 4) {
346 // ILDN: u16 flags, u16 name length, the debug name (NUL-padded): the module's PDB path, which names the
347 // container (docs/embedded_shaders.md section 3). Only the file name is printed.
348 const uint32_t name_length = u32(data) >> 16;
349 if (size_t(data) + 4 + name_length <= length && name_length > 0) {
350 std::string name(reinterpret_cast<const char*>(b + data + 4), name_length);
351 name.erase(name.find_last_not_of('\0') + 1);
352 name = name.substr(name.find_last_of("\\/") + 1);
353 out += "(" + name + ")";
354 }
343 } 355 }
344 } 356 }
345 return out; 357 // The first four bytes of the container digest (bytes 4..19 of the header), to tell two creations of the same
358 // container from two containers with the same module name.
359 char digest[24];
360 std::snprintf(digest, sizeof(digest), " digest %02x%02x%02x%02x", b[4], b[5], b[6], b[7]);
361 return out + digest;
346} 362}
347 363
348// The module a container belongs to: the file name (without ".pdb") in its ILDN part, a DXIL debug-name record 364// The module a container belongs to: the file name (without ".pdb") in its ILDN part, a DXIL debug-name record
diff --git a/runtime/test/check_atexit.cmake b/runtime/test/check_atexit.cmake
new file mode 100644
index 000000000..255bb3a4f
--- /dev/null
+++ b/runtime/test/check_atexit.cmake
@@ -0,0 +1,71 @@
1# atexit handlers, static destructors and every way out: tiny_atexit run through `gta6rt --run` must print the
2# sequence written below and end with its exit code. That is what the program does natively on Windows, and the
3# native run is held to the same sequence, so the two cannot agree on a wrong answer. Under Wine both runs go through
4# RUNNER, and Wine's own CRT differs in places (it drops a handler registered while handlers run, and its _exit does
5# not wait for the exit lock), so there a native difference is reported without failing; --run is still held to the
6# Windows sequence.
7get_filename_component(guest_dir "${GUEST}" DIRECTORY)
8get_filename_component(guest_name "${GUEST}" NAME)
9
10set(ctors "ctor first;ctor second;main")
11set(handlers "atexit two;atexit registers late;atexit late;atexit one;dtor second;dtor first")
12set(expect_return "${ctors};${handlers}")
13set(code_return 3)
14set(expect_exit "${ctors};${handlers}")
15set(code_exit 7)
16set(expect__exit "${ctors}")
17set(code__exit 8)
18set(expect_quick_exit "${ctors}")
19set(code_quick_exit 9)
20set(expect_ExitProcess "${ctors}")
21set(code_ExitProcess 10)
22set(expect_cexit "${ctors};${handlers};after _cexit")
23set(code_cexit 11)
24set(expect_c_exit "${ctors};after _c_exit;${handlers}")
25set(code_c_exit 12)
26# exit(7) is running a slow handler when a second thread calls _exit(7): the exit lock holds it back.
27set(expect_concurrent_exit "${ctors};slow handler started;slow handler done;${handlers}")
28set(code_concurrent_exit 7)
29
30# The program's own lines, in order, without the prefix; everything gta6rt prints is dropped.
31function(guest_lines output result)
32 string(REPLACE "\r\n" "\n" output "${output}")
33 string(REPLACE ";" "," output "${output}")
34 string(REPLACE "\n" ";" output "${output}")
35 set(lines)
36 foreach(line IN LISTS output)
37 if(line MATCHES "^tiny_atexit: (.*)$")
38 list(APPEND lines "${CMAKE_MATCH_1}")
39 endif()
40 endforeach()
41 set(${result} "${lines}" PARENT_SCOPE)
42endfunction()
43
44set(failures "")
45foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit)
46 execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode}
47 WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60
48 RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err)
49 execute_process(COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" -- ${mode}
50 WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60
51 RESULT_VARIABLE run_code OUTPUT_VARIABLE run_out ERROR_VARIABLE run_err)
52 guest_lines("${native_out}" native_lines)
53 guest_lines("${run_out}" run_lines)
54 if(NOT native_code STREQUAL code_${mode} OR NOT native_lines STREQUAL expect_${mode})
55 string(CONCAT native_diff "[${mode}] native run differs from the expected sequence"
56 "\n expected (${code_${mode}}): ${expect_${mode}}\n native (${native_code}): ${native_lines}")
57 if(RUNNER)
58 message(STATUS "${native_diff}\n (the host CRT differs from Windows; not a gta6rt failure)")
59 else()
60 string(APPEND failures "\n${native_diff}\n (the fixture or the host changed)")
61 endif()
62 endif()
63 if(NOT run_code STREQUAL code_${mode} OR NOT run_lines STREQUAL expect_${mode})
64 string(APPEND failures "\n[${mode}] gta6rt --run differs from the expected sequence"
65 "\n expected (${code_${mode}}): ${expect_${mode}}\n --run (${run_code}): ${run_lines}\n${run_err}")
66 endif()
67endforeach()
68if(failures)
69 message(FATAL_ERROR "atexit/termination differences:${failures}")
70endif()
71message(STATUS "tiny_atexit: 8 termination paths match the Windows sequence")
diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py
new file mode 100644
index 000000000..2a2ce7470
--- /dev/null
+++ b/runtime/test/check_sparse_queue_family.py
@@ -0,0 +1,117 @@
1"""Repo-friendly, optional GPU test: byte-exact Leonida COPY/COMPUTE tiled-buffer replay
2AND actual VK_SHARING_MODE_CONCURRENT on *every* sparse VkBuffer created by the layer.
3
4Runs the original synthetic `d3d12_sparse_queue_family_test` target.
5Invokes the SDK's VK_LAYER_LUNARG_api_dump in a short-lived isolated directory;
6no private-game files, asset paths, device memory dumps, or committed logs.
7
8 python -I check_sparse_queue_family.py path/to/d3d12_sparse_queue_family_test.exe
9 python -I check_sparse_queue_family.py path/to/baseline.exe --expect-baseline-exclusive
10
11By default the baseline fails (exit 1) and patched runtime passes (exit 0).
12If the API dump layer is absent the result skips (exit 77, CTest SKIP_RETURN_CODE).
13"""
14from __future__ import annotations
15
16import argparse
17import os
18import re
19import subprocess
20import sys
21import tempfile
22from pathlib import Path
23
24
25SPARSE_FLAGS = "VkBufferCreateFlags = 7 (VK_BUFFER_CREATE_SPARSE_BINDING_BIT"
26MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)")
27COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)")
28INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)")
29CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M)
30
31
32def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]:
33 rows = path.read_text(encoding="utf-8", errors="replace").splitlines()
34 seen = []
35 for i, line in enumerate(rows):
36 if SPARSE_FLAGS not in line:
37 continue
38 tail = "\n".join(rows[i + 1 : i + 13])
39 mode, count = MODE.search(tail), COUNT.search(tail)
40 if not mode or not count:
41 raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}")
42 inds = tuple(int(index) for _, index in INDICES.findall(tail))
43 seen.append((mode.group(1), int(count.group(1)), inds))
44 if len(seen) < 6 or len(seen) % 2:
45 raise AssertionError(f"insufficient sparse VkBuffer create-info records: {len(seen)}")
46 if expect_exclusive:
47 assert all(mode == "VK_SHARING_MODE_EXCLUSIVE" and count == 0
48 for mode, count, _ in seen), f"baseline negative control not reproduced: {set(seen)}"
49 else:
50 assert all(mode == "VK_SHARING_MODE_CONCURRENT" and count >= 2 and len(inds) == count
51 and len(set(inds)) == count
52 for mode, count, inds in seen), f"BUG: not all sparse buffers share active families: {set(seen)}"
53 return len(seen) // 2, len(seen)
54
55
56def main() -> int:
57 parser = argparse.ArgumentParser()
58 parser.add_argument("executable", type=Path, help="Compiled Leonida d3d12_sparse_queue_family_test binary")
59 parser.add_argument("--expect-baseline-exclusive", action="store_true",
60 help="negative-control mode: prove buggy EXCLUSIVE create infos instead of requiring fix")
61 args = parser.parse_args()
62 exe = args.executable.resolve()
63 if not exe.is_file():
64 print(f"ERROR: missing executable {exe}", file=sys.stderr)
65 return 2
66 env = os.environ.copy()
67 # An implicit Vulkan layer may be forced by the loader even if the application
68 # enabled VK_LAYER_KHRONOS_validation explicitly via LEONIDA_VK_VALIDATION.
69 env["VK_INSTANCE_LAYERS"] = "VK_LAYER_LUNARG_api_dump"
70 env["LEONIDA_VK_VALIDATION"] = "1"
71 with tempfile.TemporaryDirectory(prefix="leonida_sparse_trace_") as td:
72 path = Path(td)
73 dump_name = path / "sparse_create_info.log"
74 (path / "vk_layer_settings.txt").write_text(
75 "lunarg_api_dump.file = true\n"
76 f"lunarg_api_dump.log_filename = {dump_name}\n"
77 "lunarg_api_dump.output_format = text\n"
78 "lunarg_api_dump.pre_dump = true\n"
79 "lunarg_api_dump.detailed = true\n",
80 encoding="utf-8",
81 )
82 env["VK_LAYER_SETTINGS_PATH"] = str(path)
83 run = subprocess.run([str(exe)], cwd=path, env=env, capture_output=True,
84 text=True, encoding="utf-8", errors="replace", timeout=40)
85 out = run.stdout + "\n" + run.stderr
86 if run.returncode == 77:
87 print("SKIP 77: Leonida Vulkan device / sparse features unavailable")
88 return 77
89 # The loader refuses the instance when a layer named in VK_INSTANCE_LAYERS (or the validation layer
90 # LEONIDA_VK_VALIDATION asks for) is not installed: that is the "layer absent" skip, not a layer failure.
91 if run.returncode != 0 and "vkCreateInstance" in out and "failed" in out:
92 print("SKIP 77: VK_LAYER_LUNARG_api_dump or VK_LAYER_KHRONOS_validation unavailable (vkCreateInstance failed)")
93 return 77
94 if run.returncode != 0:
95 print(out[-7000:], file=sys.stderr)
96 raise AssertionError(f"Leonida GPU test failed exit={run.returncode}")
97 kinds = sorted(CASE.findall(out))
98 if len(kinds) != 3 or "LAYER_FINAL PASS" not in out:
99 raise AssertionError(f"GPU byte verification missing: cases={kinds}; tail={out[-2000:]}")
100 candidates = list(path.glob("sparse_create_info.log*"))
101 if not candidates:
102 print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace")
103 return 77
104 calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive)
105 print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros")
106 print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = "
107 f"{'EXCLUSIVE negative-control' if args.expect_baseline_exclusive else 'CONCURRENT with 2+ unique families'}")
108 print("Khronos validation enabled; no validation errors observed (GPU does not need to corrupt data for this test)")
109 return 0
110
111
112if __name__ == "__main__":
113 try:
114 raise SystemExit(main())
115 except (AssertionError, subprocess.TimeoutExpired) as error:
116 print(f"FAIL: {error}", file=sys.stderr)
117 raise SystemExit(1)
diff --git a/runtime/test/check_tiny_frame.py b/runtime/test/check_tiny_frame.py
new file mode 100644
index 000000000..8d7dbd8ac
--- /dev/null
+++ b/runtime/test/check_tiny_frame.py
@@ -0,0 +1,124 @@
1"""Run tiny_frame under `gta6rt --run --trace-d3d12` on the Vulkan D3D12 device and check the run from outside.
2
3 python -I check_tiny_frame.py <gta6rt.exe> <tiny_frame.exe> [--probe d3d12_com_test.exe] [--runner wine ...]
4
5Checks the guest's verdict and exit code, that the loader's report binds d3d12_xs.dll!D3D12XboxCreateDevice to the
6shim, and that the D3D12 trace is a gapless numbered sequence in which the calls a first frame needs appear in
7order. Exits 77 (ctest: skipped) when --probe, one of the Vulkan device tests, says
8there is no usable Vulkan device on this machine.
9"""
10
11import argparse
12import os
13import re
14import subprocess
15import sys
16
17SKIP = 77
18
19# The first frame, in the order the fixture makes the calls, as the trace words them (`called` for a method that
20# returns nothing). Other traced calls, such as the queue and fence proxies' own entries, may sit between them.
21EXPECTED = [
22 "D3D12XboxCreateDevice ok",
23 "ID3D12Device::CreateCommandQueue ok",
24 "ID3D12Device::CreateCommandAllocator ok",
25 "ID3D12Device::CreateCommandList ok",
26 "ID3D12Device::CreateFence ok",
27 "ID3D12Device::CreateDescriptorHeap ok",
28 "ID3D12Device::CreateCommittedResource ok",
29 "ID3D12Device::CreateCommittedResource ok",
30 "ID3D12Device::CreateRenderTargetView called",
31 "ID3D12GraphicsCommandList::ClearRenderTargetView called",
32 "ID3D12GraphicsCommandList::ResourceBarrier called",
33 "ID3D12GraphicsCommandList::CopyTextureRegion called",
34 "ID3D12GraphicsCommandList::Close ok",
35 "ID3D12CommandQueue::ExecuteCommandLists ok",
36 "ID3D12CommandQueue::Signal ok",
37]
38
39
40def ordered_subsequence(expected, entries):
41 """The first expected entry that does not appear, in order, in entries; None when all do."""
42 position = 0
43 for want in expected:
44 while position < len(entries) and entries[position] != want:
45 position += 1
46 if position == len(entries):
47 return want
48 position += 1
49 return None
50
51
52def parse_trace(lines):
53 """[(method, outcome)] from the `[d3d12-trace] #N method outcome` lines; raises ValueError on a gap."""
54 entries = []
55 for line in lines:
56 if not line.startswith("[d3d12-trace]"):
57 continue
58 match = re.fullmatch(r"\[d3d12-trace\] #(\d+) (.+) (called|ok|failed|unsupported|ignored|refused)", line)
59 if not match or int(match[1]) != len(entries) + 1:
60 raise ValueError(f"invalid trace sequence at entry {len(entries) + 1}: {line}")
61 entries.append((match[2], match[3]))
62 return entries
63
64
65def check_output(code, output):
66 """A list of problems with one run's exit code and combined output; empty when it is what the test expects."""
67 problems = []
68 lines = output.replace("\r\n", "\n").split("\n")
69 if code != 0:
70 problems.append(f"exit code {code}")
71 if "tiny_frame: OK" not in lines:
72 problems.append("the guest did not print `tiny_frame: OK`")
73 if any(line.startswith("tiny_frame: FAIL") for line in lines):
74 problems.append("the guest reported a failed check")
75 if "game exited with code 0" not in lines:
76 problems.append("gta6rt did not report `game exited with code 0`")
77 if not any(re.fullmatch(r" +shim +d3d12_xs\.dll!D3D12XboxCreateDevice", line) for line in lines):
78 problems.append("d3d12_xs.dll!D3D12XboxCreateDevice was not bound to the shim")
79 try:
80 entries = parse_trace(lines)
81 except ValueError as error:
82 return problems + [str(error)]
83 bad = [f"{method} {outcome}" for method, outcome in entries if outcome in ("failed", "unsupported", "refused")]
84 if bad:
85 problems.append("traced calls that did not succeed: " + ", ".join(bad))
86 missing = ordered_subsequence(EXPECTED, [f"{method} {outcome}" for method, outcome in entries])
87 if missing:
88 problems.append(f"the trace has no `{missing}` at its place in the first-frame order")
89 return problems
90
91
92def main():
93 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
94 parser.add_argument("loader")
95 parser.add_argument("guest")
96 parser.add_argument("--probe", help="a Vulkan device test; its exit code 77 skips this test")
97 parser.add_argument("--runner", action="append", default=[],
98 help="run Windows executables through this command (repeat for its arguments), e.g. wine")
99 options = parser.parse_args()
100 timeout = 180 if options.runner else 90 # a first start of Wine in a fresh prefix can take tens of seconds
101
102 if options.probe:
103 probe = subprocess.run([*options.runner, options.probe], capture_output=True, timeout=timeout)
104 if probe.returncode == SKIP:
105 print("SKIP: no usable Vulkan device (the probe test skipped)")
106 return SKIP
107
108 environment = dict(os.environ, LEONIDA_D3D12="vulkan")
109 run = subprocess.run([*options.runner, options.loader, "--run", os.path.basename(options.guest), "--trace-d3d12"],
110 cwd=os.path.dirname(os.path.abspath(options.guest)), env=environment, capture_output=True,
111 text=True, encoding="utf-8", errors="replace", timeout=timeout)
112 output = run.stdout + run.stderr
113 problems = check_output(run.returncode, output)
114 if problems:
115 print(output)
116 for problem in problems:
117 print(f"FAIL: {problem}")
118 return 1
119 print("tiny_frame under gta6rt --run on the Vulkan D3D12 device: OK")
120 return 0
121
122
123if __name__ == "__main__":
124 sys.exit(main())
diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp
index e459b4cc8..4d877d429 100644
--- a/runtime/test/command_list_test.cpp
+++ b/runtime/test/command_list_test.cpp
@@ -306,6 +306,6 @@ int main() {
306 CHECK(query_fits_heap(h::copy_queue_timestamp, q::timestamp) && !query_fits_heap(h::timestamp, q::occlusion)); 306 CHECK(query_fits_heap(h::copy_queue_timestamp, q::timestamp) && !query_fits_heap(h::timestamp, q::occlusion));
307 CHECK(query_fits_heap(h::so_statistics, q::so_statistics_stream3) && !query_fits_heap(6, q::occlusion)); 307 CHECK(query_fits_heap(h::so_statistics, q::so_statistics_stream3) && !query_fits_heap(6, q::occlusion));
308 CHECK(query_result_size(q::occlusion) == 8 && query_result_size(q::timestamp) == 8); 308 CHECK(query_result_size(q::occlusion) == 8 && query_result_size(q::timestamp) == 8);
309 CHECK(query_result_size(q::pipeline_statistics) == 88 && query_result_size(q::so_statistics_stream0) == 0); 309 CHECK(query_result_size(q::pipeline_statistics) == 88 && query_result_size(q::so_statistics_stream0) == 16);
310 return 0; 310 return 0;
311} 311}
diff --git a/runtime/test/cpp_unwind_test.cpp b/runtime/test/cpp_unwind_test.cpp
new file mode 100644
index 000000000..30cfc6ca1
--- /dev/null
+++ b/runtime/test/cpp_unwind_test.cpp
@@ -0,0 +1,31 @@
1#include <cstdio>
2
3namespace {
4
5struct UnwindMarker {
6 bool& destroyed;
7 ~UnwindMarker() { destroyed = true; }
8};
9
10struct TestException {};
11
12// Keep the object in a separate frame, outside the catch handler's function.
13__declspec(noinline) void throw_with_marker(bool& destroyed) {
14 UnwindMarker marker{destroyed};
15 throw TestException{};
16}
17
18} // namespace
19
20int main() {
21 bool destroyed = false;
22 try {
23 throw_with_marker(destroyed);
24 } catch (const TestException&) {
25 if (destroyed) return 0;
26 std::fputs("C++ exception unwound without running a destructor\n", stderr);
27 return 1;
28 }
29 std::fputs("Expected a C++ exception\n", stderr);
30 return 1;
31}
diff --git a/runtime/test/cs_wave_probe_spv.h b/runtime/test/cs_wave_probe_spv.h
new file mode 100644
index 000000000..28745ac06
--- /dev/null
+++ b/runtime/test/cs_wave_probe_spv.h
@@ -0,0 +1,63 @@
1// runtime/test/glsl/cs_wave_probe.comp, generated with glslang 16.6.0 (tests/test_cs_wave_probe_spv.py checks it):
2// glslangValidator -V --target-env vulkan1.2 -Os -o cs_wave_probe.spv runtime/test/glsl/cs_wave_probe.comp
3// SPIR-V 1.5, as the translator emits, so varying subgroup sizes are not allowed in it either.
4#pragma once
5#include <cstdint>
6namespace leonida::vk_test {
7inline constexpr std::uint32_t cs_wave_probe_spirv[] = {
8 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000042u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u,
9 0x0000003du, 0x00020011u, 0x00000040u, 0x00020011u, 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u,
10 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x000014e4u, 0x00000001u, 0x000a000fu, 0x00000005u,
11 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000fu, 0x00000019u, 0x00000021u, 0x00000029u, 0x00000030u,
12 0x00060010u, 0x00000004u, 0x00000011u, 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u,
13 0x000001c2u, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x0065636eu,
14 0x00090004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x5f65636eu, 0x63657675u,
15 0x00000032u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u, 0x625f7075u,
16 0x6f6c6c61u, 0x00000074u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u,
17 0x625f7075u, 0x63697361u, 0x00000000u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u,
18 0x00000009u, 0x64726f57u, 0x00000073u, 0x00040006u, 0x00000009u, 0x00000000u, 0x00000077u, 0x00050005u,
19 0x0000000du, 0x72657355u, 0x61746144u, 0x00000000u, 0x00050006u, 0x0000000du, 0x00000000u, 0x65736162u,
20 0x00000000u, 0x00030005u, 0x0000000fu, 0x00006370u, 0x00080005u, 0x00000019u, 0x4c5f6c67u, 0x6c61636fu,
21 0x6f766e49u, 0x69746163u, 0x6e496e6fu, 0x00786564u, 0x00060005u, 0x00000021u, 0x535f6c67u, 0x72676275u,
22 0x5370756fu, 0x00657a69u, 0x00080005u, 0x00000029u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x636f766eu,
23 0x6f697461u, 0x0044496eu, 0x00060005u, 0x00000030u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x00000044u,
24 0x00040047u, 0x00000008u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000009u, 0x00000002u, 0x00050048u,
25 0x00000009u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x0000000du, 0x00000002u, 0x00050048u,
26 0x0000000du, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000019u, 0x0000000bu, 0x0000001du,
27 0x00030047u, 0x00000021u, 0x00000000u, 0x00040047u, 0x00000021u, 0x0000000bu, 0x00000024u, 0x00030047u,
28 0x00000022u, 0x00000000u, 0x00030047u, 0x00000029u, 0x00000000u, 0x00040047u, 0x00000029u, 0x0000000bu,
29 0x00000029u, 0x00030047u, 0x0000002au, 0x00000000u, 0x00040047u, 0x00000030u, 0x0000000bu, 0x00000028u,
30 0x00040047u, 0x0000003du, 0x00000001u, 0x00000000u, 0x00040047u, 0x0000003eu, 0x00000001u, 0x00000001u,
31 0x00040047u, 0x0000003fu, 0x00000001u, 0x00000002u, 0x00040047u, 0x00000041u, 0x0000000bu, 0x00000019u,
32 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030027u, 0x00000006u, 0x000014e5u,
33 0x00040015u, 0x00000007u, 0x00000020u, 0x00000000u, 0x0003001du, 0x00000008u, 0x00000007u, 0x0003001eu,
34 0x00000009u, 0x00000008u, 0x00040020u, 0x00000006u, 0x000014e5u, 0x00000009u, 0x00040017u, 0x0000000cu,
35 0x00000007u, 0x00000002u, 0x0003001eu, 0x0000000du, 0x0000000cu, 0x00040020u, 0x0000000eu, 0x00000009u,
36 0x0000000du, 0x0004003bu, 0x0000000eu, 0x0000000fu, 0x00000009u, 0x00040015u, 0x00000010u, 0x00000020u,
37 0x00000001u, 0x0004002bu, 0x00000010u, 0x00000011u, 0x00000000u, 0x00040020u, 0x00000012u, 0x00000009u,
38 0x0000000cu, 0x00040020u, 0x00000018u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000018u, 0x00000019u,
39 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000001bu, 0x00000004u, 0x0004003bu, 0x00000018u, 0x00000021u,
40 0x00000001u, 0x00040020u, 0x00000023u, 0x000014e5u, 0x00000007u, 0x0004002bu, 0x00000007u, 0x00000027u,
41 0x00000001u, 0x0004003bu, 0x00000018u, 0x00000029u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000002eu,
42 0x00000002u, 0x0004003bu, 0x00000018u, 0x00000030u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x00000035u,
43 0x00000003u, 0x00020014u, 0x00000037u, 0x00030029u, 0x00000037u, 0x00000038u, 0x00040017u, 0x00000039u,
44 0x00000007u, 0x00000004u, 0x00040032u, 0x00000007u, 0x0000003du, 0x00000001u, 0x00040032u, 0x00000007u,
45 0x0000003eu, 0x00000001u, 0x00040032u, 0x00000007u, 0x0000003fu, 0x00000001u, 0x00040017u, 0x00000040u,
46 0x00000007u, 0x00000003u, 0x00060033u, 0x00000040u, 0x00000041u, 0x0000003du, 0x0000003eu, 0x0000003fu,
47 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u,
48 0x00000012u, 0x00000013u, 0x0000000fu, 0x00000011u, 0x0004003du, 0x0000000cu, 0x00000014u, 0x00000013u,
49 0x0004007cu, 0x00000006u, 0x00000015u, 0x00000014u, 0x0004003du, 0x00000007u, 0x0000001au, 0x00000019u,
50 0x00050084u, 0x00000007u, 0x0000001cu, 0x0000001au, 0x0000001bu, 0x0004003du, 0x00000007u, 0x00000022u,
51 0x00000021u, 0x00060041u, 0x00000023u, 0x00000024u, 0x00000015u, 0x00000011u, 0x0000001cu, 0x0005003eu,
52 0x00000024u, 0x00000022u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000028u, 0x0000001cu,
53 0x00000027u, 0x0004003du, 0x00000007u, 0x0000002au, 0x00000029u, 0x00060041u, 0x00000023u, 0x0000002bu,
54 0x00000015u, 0x00000011u, 0x00000028u, 0x0005003eu, 0x0000002bu, 0x0000002au, 0x00000002u, 0x00000004u,
55 0x00050080u, 0x00000007u, 0x0000002fu, 0x0000001cu, 0x0000002eu, 0x0004003du, 0x00000007u, 0x00000031u,
56 0x00000030u, 0x00060041u, 0x00000023u, 0x00000032u, 0x00000015u, 0x00000011u, 0x0000002fu, 0x0005003eu,
57 0x00000032u, 0x00000031u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000036u, 0x0000001cu,
58 0x00000035u, 0x00050153u, 0x00000039u, 0x0000003au, 0x00000035u, 0x00000038u, 0x00060156u, 0x00000007u,
59 0x0000003bu, 0x00000035u, 0x00000000u, 0x0000003au, 0x00060041u, 0x00000023u, 0x0000003cu, 0x00000015u,
60 0x00000011u, 0x00000036u, 0x0005003eu, 0x0000003cu, 0x0000003bu, 0x00000002u, 0x00000004u, 0x000100fdu,
61 0x00010038u,
62};
63}
diff --git a/runtime/test/d3d12_buffer_tiles_test.cpp b/runtime/test/d3d12_buffer_tiles_test.cpp
index 0e2b4bad7..8e6079bdd 100644
--- a/runtime/test/d3d12_buffer_tiles_test.cpp
+++ b/runtime/test/d3d12_buffer_tiles_test.cpp
@@ -6,8 +6,10 @@
6 6
7#include <algorithm> 7#include <algorithm>
8#include <array> 8#include <array>
9#include <cctype>
9#include <cstdint> 10#include <cstdint>
10#include <cstdio> 11#include <cstdio>
12#include <string>
11 13
12#define EXPECT(condition) do { \ 14#define EXPECT(condition) do { \
13 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ 15 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \
@@ -170,25 +172,55 @@ bool run(ID3D12Device& device, Results& result, bool layer = false) {
170 172
171 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); 173 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
172 const auto* data = static_cast<const std::uint32_t*>(mapped); 174 const auto* data = static_cast<const std::uint32_t*>(mapped);
175 // Every word of every tile, with the first wrong word of each tile printed, so a failure says which side,
176 // snapshot and tile differ and what was read there.
177 UINT wrong_tiles = 0;
173 for (UINT i = 0; i < snapshots; ++i) { 178 for (UINT i = 0; i < snapshots; ++i) {
174 for (UINT tile = 0; tile < tiles_per_buffer; ++tile) { 179 for (UINT tile = 0; tile < tiles_per_buffer; ++tile) {
175 const auto* first = data + (i * tiles_per_buffer + tile) * words_per_tile; 180 const auto* first = data + (i * tiles_per_buffer + tile) * words_per_tile;
176 result[i][tile] = *first; 181 result[i][tile] = *first;
177 EXPECT(std::all_of(first, first + words_per_tile, [&](auto word) { return word == expected[i][tile]; })); 182 const auto* bad = std::find_if(first, first + words_per_tile, [&](auto word) { return word != expected[i][tile]; });
183 if (bad == first + words_per_tile) continue;
184 ++wrong_tiles;
185 const auto wrong_words = std::count_if(bad, first + words_per_tile,
186 [&](auto word) { return word != expected[i][tile]; });
187 std::fprintf(stderr, "%s snapshot %u tile %u: word %u reads %#010x, want %#010x (%lld of %llu words wrong)\n",
188 layer ? "Vulkan layer" : "native D3D12", i, tile, unsigned(bad - first), unsigned(*bad),
189 unsigned(expected[i][tile]), static_cast<long long>(wrong_words),
190 static_cast<unsigned long long>(words_per_tile));
178 } 191 }
179 } 192 }
180 readback->Unmap(0, &empty); 193 readback->Unmap(0, &empty);
194 EXPECT(wrong_tiles == 0);
181 return true; 195 return true;
182} 196}
183 197
198// The host adapter for the native half. LEONIDA_HOST_ADAPTER picks it as in d3d12_copy_compare.h: "warp", or part of
199// an adapter name (case-insensitive); a value that names no adapter with tiled resources tier 2 skips the native half
200// rather than testing another GPU. Unset: the first hardware adapter with tier 2 or more.
184ComPtr<ID3D12Device> native_device() { 201ComPtr<ID3D12Device> native_device() {
185 ComPtr<IDXGIFactory4> factory; 202 ComPtr<IDXGIFactory4> factory;
186 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {}; 203 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {};
204 char want[128] = {};
205 GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want));
206 std::string needle(want);
207 std::transform(needle.begin(), needle.end(), needle.begin(), [](unsigned char c) { return char(std::tolower(c)); });
187 for (UINT i = 0;; ++i) { 208 for (UINT i = 0;; ++i) {
188 ComPtr<IDXGIAdapter1> adapter; 209 ComPtr<IDXGIAdapter1> adapter;
189 if (factory->EnumAdapters1(i, &adapter) != S_OK) return {}; 210 if (needle == "warp") {
211 if (i > 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) break;
212 } else if (factory->EnumAdapters1(i, &adapter) != S_OK) {
213 break;
214 }
190 DXGI_ADAPTER_DESC1 desc{}; 215 DXGI_ADAPTER_DESC1 desc{};
191 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue; 216 if (FAILED(adapter->GetDesc1(&desc))) continue;
217 if (needle.empty()) {
218 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue;
219 } else if (needle != "warp") {
220 std::string name;
221 for (const wchar_t* c = desc.Description; *c; ++c) name += char(std::tolower(*c < 128 ? *c : '?'));
222 if (name.find(needle) == std::string::npos) continue;
223 }
192 ComPtr<ID3D12Device> device; 224 ComPtr<ID3D12Device> device;
193 if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue; 225 if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue;
194 D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; 226 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
@@ -197,6 +229,10 @@ ComPtr<ID3D12Device> native_device() {
197 std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier)); 229 std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier));
198 return device; 230 return device;
199 } 231 }
232 if (!needle.empty())
233 std::printf("Native D3D12: no adapter matching LEONIDA_HOST_ADAPTER=%s with tiled resources tier 2 or more; "
234 "native half skipped\n", want);
235 return {};
200} 236}
201 237
202} // namespace 238} // namespace
diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp
index fd14dc29b..9839f17f7 100644
--- a/runtime/test/d3d12_bundle_test.cpp
+++ b/runtime/test/d3d12_bundle_test.cpp
@@ -12,6 +12,7 @@
12// (one line per call the application made, however often the bundle runs) and for object lifetimes. 12// (one line per call the application made, however often the bundle runs) and for object lifetimes.
13// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped. 13// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped.
14// No game data. 14// No game data.
15#include "test_temp_dir.h"
15#include "vk_test_device.h" 16#include "vk_test_device.h"
16#include "d3d12_test_shaders.h" 17#include "d3d12_test_shaders.h"
17#include "host_wine.h" 18#include "host_wine.h"
@@ -730,18 +731,10 @@ int main() {
730 const auto vs_program = fssm_program({0x56530101, 0xbf810000}); 731 const auto vs_program = fssm_program({0x56530101, 0xbf810000});
731 const auto ps_program = fssm_program({0x50530101, 0xbf810000}); 732 const auto ps_program = fssm_program({0x50530101, 0xbf810000});
732 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); 733 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
733 // Removed on every way out of main. 734 const testfiles::ScratchDir scratch("leonida_bundle_test"); // removed on every way out of main
734 struct Scratch { 735 const auto& library = scratch.path();
735 std::filesystem::path path = std::filesystem::temp_directory_path() / "leonida_bundle_test"; 736 REQUIRE(testfiles::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv"));
736 Scratch() { std::filesystem::create_directories(path); } 737 REQUIRE(testfiles::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv"));
737 ~Scratch() {
738 std::error_code ignored;
739 std::filesystem::remove_all(path, ignored);
740 }
741 } scratch;
742 const auto& library = scratch.path;
743 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing);
744 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing);
745 { 738 {
746 std::ofstream index(library / "index.json", std::ios::binary); 739 std::ofstream index(library / "index.json", std::ios::binary);
747 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 740 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp
index eb921ddce..e9eeed3a6 100644
--- a/runtime/test/d3d12_com_test.cpp
+++ b/runtime/test/d3d12_com_test.cpp
@@ -31,8 +31,10 @@ struct Ref {
31 31
32static_assert(std::is_move_constructible_v<leonida::Draw>); 32static_assert(std::is_move_constructible_v<leonida::Draw>);
33static_assert(std::is_move_assignable_v<leonida::Draw>); 33static_assert(std::is_move_assignable_v<leonida::Draw>);
34static_assert(sizeof(leonida::Draw::render_targets) == sizeof(leonida::TargetView) * 8); 34static_assert(sizeof(leonida::DrawViews::render_targets) == sizeof(leonida::TargetView) * 8);
35static_assert(sizeof(leonida::Draw::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32); 35static_assert(sizeof(leonida::DrawViews::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32);
36// The views stay out of the variant: a recorded command is sized by its largest member, Draw included.
37static_assert(sizeof(leonida::Draw) < sizeof(leonida::DrawViews));
36 38
37int main(int argc, char** argv) { 39int main(int argc, char** argv) {
38 if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true); 40 if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true);
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index 2b0b14cda..c8b29d29c 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -9,7 +9,9 @@
9// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract. 9// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract.
10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
11#include "shader_fixture_path.h" 11#include "shader_fixture_path.h"
12#include "test_temp_dir.h"
12#include "vk_test_device.h" 13#include "vk_test_device.h"
14#include "host_wine.h"
13#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
14#include "../src/gfx10_descriptors.h" 16#include "../src/gfx10_descriptors.h"
15#include "../src/cached_pso.h" 17#include "../src/cached_pso.h"
@@ -203,9 +205,11 @@ std::vector<HRESULT> cached_pso_cases(Device* device, D3D12_COMPUTE_PIPELINE_STA
203} 205}
204 206
205// The same cases on the PC runtime, with an empty compute shader from d3dcompiler_47: the default adapter, then WARP. 207// The same cases on the PC runtime, with an empty compute shader from d3dcompiler_47: the default adapter, then WARP.
206// Empty when the host has no D3D12 device or no compiler (Wine), which the caller reports as a skip. 208// Empty when the host has no D3D12 device or no compiler, or is Wine's, which the caller reports as a skip: vkd3d has
209// both, but its GetCachedBlob is a stub, so every host answered nothing and the comparison failed on each run.
207std::vector<std::vector<HRESULT>> host_cached_pso_cases(const std::vector<std::uint8_t>& root_blob, 210std::vector<std::vector<HRESULT>> host_cached_pso_cases(const std::vector<std::uint8_t>& root_blob,
208 const std::vector<std::uint8_t>& other_root_blob) { 211 const std::vector<std::uint8_t>& other_root_blob) {
212 if (hostwine::host_is_wine()) return {};
209 using CompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT, 213 using CompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT,
210 ID3DBlob**, ID3DBlob**); 214 ID3DBlob**, ID3DBlob**);
211 using CreateDeviceFn = decltype(&::D3D12CreateDevice); 215 using CreateDeviceFn = decltype(&::D3D12CreateDevice);
@@ -268,10 +272,9 @@ int main() {
268 for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); // filler, s_endpgm-like words 272 for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); // filler, s_endpgm-like words
269 const auto container = shader_container(fssm); 273 const auto container = shader_container(fssm);
270 EXPECT(leonida::fssm_program(container) == fssm); 274 EXPECT(leonida::fssm_program(container) == fssm);
271 const auto library = std::filesystem::temp_directory_path() / "leonida_compute_test"; 275 const testfiles::ScratchDir scratch("leonida_compute_test");
272 std::filesystem::create_directories(library); 276 const auto& library = scratch.path();
273 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv", 277 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv"));
274 std::filesystem::copy_options::overwrite_existing);
275 { 278 {
276 std::ofstream index(library / "index.json", std::ios::binary); 279 std::ofstream index(library / "index.json", std::ios::binary);
277 // An entry for the same program with set-0 bindings comes first, as in one group of the corpus: the PSO 280 // An entry for the same program with set-0 bindings comes first, as in one group of the corpus: the PSO
@@ -387,7 +390,9 @@ int main() {
387 E_INVALIDARG, E_INVALIDARG, S_OK}; 390 E_INVALIDARG, E_INVALIDARG, S_OK};
388 EXPECT(layer == expected); 391 EXPECT(layer == expected);
389 const auto hosts = host_cached_pso_cases(root_blob, other_root_blob); 392 const auto hosts = host_cached_pso_cases(root_blob, other_root_blob);
390 if (hosts.empty()) std::printf("SKIP: no host D3D12 device or compiler for the CachedPSO comparison\n"); 393 if (hosts.empty())
394 std::printf("SKIP: no host D3D12 reference (Wine, or no device or compiler) for the CachedPSO "
395 "comparison\n");
391 for (const auto& host : hosts) EXPECT(host == layer); 396 for (const auto& host : hosts) EXPECT(host == layer);
392 if (!hosts.empty()) std::printf("cached PSO: %zu host adapter(s) gave the same %d answers\n", hosts.size(), cached_case_count); 397 if (!hosts.empty()) std::printf("cached PSO: %zu host adapter(s) gave the same %d answers\n", hosts.size(), cached_case_count);
393 398
@@ -889,7 +894,6 @@ int main() {
889 fence.reset(); 894 fence.reset();
890 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 895 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
891 } 896 }
892 std::filesystem::remove_all(library);
893 897
894 unsigned mismatches = 0; 898 unsigned mismatches = 0;
895 for (std::uint32_t i = 0; i < elements; ++i) { 899 for (std::uint32_t i = 0; i < elements; ++i) {
diff --git a/runtime/test/d3d12_copy_xfmt_test.cpp b/runtime/test/d3d12_copy_xfmt_test.cpp
index 0a504b266..e4b22868c 100644
--- a/runtime/test/d3d12_copy_xfmt_test.cpp
+++ b/runtime/test/d3d12_copy_xfmt_test.cpp
@@ -49,11 +49,13 @@ D3D12_RESOURCE_DESC buf(UINT64 bytes) {
49struct Case { 49struct Case {
50 const char* name; 50 const char* name;
51 D3D12_RESOURCE_DESC src, dst; 51 D3D12_RESOURCE_DESC src, dst;
52 bool whole; // CopyResource, else CopyTextureRegion of subresource 0 with no box 52 bool whole; // CopyResource, else CopyTextureRegion
53 bool depth_values; // also marks the depth <-> colour cases, counted apart from the BC ones (both fail the test) 53 bool depth_values; // also marks the depth <-> colour cases, counted apart from the BC ones (both fail the test)
54 UINT x = 0, y = 0; // CopyTextureRegion destination offset 54 UINT x = 0, y = 0; // CopyTextureRegion destination offset
55 bool has_box = false; 55 bool has_box = false;
56 D3D12_BOX box{}; 56 D3D12_BOX box{};
57 UINT dst_mip = 0;
58 bool check_edge_bytes = false;
57}; 59};
58 60
59D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { 61D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) {
@@ -66,7 +68,11 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3
66 return x; 68 return x;
67} 69}
68 70
69// Returns false when the device refuses something; out: the destination's footprint rows, every mip. 71unsigned char upload_byte(UINT64 index) {
72 return static_cast<unsigned char>(index * 7 + 3);
73}
74
75// Pack the destination footprint rows for the copied mip, or every mip for CopyResource.
70bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRESULT& close_hr) { 76bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRESULT& close_hr) {
71 D3D12_COMMAND_QUEUE_DESC qd{}; 77 D3D12_COMMAND_QUEUE_DESC qd{};
72 Ref<ID3D12CommandQueue> q; 78 Ref<ID3D12CommandQueue> q;
@@ -78,7 +84,7 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
78 FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, a.p, nullptr, IID_PPV_ARGS(&l.p))) || 84 FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, a.p, nullptr, IID_PPV_ARGS(&l.p))) ||
79 FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) 85 FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
80 return false; 86 return false;
81 // Every mip goes up and comes back (one array layer). 87 // One array layer. Upload every source mip so both copy calls have initialized input.
82 const UINT ns = c.src.MipLevels, nd = c.dst.MipLevels; 88 const UINT ns = c.src.MipLevels, nd = c.dst.MipLevels;
83 D3D12_PLACED_SUBRESOURCE_FOOTPRINT sf[16]{}, df[16]{}; 89 D3D12_PLACED_SUBRESOURCE_FOOTPRINT sf[16]{}, df[16]{};
84 UINT rows[16]{}; 90 UINT rows[16]{};
@@ -100,12 +106,21 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
100 return false; 106 return false;
101 unsigned char* p = nullptr; 107 unsigned char* p = nullptr;
102 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false; 108 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false;
103 for (UINT64 i = 0; i < sbytes; ++i) p[i] = static_cast<unsigned char>(i * 7 + 3); 109 for (UINT64 i = 0; i < sbytes; ++i) p[i] = upload_byte(i);
104 if (c.depth_values) // normal floats in [0, 1): a host driver may flush denormals 110 if (c.depth_values) // normal floats in [0, 1): a host driver may flush denormals
105 for (UINT64 i = 0; i + 4 <= sbytes; i += 4) { 111 for (UINT64 i = 0; i + 4 <= sbytes; i += 4) {
106 const float v = float((i / 4) % 1000) / 1000.0f; 112 const float v = float((i / 4) % 1000) / 1000.0f;
107 std::memcpy(p + i, &v, 4); 113 std::memcpy(p + i, &v, 4);
108 } 114 }
115 if (c.check_edge_bytes) {
116 // The edge fixtures copy whole R32G32_UINT source rows, one eight-byte texel per BC1 block.
117 // Count the data bytes, excluding padding, so each row contains a different pattern.
118 const UINT64 bytes_per_row = c.src.Width * 8;
119 for (UINT y = 0; y < c.src.Height; ++y) {
120 auto* row = p + sf[0].Offset + UINT64(y) * sf[0].Footprint.RowPitch;
121 for (UINT64 x = 0; x < bytes_per_row; ++x) row[x] = upload_byte(y * bytes_per_row + x);
122 }
123 }
109 upload->Unmap(0, nullptr); 124 upload->Unmap(0, nullptr);
110 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false; 125 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false;
111 std::memset(p, 0xcd, size_t(dbytes)); 126 std::memset(p, 0xcd, size_t(dbytes));
@@ -123,11 +138,13 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
123 l->CopyResource(dst.p, src.p); 138 l->CopyResource(dst.p, src.p);
124 } else { 139 } else {
125 D3D12_TEXTURE_COPY_LOCATION s{src.p}, d{dst.p}; 140 D3D12_TEXTURE_COPY_LOCATION s{src.p}, d{dst.p};
141 d.SubresourceIndex = c.dst_mip;
126 l->CopyTextureRegion(&d, c.x, c.y, 0, &s, c.has_box ? &c.box : nullptr); 142 l->CopyTextureRegion(&d, c.x, c.y, 0, &s, c.has_box ? &c.box : nullptr);
127 } 143 }
128 b = transition(dst.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); 144 b = transition(dst.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
129 l->ResourceBarrier(1, &b); 145 l->ResourceBarrier(1, &b);
130 for (UINT i = 0; i < nd; ++i) { 146 const UINT first_mip = c.whole ? 0 : c.dst_mip, end_mip = c.whole ? nd : c.dst_mip + 1;
147 for (UINT i = first_mip; i < end_mip; ++i) {
131 D3D12_TEXTURE_COPY_LOCATION rs{dst.p}, rd{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; 148 D3D12_TEXTURE_COPY_LOCATION rs{dst.p}, rd{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
132 rs.SubresourceIndex = i; 149 rs.SubresourceIndex = i;
133 rd.PlacedFootprint = df[i]; 150 rd.PlacedFootprint = df[i];
@@ -143,9 +160,9 @@ bool run(ID3D12Device* dev, const Case& c, std::vector<unsigned char>& out, HRES
143 WaitForSingleObject(e, 10000); 160 WaitForSingleObject(e, 10000);
144 CloseHandle(e); 161 CloseHandle(e);
145 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false; 162 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&p)))) return false;
146 // Only the bytes inside each row, every mip. 163 // Compare the bytes inside the rows and leave footprint padding out.
147 out.clear(); 164 out.clear();
148 for (UINT i = 0; i < nd; ++i) 165 for (UINT i = first_mip; i < end_mip; ++i)
149 for (UINT r = 0; r < rows[i]; ++r) { 166 for (UINT r = 0; r < rows[i]; ++r) {
150 const unsigned char* row = p + df[i].Offset + r * df[i].Footprint.RowPitch; 167 const unsigned char* row = p + df[i].Offset + r * df[i].Footprint.RowPitch;
151 out.insert(out.end(), row, row + row_bytes[i]); 168 out.insert(out.end(), row, row + row_bytes[i]);
@@ -207,6 +224,12 @@ int main() {
207 {"CopyTextureRegion BC7 16x16 -> R32G32B32A32_UINT 4x4", tex(DXGI_FORMAT_BC7_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), false, false}, 224 {"CopyTextureRegion BC7 16x16 -> R32G32B32A32_UINT 4x4", tex(DXGI_FORMAT_BC7_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), false, false},
208 {"CopyTextureRegion BC1 box 4..12 x 8..16 -> R16G16B16A16_UINT 8x8 at (3, 1)", tex(DXGI_FORMAT_BC1_UNORM, 16, 16), tex(DXGI_FORMAT_R16G16B16A16_UINT, 8, 8), false, false, 3, 1, true, {4, 8, 0, 12, 16, 1}}, 225 {"CopyTextureRegion BC1 box 4..12 x 8..16 -> R16G16B16A16_UINT 8x8 at (3, 1)", tex(DXGI_FORMAT_BC1_UNORM, 16, 16), tex(DXGI_FORMAT_R16G16B16A16_UINT, 8, 8), false, false, 3, 1, true, {4, 8, 0, 12, 16, 1}},
209 {"CopyTextureRegion BC1 10x6 (padded box) -> R32G32_UINT 3x2", tex(DXGI_FORMAT_BC1_UNORM, 10, 6), tex(DXGI_FORMAT_R32G32_UINT, 3, 2), false, false}, 226 {"CopyTextureRegion BC1 10x6 (padded box) -> R32G32_UINT 3x2", tex(DXGI_FORMAT_BC1_UNORM, 10, 6), tex(DXGI_FORMAT_R32G32_UINT, 3, 2), false, false},
227 {.name = "CopyTextureRegion R32G32_UINT 3x2 -> BC1 10x6",
228 .src = tex(DXGI_FORMAT_R32G32_UINT, 3, 2), .dst = tex(DXGI_FORMAT_BC1_UNORM, 10, 6),
229 .whole = false, .depth_values = false, .check_edge_bytes = true},
230 {.name = "CopyTextureRegion R32G32_UINT 2x1 -> BC1 12x8 mip 1 (6x4)",
231 .src = tex(DXGI_FORMAT_R32G32_UINT, 2, 1), .dst = mips(tex(DXGI_FORMAT_BC1_UNORM, 12, 8), 2),
232 .whole = false, .depth_values = false, .dst_mip = 1, .check_edge_bytes = true},
210 {"CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)", tex(DXGI_FORMAT_R32G32_UINT, 2, 2), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 8, 4}, 233 {"CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)", tex(DXGI_FORMAT_R32G32_UINT, 2, 2), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 8, 4},
211 {"negative control: CopyTextureRegion R32_UINT 4x4 -> BC1 16x16", tex(DXGI_FORMAT_R32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false}, 234 {"negative control: CopyTextureRegion R32_UINT 4x4 -> BC1 16x16", tex(DXGI_FORMAT_R32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false},
212 {"negative control: CopyTextureRegion R32G32_UINT 4x4 -> BC1 16x16 at (12, 0)", tex(DXGI_FORMAT_R32G32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 12, 0}, 235 {"negative control: CopyTextureRegion R32G32_UINT 4x4 -> BC1 16x16 at (12, 0)", tex(DXGI_FORMAT_R32G32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 12, 0},
@@ -225,6 +248,23 @@ int main() {
225 unsigned differ = 0, differ_depth = 0, compared = 0; 248 unsigned differ = 0, differ_depth = 0, compared = 0;
226 for (const bool warp : {false, true}) { 249 for (const bool warp : {false, true}) {
227 for (const Case& c : cases) { 250 for (const Case& c : cases) {
251 // Check the full output of the partial-edge fixtures against the upload bytes on every available
252 // Vulkan device. Compare the same cases against native D3D12 using WARP when available.
253 if (!warp && (c.check_edge_bytes || std::strncmp(c.name, "negative", 8) == 0)) continue;
254 std::vector<unsigned char> h, o;
255 HRESULT hh = S_OK, oh = S_OK;
256 if (c.check_edge_bytes) {
257 std::vector<unsigned char> expected(size_t(c.src.Width) * c.src.Height * 8);
258 for (size_t i = 0; i < expected.size(); ++i) expected[i] = upload_byte(i);
259 const bool ours_ok = run(ours.p, c, o, oh);
260 if (!ours_ok || o != expected) {
261 std::fprintf(stderr, "%s: expected %zu upload bytes (read %zu bytes, Close 0x%08lx)\n",
262 c.name, expected.size(), o.size(), (unsigned long)oh);
263 ++differ;
264 continue;
265 }
266 std::printf("%s: matches %zu upload bytes\n", c.name, expected.size());
267 }
228 // A fresh device per case: an invalid copy removes the host device. 268 // A fresh device per case: an invalid copy removes the host device.
229 Ref<IDXGIAdapter> adapter; 269 Ref<IDXGIAdapter> adapter;
230 Ref<ID3D12Device> host; 270 Ref<ID3D12Device> host;
@@ -232,15 +272,12 @@ int main() {
232 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue; 272 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
233 const char* hn = adapter_name.c_str(); 273 const char* hn = adapter_name.c_str();
234 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 274 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
235 // Only WARP validates; a hardware driver may run an invalid copy.
236 if (!warp && std::strncmp(c.name, "negative", 8) == 0) continue;
237 std::vector<unsigned char> h, o;
238 HRESULT hh = S_OK, oh = S_OK;
239 const bool host_ok = run(host.p, c, h, hh); 275 const bool host_ok = run(host.p, c, h, hh);
240 drain(host.p); 276 drain(host.p);
241 if (!host_ok) { 277 if (!host_ok) {
242 std::printf("%s: %s refuses it (Close 0x%08lx, removed reason 0x%08lx), skipped\n", c.name, hn, 278 std::printf("%s: %s refuses it (Close 0x%08lx, removed reason 0x%08lx), skipped\n", c.name, hn,
243 (unsigned long)hh, (unsigned long)host->GetDeviceRemovedReason()); 279 (unsigned long)hh, (unsigned long)host->GetDeviceRemovedReason());
280 if (c.check_edge_bytes) continue; // the layer's output was already checked against the upload
244 // The layer must refuse it too (at Close or execution), never write out of bounds (validation). 281 // The layer must refuse it too (at Close or execution), never write out of bounds (validation).
245 const unsigned before = vk.validation_errors(); 282 const unsigned before = vk.validation_errors();
246 run(ours.p, c, o, oh); 283 run(ours.p, c, o, oh);
@@ -248,7 +285,7 @@ int main() {
248 vk.validation_errors() - before); 285 vk.validation_errors() - before);
249 continue; 286 continue;
250 } 287 }
251 const bool ours_ok = run(ours.p, c, o, oh); 288 const bool ours_ok = c.check_edge_bytes || run(ours.p, c, o, oh);
252 ++compared; 289 ++compared;
253 if (ours_ok && o == h) { 290 if (ours_ok && o == h) {
254 std::printf("%s: matches %s\n", c.name, hn); 291 std::printf("%s: matches %s\n", c.name, hn);
diff --git a/runtime/test/d3d12_depth24_draw_test.cpp b/runtime/test/d3d12_depth24_draw_test.cpp
new file mode 100644
index 000000000..436336e02
--- /dev/null
+++ b/runtime/test/d3d12_depth24_draw_test.cpp
@@ -0,0 +1,464 @@
1// D24_UNORM_S8_UINT in draws (D3D-309): depth bias in D24 units and depth quantised to 24 bits, as D3D12 gives on
2// any device. On a GPU without a D24 attachment (AMD) the layer stores D32_SFLOAT_S8_UINT and its pixel stage writes
3// the depth D24 would hold (src/depth24_fragment.h); with a native D24 the same expectations hold, so the test runs
4// on both and says which path it took.
5//
6// The cases of the finding (@marquezinii, measured by @Vonsek on #291, native D3D12 on an RTX 5080, a Radeon iGPU and
7// WARP): with the target cleared to 0.15625 + 2^-24 and a LESS test, a flat triangle at 0.15625 passes with bias 0
8// and fails everywhere with bias +1 and +2; an EQUAL test at exactly the cleared 0.15625 passes everywhere. Passing
9// pixels are counted through the stencil plane (INCR on pass), so pipelines without a pixel shader count too. Then
10// stored depth is read back through a footprint: a flat triangle with a constant bias, a sloped one with a
11// slope-scaled bias (with and without DepthBiasClamp, within one 24-bit step: the slope is the GPU's), and a pixel
12// shader that writes its own depth (stored quantised, not biased). Each runs with and without a pixel shader. The
13// finding's cases run once more through a pass-through geometry shader without a pixel shader, which also gets the
14// built-in depth stage.
15//
16// The shaders are GLSL written to the translator's contract (test/glsl/vs_depth.vert, ps_depth_empty.frag,
17// ps_depth_write.frag, gs_depth.geom). No game data.
18#include "vk_test_device.h"
19#include "d3d12_test_shaders.h"
20#include "../shims/d3d12_com.h"
21#include "../shims/d3d12_xs_device.h"
22#include "../src/depth24.h"
23#include "../src/shader_library.h"
24
25#include <algorithm>
26#include <cmath>
27#include <cstdio>
28#include <cstring>
29#include <fstream>
30#include <string>
31
32#if !defined(LEONIDA_TEST_VS_DEPTH_SPV) || !defined(LEONIDA_TEST_PS_DEPTH_EMPTY_SPV) || \
33 !defined(LEONIDA_TEST_PS_DEPTH_WRITE_SPV) || !defined(LEONIDA_TEST_GS_DEPTH_SPV)
34#error "the compiled test shaders must be named"
35#endif
36
37#define EXPECT(condition) do { \
38 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
39} while (0)
40
41using namespace d3d12test;
42using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX
43
44namespace {
45
46constexpr UINT target_side = 64;
47int g_failures = 0;
48
49void check(bool ok, const std::string& what) {
50 std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str());
51 if (!ok) ++g_failures;
52}
53
54std::uint32_t f2u(float f) {
55 std::uint32_t u;
56 std::memcpy(&u, &f, 4);
57 return u;
58}
59
60// D3D's bias for a UNORM24 target: (float)DepthBias * r + SlopeScaledDepthBias * MaxDepthSlope, clamped.
61float d3d_bias(int constant, float slope, float clamp, float max_slope) {
62 float bias = float(constant) * float(1.0 / 16777215.0) + slope * max_slope;
63 if (clamp > 0.0f) bias = std::fmin(bias, clamp);
64 if (clamp < 0.0f) bias = std::fmax(bias, clamp);
65 return bias;
66}
67
68struct Pass {
69 bool pixel_shader = false; // ps_depth_empty, else no pixel shader
70 bool shader_depth = false; // ps_depth_write instead
71 bool geometry_shader = false; // gs_depth between the VS and the (absent) pixel shader
72 int bias = 0;
73 float slope = 0.0f, clamp = 0.0f;
74 D3D12_COMPARISON_FUNC func = D3D12_COMPARISON_FUNC_ALWAYS;
75 bool write = true;
76 float clear = 1.0f;
77 float z = 0.5f, dz = 0.0f, shader_z = 0.0f; // s0, s1 (vs_depth.vert), s2 (ps_depth_write.frag)
78};
79
80struct Result {
81 std::vector<std::uint32_t> depth; // 24-bit codes, target_side * target_side
82 std::vector<std::uint8_t> stencil;
83};
84
85struct Harness {
86 ID3D12Device* device = nullptr;
87 ID3D12RootSignature* root = nullptr;
88 std::vector<std::uint8_t> vs, ps_empty, ps_write, gs;
89 Ref<ID3D12Resource> depth, readback;
90 Ref<ID3D12DescriptorHeap> dsv_heap;
91 D3D12_CPU_DESCRIPTOR_HANDLE dsv{};
92 D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot[2]{};
93 Ref<ID3D12CommandQueue> queue;
94 Ref<ID3D12CommandAllocator> allocator;
95 Ref<ID3D12GraphicsCommandList> list;
96 Ref<ID3D12Fence> fence;
97 UINT64 fence_value = 0;
98
99 bool run(const Pass& p, Result& out, std::string& error) {
100 D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{};
101 desc.pRootSignature = root;
102 desc.VS = {vs.data(), vs.size()};
103 if (p.shader_depth)
104 desc.PS = {ps_write.data(), ps_write.size()};
105 else if (p.pixel_shader)
106 desc.PS = {ps_empty.data(), ps_empty.size()};
107 if (p.geometry_shader) desc.GS = {gs.data(), gs.size()};
108 desc.SampleMask = 0xffffffff;
109 desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
110 desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
111 desc.RasterizerState.DepthClipEnable = TRUE;
112 desc.RasterizerState.DepthBias = p.bias;
113 desc.RasterizerState.SlopeScaledDepthBias = p.slope;
114 desc.RasterizerState.DepthBiasClamp = p.clamp;
115 desc.DepthStencilState.DepthEnable = TRUE;
116 desc.DepthStencilState.DepthWriteMask = p.write ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
117 desc.DepthStencilState.DepthFunc = p.func;
118 desc.DepthStencilState.StencilEnable = TRUE;
119 desc.DepthStencilState.StencilReadMask = 0xff;
120 desc.DepthStencilState.StencilWriteMask = 0xff;
121 const D3D12_DEPTH_STENCILOP_DESC count{D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP,
122 D3D12_STENCIL_OP_INCR_SAT, D3D12_COMPARISON_FUNC_ALWAYS};
123 desc.DepthStencilState.FrontFace = desc.DepthStencilState.BackFace = count;
124 desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
125 desc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
126 desc.SampleDesc.Count = 1;
127 Ref<ID3D12PipelineState> pso;
128 if (FAILED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))) {
129 error = "CreateGraphicsPipelineState failed";
130 return false;
131 }
132 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, pso.p))) {
133 error = "list reset failed";
134 return false;
135 }
136 D3D12_RESOURCE_BARRIER to_write = transition(depth.p, D3D12_RESOURCE_STATE_COPY_SOURCE,
137 D3D12_RESOURCE_STATE_DEPTH_WRITE);
138 list->ResourceBarrier(1, &to_write);
139 list->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, p.clear, 0, 0, nullptr);
140 list->SetGraphicsRootSignature(root);
141 const std::uint32_t constants[3] = {f2u(p.z), f2u(p.dz), f2u(p.shader_z)};
142 list->SetGraphicsRoot32BitConstants(0, 3, constants, 0);
143 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
144 const D3D12_VIEWPORT viewport{0, 0, float(target_side), float(target_side), 0, 1};
145 const D3D12_RECT scissor{0, 0, LONG(target_side), LONG(target_side)};
146 list->RSSetViewports(1, &viewport);
147 list->RSSetScissorRects(1, &scissor);
148 list->OMSetRenderTargets(0, nullptr, FALSE, &dsv);
149 list->DrawInstanced(3, 1, 0, 0);
150 D3D12_RESOURCE_BARRIER to_copy = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE,
151 D3D12_RESOURCE_STATE_COPY_SOURCE);
152 list->ResourceBarrier(1, &to_copy);
153 for (UINT plane = 0; plane < 2; ++plane) {
154 D3D12_TEXTURE_COPY_LOCATION dst{};
155 dst.pResource = readback.p;
156 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
157 dst.PlacedFootprint = foot[plane];
158 D3D12_TEXTURE_COPY_LOCATION src{};
159 src.pResource = depth.p;
160 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
161 src.SubresourceIndex = plane;
162 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
163 }
164 if (list->Close() != S_OK) {
165 error = "Close failed";
166 return false;
167 }
168 ID3D12CommandList* lists[] = {list.p};
169 queue->ExecuteCommandLists(1, lists);
170 if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) {
171 error = "the layer refused the list";
172 return false;
173 }
174 if (FAILED(queue->Signal(fence.p, ++fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) {
175 error = "fence wait failed";
176 return false;
177 }
178 std::uint8_t* mapped = nullptr;
179 if (FAILED(readback->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) {
180 error = "Map failed";
181 return false;
182 }
183 out.depth.assign(target_side * target_side, 0);
184 out.stencil.assign(target_side * target_side, 0);
185 for (UINT y = 0; y < target_side; ++y)
186 for (UINT x = 0; x < target_side; ++x) {
187 std::uint32_t word;
188 std::memcpy(&word, mapped + foot[0].Offset + y * foot[0].Footprint.RowPitch + x * 4, 4);
189 out.depth[y * target_side + x] = word & leonida::depth24_max;
190 out.stencil[y * target_side + x] = mapped[foot[1].Offset + y * foot[1].Footprint.RowPitch + x];
191 }
192 readback->Unmap(0, nullptr);
193 return true;
194 }
195};
196
197std::string describe(const Pass& p) {
198 char text[200];
199 const char* stages = p.shader_depth ? "PS writes depth"
200 : p.pixel_shader ? "with PS"
201 : p.geometry_shader ? "GS, no PS"
202 : "no PS";
203 std::snprintf(text, sizeof(text), "%s, bias %d, slope %g, clamp %g", stages, p.bias, p.slope, p.clamp);
204 return text;
205}
206
207} // namespace
208
209int main() {
210 vktest::Device d;
211 const auto device_status = d.initialize();
212 if (device_status == vktest::DeviceStatus::unavailable) {
213 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
214 return 77;
215 }
216 EXPECT(device_status == vktest::DeviceStatus::ready);
217 bool native = true;
218 {
219 const auto props = reinterpret_cast<PFN_vkGetPhysicalDeviceFormatProperties>(
220 d.instance_proc(d.instance, "vkGetPhysicalDeviceFormatProperties"));
221 VkFormatProperties d24{};
222 props(d.physical, VK_FORMAT_D24_UNORM_S8_UINT, &d24);
223 native = d24.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
224 std::printf("D24_UNORM_S8_UINT: %s\n", native ? "native D24" : "stored as D32_SFLOAT_S8_UINT");
225 }
226
227 const auto vs_program = fssm_program({0x56530309, 0xbf810000});
228 const auto ps_empty_program = fssm_program({0x50530309, 0xbf810000});
229 const auto ps_write_program = fssm_program({0x50530310, 0xbf810000});
230 const auto gs_program = fssm_program({0x47530309, 0xbf810000});
231 const auto library = std::filesystem::temp_directory_path() / "leonida_depth24_draw_test";
232 std::filesystem::create_directories(library);
233 const auto copy = std::filesystem::copy_options::overwrite_existing;
234 std::filesystem::copy_file(LEONIDA_TEST_VS_DEPTH_SPV, library / "vs_depth.spv", copy);
235 std::filesystem::copy_file(LEONIDA_TEST_PS_DEPTH_EMPTY_SPV, library / "ps_depth_empty.spv", copy);
236 std::filesystem::copy_file(LEONIDA_TEST_PS_DEPTH_WRITE_SPV, library / "ps_depth_write.spv", copy);
237 std::filesystem::copy_file(LEONIDA_TEST_GS_DEPTH_SPV, library / "gs_depth.spv", copy);
238 {
239 std::ofstream index(library / "index.json", std::ios::binary);
240 index << "{\"vs_depth\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
241 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n"
242 " \"ps_depth_empty\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_empty_program)
243 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": []},\n"
244 " \"ps_depth_write\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_write_program)
245 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": []},\n"
246 " \"gs_depth\": {\"stage\": \"gs\", \"fssm_sha256\": \"" << leonida::sha256_hex(gs_program)
247 << "\", \"bindings\": [], \"push_constant_bytes\": 144}}";
248 }
249
250 {
251 rt::d3d12::VulkanDeviceInfo info{};
252 info.get_instance_proc = d.instance_proc;
253 info.instance = d.instance;
254 info.physical = d.physical;
255 info.device = d.device;
256 info.queue = d.queue;
257 info.queue_family = d.family;
258 info.buffer_device_address = true;
259 info.subgroup = d.subgroup;
260 info.shader_dir = library.string();
261 info.features = d.enabled; // depthBiasClamp and geometryShader among them
262 ID3D12Device* inner = nullptr;
263 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
264 Ref<ID3D12Device> device;
265 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
266 reinterpret_cast<void**>(&device.p))));
267 rt::d3d12::set_device_outer(inner, device.p);
268
269 D3D12_ROOT_PARAMETER param{};
270 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
271 param.Constants = {0, 0, 3};
272 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
273 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
274 root_desc.Desc_1_0 = {1, &param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
275 const auto root_blob = serialize_root_signature(root_desc);
276 EXPECT(!root_blob.empty());
277 Ref<ID3D12RootSignature> root;
278 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
279
280 Harness h;
281 h.device = device.p;
282 h.root = root.p;
283 h.vs = shader_container(vs_program);
284 h.ps_empty = shader_container(ps_empty_program);
285 h.ps_write = shader_container(ps_write_program);
286 h.gs = shader_container(gs_program);
287
288 D3D12_RESOURCE_DESC depth_desc{};
289 depth_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
290 depth_desc.Width = depth_desc.Height = target_side;
291 depth_desc.DepthOrArraySize = 1;
292 depth_desc.MipLevels = 1;
293 depth_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
294 depth_desc.SampleDesc.Count = 1;
295 depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
296 D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
297 D3D12_CLEAR_VALUE clear{};
298 clear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
299 clear.DepthStencil.Depth = 1.0f;
300 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &depth_desc,
301 D3D12_RESOURCE_STATE_COPY_SOURCE, &clear,
302 IID_PPV_ARGS(&h.depth.p))));
303 UINT64 total = 0;
304 device->GetCopyableFootprints(&depth_desc, 0, 2, 0, h.foot, nullptr, nullptr, &total);
305 D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
306 const D3D12_RESOURCE_DESC readback_desc = buffer_desc(total);
307 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
308 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
309 IID_PPV_ARGS(&h.readback.p))));
310 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
311 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&h.dsv_heap.p))));
312 h.dsv = {SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(h.dsv_heap.p, 9))(h.dsv_heap.p))};
313 device->CreateDepthStencilView(h.depth.p, nullptr, h.dsv);
314 D3D12_COMMAND_QUEUE_DESC queue_desc{};
315 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&h.queue.p))));
316 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&h.allocator.p))));
317 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, h.allocator.p, nullptr,
318 IID_PPV_ARGS(&h.list.p))));
319 EXPECT(SUCCEEDED(h.list->Close()));
320 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&h.fence.p))));
321
322 const auto passing = [](const Result& r) {
323 int n = 0;
324 for (std::uint8_t s : r.stencil) n += s != 0;
325 return n;
326 };
327 constexpr int all = int(target_side * target_side);
328 // Without a pixel shader, with one, and through a geometry shader without one.
329 for (int mode = 0; mode < 3; ++mode) {
330 const bool ps = mode == 1, gs = mode == 2;
331 if (gs && !d.enabled.geometryShader) {
332 std::printf("SKIP the geometry-shader cases: no geometryShader on this GPU\n");
333 continue;
334 }
335 // The finding's cases: one 24-bit step above 0.15625, LESS, bias 0, +1, +2.
336 const float above = 0.15625f + 5.9604645e-8f; // 0.15625 + 2^-24
337 for (int bias : {0, 1, 2}) {
338 Pass p;
339 p.pixel_shader = ps;
340 p.geometry_shader = gs;
341 p.bias = bias;
342 p.func = D3D12_COMPARISON_FUNC_LESS;
343 p.write = false;
344 p.clear = above;
345 p.z = 0.15625f;
346 Result r;
347 std::string error;
348 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
349 const int expected = bias == 0 ? all : 0;
350 check(passing(r) == expected, "LESS against 0.15625 + 2^-24, " + describe(p) + ": " +
351 std::to_string(passing(r)) + " of " + std::to_string(all) +
352 " pass, expected " + std::to_string(expected));
353 }
354 { // EQUAL at exactly the cleared value.
355 Pass p;
356 p.pixel_shader = ps;
357 p.geometry_shader = gs;
358 p.func = D3D12_COMPARISON_FUNC_EQUAL;
359 p.write = false;
360 p.clear = 0.15625f;
361 p.z = 0.15625f;
362 Result r;
363 std::string error;
364 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
365 check(passing(r) == all, "EQUAL at the cleared 0.15625, " + describe(p) + ": " +
366 std::to_string(passing(r)) + " of " + std::to_string(all) + " pass");
367 }
368 // Stored depth, flat: the D24 code of z + bias * r. z sits on a 24-bit step, so no rounding tie decides the
369 // code (NVIDIA breaks ties differently from WARP and AMD, depth24.h).
370 for (int bias : {0, 3, -5, 1000}) {
371 Pass p;
372 p.pixel_shader = ps;
373 p.geometry_shader = gs;
374 p.bias = bias;
375 p.z = leonida::depth24_to_float(5033000);
376 Result r;
377 std::string error;
378 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
379 const std::uint32_t expected = leonida::depth24_quantize(p.z + d3d_bias(bias, 0, 0, 0));
380 int wrong = 0;
381 for (std::uint32_t c : r.depth) wrong += c != expected;
382 if (native && bias != 0 && wrong) {
383 // Vulkan lets a fixed-point attachment's r be up to 2 * 2^-24 without VK_EXT_depth_bias_control's
384 // depthBiasExact, and the layer doesn't ask for it yet: reported, not failed (follow-up).
385 std::printf("KNOWN stored depth, flat, %s: native D24 bias not exact (code %u, D3D gives %u)\n",
386 describe(p).c_str(), r.depth[0], expected);
387 continue;
388 }
389 check(wrong == 0, "stored depth, flat, " + describe(p) + ": " + std::to_string(wrong) +
390 " of " + std::to_string(all) + " differ from code " + std::to_string(expected) +
391 " (first " + std::to_string(r.depth[0]) + ")");
392 }
393 // Stored depth, sloped: z = 0.5 + 0.25 * x_clip, so 1/128 per pixel in x. Within one 24-bit step without a
394 // slope term; with one, within two: on the D32 path the slope comes from the derivatives of the
395 // interpolated depth (a few float ulps), where D24 hardware uses the triangle's plane.
396 for (const auto& [slope, clamp] : {std::pair{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 0.004f}, {-2.0f, -0.01f}}) {
397 Pass p;
398 p.pixel_shader = ps;
399 p.geometry_shader = gs;
400 p.bias = 2;
401 p.slope = slope;
402 p.clamp = clamp;
403 p.z = 0.5f;
404 p.dz = 0.25f;
405 if (clamp != 0.0f && native && !d.enabled.depthBiasClamp) {
406 // The native path clamps in the rasterizer, which needs the feature this device left off.
407 std::printf("SKIP stored depth, sloped, %s: no depthBiasClamp on a native D24\n",
408 describe(p).c_str());
409 continue;
410 }
411 Result r;
412 std::string error;
413 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
414 int wrong = 0;
415 std::uint32_t first_bad = 0, first_expected = 0, worst = 0;
416 const std::uint32_t tolerance = slope != 0.0f ? 2 : 1;
417 for (UINT y = 0; y < target_side; ++y)
418 for (UINT x = 0; x < target_side; ++x) {
419 const float x_clip = (float(x) + 0.5f) * 2.0f / float(target_side) - 1.0f;
420 const float z = 0.5f + 0.25f * x_clip;
421 const std::uint32_t expected =
422 leonida::depth24_quantize(z + d3d_bias(p.bias, slope, clamp, 0.25f * 2.0f / float(target_side)));
423 const std::uint32_t got = r.depth[y * target_side + x];
424 const std::uint32_t diff = got > expected ? got - expected : expected - got;
425 worst = std::max(worst, diff);
426 if (diff > tolerance) {
427 if (!wrong) first_bad = got, first_expected = expected;
428 ++wrong;
429 }
430 }
431 if (native && wrong) {
432 std::printf("KNOWN stored depth, sloped, %s: native D24 bias not exact (code %u, D3D gives %u)\n",
433 describe(p).c_str(), first_bad, first_expected);
434 continue;
435 }
436 check(wrong == 0, "stored depth, sloped, " + describe(p) + ": " + std::to_string(wrong) + " of " +
437 std::to_string(all) + " more than " + std::to_string(tolerance) +
438 " step(s) off, largest " + std::to_string(worst) +
439 (wrong ? " (got " + std::to_string(first_bad) + ", expected " +
440 std::to_string(first_expected) + ")"
441 : std::string()));
442 }
443 }
444 // A pixel shader that writes its own depth: stored quantised, and D3D adds no bias to it.
445 for (int bias : {0, 7}) {
446 Pass p;
447 p.shader_depth = true;
448 p.bias = bias;
449 p.shader_z = 0.7f;
450 Result r;
451 std::string error;
452 EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false));
453 const std::uint32_t expected = leonida::depth24_quantize(0.7f);
454 int wrong = 0;
455 for (std::uint32_t c : r.depth) wrong += c != expected;
456 check(wrong == 0, "stored depth, " + describe(p) + " 0.7: " + std::to_string(wrong) + " of " +
457 std::to_string(all) + " differ from code " + std::to_string(expected) + " (first " +
458 std::to_string(r.depth[0]) + ")");
459 }
460 }
461 std::filesystem::remove_all(library);
462 std::printf("%d failure(s)\n", g_failures);
463 return g_failures ? 1 : 0;
464}
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index 77d37fa1e..e89735782 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -58,6 +58,23 @@ struct Ref {
58 58
59void* slot(void* object, unsigned index) { return (*reinterpret_cast<void***>(object))[index]; } 59void* slot(void* object, unsigned index) { return (*reinterpret_cast<void***>(object))[index]; }
60 60
61// A root signature blob from the PC runtime's own serializer; empty when it has none for that version.
62std::vector<std::uint8_t> serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) {
63 using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
64 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
65 const auto fn = d3d12 ? reinterpret_cast<SerializeFn>(
66 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
67 : nullptr;
68 std::vector<std::uint8_t> out;
69 ID3DBlob* blob = nullptr;
70 if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) {
71 const auto* bytes = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
72 out.assign(bytes, bytes + blob->GetBufferSize());
73 blob->Release();
74 }
75 return out;
76}
77
61D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { 78D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) {
62 D3D12_RESOURCE_DESC desc{}; 79 D3D12_RESOURCE_DESC desc{};
63 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; 80 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
@@ -869,6 +886,90 @@ int main() {
869 const g::SamplerWords biased_samplers[] = {negative_bias, positive_bias}; 886 const g::SamplerWords biased_samplers[] = {negative_bias, positive_bias};
870 EXPECT(rt::d3d12::register_samplers(device.p, biased_samplers) == S_OK); 887 EXPECT(rt::d3d12::register_samplers(device.p, biased_samplers) == S_OK);
871 888
889 // Static samplers of a root signature (docs/d3d12_vulkan.md section 3.5): no heap slot and no root argument,
890 // the shader holds the S# by value, so CreateRootSignature has to register it. One per blob version, each
891 // the wrapping sampler above with its own LOD range (so its own key), and one that only the fourth has:
892 // a border sampler with the UINT white border of the static enum. None is in the hash table before its
893 // root signature is created, all are after. A version the PC serializer here does not write is skipped.
894 const auto sampler_index = [&](const g::SamplerWords& words) {
895 std::uint32_t key[8]{~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u};
896 std::memcpy(key, words.data(), sizeof(words));
897 return rt::d3d12::bindless_hash_lookup(device.p, key);
898 };
899 struct StaticCase {
900 D3D_ROOT_SIGNATURE_VERSION version;
901 const char* name;
902 float max_lod;
903 bool uint_white_border;
904 g::SamplerWords words;
905 bool created;
906 } static_cases[] = {{D3D_ROOT_SIGNATURE_VERSION_1_0, "1.0", 6.0f, false, {}, false},
907 {D3D_ROOT_SIGNATURE_VERSION_1_1, "1.1", 7.0f, false, {}, false},
908 {D3D_ROOT_SIGNATURE_VERSION_1_2, "1.2", 8.0f, false, {}, false},
909 {D3D_ROOT_SIGNATURE_VERSION_1_1, "1.1, UINT white border", 9.0f, true, {}, false}};
910 std::vector<Ref<ID3D12RootSignature>> static_roots(std::size(static_cases));
911 UINT static_created = 0;
912 for (std::size_t c = 0; c < std::size(static_cases); ++c) {
913 StaticCase& test = static_cases[c];
914 g::Sampler expected = sampler;
915 expected.max_lod = test.max_lod;
916 if (test.uint_white_border) {
917 expected.address_u = g::AddressMode::clamp_border;
918 expected.border_color = g::BorderColor::opaque_white;
919 expected.integer_border = true;
920 }
921 test.words = g::encode(expected);
922 EXPECT(test.words != sampler_words && sampler_index(test.words) == 0);
923
924 D3D12_STATIC_SAMPLER_DESC1 fixed{};
925 fixed.Filter = sampler_desc.Filter;
926 fixed.AddressU = test.uint_white_border ? D3D12_TEXTURE_ADDRESS_MODE_BORDER : sampler_desc.AddressU;
927 fixed.AddressV = sampler_desc.AddressV;
928 fixed.AddressW = sampler_desc.AddressW;
929 fixed.MaxAnisotropy = sampler_desc.MaxAnisotropy;
930 fixed.ComparisonFunc = sampler_desc.ComparisonFunc;
931 fixed.BorderColor = test.uint_white_border ? D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT
932 : D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
933 fixed.MaxLOD = test.max_lod;
934 fixed.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
935 // D3D12_STATIC_SAMPLER_DESC is D3D12_STATIC_SAMPLER_DESC1 without the trailing Flags.
936 D3D12_STATIC_SAMPLER_DESC fixed0{};
937 std::memcpy(&fixed0, &fixed, sizeof(fixed0));
938 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
939 root_desc.Version = test.version;
940 if (test.version == D3D_ROOT_SIGNATURE_VERSION_1_0) {
941 root_desc.Desc_1_0.NumStaticSamplers = 1;
942 root_desc.Desc_1_0.pStaticSamplers = &fixed0;
943 } else if (test.version == D3D_ROOT_SIGNATURE_VERSION_1_1) {
944 root_desc.Desc_1_1.NumStaticSamplers = 1;
945 root_desc.Desc_1_1.pStaticSamplers = &fixed0;
946 } else {
947 root_desc.Desc_1_2.NumStaticSamplers = 1;
948 root_desc.Desc_1_2.pStaticSamplers = &fixed;
949 }
950 const std::vector<std::uint8_t> blob = serialize_root_signature(root_desc);
951 if (blob.empty()) {
952 std::printf("static sampler, root signature %s: the PC serializer does not write it, skipped\n",
953 test.name);
954 continue;
955 }
956 EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(),
957 IID_PPV_ARGS(&static_roots[c].p))));
958 EXPECT(sampler_index(test.words) != 0);
959 test.created = true;
960 ++static_created;
961 }
962 // The entries outlive their root signatures, as a heap slot's S# outlives the heap: the shader pass below
963 // samples with them after the last reference is gone.
964 for (std::size_t c = 0; c < std::size(static_cases); ++c) {
965 const std::uint32_t before = sampler_index(static_cases[c].words);
966 static_roots[c].reset();
967 EXPECT(sampler_index(static_cases[c].words) == before);
968 }
969 std::printf("static samplers: %u of %u root signatures registered their S#\n", static_created,
970 UINT(std::size(static_cases)));
971 EXPECT(static_created >= 3); // 1.0 and 1.1 are in every d3d12.dll; 1.2 came later
972
872 // The UINT texture's view in slot 0, and three border samplers after the first: UINT (0,0,0,0) and 973 // The UINT texture's view in slot 0, and three border samplers after the first: UINT (0,0,0,0) and
873 // (1,1,1,1) from CreateSampler2, which the proxy does not have (the inner device does), and float white. 974 // (1,1,1,1) from CreateSampler2, which the proxy does not have (the inner device does), and float white.
874 constexpr UINT uint_slot = 0, uint_black = 1, uint_white = 2, float_white = 3; 975 constexpr UINT uint_slot = 0, uint_black = 1, uint_white = 2, float_white = 3;
@@ -1551,6 +1652,24 @@ int main() {
1551 clamped, texels); 1652 clamped, texels);
1552 EXPECT(wrapped == texels && clamped == texels); 1653 EXPECT(wrapped == texels && clamped == texels);
1553 1654
1655 // The static samplers' S#s: the three wrapping ones give the texture, texel for texel, as the registered
1656 // literal does. Unregistered (CreateRootSignature dropping them) they would clamp like the second above.
1657 for (const StaticCase& test : static_cases) {
1658 if (!test.created || test.uint_white_border) continue;
1659 SampleKeys key = keys[0];
1660 std::memcpy(key.ssharp, test.words.data(), sizeof(key.ssharp));
1661 std::array<std::uint8_t, bytes> pixels{};
1662 EXPECT(sample_through_set(d, set0, set0_layout, {&key, 1}, pixels.data()));
1663 UINT static_wrapped = 0, static_clamped = 0;
1664 for (UINT i = 0; i < texels; ++i) {
1665 static_wrapped += std::memcmp(pixels.data() + 4 * i, texel(i % size, i / size).data(), 4) == 0;
1666 static_clamped += std::memcmp(pixels.data() + 4 * i, texel(size - 1, i / size).data(), 4) == 0;
1667 }
1668 std::printf("static sampler, root signature %s: %u/%u texels wrapped (%u would match a clamp)\n",
1669 test.name, static_wrapped, texels, static_clamped);
1670 EXPECT(static_wrapped == texels && static_clamped < texels);
1671 }
1672
1554 // With LOD zero requested, opposite bias extremes select the first and last mips. 1673 // With LOD zero requested, opposite bias extremes select the first and last mips.
1555 for (const auto& words : biased_samplers) { 1674 for (const auto& words : biased_samplers) {
1556 SampleKeys key = keys[0]; 1675 SampleKeys key = keys[0];
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 25c198d7a..eb530b084 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -13,6 +13,7 @@
13// The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. 13// The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data.
14// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 14// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
15#include "shader_fixture_path.h" 15#include "shader_fixture_path.h"
16#include "test_temp_dir.h"
16#include "vk_test_device.h" 17#include "vk_test_device.h"
17#include "d3d12_test_shaders.h" 18#include "d3d12_test_shaders.h"
18#include "../shims/d3d12_com.h" 19#include "../shims/d3d12_com.h"
@@ -68,14 +69,13 @@ int main() {
68 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); 69 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
69 const auto fullscreen_container = shader_container(fullscreen_program); 70 const auto fullscreen_container = shader_container(fullscreen_program);
70 const auto vs_int_container = shader_container(vs_int_program); 71 const auto vs_int_container = shader_container(vs_int_program);
71 const auto library = std::filesystem::temp_directory_path() / "leonida_draw_test"; 72 const testfiles::ScratchDir scratch("leonida_draw_test");
72 std::filesystem::create_directories(library); 73 const auto& library = scratch.path();
73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); 74 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv"));
74 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); 75 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv"));
75 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV), library / "vs_fullscreen.spv", 76 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV),
76 std::filesystem::copy_options::overwrite_existing); 77 library / "vs_fullscreen.spv"));
77 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_INT_SPV), library / "vs_draw_int.spv", 78 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_INT_SPV), library / "vs_draw_int.spv"));
78 std::filesystem::copy_options::overwrite_existing);
79 { 79 {
80 std::ofstream index(library / "index.json", std::ios::binary); 80 std::ofstream index(library / "index.json", std::ios::binary);
81 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 81 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
@@ -895,7 +895,6 @@ int main() {
895 fence.reset(); 895 fence.reset();
896 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 896 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
897 } 897 }
898 std::filesystem::remove_all(library);
899 898
900 unsigned mismatches = 0; 899 unsigned mismatches = 0;
901 for (UINT row = 0; row < size; ++row) { 900 for (UINT row = 0; row < size; ++row) {
diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp
index 22202dd50..2f788dc75 100644
--- a/runtime/test/d3d12_fspx_compute_test.cpp
+++ b/runtime/test/d3d12_fspx_compute_test.cpp
@@ -10,6 +10,7 @@
10// The shader (test/glsl/cs_user_data.comp) stands in for a translated one. No game data. Set LEONIDA_VK_VALIDATION=1 10// The shader (test/glsl/cs_user_data.comp) stands in for a translated one. No game data. Set LEONIDA_VK_VALIDATION=1
11// to run under VK_LAYER_KHRONOS_validation. 11// to run under VK_LAYER_KHRONOS_validation.
12#include "shader_fixture_path.h" 12#include "shader_fixture_path.h"
13#include "test_temp_dir.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
15#include "../src/shader_library.h" 16#include "../src/shader_library.h"
@@ -163,15 +164,18 @@ int main() {
163 constexpr std::uint32_t marker_a = 5000, marker_b = 7000; 164 constexpr std::uint32_t marker_a = 5000, marker_b = 7000;
164 const auto code_a = kind6(marker_a), code_b = kind6(marker_b); 165 const auto code_a = kind6(marker_a), code_b = kind6(marker_b);
165 const auto container_a = container(payload(code_a)); 166 const auto container_a = container(payload(code_a));
166 const auto library = std::filesystem::temp_directory_path() / "leonida_fspx_compute_test"; 167 const testfiles::ScratchDir scratch("leonida_fspx_compute_test");
167 std::filesystem::remove_all(library); 168 const auto& library = scratch.path();
168 std::filesystem::create_directories(library / "fspx"); 169 std::filesystem::create_directories(library / "fspx");
169 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data.spv"); 170 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV),
170 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data_b.spv"); 171 library / "fspx" / "cs_user_data.spv"));
172 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV),
173 library / "fspx" / "cs_user_data_b.spv"));
171 // The review case on #1911: program C in two containers whose kind-0 entries differ, translated to two 174 // The review case on #1911: program C in two containers whose kind-0 entries differ, translated to two
172 // different modules (the second has another generator word in its header, still a valid module). 175 // different modules (the second has another generator word in its header, still a valid module).
173 const auto code_c = kind6(9100); 176 const auto code_c = kind6(9100);
174 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_c_state1.spv"); 177 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV),
178 library / "fspx" / "cs_c_state1.spv"));
175 { 179 {
176 std::ifstream in(LEONIDA_TEST_CS_SPV, std::ios::binary); 180 std::ifstream in(LEONIDA_TEST_CS_SPV, std::ios::binary);
177 std::vector<char> words((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); 181 std::vector<char> words((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
@@ -395,7 +399,6 @@ int main() {
395 fence.reset(); 399 fence.reset();
396 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 400 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
397 } 401 }
398 std::filesystem::remove_all(library);
399 402
400 unsigned mismatches = 0; 403 unsigned mismatches = 0;
401 for (std::uint32_t i = 0; i < elements; ++i) { 404 for (std::uint32_t i = 0; i < elements; ++i) {
diff --git a/runtime/test/d3d12_geometry_test.cpp b/runtime/test/d3d12_geometry_test.cpp
index 3ee4420c3..1cfe035b7 100644
--- a/runtime/test/d3d12_geometry_test.cpp
+++ b/runtime/test/d3d12_geometry_test.cpp
@@ -40,7 +40,9 @@ struct Vertex {
40 40
41int main() { 41int main() {
42 vktest::Device d; 42 vktest::Device d;
43 EXPECT(d.create()); 43 const auto device_status = d.initialize();
44 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU (hosted CI): ctest skips
45 EXPECT(device_status == vktest::DeviceStatus::ready);
44 if (!d.enabled.geometryShader) { 46 if (!d.enabled.geometryShader) {
45 std::printf("SKIP: no geometryShader on this GPU\n"); 47 std::printf("SKIP: no geometryShader on this GPU\n");
46 return 77; // ctest's SKIP_RETURN_CODE 48 return 77; // ctest's SKIP_RETURN_CODE
diff --git a/runtime/test/d3d12_heap_properties_test.cpp b/runtime/test/d3d12_heap_properties_test.cpp
new file mode 100644
index 000000000..434a7522b
--- /dev/null
+++ b/runtime/test/d3d12_heap_properties_test.cpp
@@ -0,0 +1,284 @@
1// ID3D12Resource::GetHeapProperties on the Vulkan-backed device, compared with the host PC runtime: the properties
2// (type, CPU page property, memory pool, node masks) and heap flags it reports for committed resources in every heap
3// type (custom ones included) and with SHARED, ALLOW_DISPLAY, CREATE_NOT_ZEROED and CREATE_NOT_RESIDENT, for placed
4// resources in heaps of each kind, and for a reserved resource, with null arguments too. d3d12_node_mask_test covers
5// the node masks and DENY bits of a few committed resources; this test covers the rest. Every value is recorded,
6// with whether the call wrote its outputs (they start as a sentinel), and the two records must be the same. A
7// resource one device refuses to create is reported and its steps aren't compared. No shaders or game data. Skips
8// (77) without a Vulkan GPU or the standalone device; without a host D3D12 device only the layer's own record is
9// printed. Set LEONIDA_D3D49_VERBOSE=1 to print every value.
10#include "../shims/d3d12_com.h"
11
12#include <cstdint>
13#include <cstdio>
14#include <cstring>
15#include <string>
16#include <vector>
17
18#define EXPECT(condition) do { \
19 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
20} while (0)
21
22namespace {
23
24template<class T>
25struct Ref {
26 T* p = nullptr;
27 ~Ref() { reset(); }
28 void reset() {
29 if (p) p->Release();
30 p = nullptr;
31 }
32 T* operator->() const { return p; }
33};
34
35constexpr std::uint64_t kFaulted = 0xFA017EDull;
36constexpr std::uint64_t kNotCreated = 0x5C1F1Dull; // the resource couldn't be created on this device
37constexpr UINT kSentinel = 0xCDCDCDCDu;
38
39D3D12_RESOURCE_DESC buffer(UINT64 bytes = 64 * 1024) {
40 D3D12_RESOURCE_DESC d{};
41 d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
42 d.Width = bytes;
43 d.Height = 1;
44 d.DepthOrArraySize = 1;
45 d.MipLevels = 1;
46 d.SampleDesc.Count = 1;
47 d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
48 return d;
49}
50
51D3D12_RESOURCE_DESC texture(DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM,
52 D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
53 D3D12_RESOURCE_DESC d{};
54 d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
55 d.Width = 64;
56 d.Height = 64;
57 d.DepthOrArraySize = 1;
58 d.MipLevels = 1;
59 d.Format = format;
60 d.SampleDesc.Count = 1;
61 d.Flags = flags;
62 return d;
63}
64
65D3D12_HEAP_PROPERTIES heap(D3D12_HEAP_TYPE type) { return D3D12_HEAP_PROPERTIES{type}; }
66D3D12_HEAP_PROPERTIES custom(D3D12_CPU_PAGE_PROPERTY page, D3D12_MEMORY_POOL pool) {
67 return D3D12_HEAP_PROPERTIES{D3D12_HEAP_TYPE_CUSTOM, page, pool};
68}
69
70enum class Kind { committed, placed, reserved };
71
72struct Case {
73 const char* name;
74 Kind kind;
75 D3D12_HEAP_PROPERTIES props; // the committed resource's, or the placed resource's heap
76 D3D12_HEAP_FLAGS flags;
77 D3D12_RESOURCE_DESC desc;
78 D3D12_RESOURCE_STATES state;
79};
80
81const D3D12_HEAP_FLAGS kNone = D3D12_HEAP_FLAG_NONE;
82const D3D12_RESOURCE_STATES kCommon = D3D12_RESOURCE_STATE_COMMON;
83
84std::vector<Case> cases() {
85 const auto rt = texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
86 const auto ds = texture(DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
87 const auto uav = texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
88 auto uav_buffer = buffer();
89 uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
90 const auto wb = custom(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0);
91 const auto wc = custom(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0);
92 const auto none_l0 = custom(D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, D3D12_MEMORY_POOL_L0);
93 const auto none_l1 = custom(D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, D3D12_MEMORY_POOL_L1);
94 auto masks = heap(D3D12_HEAP_TYPE_DEFAULT);
95 masks.CreationNodeMask = 1;
96 masks.VisibleNodeMask = 1;
97 return {
98 {"committed buffer, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, buffer(), kCommon},
99 {"committed UAV buffer, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, uav_buffer, kCommon},
100 {"committed buffer, UPLOAD", Kind::committed, heap(D3D12_HEAP_TYPE_UPLOAD), kNone, buffer(),
101 D3D12_RESOURCE_STATE_GENERIC_READ},
102 {"committed buffer, READBACK", Kind::committed, heap(D3D12_HEAP_TYPE_READBACK), kNone, buffer(),
103 D3D12_RESOURCE_STATE_COPY_DEST},
104 {"committed buffer, CUSTOM write-back L0", Kind::committed, wb, kNone, buffer(), kCommon},
105 {"committed buffer, CUSTOM write-combine L0", Kind::committed, wc, kNone, buffer(), kCommon},
106 {"committed buffer, CUSTOM not-available L0", Kind::committed, none_l0, kNone, buffer(), kCommon},
107 {"committed buffer, CUSTOM not-available L1", Kind::committed, none_l1, kNone, buffer(), kCommon},
108 {"committed buffer, DEFAULT with node masks 1", Kind::committed, masks, kNone, buffer(), kCommon},
109 {"committed buffer, DEFAULT, SHARED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_SHARED,
110 buffer(), kCommon},
111 {"committed buffer, DEFAULT, CREATE_NOT_ZEROED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
112 D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon},
113 {"committed buffer, DEFAULT, CREATE_NOT_RESIDENT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
114 D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT, buffer(), kCommon},
115 {"committed buffer, DEFAULT, SHARED | CREATE_NOT_ZEROED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
116 D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon},
117 {"committed texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, texture(), kCommon},
118 {"committed render target, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, rt, kCommon},
119 {"committed depth texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, ds,
120 D3D12_RESOURCE_STATE_DEPTH_WRITE},
121 {"committed UAV texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, uav, kCommon},
122 {"committed render target, DEFAULT, ALLOW_DISPLAY", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
123 D3D12_HEAP_FLAG_ALLOW_DISPLAY, rt, kCommon},
124 {"committed render target, DEFAULT, SHARED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT),
125 D3D12_HEAP_FLAG_SHARED, rt, kCommon},
126 {"committed texture, CUSTOM write-back L0", Kind::committed, wb, kNone, texture(), kCommon},
127 {"committed texture, CUSTOM write-combine L0", Kind::committed, wc, kNone, texture(), kCommon},
128
129 {"placed buffer, DEFAULT heap, ALLOW_ONLY_BUFFERS", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
130 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), kCommon},
131 {"placed buffer, DEFAULT heap, ALLOW_ALL", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
132 D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES, buffer(), kCommon},
133 {"placed texture, DEFAULT heap, ALLOW_ONLY_NON_RT_DS_TEXTURES", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
134 D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, texture(), kCommon},
135 {"placed render target, DEFAULT heap, ALLOW_ONLY_RT_DS_TEXTURES", Kind::placed,
136 heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES, rt, kCommon},
137 {"placed texture, DEFAULT heap, ALLOW_ALL", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
138 D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES, texture(), kCommon},
139 {"placed buffer, UPLOAD heap", Kind::placed, heap(D3D12_HEAP_TYPE_UPLOAD),
140 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), D3D12_RESOURCE_STATE_GENERIC_READ},
141 {"placed buffer, READBACK heap", Kind::placed, heap(D3D12_HEAP_TYPE_READBACK),
142 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), D3D12_RESOURCE_STATE_COPY_DEST},
143 {"placed buffer, CUSTOM write-back L0 heap", Kind::placed, wb, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(),
144 kCommon},
145 {"placed buffer, DEFAULT heap, SHARED", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
146 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_SHARED, buffer(), kCommon},
147 {"placed buffer, DEFAULT heap, CREATE_NOT_ZEROED", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT),
148 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon},
149
150 {"reserved buffer", Kind::reserved, {}, kNone, buffer(), kCommon},
151 {"reserved texture", Kind::reserved, {}, kNone, [] {
152 auto d = texture();
153 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
154 return d;
155 }(), kCommon},
156 };
157}
158
159struct Record {
160 std::vector<std::string> names;
161 std::vector<std::uint64_t> values;
162 void add(const std::string& name, std::uint64_t value) {
163 names.push_back(name);
164 values.push_back(value);
165 }
166};
167
168HRESULT create(ID3D12Device* device, const Case& c, Ref<ID3D12Heap>& h, Ref<ID3D12Resource>& r) {
169 switch (c.kind) {
170 case Kind::committed:
171 return device->CreateCommittedResource(&c.props, c.flags, &c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p));
172 case Kind::placed: {
173 D3D12_HEAP_DESC hd{};
174 hd.SizeInBytes = 4 * 1024 * 1024;
175 hd.Properties = c.props;
176 hd.Flags = c.flags;
177 const HRESULT hr = device->CreateHeap(&hd, IID_PPV_ARGS(&h.p));
178 if (FAILED(hr)) return hr;
179 return device->CreatePlacedResource(h.p, 0, &c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p));
180 }
181 case Kind::reserved:
182 return device->CreateReservedResource(&c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p));
183 }
184 return E_FAIL;
185}
186
187HRESULT get(ID3D12Resource* r, D3D12_HEAP_PROPERTIES* p, D3D12_HEAP_FLAGS* f) {
188 __try {
189 return r->GetHeapProperties(p, f);
190 } __except (EXCEPTION_EXECUTE_HANDLER) {
191 return HRESULT(kFaulted);
192 }
193}
194
195void record_call(Record& out, const std::string& what, ID3D12Resource* r, bool want_props, bool want_flags) {
196 D3D12_HEAP_PROPERTIES p;
197 std::memset(&p, 0xCD, sizeof(p));
198 auto f = D3D12_HEAP_FLAGS(kSentinel);
199 const HRESULT hr = get(r, want_props ? &p : nullptr, want_flags ? &f : nullptr);
200 out.add(what + ": hr", std::uint32_t(hr));
201 if (want_props) {
202 out.add(what + ": Type", std::uint32_t(p.Type));
203 out.add(what + ": CPUPageProperty", std::uint32_t(p.CPUPageProperty));
204 out.add(what + ": MemoryPoolPreference", std::uint32_t(p.MemoryPoolPreference));
205 out.add(what + ": CreationNodeMask", p.CreationNodeMask);
206 out.add(what + ": VisibleNodeMask", p.VisibleNodeMask);
207 }
208 if (want_flags) out.add(what + ": flags", std::uint32_t(f));
209}
210
211void run(ID3D12Device* device, Record& out) {
212 for (const Case& c : cases()) {
213 Ref<ID3D12Heap> h;
214 Ref<ID3D12Resource> r;
215 const HRESULT created = create(device, c, h, r);
216 out.add(std::string(c.name) + ": created", std::uint32_t(created));
217 if (FAILED(created) || !r.p) {
218 out.add(std::string(c.name) + " [not created]", kNotCreated);
219 continue;
220 }
221 record_call(out, c.name, r.p, true, true);
222 record_call(out, std::string(c.name) + ", properties only", r.p, true, false);
223 record_call(out, std::string(c.name) + ", flags only", r.p, false, true);
224 record_call(out, std::string(c.name) + ", both null", r.p, false, false);
225 }
226}
227
228} // namespace
229
230int main() {
231 Ref<ID3D12Device> device;
232 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) {
233 std::printf("heap properties: no Vulkan device, skipped\n");
234 return 77;
235 }
236 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
237 Record ours;
238 run(device.p, ours);
239
240 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
241 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
242 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
243 : nullptr;
244 Ref<ID3D12Device> host;
245 if (!create_host || FAILED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) {
246 std::printf("heap properties: no host D3D12 device to compare with; %zu values recorded, not compared\n",
247 ours.values.size());
248 } else {
249 Record theirs;
250 run(host.p, theirs);
251 // A resource one side couldn't create has fewer entries: compare case by case on the names both have.
252 int mismatches = 0, compared = 0, skipped = 0;
253 std::size_t j = 0;
254 for (std::size_t i = 0; i < ours.names.size(); ++i) {
255 while (j < theirs.names.size() && theirs.names[j] != ours.names[i]) ++j;
256 if (j == theirs.names.size()) {
257 std::printf("heap properties %s: ours 0x%llx, the host has no such value (not compared)\n",
258 ours.names[i].c_str(), static_cast<unsigned long long>(ours.values[i]));
259 ++skipped;
260 j = 0;
261 continue;
262 }
263 const std::uint64_t a = ours.values[i], b = theirs.values[j];
264 if (b == kFaulted) {
265 std::printf("heap properties %s: the host faults, not compared (ours 0x%llx)\n", ours.names[i].c_str(),
266 static_cast<unsigned long long>(a));
267 ++skipped;
268 continue;
269 }
270 ++compared;
271 const bool same = a == b;
272 if (verbose || !same)
273 std::printf("heap properties %s: ours 0x%llx host 0x%llx%s\n", ours.names[i].c_str(),
274 static_cast<unsigned long long>(a), static_cast<unsigned long long>(b),
275 same ? "" : " MISMATCH");
276 mismatches += !same;
277 }
278 std::printf("heap properties: %d values compared with the host (%d more not compared), %d mismatches\n",
279 compared, skipped, mismatches);
280 EXPECT(mismatches == 0);
281 }
282 std::printf("d3d12_heap_properties_test: OK\n");
283 return 0;
284}
diff --git a/runtime/test/d3d12_indirect_dispatch_count_test.cpp b/runtime/test/d3d12_indirect_dispatch_count_test.cpp
new file mode 100644
index 000000000..75a86b220
--- /dev/null
+++ b/runtime/test/d3d12_indirect_dispatch_count_test.cpp
@@ -0,0 +1,231 @@
1// D3D12 ExecuteIndirect with a GPU count buffer and one DISPATCH argument per record.
2// The same synthetic workload runs on native WARP and on the Vulkan layer, with actual GPU readback.
3// Set LEONIDA_VK_VALIDATION=1 to enable Vulkan core and synchronization validation.
4#include "vk_test_device.h"
5#include "shader_fixture_path.h"
6#include "d3d12_test_shaders.h"
7#include "../shims/d3d12_com.h"
8#include "../src/shader_library.h"
9#include <dxgi1_4.h>
10#include <d3dcompiler.h>
11#include <array>
12#include <cstdio>
13#include <cstring>
14#include <fstream>
15
16#ifndef LEONIDA_TEST_INDIRECT_COUNT_SPV
17#error "LEONIDA_TEST_INDIRECT_COUNT_SPV must name the synthetic GLSL compute module"
18#endif
19
20using namespace d3d12test;
21namespace {
22constexpr UINT kMaximum = 3, kStride = 20, kArgsOffset = 32, kCountOffset = 44;
23const char native_shader[] = R"(
24RWByteAddressBuffer output : register(u0);
25[numthreads(1,1,1)]
26void main(uint3 group : SV_GroupID) {
27 uint old;
28 output.InterlockedAdd(0, 1, old);
29 output.InterlockedAdd(4, group.x + 1, old);
30}
31)";
32
33bool run(ID3D12Device* dev, const std::vector<std::uint8_t>& shader, UINT count, bool gpu_update,
34 std::array<UINT, 2>& result, bool shim) {
35 Ref<ID3D12RootSignature> root;
36 D3D12_ROOT_PARAMETER param{};
37 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
38 param.Descriptor = {0, 0};
39 param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
40 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
41 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
42 root_desc.Desc_1_0 = {1, &param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
43 const auto serialized = serialize_root_signature(root_desc);
44 if (serialized.empty() ||
45 FAILED(dev->CreateRootSignature(0, serialized.data(), serialized.size(), IID_PPV_ARGS(&root.p))))
46 return false;
47 D3D12_COMPUTE_PIPELINE_STATE_DESC desc{};
48 desc.pRootSignature = root.p;
49 desc.CS = {shader.data(), shader.size()};
50 Ref<ID3D12PipelineState> pso;
51 if (FAILED(dev->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p)))) return false;
52 const D3D12_INDIRECT_ARGUMENT_DESC argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH};
53 const D3D12_COMMAND_SIGNATURE_DESC signature_desc{kStride, 1, &argument, 0};
54 Ref<ID3D12CommandSignature> signature;
55 if (FAILED(dev->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p))))
56 return false;
57 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
58 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
59 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
60 Ref<ID3D12Resource> source, args, counts, output, readback;
61 const auto create = [&](Ref<ID3D12Resource>& dest, D3D12_HEAP_PROPERTIES heap,
62 D3D12_RESOURCE_STATES state, D3D12_RESOURCE_FLAGS flags) {
63 const auto buffer = buffer_desc(256, flags);
64 return SUCCEEDED(dev->CreateCommittedResource(
65 &heap, D3D12_HEAP_FLAG_NONE, &buffer, state, nullptr, IID_PPV_ARGS(&dest.p)));
66 };
67 if (!create(source, upload_heap, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE) ||
68 !create(args, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE) ||
69 !create(counts, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE) ||
70 !create(output, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ||
71 !create(readback, readback_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE))
72 return false;
73 std::array<UINT, 64> input{};
74 for (UINT i = 0; i < kMaximum; ++i) {
75 const UINT base = (kArgsOffset + i * kStride) / 4;
76 input[base] = i + 1; // number of groups in the record, 1 then 2 then 3
77 input[base + 1] = input[base + 2] = 1;
78 input[base + 3] = 0xa5a5a5a5; // padding: must be ignored
79 input[base + 4] = 0x5a5a5a5a;
80 }
81 input[40] = count; // source offset 160, copied to destination +44
82 input[41] = 3; // update count from source offset 164
83 void* mapped = nullptr;
84 if (FAILED(source->Map(0, nullptr, &mapped)) || !mapped) return false;
85 std::memcpy(mapped, input.data(), sizeof(input));
86 source->Unmap(0, nullptr);
87
88 const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_COMPUTE};
89 Ref<ID3D12CommandQueue> queue;
90 Ref<ID3D12CommandAllocator> allocator;
91 Ref<ID3D12GraphicsCommandList> list;
92 Ref<ID3D12Fence> fence;
93 if (FAILED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) ||
94 FAILED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&allocator.p))) ||
95 FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, allocator.p,
96 pso.p, IID_PPV_ARGS(&list.p))) ||
97 FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
98 return false;
99 list->CopyBufferRegion(args.p, kArgsOffset, source.p, kArgsOffset, kMaximum * kStride);
100 list->CopyBufferRegion(counts.p, kCountOffset, source.p, 160, 4);
101 list->CopyBufferRegion(output.p, 0, source.p, 0, 8); // initialize the UAV to zero
102 const D3D12_RESOURCE_BARRIER ready[] = {
103 transition(args.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
104 transition(counts.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
105 transition(output.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)};
106 list->ResourceBarrier(3, ready);
107 list->SetComputeRootSignature(root.p);
108 list->SetPipelineState(pso.p);
109 list->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress());
110 list->ExecuteIndirect(signature.p, kMaximum, args.p, kArgsOffset, counts.p, kCountOffset);
111 if (gpu_update) {
112 auto to_copy = transition(counts.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
113 D3D12_RESOURCE_STATE_COPY_DEST);
114 list->ResourceBarrier(1, &to_copy);
115 list->CopyBufferRegion(counts.p, kCountOffset, source.p, 164, 4);
116 auto to_indirect = transition(counts.p, D3D12_RESOURCE_STATE_COPY_DEST,
117 D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
118 list->ResourceBarrier(1, &to_indirect);
119 // Repeat with a count produced by a GPU copy after the previous indirect dispatch.
120 list->ExecuteIndirect(signature.p, kMaximum, args.p, kArgsOffset, counts.p, kCountOffset);
121 }
122 const auto to_copy = transition(output.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
123 D3D12_RESOURCE_STATE_COPY_SOURCE);
124 list->ResourceBarrier(1, &to_copy);
125 list->CopyBufferRegion(readback.p, 0, output.p, 0, 8);
126 if (FAILED(list->Close())) return false;
127 ID3D12CommandList* lists[] = {list.p};
128 queue->ExecuteCommandLists(1, lists);
129 if (shim && rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false;
130 if (FAILED(queue->Signal(fence.p, 1))) return false;
131 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
132 if (!event) return false;
133 const bool completed = SUCCEEDED(fence->SetEventOnCompletion(1, event)) &&
134 WaitForSingleObject(event, 20000) == WAIT_OBJECT_0;
135 CloseHandle(event);
136 if (!completed || FAILED(readback->Map(0, nullptr, &mapped)) || !mapped) return false;
137 std::memcpy(result.data(), mapped, sizeof(result));
138 readback->Unmap(0, nullptr);
139 return true;
140}
141
142std::array<UINT, 2> expected(UINT count, bool update) {
143 auto result = std::array<UINT, 2>{};
144 const auto accumulate = [&](UINT c) {
145 for (UINT i = 0; i < std::min(c, kMaximum); ++i) {
146 result[0] += i + 1;
147 result[1] += (i + 1) * (i + 2) / 2;
148 }
149 };
150 accumulate(count);
151 if (update) accumulate(3);
152 return result;
153}
154} // namespace
155
156int main() {
157 using Compile = decltype(&D3DCompile);
158 const HMODULE compiler = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
159 if (!compiler) return 77;
160 const auto compile = reinterpret_cast<Compile>(GetProcAddress(compiler, "D3DCompile"));
161 if (!compile) return 77;
162 Ref<ID3DBlob> native, errors;
163 if (FAILED(compile(native_shader, std::strlen(native_shader), nullptr, nullptr, nullptr,
164 "main", "cs_5_0", 0, 0, &native.p, &errors.p)) || !native.p)
165 return 1;
166 const auto* native_bytes = static_cast<const std::uint8_t*>(native->GetBufferPointer());
167 const std::vector<std::uint8_t> native_code(native_bytes, native_bytes + native->GetBufferSize());
168 Ref<IDXGIFactory4> factory;
169 Ref<IDXGIAdapter> warp;
170 Ref<ID3D12Device> host;
171 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) ||
172 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) ||
173 FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p))))
174 return 77;
175
176 vktest::Device vk;
177 vk.request_buffer_device_address = true;
178 const auto status = vk.initialize();
179 if (status == vktest::DeviceStatus::unavailable) return 77;
180 if (status != vktest::DeviceStatus::ready) return 1;
181 if (!vk.buffer_device_address) return 77;
182 std::vector<std::uint8_t> program = fssm_program({0x1100u, 0x44u, 0x55u, 0x66u, 0x77u, 0x88u});
183 for (UINT i = 0; i < 12; ++i) put32(program, 0xbf810000 + i);
184 const auto container = shader_container(program);
185 const auto fixture = std::filesystem::temp_directory_path() /
186 ("leonida_indirect_dispatch_count_" + std::to_string(GetCurrentProcessId()));
187 std::filesystem::create_directories(fixture);
188 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_INDIRECT_COUNT_SPV),
189 fixture / "count.spv", std::filesystem::copy_options::overwrite_existing);
190 {
191 std::ofstream index(fixture / "index.json", std::ios::binary);
192 index << "{\"count\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program)
193 << "\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1],"
194 "\"uses_code_base\":false,\"wave64\":false}}";
195 }
196 rt::d3d12::VulkanDeviceInfo info{};
197 info.get_instance_proc = vk.instance_proc;
198 info.instance = vk.instance;
199 info.physical = vk.physical;
200 info.device = vk.device;
201 info.queue = vk.queue;
202 info.queue_family = vk.family;
203 info.buffer_device_address = vk.buffer_device_address;
204 info.shader_dir = fixture.string();
205 Ref<ID3D12Device> layer;
206 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&layer.p)))) return 1;
207
208 unsigned cases = 0;
209 for (UINT count : {0u, 1u, 3u, 7u}) {
210 for (bool update : {false, true}) {
211 std::array<UINT, 2> native_result{}, layer_result{};
212 if (!run(host.p, native_code, count, update, native_result, false) ||
213 !run(layer.p, container, count, update, layer_result, true) ||
214 native_result != expected(count, update) || layer_result != native_result) {
215 std::fprintf(stderr, "count %u update %d: host %u/%u, layer %u/%u, expected %u/%u\n",
216 count, int(update), native_result[0], native_result[1],
217 layer_result[0], layer_result[1],
218 expected(count, update)[0], expected(count, update)[1]);
219 return 1;
220 }
221 ++cases;
222 }
223 }
224 if (vk.validation_errors()) {
225 std::fprintf(stderr, "validation errors: %u\n", vk.validation_errors());
226 return 1;
227 }
228 std::printf("counted ExecuteIndirect(DISPATCH): %u native WARP / Vulkan GPU comparisons passed; "
229 "count=0,1,max,>max, nonzero offsets and GPU count overwrite, no validation errors\n", cases);
230 return 0;
231}
diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp
index e742de72e..cd9448c75 100644
--- a/runtime/test/d3d12_m2_textured_test.cpp
+++ b/runtime/test/d3d12_m2_textured_test.cpp
@@ -14,6 +14,9 @@
14// the left half is drawn from the gradient, the right half (the second draw switches the SRV table to slot 1) from 14// the left half is drawn from the gradient, the right half (the second draw switches the SRV table to slot 1) from
15// the reflected texture. Compared byte for byte (error 0). The test also checks the hash table: the T# of each view and the S# 15// the reflected texture. Compared byte for byte (error 0). The test also checks the hash table: the T# of each view and the S#
16// have distinct non-zero indices, and bytes that were never created have none (the fallback, 0). 16// have distinct non-zero indices, and bytes that were never created have none (the fallback, 0).
17// The same quad is also drawn with LINEAR/CLAMP. Each RGBA8 channel is checked against the four clamped
18// texels at that pixel center, allowing one quantization level.
19//
17// Sampler control (suggested and measured by @Vonsek in #1489): with U in range, POINT/CLAMP, POINT/WRAP and the 20// Sampler control (suggested and measured by @Vonsek in #1489): with U in range, POINT/CLAMP, POINT/WRAP and the
18// fallback sampler all give the same pixels, so the draw above cannot tell which sampler it used. A second pass draws 21// fallback sampler all give the same pixels, so the draw above cannot tell which sampler it used. A second pass draws
19// with ps_m2_uoff.asm, which adds 1 to U just before image_sample, and two sampler-heap slots, [0] POINT/CLAMP and 22// with ps_m2_uoff.asm, which adds 1 to U just before image_sample, and two sampler-heap slots, [0] POINT/CLAMP and
@@ -30,6 +33,7 @@
30 33
31#include <algorithm> 34#include <algorithm>
32#include <array> 35#include <array>
36#include <cmath>
33#include <cstring> 37#include <cstring>
34#include <filesystem> 38#include <filesystem>
35#include <fstream> 39#include <fstream>
@@ -66,6 +70,26 @@ Texel gradient(UINT x, UINT y) {
66// The second texture: the first one point-reflected, so no texel of it is in the same place. 70// The second texture: the first one point-reflected, so no texel of it is in the same place.
67Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); } 71Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); }
68 72
73Texel linear_clamp(UINT col, UINT row) {
74 const float x = (col + 0.5f) * texture_size / target_size - 0.5f;
75 const float y = (row + 0.5f) * texture_size / target_size - 0.5f;
76 const int x0 = int(std::floor(x)), y0 = int(std::floor(y));
77 const float fx = x - x0, fy = y - y0;
78 const auto texel = col < target_size / 2 ? gradient : reflected;
79 auto tap = [&](int dx, int dy) {
80 return texel(std::clamp(x0 + dx, 0, int(texture_size) - 1),
81 std::clamp(y0 + dy, 0, int(texture_size) - 1));
82 };
83 const Texel a = tap(0, 0), b = tap(1, 0), c = tap(0, 1), d = tap(1, 1);
84 Texel result{};
85 for (unsigned k = 0; k < result.size(); ++k) {
86 const float top = a[k] + fx * (b[k] - a[k]);
87 const float bottom = c[k] + fx * (d[k] - c[k]);
88 result[k] = std::uint8_t(std::lround(top + fy * (bottom - top)));
89 }
90 return result;
91}
92
69} // namespace 93} // namespace
70 94
71int main() { 95int main() {
@@ -92,8 +116,15 @@ int main() {
92 const auto uoff_program = read_file(root_dir / "fssm" / "ps_m2_uoff.fssm"); 116 const auto uoff_program = read_file(root_dir / "fssm" / "ps_m2_uoff.fssm");
93 EXPECT(uoff_program.size() >= 4 && library.find("ps", leonida::sha256_hex(uoff_program))); 117 EXPECT(uoff_program.size() >= 4 && library.find("ps", leonida::sha256_hex(uoff_program)));
94 const auto uoff_container = shader_container(uoff_program); 118 const auto uoff_container = shader_container(uoff_program);
119 // ps_m2_literal builds its S# from immediates: the index lists it under literal_samplers.
120 const auto literal_program = read_file(root_dir / "fssm" / "ps_m2_literal.fssm");
121 const auto* literal_entry = library.find("ps", leonida::sha256_hex(literal_program));
122 EXPECT(literal_program.size() >= 4 && literal_entry);
123 const leonida::gfx10::SamplerWords literal_words{0x92u, 0xc00000u, 0x14500000u, 0u};
124 EXPECT(literal_entry->literal_samplers.size() == 1 && literal_entry->literal_samplers[0] == literal_words);
125 const auto literal_container = shader_container(literal_program);
95 126
96 std::vector<std::uint8_t> pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels; 127 std::vector<std::uint8_t> pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels, linear_pixels = pixels;
97 unsigned image_hits = 0, sampler_hits = 0; 128 unsigned image_hits = 0, sampler_hits = 0;
98 { 129 {
99 rt::d3d12::VulkanDeviceInfo info{}; 130 rt::d3d12::VulkanDeviceInfo info{};
@@ -167,6 +198,20 @@ int main() {
167 pso_desc.pRootSignature = indexed_root.p; 198 pso_desc.pRootSignature = indexed_root.p;
168 pso_desc.PS = {uoff_container.data(), uoff_container.size()}; 199 pso_desc.PS = {uoff_container.data(), uoff_container.size()};
169 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p)))); 200 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p))));
201 {
202 // A pipeline with a literal-S# shader registers that S#: before it the hash table has no key for the
203 // words (a lookup gives the fallback, 0), after it a sampler index. Nothing else names this S#.
204 std::uint32_t key[8];
205 std::memcpy(key, literal_words.data(), 16);
206 std::fill(key + 4, key + 8, 0xffffffffu);
207 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) == 0);
208 D3D12_GRAPHICS_PIPELINE_STATE_DESC literal_desc = pso_desc;
209 literal_desc.pRootSignature = root.p;
210 literal_desc.PS = {literal_container.data(), literal_container.size()};
211 Ref<ID3D12PipelineState> literal_pso;
212 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&literal_desc, IID_PPV_ARGS(&literal_pso.p))));
213 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) != 0);
214 }
170 215
171 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; 216 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
172 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; 217 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
@@ -218,7 +263,7 @@ int main() {
218 // The two heaps; their start handles come back in RAX (heap slots 9 and 10). 263 // The two heaps; their start handles come back in RAX (heap slots 9 and 10).
219 const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, 264 const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4,
220 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 265 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
221 const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2, 266 const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 3,
222 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 267 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
223 Ref<ID3D12DescriptorHeap> srv_heap, sampler_heap; 268 Ref<ID3D12DescriptorHeap> srv_heap, sampler_heap;
224 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); 269 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p))));
@@ -252,6 +297,10 @@ int main() {
252 EXPECT(sampler_step >= 16); 297 EXPECT(sampler_step >= 16);
253 sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; 298 sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
254 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + sampler_step)}); 299 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + sampler_step)});
300 sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
301 sampler_desc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
302 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + 2 * sampler_step)});
303
255 304
256 // The hash table, after the descriptors were created and before anything has run: a T# is 8 dwords of the 305 // The hash table, after the descriptors were created and before anything has run: a T# is 8 dwords of the
257 // heap slot, an S# 4 dwords followed by 0xFFFFFFFF x4. Each of the three has an index, they differ, and 306 // heap slot, an S# 4 dwords followed by 0xFFFFFFFF x4. Each of the three has an index, they differ, and
@@ -326,15 +375,18 @@ int main() {
326 const D3D12_VIEWPORT viewport{0, 0, float(target_size), float(target_size), 0, 1}; 375 const D3D12_VIEWPORT viewport{0, 0, float(target_size), float(target_size), 0, 1};
327 list->RSSetViewports(1, &viewport); 376 list->RSSetViewports(1, &viewport);
328 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); 377 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
329 list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu}); 378 auto draw_halves = [&](std::uint64_t sampler) {
330 for (UINT half = 0; half < 2; ++half) { 379 list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler});
331 // The same quad over the whole target; the scissor rectangle keeps one half, and the SRV table names 380 for (UINT half = 0; half < 2; ++half) {
332 // the texture of that half. 381 // The same quad over the whole target; the scissor rectangle keeps one half, and the SRV table names
333 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)}; 382 // the texture of that half.
334 list->RSSetScissorRects(1, &scissor); 383 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)};
335 list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step}); 384 list->RSSetScissorRects(1, &scissor);
336 list->DrawIndexedInstanced(6, 1, 0, 0, 0); 385 list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step});
337 } 386 list->DrawIndexedInstanced(6, 1, 0, 0, 0);
387 }
388 };
389 draw_halves(sampler_gpu);
338 390
339 D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, 391 D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET,
340 D3D12_RESOURCE_STATE_COPY_SOURCE); 392 D3D12_RESOURCE_STATE_COPY_SOURCE);
@@ -347,6 +399,13 @@ int main() {
347 src.pResource = target.p; 399 src.pResource = target.p;
348 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; 400 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
349 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); 401 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
402 auto to_render = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
403 list->ResourceBarrier(1, &to_render);
404 list->ClearRenderTargetView(rtv, clear, 0, nullptr);
405 draw_halves(sampler_gpu + 2 * sampler_step);
406 list->ResourceBarrier(1, &to_copy);
407 dst.pResource = readback2.p;
408 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
350 EXPECT(list->Close() == S_OK); 409 EXPECT(list->Close() == S_OK);
351 ID3D12CommandList* lists[] = {list.p}; 410 ID3D12CommandList* lists[] = {list.p};
352 queue->ExecuteCommandLists(1, lists); 411 queue->ExecuteCommandLists(1, lists);
@@ -357,6 +416,11 @@ int main() {
357 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); 416 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
358 std::memcpy(pixels.data(), mapped, pixels.size()); 417 std::memcpy(pixels.data(), mapped, pixels.size());
359 418
419 void* mapped_linear = nullptr;
420 EXPECT(SUCCEEDED(readback2->Map(0, nullptr, &mapped_linear)));
421 std::memcpy(linear_pixels.data(), mapped_linear, linear_pixels.size());
422 readback2->Unmap(0, nullptr);
423
360 // The control pass: U + 1 in the PS, WRAP sampler (slot 1) on the left, CLAMP (slot 0) on the right. 424 // The control pass: U + 1 in the PS, WRAP sampler (slot 1) on the left, CLAMP (slot 0) on the right.
361 Ref<ID3D12CommandAllocator> allocator2; 425 Ref<ID3D12CommandAllocator> allocator2;
362 Ref<ID3D12GraphicsCommandList> list2; 426 Ref<ID3D12GraphicsCommandList> list2;
@@ -418,12 +482,22 @@ int main() {
418 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 482 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
419 } 483 }
420 484
421 unsigned mismatches = 0; 485 unsigned mismatches = 0, linear_mismatches = 0;
486 int max_linear_error = 0;
422 for (UINT row = 0; row < target_size; ++row) { 487 for (UINT row = 0; row < target_size; ++row) {
423 for (UINT col = 0; col < target_size; ++col) { 488 for (UINT col = 0; col < target_size; ++col) {
424 const UINT tx = col / (target_size / texture_size), ty = row / (target_size / texture_size); 489 const UINT tx = col / (target_size / texture_size), ty = row / (target_size / texture_size);
425 const Texel want = col < target_size / 2 ? gradient(tx, ty) : reflected(tx, ty); 490 const Texel want = col < target_size / 2 ? gradient(tx, ty) : reflected(tx, ty);
426 const std::uint8_t* got = &pixels[std::size_t(row) * target_pitch + col * 4]; 491 const std::uint8_t* got = &pixels[std::size_t(row) * target_pitch + col * 4];
492 const Texel filtered = linear_clamp(col, row);
493 const auto* linear = &linear_pixels[std::size_t(row) * target_pitch + col * 4];
494 for (unsigned k = 0; k < filtered.size(); ++k) {
495 const int error = std::abs(int(linear[k]) - filtered[k]);
496 max_linear_error = std::max(max_linear_error, error);
497 if (error > 1 && linear_mismatches++ < 8)
498 std::fprintf(stderr, "LINEAR (%u, %u) channel %u: got %u want %u\n",
499 col, row, k, unsigned(linear[k]), unsigned(filtered[k]));
500 }
427 if (std::memcmp(got, want.data(), 4) == 0) continue; 501 if (std::memcmp(got, want.data(), 4) == 0) continue;
428 if (mismatches++ < 8) 502 if (mismatches++ < 8)
429 std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1], 503 std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1],
@@ -431,6 +505,8 @@ int main() {
431 } 505 }
432 } 506 }
433 EXPECT(!mismatches); 507 EXPECT(!mismatches);
508 EXPECT(!linear_mismatches);
509 std::printf("M2 LINEAR: %u pixels, maximum RGBA8 channel error %d\n", target_size * target_size, max_linear_error);
434 510
435 // The control pass: left half the gradient (WRAP: U + 1 wraps back), right half the reflected texture's last 511 // The control pass: left half the gradient (WRAP: U + 1 wraps back), right half the reflected texture's last
436 // column per row (CLAMP: U + 1 is past the edge). Pixels that differ from the plain pass tell the clamp was used. 512 // column per row (CLAMP: U + 1 is past the edge). Pixels that differ from the plain pass tell the clamp was used.
diff --git a/runtime/test/d3d12_method_variants_test.cpp b/runtime/test/d3d12_method_variants_test.cpp
index 943577fff..d1b8edf4a 100644
--- a/runtime/test/d3d12_method_variants_test.cpp
+++ b/runtime/test/d3d12_method_variants_test.cpp
@@ -1,5 +1,6 @@
1// The 1/2/3 method variants of the Vulkan-backed ID3D12Device (D3D-28), each compared with the method it wraps: 1// The 1/2/3 method variants of the Vulkan-backed ID3D12Device (D3D-28), each compared with the method it wraps:
2// CreateCommittedResource1/2/3 with CreateCommittedResource, CreateCommandQueue1 with CreateCommandQueue and 2// CreateCommittedResource1/2/3 with CreateCommittedResource, CreatePlacedResource2 with CreatePlacedResource,
3// CreateReservedResource1/2 with CreateReservedResource, CreateCommandQueue1 with CreateCommandQueue and
3// GetCopyableFootprints1 with GetCopyableFootprints. The device is called directly, not through the Xbox-ABI proxy, 4// GetCopyableFootprints1 with GetCopyableFootprints. The device is called directly, not through the Xbox-ABI proxy,
4// because the proxy's slot 76 is the Xbox texture method, not CreateCommittedResource3 (docs/d3d12_vulkan.md 5// because the proxy's slot 76 is the Xbox texture method, not CreateCommittedResource3 (docs/d3d12_vulkan.md
5// section 7). The newer arguments' edge cases are checked against the PC runtime's answers, live when the host has 6// section 7). The newer arguments' edge cases are checked against the PC runtime's answers, live when the host has
@@ -215,22 +216,65 @@ struct Edge {
215// The edge cases of the newer arguments, run on any ID3D12Device10: ours, or the host's PC runtime to compare 216// The edge cases of the newer arguments, run on any ID3D12Device10: ours, or the host's PC runtime to compare
216// with. A GetCopyableFootprints1 answer is S_FALSE when every output is all ones (the failure answer), S_OK when 217// with. A GetCopyableFootprints1 answer is S_FALSE when every output is all ones (the failure answer), S_OK when
217// the footprint is the ordinary one, E_FAIL otherwise. 218// the footprint is the ordinary one, E_FAIL otherwise.
218std::vector<Edge> edge_answers(ID3D12Device10* device) { 219std::vector<Edge> edge_answers(ID3D12Device10* device, ID3D12Device10* placed_device,
219 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD}; 220 ID3D12Device* size_host = nullptr) {
221 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD},
222 readback_heap{D3D12_HEAP_TYPE_READBACK}, bad_heap{D3D12_HEAP_TYPE(99)};
220 D3D12_RESOURCE_DESC1 texture = desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); 223 D3D12_RESOURCE_DESC1 texture = desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
224 D3D12_RESOURCE_DESC1 rt_tex =
225 desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET));
226 D3D12_RESOURCE_DESC1 ds_tex =
227 desc1(texture_desc(8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL));
228 D3D12_RESOURCE_DESC1 ds_deny_tex = desc1(texture_desc(
229 8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE));
230 D3D12_RESOURCE_DESC1 uav_tex =
231 desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
232 D3D12_RESOURCE_DESC1 rt_ds_tex = desc1(texture_desc(
233 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL));
234 D3D12_RESOURCE_DESC1 ds_uav_tex = desc1(texture_desc(
235 8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
236 D3D12_RESOURCE_DESC1 deny_only_tex =
237 desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE));
238 D3D12_RESOURCE_DESC1 zero_width_tex = desc1(texture_desc(0, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
239 D3D12_RESOURCE_DESC1 big_tex =
240 desc1(texture_desc(1024, 1024, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
241 D3D12_RESOURCE_DESC1 tex_256x256 =
242 desc1(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
243 D3D12_RESOURCE_DESC base_1000x600_10m =
244 texture_desc(1000, 600, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 10);
245 D3D12_RESOURCE_DESC base_300x200_f16 =
246 texture_desc(300, 200, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE);
247 D3D12_RESOURCE_DESC base_1x1024 =
248 texture_desc(1, 1024, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
249
221 D3D12_RESOURCE_DESC1 buffer = desc1(buffer_desc(300)); 250 D3D12_RESOURCE_DESC1 buffer = desc1(buffer_desc(300));
251 D3D12_RESOURCE_DESC1 uav_buffer = desc1(buffer_desc(256));
252 uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
253 D3D12_RESOURCE_DESC1 tall_buffer = desc1(buffer_desc(256));
254 tall_buffer.Height = 2;
255
222 D3D12_RESOURCE_DESC1 texture_region = texture, buffer_region = buffer; 256 D3D12_RESOURCE_DESC1 texture_region = texture, buffer_region = buffer;
223 texture_region.SamplerFeedbackMipRegion = buffer_region.SamplerFeedbackMipRegion = {4, 4, 1}; 257 texture_region.SamplerFeedbackMipRegion = buffer_region.SamplerFeedbackMipRegion = {4, 4, 1};
258
259 D3D12_CLEAR_VALUE cv_rt{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}};
260 D3D12_CLEAR_VALUE cv_ds{DXGI_FORMAT_D32_FLOAT, {1.f, 0}};
261 D3D12_CLEAR_VALUE cv_bad{DXGI_FORMAT_R32_FLOAT, {0.f, 0.f, 0.f, 1.f}};
262
263 const DXGI_FORMAT srgb_cast[] = {DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
264 const DXGI_FORMAT unknown_cast[] = {DXGI_FORMAT_UNKNOWN};
265 const DXGI_FORMAT wide_cast[] = {DXGI_FORMAT_R16G16B16A16_FLOAT};
266
224 const auto v2 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc) { 267 const auto v2 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc) {
225 Ref<ID3D12Resource> r; 268 Ref<ID3D12Resource> r;
226 return device->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 269 return device->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON,
227 nullptr, nullptr, IID_PPV_ARGS(&r.p)); 270 nullptr, nullptr, IID_PPV_ARGS(&r.p));
228 }; 271 };
229 const auto v3 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout, 272 const auto v3 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout,
230 UINT32 castable_count = 0, bool output = true) { 273 UINT32 castable_count = 0, bool output = true, D3D12_HEAP_FLAGS heap_flags = D3D12_HEAP_FLAG_NONE,
274 const D3D12_CLEAR_VALUE* clear = nullptr, const DXGI_FORMAT* castable = nullptr) {
231 Ref<ID3D12Resource> r; 275 Ref<ID3D12Resource> r;
232 return device->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &desc, layout, nullptr, nullptr, 276 return device->CreateCommittedResource3(&heap, heap_flags, &desc, layout, clear, nullptr, castable_count,
233 castable_count, nullptr, __uuidof(ID3D12Resource), 277 castable, __uuidof(ID3D12Resource),
234 output ? reinterpret_cast<void**>(&r.p) : nullptr); 278 output ? reinterpret_cast<void**>(&r.p) : nullptr);
235 }; 279 };
236 const auto footprint = [&](const D3D12_RESOURCE_DESC1& desc) { 280 const auto footprint = [&](const D3D12_RESOURCE_DESC1& desc) {
@@ -245,6 +289,53 @@ std::vector<Edge> edge_answers(ID3D12Device10* device) {
245 void* queue = nullptr; 289 void* queue = nullptr;
246 const HRESULT null_queue = device->CreateCommandQueue1(nullptr, creator, __uuidof(ID3D12CommandQueue), &queue); 290 const HRESULT null_queue = device->CreateCommandQueue1(nullptr, creator, __uuidof(ID3D12CommandQueue), &queue);
247 if (queue) static_cast<IUnknown*>(queue)->Release(); 291 if (queue) static_cast<IUnknown*>(queue)->Release();
292
293 // Placed v2 setup.
294 D3D12_HEAP_DESC placed_heap_desc{256 * 1024, default_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
295 D3D12_HEAP_FLAG_NONE};
296 D3D12_HEAP_DESC upload_heap_desc{256 * 1024, upload_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
297 D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS};
298 Ref<ID3D12Heap> placed_heap, upload_placed_heap;
299 placed_device->CreateHeap(&placed_heap_desc, IID_PPV_ARGS(&placed_heap.p));
300 placed_device->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p));
301 const auto p2 = [&](ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout,
302 const D3D12_CLEAR_VALUE* clear = nullptr, UINT32 cast_count = 0,
303 const DXGI_FORMAT* cast = nullptr) {
304 Ref<ID3D12Resource> r;
305 return placed_device->CreatePlacedResource2(heap, offset, &desc, layout, clear, cast_count, cast,
306 IID_PPV_ARGS(&r.p));
307 };
308 const auto p2_host_sized = [&](const D3D12_RESOURCE_DESC& base, UINT64 fallback_bytes) {
309 const UINT64 bytes = size_host ? size_host->GetResourceAllocationInfo(0, 1, &base).SizeInBytes
310 : fallback_bytes;
311 D3D12_HEAP_DESC hd{bytes, default_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, D3D12_HEAP_FLAG_NONE};
312 Ref<ID3D12Heap> h;
313 if (FAILED(placed_device->CreateHeap(&hd, IID_PPV_ARGS(&h.p)))) return E_FAIL;
314 return p2(h.p, 0, desc1(base), D3D12_BARRIER_LAYOUT_COMMON);
315 };
316
317 // Reserved v1/v2 setup.
318 D3D12_RESOURCE_DESC res_tex = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
319 res_tex.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
320 D3D12_RESOURCE_DESC res_rt = res_tex;
321 res_rt.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
322 D3D12_RESOURCE_DESC res_uav = res_tex;
323 res_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
324 D3D12_RESOURCE_DESC res_ds_deny = texture_desc(
325 64, 64, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);
326 res_ds_deny.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
327 D3D12_RESOURCE_DESC res_buf = buffer_desc(65536);
328 const auto r1 = [&](const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) {
329 Ref<ID3D12Resource> r;
330 return device->CreateReservedResource1(&desc, state, clear, nullptr, IID_PPV_ARGS(&r.p));
331 };
332 const auto r2 = [&](const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout,
333 const D3D12_CLEAR_VALUE* clear = nullptr, UINT32 cast_count = 0,
334 const DXGI_FORMAT* cast = nullptr) {
335 Ref<ID3D12Resource> r;
336 return device->CreateReservedResource2(&desc, layout, clear, nullptr, cast_count, cast, IID_PPV_ARGS(&r.p));
337 };
338
248 return { 339 return {
249 {"CreateCommittedResource2, texture with a mip region", v2(default_heap, texture_region), E_INVALIDARG}, 340 {"CreateCommittedResource2, texture with a mip region", v2(default_heap, texture_region), E_INVALIDARG},
250 {"CreateCommittedResource2, buffer with a mip region", v2(upload_heap, buffer_region), S_OK}, 341 {"CreateCommittedResource2, buffer with a mip region", v2(upload_heap, buffer_region), S_OK},
@@ -254,12 +345,138 @@ std::vector<Edge> edge_answers(ID3D12Device10* device) {
254 v3(upload_heap, buffer_region, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, 345 v3(upload_heap, buffer_region, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
255 {"CreateCommittedResource3, buffer in layout COMMON", v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON), 346 {"CreateCommittedResource3, buffer in layout COMMON", v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON),
256 E_INVALIDARG}, 347 E_INVALIDARG},
348 {"CreateCommittedResource3, upload buffer in UNDEFINED",
349 v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
350 {"CreateCommittedResource3, readback buffer in COMMON",
351 v3(readback_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
352 {"CreateCommittedResource3, readback buffer in UNDEFINED",
353 v3(readback_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
354 {"CreateCommittedResource3, upload buffer with ALLOW_UAV",
355 v3(upload_heap, uav_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
356 {"CreateCommittedResource3, buffer with Height=2",
357 v3(default_heap, tall_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
257 {"CreateCommittedResource3, texture in layout UNDEFINED", 358 {"CreateCommittedResource3, texture in layout UNDEFINED",
258 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, 359 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
259 {"CreateCommittedResource3, castable count with a null list", 360 {"CreateCommittedResource3, castable count with a null list",
260 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 2), S_OK}, 361 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 2), S_OK},
261 {"CreateCommittedResource3, null output", 362 {"CreateCommittedResource3, null output",
262 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, false), S_FALSE}, 363 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, false), S_FALSE},
364 {"CreateCommittedResource3, bad heap type",
365 v3(bad_heap, texture, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
366 {"CreateCommittedResource3, DENY_BUFFERS heap flag",
367 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_DENY_BUFFERS), E_INVALIDARG},
368 {"CreateCommittedResource3, ALLOW_DISPLAY on buffer",
369 v3(default_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, 0, true, D3D12_HEAP_FLAG_ALLOW_DISPLAY),
370 E_INVALIDARG},
371 {"CreateCommittedResource3, clear value on buffer",
372 v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), E_INVALIDARG},
373 {"CreateCommittedResource3, clear value on plain texture",
374 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), E_INVALIDARG},
375 {"CreateCommittedResource3, mismatched clear value on RT",
376 v3(default_heap, rt_tex, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_NONE, &cv_bad), E_INVALIDARG},
377 {"CreateCommittedResource3, valid clear value on RT",
378 v3(default_heap, rt_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), S_OK},
379 {"CreateCommittedResource3, valid clear value on DS",
380 v3(default_heap, ds_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, 0, true, D3D12_HEAP_FLAG_NONE, &cv_ds),
381 S_OK},
382 {"CreateCommittedResource3, RT | DS flags",
383 v3(default_heap, rt_ds_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
384 {"CreateCommittedResource3, DS | UAV flags",
385 v3(default_heap, ds_uav_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
386 {"CreateCommittedResource3, DENY_SHADER_RESOURCE without DS",
387 v3(default_heap, deny_only_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
388 {"CreateCommittedResource3, texture Width=0",
389 v3(default_heap, zero_width_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
390 {"CreateCommittedResource3, non-RT texture in RENDER_TARGET",
391 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG},
392 {"CreateCommittedResource3, non-UAV texture in UNORDERED_ACCESS",
393 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG},
394 {"CreateCommittedResource3, non-UAV texture in DIRECT_QUEUE_UAV",
395 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS), E_INVALIDARG},
396 {"CreateCommittedResource3, non-UAV texture in COMPUTE_QUEUE_UAV",
397 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS), E_INVALIDARG},
398 {"CreateCommittedResource3, UAV texture in DIRECT_QUEUE_UAV",
399 v3(default_heap, uav_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS), S_OK},
400 {"CreateCommittedResource3, non-DS texture in DEPTH_STENCIL_WRITE",
401 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG},
402 {"CreateCommittedResource3, non-DS texture in DEPTH_STENCIL_READ",
403 v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ), E_INVALIDARG},
404 {"CreateCommittedResource3, DS texture in DEPTH_STENCIL_READ",
405 v3(default_heap, ds_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ), S_OK},
406 {"CreateCommittedResource3, DS+DENY_SR in SHADER_RESOURCE",
407 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE), E_INVALIDARG},
408 {"CreateCommittedResource3, DS+DENY_SR in DIRECT_QUEUE_SHADER_RESOURCE",
409 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE), E_INVALIDARG},
410 {"CreateCommittedResource3, DS+DENY_SR in COMPUTE_QUEUE_SHADER_RESOURCE",
411 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE), E_INVALIDARG},
412 {"CreateCommittedResource3, DS+DENY_SR in GENERIC_READ",
413 v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_GENERIC_READ), S_OK},
414 {"CreatePlacedResource2, buffer in COMMON",
415 p2(upload_placed_heap.p, 0, buffer, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
416 {"CreatePlacedResource2, buffer with Height=2",
417 p2(placed_heap.p, 0, tall_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
418 {"CreatePlacedResource2, upload buffer with ALLOW_UAV",
419 p2(upload_placed_heap.p, 0, uav_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG},
420 {"CreatePlacedResource2, clear value on buffer",
421 p2(placed_heap.p, 0, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, &cv_rt), E_INVALIDARG},
422 {"CreatePlacedResource2, clear value on plain texture",
423 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_COMMON, &cv_rt), E_INVALIDARG},
424 {"CreatePlacedResource2, valid clear value on RT",
425 p2(placed_heap.p, 0, rt_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET, &cv_rt), S_OK},
426 {"CreatePlacedResource2, oversized 1024x1024 texture in 256 KiB heap",
427 p2(placed_heap.p, 0, big_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
428 {"CreatePlacedResource2, 256x256 at 64 KiB in 256 KiB heap",
429 p2(placed_heap.p, 65536, tex_256x256, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
430 {"CreatePlacedResource2, 1000x600 RGBA8 10 mips in host-sized heap",
431 p2_host_sized(base_1000x600_10m, 3538944), S_OK},
432 {"CreatePlacedResource2, 300x200 RGBA16F in host-sized heap",
433 p2_host_sized(base_300x200_f16, 589824), S_OK},
434 {"CreatePlacedResource2, 1x1024 RGBA8 in 64 KiB heap",
435 p2_host_sized(base_1x1024, 65536), S_OK},
436 {"CreatePlacedResource2, 8x8 texture at 192 KiB in 256 KiB heap",
437 p2(placed_heap.p, 3 * 65536, texture, D3D12_BARRIER_LAYOUT_COMMON), S_OK},
438 {"CreatePlacedResource2, non-RT texture in RENDER_TARGET",
439 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG},
440 {"CreatePlacedResource2, non-UAV texture in UNORDERED_ACCESS",
441 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG},
442 {"CreatePlacedResource2, non-DS texture in DEPTH_STENCIL_WRITE",
443 p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG},
444 {"CreatePlacedResource2, DS+DENY_SR in DIRECT_QUEUE_SHADER_RESOURCE",
445 p2(placed_heap.p, 0, ds_deny_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE), E_INVALIDARG},
446 {"CreateReservedResource1, clear value on plain texture",
447 r1(res_tex, D3D12_RESOURCE_STATE_COMMON, &cv_rt), E_INVALIDARG},
448 {"CreateReservedResource2, buffer in COMMON",
449 r2(res_buf, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG},
450 {"CreateReservedResource2, buffer in UNDEFINED",
451 r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK},
452 {"CreateReservedResource2, clear value on buffer",
453 r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, &cv_rt), E_INVALIDARG},
454 {"CreateReservedResource2, clear value on plain texture",
455 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, &cv_rt), E_INVALIDARG},
456 {"CreateReservedResource2, mismatched clear value on RT",
457 r2(res_rt, D3D12_BARRIER_LAYOUT_COMMON, &cv_bad), E_INVALIDARG},
458 {"CreateReservedResource2, valid clear value on RT",
459 r2(res_rt, D3D12_BARRIER_LAYOUT_RENDER_TARGET, &cv_rt), S_OK},
460 {"CreateReservedResource2, non-RT texture in RENDER_TARGET",
461 r2(res_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG},
462 {"CreateReservedResource2, non-UAV texture in UNORDERED_ACCESS",
463 r2(res_tex, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG},
464 {"CreateReservedResource2, UAV texture in COMPUTE_QUEUE_UAV",
465 r2(res_uav, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS), S_OK},
466 {"CreateReservedResource2, non-DS texture in DEPTH_STENCIL_WRITE",
467 r2(res_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG},
468 {"CreateReservedResource2, DS+DENY_SR in SHADER_RESOURCE",
469 r2(res_ds_deny, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE), E_INVALIDARG},
470 {"CreateReservedResource2, castable format on buffer",
471 r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 1, srgb_cast), E_INVALIDARG},
472 {"CreateReservedResource2, unknown castable format on texture",
473 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, unknown_cast), E_INVALIDARG},
474 {"CreateReservedResource2, mismatched texel-size castable format",
475 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, wide_cast), E_INVALIDARG},
476 {"CreateReservedResource2, valid castable format on texture",
477 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, srgb_cast), S_OK},
478 {"CreateReservedResource2, castable count with null list",
479 r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 2, nullptr), S_OK},
263 {"CreateCommandQueue1, null description", null_queue, E_INVALIDARG}, 480 {"CreateCommandQueue1, null description", null_queue, E_INVALIDARG},
264 {"GetCopyableFootprints1, texture with a mip region", footprint(texture_region), S_FALSE}, 481 {"GetCopyableFootprints1, texture with a mip region", footprint(texture_region), S_FALSE},
265 {"GetCopyableFootprints1, buffer with a mip region", footprint(buffer_region), S_OK}, 482 {"GetCopyableFootprints1, buffer with a mip region", footprint(buffer_region), S_OK},
@@ -297,32 +514,47 @@ int main() {
297 EXPECT(create(device.p, via, upload_heap, buffer_desc(256), &out, fake_session()) == E_INVALIDARG); 514 EXPECT(create(device.p, via, upload_heap, buffer_desc(256), &out, fake_session()) == E_INVALIDARG);
298 EXPECT(out == nullptr); 515 EXPECT(out == nullptr);
299 } 516 }
517 {
518 D3D12_RESOURCE_DESC tiled_buf = buffer_desc(65536);
519 void* out = reinterpret_cast<void*>(1);
520 EXPECT(device->CreateReservedResource1(&tiled_buf, D3D12_RESOURCE_STATE_COMMON, nullptr, fake_session(),
521 __uuidof(ID3D12Resource), &out) == E_INVALIDARG);
522 EXPECT(out == nullptr);
523 out = reinterpret_cast<void*>(1);
524 EXPECT(device->CreateReservedResource2(&tiled_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, fake_session(),
525 0, nullptr, __uuidof(ID3D12Resource), &out) == E_INVALIDARG);
526 EXPECT(out == nullptr);
527 }
300 528
301 // The newer arguments' edge cases, each with the answer the PC runtime gives (and, when the host has a 529 // The newer arguments' edge cases, each with the answer the PC runtime gives (and, when the host has a
302 // D3D12 device, compared with it live). 530 // D3D12 device, compared with it live). Placed cases use standalone_device so the heap arena is present.
303 const std::vector<Edge> ours = edge_answers(device.p); 531 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
532 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
533 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
534 : nullptr;
535 Ref<ID3D12Device10> host;
536 const bool have_host =
537 create_host && SUCCEEDED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)));
538 Ref<ID3D12Device> standalone_base;
539 Ref<ID3D12Device10> standalone_device;
540 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&standalone_base.p))));
541 EXPECT(SUCCEEDED(standalone_base->QueryInterface(IID_PPV_ARGS(&standalone_device.p))));
542 const std::vector<Edge> ours = edge_answers(device.p, standalone_device.p, host.p);
304 for (const Edge& e : ours) { 543 for (const Edge& e : ours) {
305 if (e.got == e.want) continue; 544 if (e.got == e.want) continue;
306 std::fprintf(stderr, "%s: got %08lx, want %08lx\n", e.name, e.got, e.want); 545 std::fprintf(stderr, "%s: got %08lx, want %08lx\n", e.name, e.got, e.want);
307 return 1; 546 return 1;
308 } 547 }
309 { 548 if (have_host) {
310 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 549 const std::vector<Edge> theirs = edge_answers(host.p, host.p, host.p);
311 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>( 550 for (std::size_t i = 0; i < ours.size(); ++i) {
312 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice"))) 551 if (ours[i].got == theirs[i].got) continue;
313 : nullptr; 552 std::fprintf(stderr, "%s: ours %08lx, host runtime %08lx\n", ours[i].name, ours[i].got,
314 Ref<ID3D12Device10> host; 553 theirs[i].got);
315 if (create_host && SUCCEEDED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { 554 return 1;
316 const std::vector<Edge> theirs = edge_answers(host.p);
317 for (std::size_t i = 0; i < ours.size(); ++i) {
318 if (ours[i].got == theirs[i].got) continue;
319 std::fprintf(stderr, "%s: ours %08lx, host runtime %08lx\n", ours[i].name, ours[i].got,
320 theirs[i].got);
321 return 1;
322 }
323 } else {
324 std::printf("no host D3D12 device: edge cases checked against their recorded answers only\n");
325 } 555 }
556 } else {
557 std::printf("no host D3D12 device: edge cases checked against their recorded answers only\n");
326 } 558 }
327 559
328 // Castable formats: the layer reports relaxed format casting and passes a real list to 560 // Castable formats: the layer reports relaxed format casting and passes a real list to
@@ -359,7 +591,7 @@ int main() {
359 Ref<ID3D12DescriptorHeap> heap; 591 Ref<ID3D12DescriptorHeap> heap;
360 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; 592 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
361 heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; 593 heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
362 heap_desc.NumDescriptors = 3; 594 heap_desc.NumDescriptors = 4;
363 heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; 595 heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
364 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); 596 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
365 D3D12_CPU_DESCRIPTOR_HANDLE slot = heap->GetCPUDescriptorHandleForHeapStart(); 597 D3D12_CPU_DESCRIPTOR_HANDLE slot = heap->GetCPUDescriptorHandleForHeapStart();
@@ -413,6 +645,30 @@ int main() {
413 nonzero = false; 645 nonzero = false;
414 for (std::uint32_t word : words) nonzero = nonzero || word != 0; 646 for (std::uint32_t word : words) nonzero = nonzero || word != 0;
415 EXPECT(nonzero); 647 EXPECT(nonzero);
648
649 // CreateReservedResource2 forwards its castable list to the backing Vulkan image too.
650 const auto slot_is_zero = [](D3D12_CPU_DESCRIPTOR_HANDLE handle) {
651 std::uint32_t descriptor_words[8]{};
652 std::memcpy(descriptor_words, reinterpret_cast<void*>(handle.ptr), sizeof(descriptor_words));
653 for (std::uint32_t word : descriptor_words)
654 if (word != 0) return false;
655 return true;
656 };
657 D3D12_RESOURCE_DESC res_tex = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
658 res_tex.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
659 Ref<ID3D12Resource> reserved_srgb;
660 EXPECT(SUCCEEDED(device->CreateReservedResource2(&res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr, 1,
661 srgb_only, IID_PPV_ARGS(&reserved_srgb.p))));
662 slot.ptr += stride;
663 srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
664 device->CreateShaderResourceView(reserved_srgb.p, &srv, slot);
665 EXPECT(!slot_is_zero(slot));
666 srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
667 device->CreateShaderResourceView(reserved_srgb.p, &srv, slot);
668 EXPECT(!slot_is_zero(slot));
669 srv.Format = DXGI_FORMAT_R8G8B8A8_UINT;
670 device->CreateShaderResourceView(reserved_srgb.p, &srv, slot);
671 EXPECT(slot_is_zero(slot));
416 } 672 }
417 673
418 // A texture from CreateCommittedResource3 (a castable count with a null list, which is no list) is 674 // A texture from CreateCommittedResource3 (a castable count with a null list, which is no list) is
@@ -523,7 +779,8 @@ int main() {
523 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 779 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
524 return 1; 780 return 1;
525 } 781 }
526 std::printf("D3D12 method variants: CreateCommittedResource1/2/3, CreateCommandQueue1 and GetCopyableFootprints1 " 782 std::printf("D3D12 method variants: CreateCommittedResource1/2/3, CreatePlacedResource2, "
527 "matched their base methods and the PC runtime's edge-case answers; a texture round-tripped\n"); 783 "CreateReservedResource1/2, CreateCommandQueue1 and GetCopyableFootprints1 matched their base methods "
784 "and the PC runtime's edge-case answers; a texture round-tripped\n");
528 return 0; 785 return 0;
529} 786}
diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp
index 9cafc994e..3437fe030 100644
--- a/runtime/test/d3d12_msaa_draw_test.cpp
+++ b/runtime/test/d3d12_msaa_draw_test.cpp
@@ -11,6 +11,7 @@
11// (invalid_subresource) instead of reaching the driver. Shaders: test/glsl/vs_draw.vert, ps_draw.frag. No game data. 11// (invalid_subresource) instead of reaching the driver. Shaders: test/glsl/vs_draw.vert, ps_draw.frag. No game data.
12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
13#include "shader_fixture_path.h" 13#include "shader_fixture_path.h"
14#include "test_temp_dir.h"
14#include "vk_test_device.h" 15#include "vk_test_device.h"
15#include "d3d12_test_shaders.h" 16#include "d3d12_test_shaders.h"
16#include "../shims/d3d12_com.h" 17#include "../shims/d3d12_com.h"
@@ -54,10 +55,10 @@ int main() {
54 const auto vs_program = fssm_program({0x56530001, 0xbf810000}); 55 const auto vs_program = fssm_program({0x56530001, 0xbf810000});
55 const auto ps_program = fssm_program({0x50530001, 0xbf810000}); 56 const auto ps_program = fssm_program({0x50530001, 0xbf810000});
56 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); 57 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
57 const auto library = std::filesystem::temp_directory_path() / "leonida_msaa_draw_test"; 58 const testfiles::ScratchDir scratch("leonida_msaa_draw_test");
58 std::filesystem::create_directories(library); 59 const auto& library = scratch.path();
59 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); 60 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv"));
60 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); 61 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv"));
61 { 62 {
62 std::ofstream index(library / "index.json", std::ios::binary); 63 std::ofstream index(library / "index.json", std::ios::binary);
63 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 64 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
@@ -310,7 +311,6 @@ int main() {
310 fence.reset(); 311 fence.reset();
311 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 312 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
312 } 313 }
313 std::filesystem::remove_all(library);
314 314
315 // Pixel centre in clip space; the triangle covers y > x. Sample offsets are under half a pixel on each axis, 315 // Pixel centre in clip space; the triangle covers y > x. Sample offsets are under half a pixel on each axis,
316 // so a pixel whose centre is more than one pixel width (2 / size in clip space, over both axes) from the edge 316 // so a pixel whose centre is more than one pixel width (2 / size in clip space, over both axes) from the edge
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
index fbc7bb5fc..08d6a5323 100644
--- a/runtime/test/d3d12_pipeline_library_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -9,6 +9,7 @@
9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1. 9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1.
10// No game data. 10// No game data.
11#include "shader_fixture_path.h" 11#include "shader_fixture_path.h"
12#include "test_temp_dir.h"
12#include "vk_test_device.h" 13#include "vk_test_device.h"
13#include "d3d12_test_shaders.h" 14#include "d3d12_test_shaders.h"
14#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
@@ -68,14 +69,11 @@ int main() {
68 const auto vs_dxbc = shader_container(vs_prog); 69 const auto vs_dxbc = shader_container(vs_prog);
69 const auto ps_dxbc = shader_container(ps_prog); 70 const auto ps_dxbc = shader_container(ps_prog);
70 71
71 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test"; 72 const testfiles::ScratchDir scratch("leonida_pipeline_library_test");
72 std::filesystem::create_directories(lib_dir); 73 const auto& lib_dir = scratch.path();
73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv", 74 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv"));
74 std::filesystem::copy_options::overwrite_existing); 75 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv"));
75 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv", 76 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv"));
76 std::filesystem::copy_options::overwrite_existing);
77 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv",
78 std::filesystem::copy_options::overwrite_existing);
79 { 77 {
80 std::ofstream idx(lib_dir / "index.json", std::ios::binary); 78 std::ofstream idx(lib_dir / "index.json", std::ios::binary);
81 idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog) 79 idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog)
diff --git a/runtime/test/d3d12_placed_dimensions_test.cpp b/runtime/test/d3d12_placed_dimensions_test.cpp
new file mode 100644
index 000000000..09b0894b4
--- /dev/null
+++ b/runtime/test/d3d12_placed_dimensions_test.cpp
@@ -0,0 +1,347 @@
1// Placed 1D and 3D textures (CreatePlacedResource) on the Vulkan-backed device:
2// - compared with Windows D3D12 on the default adapter and on WARP: the answer for each description in a heap sized
3// for both sides' GetResourceAllocationInfo, at offset 0 and at 64 KiB, and the description a placed resource
4// reads back. A dimension outside the enum is refused alike;
5// - on the layer alone: bytes copied through a buffer into every subresource of a placed 3D texture and a placed 1D
6// array, and back out, come back unchanged.
7// No game data or shaders. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation to the layer's device.
8#include "host_wine.h"
9#include "../shims/d3d12_com.h"
10#include <dxgi1_4.h>
11
12#include <cstdint>
13#include <cstdio>
14#include <cstring>
15#include <vector>
16
17namespace {
18template<class T>
19struct Ref {
20 T* p = nullptr;
21 ~Ref() { reset(); }
22 T* operator->() const { return p; }
23 void reset() {
24 if (p) p->Release();
25 p = nullptr;
26 }
27};
28
29constexpr UINT64 k64 = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
30constexpr auto t1 = D3D12_RESOURCE_DIMENSION_TEXTURE1D, t2 = D3D12_RESOURCE_DIMENSION_TEXTURE2D,
31 t3 = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
32
33D3D12_RESOURCE_DESC texture(D3D12_RESOURCE_DIMENSION dimension, UINT64 width, UINT height, UINT16 depth_or_layers,
34 UINT16 mips, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
35 D3D12_RESOURCE_DESC desc{};
36 desc.Dimension = dimension;
37 desc.Width = width;
38 desc.Height = height;
39 desc.DepthOrArraySize = depth_or_layers;
40 desc.MipLevels = mips;
41 desc.Format = format;
42 desc.SampleDesc.Count = 1;
43 desc.Flags = flags;
44 return desc;
45}
46
47D3D12_RESOURCE_DESC buffer(UINT64 bytes) {
48 D3D12_RESOURCE_DESC desc{};
49 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
50 desc.Width = bytes;
51 desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
52 desc.SampleDesc.Count = 1;
53 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
54 return desc;
55}
56
57UINT64 round_up(UINT64 value, UINT64 alignment) { return (value + alignment - 1) / alignment * alignment; }
58
59// A default heap of `bytes` that takes `desc`'s class of texture on any resource-heap tier.
60HRESULT make_heap(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, UINT64 bytes, ID3D12Heap** heap) {
61 D3D12_HEAP_DESC heap_desc{};
62 heap_desc.SizeInBytes = bytes;
63 heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
64 heap_desc.Alignment = k64;
65 const bool rt_ds =
66 (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0;
67 heap_desc.Flags = rt_ds ? D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES : D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
68 return device->CreateHeap(&heap_desc, IID_PPV_ARGS(heap));
69}
70
71bool same(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
72 return a.Dimension == b.Dimension && a.Alignment == b.Alignment && a.Width == b.Width && a.Height == b.Height &&
73 a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format &&
74 a.SampleDesc.Count == b.SampleDesc.Count && a.SampleDesc.Quality == b.SampleDesc.Quality &&
75 a.Layout == b.Layout && a.Flags == b.Flags;
76}
77
78struct Case {
79 const char* name;
80 D3D12_RESOURCE_DESC desc;
81};
82
83struct Placed {
84 Ref<ID3D12Heap> heap; // declared first, so the resource is released before its heap
85 Ref<ID3D12Resource> resource;
86 HRESULT hr = E_FAIL;
87};
88
89void place(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, UINT64 heap_bytes, UINT64 offset, Placed& out) {
90 out.hr = make_heap(device, desc, heap_bytes, &out.heap.p);
91 if (FAILED(out.hr)) {
92 std::fprintf(stderr, "CreateHeap of %llu bytes failed (0x%08lx)\n", static_cast<unsigned long long>(heap_bytes),
93 static_cast<unsigned long>(out.hr));
94 return;
95 }
96 out.hr = device->CreatePlacedResource(out.heap.p, offset, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
97 IID_PPV_ARGS(&out.resource.p));
98}
99
100// Every answer and every description read back must be the host's. Returns the number that differ.
101unsigned compare(ID3D12Device* ours, ID3D12Device* host, const char* host_name, const std::vector<Case>& cases,
102 unsigned& compared) {
103 unsigned differ = 0;
104 for (const Case& c : cases) {
105 // The heap is sized for the larger of the two answers: each side checks the room in the heap against its own
106 // size (the layer's is Vulkan's, which can be larger than a host driver's), and what is compared here is
107 // whether a texture of that dimension is placed at all. A description with no size (an invalid dimension)
108 // still gets a heap, to see the refusal.
109 const D3D12_RESOURCE_ALLOCATION_INFO info = host->GetResourceAllocationInfo(0, 1, &c.desc);
110 const D3D12_RESOURCE_ALLOCATION_INFO mine = ours->GetResourceAllocationInfo(0, 1, &c.desc);
111 UINT64 bytes = 1024 * 1024;
112 if (info.SizeInBytes != UINT64_MAX) {
113 bytes = info.SizeInBytes;
114 if (mine.SizeInBytes != UINT64_MAX && mine.SizeInBytes != info.SizeInBytes) {
115 std::printf("%s: %s's size %llu, the layer's %llu; the heap takes the larger\n", c.name, host_name,
116 static_cast<unsigned long long>(info.SizeInBytes),
117 static_cast<unsigned long long>(mine.SizeInBytes));
118 if (mine.SizeInBytes > bytes) bytes = mine.SizeInBytes;
119 }
120 bytes = round_up(bytes, k64);
121 }
122 for (const UINT64 offset : {UINT64(0), k64}) {
123 Placed expected, actual;
124 place(host, c.desc, bytes + offset, offset, expected);
125 place(ours, c.desc, bytes + offset, offset, actual);
126 ++compared;
127 if (expected.hr != actual.hr) {
128 ++differ;
129 std::fprintf(stderr, "%s at %llu: ours 0x%08lx, %s 0x%08lx\n", c.name,
130 static_cast<unsigned long long>(offset), static_cast<unsigned long>(actual.hr), host_name,
131 static_cast<unsigned long>(expected.hr));
132 continue;
133 }
134 if (FAILED(expected.hr)) continue;
135 ++compared;
136 if (!same(actual.resource->GetDesc(), expected.resource->GetDesc())) {
137 ++differ;
138 std::fprintf(stderr, "%s at %llu: GetDesc differs from %s\n", c.name,
139 static_cast<unsigned long long>(offset), host_name);
140 }
141 ++compared;
142 if (actual.resource->GetGPUVirtualAddress() != 0) { // only buffers are addressable
143 ++differ;
144 std::fprintf(stderr, "%s at %llu: a placed texture has a GPU VA\n", c.name,
145 static_cast<unsigned long long>(offset));
146 }
147 }
148 }
149 return differ;
150}
151
152std::uint8_t pattern(UINT subresource, UINT z, UINT y, UINT64 x) {
153 return static_cast<std::uint8_t>(subresource * 61 + z * 29 + y * 7 + x * 3 + 1);
154}
155
156// Writes a pattern into every subresource of a placed texture through an upload buffer, copies it back out to a
157// readback buffer and compares. True when every byte came back.
158bool round_trip(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64& fence_value,
159 const char* name, const D3D12_RESOURCE_DESC& desc) {
160 const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
161 if (info.SizeInBytes == UINT64_MAX) {
162 std::fprintf(stderr, "%s: no allocation size\n", name);
163 return false;
164 }
165 Ref<ID3D12Heap> heap;
166 Ref<ID3D12Resource> placed;
167 if (FAILED(make_heap(device, desc, round_up(info.SizeInBytes, k64), &heap.p)) ||
168 FAILED(device->CreatePlacedResource(heap.p, 0, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
169 IID_PPV_ARGS(&placed.p)))) {
170 std::fprintf(stderr, "%s: not placed\n", name);
171 return false;
172 }
173 const UINT layers = desc.Dimension == t3 ? 1u : desc.DepthOrArraySize;
174 const UINT count = desc.MipLevels * layers;
175 std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> layouts(count);
176 std::vector<UINT> rows(count);
177 std::vector<UINT64> row_bytes(count);
178 UINT64 total = 0;
179 device->GetCopyableFootprints(&desc, 0, count, 0, layouts.data(), rows.data(), row_bytes.data(), &total);
180
181 D3D12_HEAP_PROPERTIES upload_heap{}, readback_heap{};
182 upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
183 readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
184 const D3D12_RESOURCE_DESC staging = buffer(total);
185 Ref<ID3D12Resource> upload, readback;
186 if (FAILED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &staging,
187 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload.p))) ||
188 FAILED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &staging,
189 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))) {
190 std::fprintf(stderr, "%s: no staging buffers\n", name);
191 return false;
192 }
193 // Where row y of slice z of subresource s starts in either staging buffer.
194 const auto row_at = [&](UINT s, UINT z, UINT y) {
195 const UINT64 pitch = layouts[s].Footprint.RowPitch;
196 return layouts[s].Offset + (UINT64(z) * rows[s] + y) * pitch;
197 };
198 void* mapped = nullptr;
199 if (FAILED(upload->Map(0, nullptr, &mapped))) return false;
200 for (UINT s = 0; s < count; ++s)
201 for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z)
202 for (UINT y = 0; y < rows[s]; ++y) {
203 auto* row = static_cast<std::uint8_t*>(mapped) + row_at(s, z, y);
204 for (UINT64 x = 0; x < row_bytes[s]; ++x) row[x] = pattern(s, z, y, x);
205 }
206 upload->Unmap(0, nullptr);
207
208 Ref<ID3D12CommandAllocator> allocator;
209 Ref<ID3D12GraphicsCommandList> list;
210 if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) ||
211 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
212 IID_PPV_ARGS(&list.p))))
213 return false;
214 for (UINT s = 0; s < count; ++s) {
215 D3D12_TEXTURE_COPY_LOCATION dst{placed.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
216 dst.SubresourceIndex = s;
217 D3D12_TEXTURE_COPY_LOCATION src{upload.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
218 src.PlacedFootprint = layouts[s];
219 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
220 }
221 D3D12_RESOURCE_BARRIER barrier{};
222 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
223 barrier.Transition = {placed.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST,
224 D3D12_RESOURCE_STATE_COPY_SOURCE};
225 list->ResourceBarrier(1, &barrier);
226 for (UINT s = 0; s < count; ++s) {
227 D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
228 dst.PlacedFootprint = layouts[s];
229 D3D12_TEXTURE_COPY_LOCATION src{placed.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
230 src.SubresourceIndex = s;
231 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
232 }
233 if (FAILED(list->Close())) return false;
234 ID3D12CommandList* lists[] = {list.p};
235 queue->ExecuteCommandLists(1, lists);
236 ++fence_value;
237 if (FAILED(queue->Signal(fence, fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) {
238 std::fprintf(stderr, "%s: the copies did not finish\n", name);
239 return false;
240 }
241
242 if (FAILED(readback->Map(0, nullptr, &mapped))) return false;
243 UINT64 wrong = 0, checked = 0;
244 for (UINT s = 0; s < count; ++s)
245 for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z)
246 for (UINT y = 0; y < rows[s]; ++y) {
247 const auto* row = static_cast<const std::uint8_t*>(mapped) + row_at(s, z, y);
248 for (UINT64 x = 0; x < row_bytes[s]; ++x, ++checked) {
249 if (row[x] == pattern(s, z, y, x)) continue;
250 if (!wrong++)
251 std::fprintf(stderr, "%s: subresource %u slice %u row %u byte %llu reads 0x%02x, want 0x%02x\n",
252 name, s, z, y, static_cast<unsigned long long>(x), row[x], pattern(s, z, y, x));
253 }
254 }
255 readback->Unmap(0, nullptr);
256 if (wrong) {
257 std::fprintf(stderr, "%s: %llu of %llu bytes differ\n", name, static_cast<unsigned long long>(wrong),
258 static_cast<unsigned long long>(checked));
259 return false;
260 }
261 std::printf("%s: %u subresources, %llu bytes round-tripped\n", name, count,
262 static_cast<unsigned long long>(checked));
263 return true;
264}
265} // namespace
266
267int main() {
268 Ref<ID3D12Device> ours;
269 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&ours.p))) || !ours.p) {
270 std::printf("SKIP: no Vulkan device\n");
271 return 77;
272 }
273 unsigned failures = 0;
274
275 {
276 D3D12_COMMAND_QUEUE_DESC queue_desc{};
277 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
278 Ref<ID3D12CommandQueue> queue;
279 Ref<ID3D12Fence> fence;
280 if (FAILED(ours->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) ||
281 FAILED(ours->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) {
282 std::fprintf(stderr, "no command queue or fence\n");
283 return 1;
284 }
285 UINT64 fence_value = 0;
286 const Case trips[] = {
287 {"placed 3D R8G8B8A8_UNORM 8x8x4, 2 mips", texture(t3, 8, 8, 4, 2, DXGI_FORMAT_R8G8B8A8_UNORM)},
288 {"placed 3D R16G16B16A16_FLOAT 4x4x4", texture(t3, 4, 4, 4, 1, DXGI_FORMAT_R16G16B16A16_FLOAT)},
289 {"placed 1D array R8G8B8A8_UNORM 64 x3, 3 mips", texture(t1, 64, 1, 3, 3, DXGI_FORMAT_R8G8B8A8_UNORM)},
290 };
291 for (const Case& c : trips)
292 if (!round_trip(ours.p, queue.p, fence.p, fence_value, c.name, c.desc)) ++failures;
293 }
294
295 // A desc with a dimension outside the enum, which the host refuses.
296 D3D12_RESOURCE_DESC unknown = texture(t2, 64, 64, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM);
297 unknown.Dimension = D3D12_RESOURCE_DIMENSION_UNKNOWN;
298 D3D12_RESOURCE_DESC past_3d = unknown;
299 past_3d.Dimension = D3D12_RESOURCE_DIMENSION(5);
300 constexpr auto rgba8 = DXGI_FORMAT_R8G8B8A8_UNORM;
301 constexpr auto uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, target = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
302 const std::vector<Case> cases = {
303 {"1D 4096", texture(t1, 4096, 1, 1, 1, rgba8)},
304 {"1D 256, all mips", texture(t1, 256, 1, 1, 0, rgba8)},
305 {"1D array of 8, 13 mips", texture(t1, 4096, 1, 8, 13, rgba8)},
306 {"1D R32_FLOAT unordered access", texture(t1, 1024, 1, 1, 1, DXGI_FORMAT_R32_FLOAT, uav)},
307 {"1D render target", texture(t1, 1024, 1, 1, 1, rgba8, target)},
308 {"3D 64x64x64", texture(t3, 64, 64, 64, 1, rgba8)},
309 {"3D 32x32x32, all mips", texture(t3, 32, 32, 32, 0, rgba8)},
310 {"3D 64x16x4, all mips", texture(t3, 64, 16, 4, 0, rgba8)},
311 {"3D BC1 128x128x16", texture(t3, 128, 128, 16, 1, DXGI_FORMAT_BC1_UNORM)},
312 {"3D R16G16B16A16_FLOAT 32x32x32", texture(t3, 32, 32, 32, 1, DXGI_FORMAT_R16G16B16A16_FLOAT)},
313 {"3D R32_FLOAT unordered access", texture(t3, 64, 64, 64, 1, DXGI_FORMAT_R32_FLOAT, uav)},
314 {"3D render target", texture(t3, 64, 64, 64, 1, rgba8, target)},
315 {"2D 64x64 (control)", texture(t2, 64, 64, 1, 1, rgba8)},
316 {"dimension UNKNOWN", unknown},
317 {"dimension 5", past_3d},
318 };
319
320 if (hostwine::host_is_wine()) {
321 std::printf("placed dimensions: the host comparison is skipped under Wine\n");
322 return failures ? 1 : 0;
323 }
324 Ref<IDXGIFactory4> factory;
325 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) {
326 std::fprintf(stderr, "no DXGI factory\n");
327 return 1;
328 }
329 unsigned references = 0;
330 for (const bool warp : {false, true}) {
331 Ref<IDXGIAdapter> adapter;
332 Ref<ID3D12Device> host;
333 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue;
334 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
335 const char* name = warp ? "WARP" : "the default adapter";
336 unsigned compared = 0;
337 const unsigned differ = compare(ours.p, host.p, name, cases, compared);
338 std::printf("placed dimensions against %s: %u answers compared, %u differ\n", name, compared, differ);
339 failures += differ;
340 ++references;
341 }
342 if (!references) {
343 std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n");
344 return 1;
345 }
346 return failures ? 1 : 0;
347}
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index 520af0e98..9e638ae09 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -3,9 +3,9 @@
3// moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence. 3// moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence.
4// The window is then resized, which recreates the swapchain and scales the blit. The presented images are copied 4// The window is then resized, which recreates the swapchain and scales the blit. The presented images are copied
5// back (the presenter's capture) and must hold the clear colour at the swapchain's size. Last, the colour on screen 5// back (the presenter's capture) and must hold the clear colour at the swapchain's size. Last, the colour on screen
6// is read back with GDI on native Windows when the window is in front, the display is in SDR and GDI can read the 6// is read back with GDI on native Windows when the window is in front with no other window over its centre, the
7// screen. Under Wine, rootless XWayland can return black for desktop reads, so the swapchain checks confirm the 7// display is in SDR and GDI can read the screen. Under Wine, rootless XWayland can return black for desktop reads,
8// colour there. No shaders or game data. 8// so the swapchain checks confirm the colour there. No shaders or game data.
9// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. 9// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test.
10#include "vk_test_device.h" 10#include "vk_test_device.h"
11#include "../shims/d3d12_com.h" 11#include "../shims/d3d12_com.h"
@@ -90,6 +90,17 @@ bool has_interactive_window_station() {
90 return (flags.dwFlags & WSF_VISIBLE) != 0; 90 return (flags.dwFlags & WSF_VISIBLE) != 0;
91} 91}
92 92
93// True when the window manager reports this window as the top-level window at a screen point. Being the foreground
94// window does not make it so: an always-on-top window, or one another process showed without taking the foreground,
95// can lie over it, and a GDI read of the screen then returns that window's pixel. WindowFromPoint passes over hidden
96// and disabled windows and over windows that are transparent to hit testing (a click-through overlay,
97// WS_EX_LAYERED | WS_EX_TRANSPARENT), so an overlay of that kind drawn over the point is not noticed, and neither
98// is anything the compositor draws there itself.
99bool is_top_window_at(HWND window, POINT screen_point) {
100 const HWND hit = WindowFromPoint(screen_point);
101 return hit && GetAncestor(hit, GA_ROOT) == window;
102}
103
93void set_client_size(HWND window, int width, int height) { 104void set_client_size(HWND window, int width, int height) {
94 RECT rect{0, 0, width, height}; 105 RECT rect{0, 0, width, height};
95 AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); 106 AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
@@ -478,16 +489,44 @@ int main() {
478 GetClientRect(window, &client); 489 GetClientRect(window, &client);
479 POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2}; 490 POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2};
480 ClientToScreen(window, &centre); 491 ClientToScreen(window, &centre);
481 HDC screen = GetDC(nullptr); 492 const auto is_clear_colour = [](COLORREF c) {
482 const COLORREF pixel = GetPixel(screen, centre.x, centre.y); 493 return std::abs(GetRValue(c) - 51) <= 3 && std::abs(GetGValue(c) - 153) <= 3 &&
483 ReleaseDC(nullptr, screen); 494 std::abs(GetBValue(c) - 230) <= 3;
484 if (pixel == CLR_INVALID) { 495 };
496 // The foreground window can still be covered at its centre, so a read counts only when this window
497 // was the top one there both before and after it. How long the compositor takes to show the last
498 // frame, or to stop showing a window that has just gone, is not known (the 200 ms above is a guess),
499 // so a pixel that is not the clear colour is read again for up to a second. Nothing is presented
500 // meanwhile: a late frame passes, a wrong colour that stays fails.
501 COLORREF pixel = CLR_INVALID, first_pixel = CLR_INVALID;
502 bool covered = false;
503 int reads = 0;
504 for (;;) {
505 covered = !is_top_window_at(window, centre);
506 if (covered) break;
507 HDC screen = GetDC(nullptr);
508 pixel = GetPixel(screen, centre.x, centre.y);
509 ReleaseDC(nullptr, screen);
510 covered = !is_top_window_at(window, centre);
511 if (covered) break;
512 if (++reads == 1) first_pixel = pixel;
513 if (pixel == CLR_INVALID || is_clear_colour(pixel) || reads > 20) break;
514 Sleep(50);
515 pump();
516 }
517 if (covered) {
518 std::printf("another window covers the window centre: on-screen colour check skipped, the "
519 "colour was checked in the presented images\n");
520 } else if (pixel == CLR_INVALID) {
485 std::printf("GDI cannot read the screen here (GetPixel on the screen DC returns CLR_INVALID): " 521 std::printf("GDI cannot read the screen here (GetPixel on the screen DC returns CLR_INVALID): "
486 "on-screen colour check skipped, the colour was checked in the presented images\n"); 522 "on-screen colour check skipped, the colour was checked in the presented images\n");
487 } else { 523 } else {
488 const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel); 524 const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel);
489 std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b); 525 std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b);
490 EXPECT(std::abs(r - 51) <= 3 && std::abs(g - 153) <= 3 && std::abs(b - 230) <= 3); 526 if (reads > 1)
527 std::printf("read %d times, 50 ms apart; the first read was %d,%d,%d\n", reads,
528 GetRValue(first_pixel), GetGValue(first_pixel), GetBValue(first_pixel));
529 EXPECT(is_clear_colour(pixel));
491 screen_checked = true; 530 screen_checked = true;
492 } 531 }
493 } 532 }
diff --git a/runtime/test/d3d12_residency_test.cpp b/runtime/test/d3d12_residency_test.cpp
new file mode 100644
index 000000000..d0f90d5fc
--- /dev/null
+++ b/runtime/test/d3d12_residency_test.cpp
@@ -0,0 +1,421 @@
1// Residency on the Vulkan-backed device, compared with the host PC runtime: MakeResident, Evict,
2// SetResidencyPriority (ID3D12Device1) and EnqueueMakeResident (ID3D12Device3). The same script runs on both devices
3// with pageable objects of each (a committed buffer, a heap, a placed buffer, a descriptor heap, a query heap and a
4// fence): counts of 0, null arrays, null entries, the same object twice, evicting twice, every named priority and a
5// few others, residency flags, a null fence, and the fence values EnqueueMakeResident signals (the value the fence
6// reaches is recorded too). Every HRESULT is recorded and the two records must be the same, step by step. A step the
7// host runtime faults on is reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU;
8// without a host D3D12 device only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every
9// step.
10#include "vk_test_device.h"
11#include "../shims/d3d12_com.h"
12
13#include <cstdint>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17#include <string>
18#include <vector>
19
20#define EXPECT(condition) do { \
21 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
22} while (0)
23
24namespace {
25
26template<class T>
27struct Ref {
28 T* p = nullptr;
29 ~Ref() { reset(); }
30 void reset() {
31 if (p) p->Release();
32 p = nullptr;
33 }
34 T* operator->() const { return p; }
35};
36
37constexpr std::uint64_t kFaulted = 0xFA017EDull; // the call raised an exception
38
39struct Objects {
40 ID3D12Device1* device1 = nullptr;
41 ID3D12Device3* device3 = nullptr;
42 ID3D12Device* device = nullptr;
43 ID3D12Pageable* all[6] = {}; // buffer, heap, placed, descriptor heap, query heap, fence
44 ID3D12Fence* fence = nullptr;
45};
46
47using Call = HRESULT (*)(Objects&);
48
49HRESULT guarded(Call call, Objects* o) {
50 __try {
51 return call(*o);
52 } __except (EXCEPTION_EXECUTE_HANDLER) {
53 return HRESULT(kFaulted);
54 }
55}
56
57HRESULT priority(Objects& o, std::uint32_t value) {
58 const auto p = D3D12_RESIDENCY_PRIORITY(value);
59 return o.device1->SetResidencyPriority(1, o.all, &p);
60}
61
62HRESULT priority1(Objects& o, int which) {
63 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
64 return o.device1->SetResidencyPriority(1, o.all + which, &p);
65}
66
67struct Step {
68 const char* name;
69 Call call;
70 UINT64 fence_value = 0; // EnqueueMakeResident: also record the value the fence reaches (waits for this one)
71 bool isolated = false; // on the host, run in a process of its own (see below)
72};
73
74const Step kSteps[] = {
75 {"MakeResident 0, null", [](Objects& o) { return o.device->MakeResident(0, nullptr); }},
76 {"MakeResident all six", [](Objects& o) { return o.device->MakeResident(6, o.all); }},
77 {"MakeResident 0 with an array", [](Objects& o) { return o.device->MakeResident(0, o.all); }},
78 {"MakeResident the buffer twice", [](Objects& o) {
79 ID3D12Pageable* twice[] = {o.all[0], o.all[0]};
80 return o.device->MakeResident(2, twice);
81 }},
82 {"MakeResident a resident buffer", [](Objects& o) { return o.device->MakeResident(1, o.all); }},
83 {"Evict 0, null", [](Objects& o) { return o.device->Evict(0, nullptr); }},
84 {"Evict 0 with an array", [](Objects& o) { return o.device->Evict(0, o.all); }},
85 {"Evict the buffer", [](Objects& o) { return o.device->Evict(1, o.all); }},
86 {"Evict the buffer again", [](Objects& o) { return o.device->Evict(1, o.all); }},
87 {"MakeResident the evicted buffer", [](Objects& o) { return o.device->MakeResident(1, o.all); }},
88 {"Evict all six", [](Objects& o) { return o.device->Evict(6, o.all); }},
89 {"MakeResident all six after Evict", [](Objects& o) { return o.device->MakeResident(6, o.all); }},
90 {"Evict the heap and the placed buffer", [](Objects& o) { return o.device->Evict(2, o.all + 1); }},
91 {"MakeResident the placed buffer alone", [](Objects& o) { return o.device->MakeResident(1, o.all + 2); }},
92 {"MakeResident the heap", [](Objects& o) { return o.device->MakeResident(1, o.all + 1); }},
93
94 {"SetResidencyPriority 0, null, null", [](Objects& o) { return o.device1->SetResidencyPriority(0, nullptr, nullptr); }},
95 {"SetResidencyPriority 0 with arrays", [](Objects& o) {
96 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
97 return o.device1->SetResidencyPriority(0, o.all, &p);
98 }},
99 {"SetResidencyPriority the buffer", [](Objects& o) { return priority1(o, 0); }},
100 {"SetResidencyPriority the heap", [](Objects& o) { return priority1(o, 1); }},
101 {"SetResidencyPriority MINIMUM", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_MINIMUM)); }},
102 {"SetResidencyPriority LOW", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_LOW)); }},
103 {"SetResidencyPriority HIGH", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_HIGH)); }},
104 {"SetResidencyPriority MAXIMUM", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_MAXIMUM)); }},
105 {"SetResidencyPriority 0", [](Objects& o) { return priority(o, 0); }},
106 {"SetResidencyPriority 1", [](Objects& o) { return priority(o, 1); }},
107 {"SetResidencyPriority NORMAL + 0x1234", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_NORMAL) + 0x1234); }},
108 {"SetResidencyPriority 0x12345678", [](Objects& o) { return priority(o, 0x12345678u); }},
109 {"SetResidencyPriority 0x9fffffff", [](Objects& o) { return priority(o, 0x9fffffffu); }},
110 {"SetResidencyPriority 0xc8000000", [](Objects& o) { return priority(o, 0xc8000000u); }},
111 {"SetResidencyPriority 0xffffffff", [](Objects& o) { return priority(o, 0xffffffffu); }},
112 {"SetResidencyPriority an evicted object", [](Objects& o) {
113 o.device->Evict(1, o.all);
114 const HRESULT hr = priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_HIGH));
115 o.device->MakeResident(1, o.all);
116 return hr;
117 }},
118
119 {"EnqueueMakeResident NONE, two objects, value 7", [](Objects& o) {
120 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 2, o.all, o.fence, 7);
121 }, 7},
122 {"EnqueueMakeResident DENY_OVERBUDGET, 0, null, value 9", [](Objects& o) {
123 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, o.fence, 9);
124 }, 9},
125 {"EnqueueMakeResident all six, value 10", [](Objects& o) {
126 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 6, o.all, o.fence, 10);
127 }, 10},
128 {"EnqueueMakeResident a null fence", [](Objects& o) {
129 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, nullptr, 11);
130 }},
131 {"EnqueueMakeResident flags 0x2", [](Objects& o) {
132 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, o.all, o.fence, 11);
133 }},
134 {"EnqueueMakeResident flags 0xffffffff", [](Objects& o) {
135 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0xffffffffu), 1, o.all, o.fence, 11);
136 }},
137 {"EnqueueMakeResident 0 with an array, value 12", [](Objects& o) {
138 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 0, o.all, o.fence, 12);
139 }, 12},
140 {"EnqueueMakeResident an evicted buffer, value 13", [](Objects& o) {
141 o.device->Evict(1, o.all);
142 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 13);
143 }, 13},
144 {"EnqueueMakeResident the buffer twice, value 14", [](Objects& o) {
145 ID3D12Pageable* twice[] = {o.all[0], o.all[0]};
146 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 2, twice, o.fence, 14);
147 }, 14},
148 {"EnqueueMakeResident the fence it signals, value 15", [](Objects& o) {
149 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all + 5, o.fence, 15);
150 }, 15},
151 {"EnqueueMakeResident a value below the fence's [backwards], value 3", [](Objects& o) {
152 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 3);
153 }, 3},
154 {"EnqueueMakeResident the same value again [backwards], value 3", [](Objects& o) {
155 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 3);
156 }, 3},
157
158 // Steps after which the host runtime isn't usable any more. On the host each runs in a process of its own with a
159 // fresh device (--host-step): SetResidencyPriority on anything but a committed resource or a heap (the host
160 // answers E_INVALIDARG and removes its device, DXGI_ERROR_INVALID_CALL), and a count with a null array or a null
161 // entry in an array (the host dereferences them).
162 {"SetResidencyPriority the placed buffer", [](Objects& o) { return priority1(o, 2); }, 0, true},
163 {"SetResidencyPriority the descriptor heap", [](Objects& o) { return priority1(o, 3); }, 0, true},
164 {"SetResidencyPriority the query heap", [](Objects& o) { return priority1(o, 4); }, 0, true},
165 {"SetResidencyPriority the fence", [](Objects& o) { return priority1(o, 5); }, 0, true},
166 {"SetResidencyPriority all six NORMAL", [](Objects& o) {
167 const D3D12_RESIDENCY_PRIORITY p[6] = {D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL,
168 D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL,
169 D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL};
170 return o.device1->SetResidencyPriority(6, o.all, p);
171 }, 0, true},
172 {"SetResidencyPriority the buffer and the placed buffer", [](Objects& o) {
173 ID3D12Pageable* two[] = {o.all[0], o.all[2]};
174 const D3D12_RESIDENCY_PRIORITY p[2] = {D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL};
175 return o.device1->SetResidencyPriority(2, two, p);
176 }, 0, true},
177 {"MakeResident 1, null", [](Objects& o) { return o.device->MakeResident(1, nullptr); }, 0, true},
178 {"Evict 1, null", [](Objects& o) { return o.device->Evict(1, nullptr); }, 0, true},
179 {"SetResidencyPriority 1, objects, null", [](Objects& o) {
180 return o.device1->SetResidencyPriority(1, o.all, nullptr);
181 }, 0, true},
182 {"SetResidencyPriority 1, null, priorities", [](Objects& o) {
183 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
184 return o.device1->SetResidencyPriority(1, nullptr, &p);
185 }, 0, true},
186 {"EnqueueMakeResident 1, null objects", [](Objects& o) {
187 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, o.fence, 11);
188 }, 0, true},
189 {"MakeResident 1, [null]", [](Objects& o) {
190 ID3D12Pageable* none[] = {nullptr};
191 return o.device->MakeResident(1, none);
192 }, 0, true},
193 {"Evict 1, [null]", [](Objects& o) {
194 ID3D12Pageable* none[] = {nullptr};
195 return o.device->Evict(1, none);
196 }, 0, true},
197 {"SetResidencyPriority 1, [null]", [](Objects& o) {
198 ID3D12Pageable* none[] = {nullptr};
199 const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL;
200 return o.device1->SetResidencyPriority(1, none, &p);
201 }, 0, true},
202 {"EnqueueMakeResident 1, [null]", [](Objects& o) {
203 ID3D12Pageable* none[] = {nullptr};
204 return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, none, o.fence, 20);
205 }, 0, true},
206};
207
208struct Record {
209 std::vector<std::string> names;
210 std::vector<std::uint64_t> values;
211 void add(const std::string& name, std::uint64_t value) {
212 names.push_back(name);
213 values.push_back(value);
214 }
215};
216
217// The value `fence` settles at after an EnqueueMakeResident that asked for `want`: the host signals it from a
218// paging queue, so wait (up to 2 s) for it to reach `want`, or, for a value below the current one, to change.
219UINT64 settled(ID3D12Fence* fence, UINT64 before, UINT64 want) {
220 for (int i = 0; i < 200; ++i) {
221 const UINT64 now = fence->GetCompletedValue();
222 if (now == want || (want < before && now != before)) return now;
223 Sleep(10);
224 }
225 return fence->GetCompletedValue();
226}
227
228// The pageable objects of one device, and the references that keep them alive.
229struct Holder {
230 Ref<ID3D12Device1> device1;
231 Ref<ID3D12Device3> device3;
232 Ref<ID3D12Resource> buffer, placed;
233 Ref<ID3D12Heap> heap;
234 Ref<ID3D12DescriptorHeap> descriptors;
235 Ref<ID3D12QueryHeap> queries;
236 Ref<ID3D12Fence> fence;
237 Objects o;
238};
239
240bool make(ID3D12Device* device, Holder& h) {
241 h.o.device = device;
242 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&h.device1.p))) ||
243 FAILED(device->QueryInterface(IID_PPV_ARGS(&h.device3.p))))
244 return false;
245 h.o.device1 = h.device1.p;
246 h.o.device3 = h.device3.p;
247 const D3D12_HEAP_PROPERTIES gpu{D3D12_HEAP_TYPE_DEFAULT};
248 D3D12_RESOURCE_DESC desc{};
249 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
250 desc.Width = 64 * 1024;
251 desc.Height = 1;
252 desc.DepthOrArraySize = 1;
253 desc.MipLevels = 1;
254 desc.SampleDesc.Count = 1;
255 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
256 D3D12_HEAP_DESC heap_desc{};
257 heap_desc.SizeInBytes = 64 * 1024;
258 heap_desc.Properties = gpu;
259 heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
260 const D3D12_DESCRIPTOR_HEAP_DESC dh{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16,
261 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
262 const D3D12_QUERY_HEAP_DESC qh{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 4, 0};
263 if (FAILED(device->CreateCommittedResource(&gpu, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
264 IID_PPV_ARGS(&h.buffer.p))) ||
265 FAILED(device->CreateHeap(&heap_desc, IID_PPV_ARGS(&h.heap.p))) ||
266 FAILED(device->CreatePlacedResource(h.heap.p, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
267 IID_PPV_ARGS(&h.placed.p))) ||
268 FAILED(device->CreateDescriptorHeap(&dh, IID_PPV_ARGS(&h.descriptors.p))) ||
269 FAILED(device->CreateQueryHeap(&qh, IID_PPV_ARGS(&h.queries.p))) ||
270 FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&h.fence.p))))
271 return false;
272 h.o.all[0] = h.buffer.p;
273 h.o.all[1] = h.heap.p;
274 h.o.all[2] = h.placed.p;
275 h.o.all[3] = h.descriptors.p;
276 h.o.all[4] = h.queries.p;
277 h.o.all[5] = h.fence.p;
278 h.o.fence = h.fence.p;
279 return true;
280}
281
282ID3D12Device* create_host() {
283 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
284 const auto create = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
285 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
286 : nullptr;
287 ID3D12Device* host = nullptr;
288 if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host)))) return nullptr;
289 return host;
290}
291
292constexpr std::uint64_t kNoChild = 0xC41DFA11ull; // the child process couldn't run the step
293constexpr int kMaxNotCompared = 11; // values the host can't give: see the end of main
294
295// Step `index` on a fresh host device, in a child process (this executable with --host-step): its exit code is the
296// HRESULT, or a crash status, which counts as a fault.
297std::uint64_t isolated(std::size_t index) {
298 wchar_t exe[MAX_PATH] = {};
299 GetModuleFileNameW(nullptr, exe, MAX_PATH);
300 std::wstring command = L"\"" + std::wstring(exe) + L"\" --host-step " + std::to_wstring(index);
301 STARTUPINFOW startup{};
302 startup.cb = sizeof(startup);
303 PROCESS_INFORMATION process{};
304 if (!CreateProcessW(nullptr, command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr,
305 &startup, &process))
306 return kNoChild;
307 DWORD code = DWORD(kNoChild);
308 if (WaitForSingleObject(process.hProcess, 60000) == WAIT_OBJECT_0) GetExitCodeProcess(process.hProcess, &code);
309 else TerminateProcess(process.hProcess, DWORD(kNoChild));
310 CloseHandle(process.hThread);
311 CloseHandle(process.hProcess);
312 // Checked before the crash statuses below, which kNoChild would otherwise fall into: a child that couldn't run
313 // its step is a broken test, not a host fault, and fails it.
314 if (code == DWORD(kNoChild)) return kNoChild;
315 if ((code & 0xF0000000u) == 0xC0000000u) return kFaulted; // an access violation or fail-fast the guard missed
316 return code;
317}
318
319// Runs the script on `device` and records it. `host`: run the isolated steps in child processes.
320bool run(ID3D12Device* device, bool host, Record& out) {
321 Holder h;
322 if (!make(device, h)) return false;
323 for (std::size_t i = 0; i < sizeof(kSteps) / sizeof(kSteps[0]); ++i) {
324 const Step& s = kSteps[i];
325 if (s.isolated) {
326 out.add(s.name, host ? isolated(i) : std::uint64_t(std::uint32_t(guarded(s.call, &h.o))));
327 continue;
328 }
329 const UINT64 before = h.fence->GetCompletedValue();
330 const HRESULT hr = guarded(s.call, &h.o);
331 out.add(s.name, std::uint64_t(std::uint32_t(hr)));
332 out.add(std::string(s.name) + " (removed reason)", std::uint64_t(std::uint32_t(device->GetDeviceRemovedReason())));
333 if (s.fence_value)
334 out.add(std::string(s.name) + " (fence)",
335 hr == HRESULT(kFaulted) ? kFaulted : settled(h.fence.p, before, s.fence_value));
336 }
337 return true;
338}
339
340// --host-step N: one isolated step on a fresh host device; the exit code is its HRESULT.
341int host_step(std::size_t index) {
342 if (index >= sizeof(kSteps) / sizeof(kSteps[0])) return int(kNoChild);
343 Ref<ID3D12Device> host;
344 host.p = create_host();
345 Holder h;
346 if (!host.p || !make(host.p, h)) return int(kNoChild);
347 return int(guarded(kSteps[index].call, &h.o));
348}
349
350} // namespace
351
352int main(int argc, char** argv) {
353 if (argc == 3 && std::strcmp(argv[1], "--host-step") == 0) return host_step(std::size_t(std::atoi(argv[2])));
354 vktest::Device d;
355 const auto device_status = d.initialize();
356 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
357 if (device_status != vktest::DeviceStatus::ready) return 1;
358 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
359 {
360 rt::d3d12::VulkanDeviceInfo info{};
361 info.get_instance_proc = d.instance_proc;
362 info.instance = d.instance;
363 info.physical = d.physical;
364 info.device = d.device;
365 info.queue = d.queue;
366 info.queue_family = d.family;
367 info.buffer_device_address = true; // heaps live in the GPU address arena
368 Ref<ID3D12Device> device;
369 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
370 Record ours;
371 EXPECT(run(device.p, false, ours));
372
373 Ref<ID3D12Device> host;
374 host.p = create_host();
375 if (!host.p) {
376 std::printf("residency: no host D3D12 device to compare with; %zu steps recorded, not compared\n",
377 ours.values.size());
378 } else {
379 Record theirs;
380 EXPECT(run(host.p, true, theirs));
381 EXPECT(theirs.names == ours.names);
382 int mismatches = 0, faulted = 0;
383 for (std::size_t i = 0; i < ours.values.size(); ++i) {
384 if (theirs.values[i] == kNoChild)
385 std::printf("residency %s: the host step's child process didn't run it\n", ours.names[i].c_str());
386 EXPECT(theirs.values[i] != kNoChild);
387 if (theirs.values[i] == kFaulted) {
388 std::printf("residency %s: the host faults, not compared (ours 0x%llx)\n", ours.names[i].c_str(),
389 static_cast<unsigned long long>(ours.values[i]));
390 ++faulted;
391 continue;
392 }
393 // A fence the layer would have to move backwards: Vulkan timelines only go up, so the layer's fence
394 // stays where it was (docs/d3d12_vulkan.md); the HRESULT is still compared.
395 if (ours.names[i].find("[backwards]") != std::string::npos &&
396 ours.names[i].find("(fence)") != std::string::npos) {
397 std::printf("residency %s: ours 0x%llx host 0x%llx (a fence can't go backwards here; not "
398 "compared)\n", ours.names[i].c_str(), static_cast<unsigned long long>(ours.values[i]),
399 static_cast<unsigned long long>(theirs.values[i]));
400 ++faulted;
401 continue;
402 }
403 const bool same = ours.values[i] == theirs.values[i];
404 if (verbose || !same)
405 std::printf("residency %s: ours 0x%llx host 0x%llx%s\n", ours.names[i].c_str(),
406 static_cast<unsigned long long>(ours.values[i]),
407 static_cast<unsigned long long>(theirs.values[i]), same ? "" : " MISMATCH");
408 mismatches += !same;
409 }
410 std::printf("residency: %zu values from %zu steps compared with the host (%d more not compared), "
411 "%d mismatches\n", ours.values.size() - faulted, sizeof(kSteps) / sizeof(kSteps[0]), faulted,
412 mismatches);
413 EXPECT(mismatches == 0);
414 // The values left out are the null-pointer steps the host faults on and the backwards fence. A host that
415 // faulted on more would make the comparison vacuous while still passing, so the count is held to that.
416 EXPECT(faulted <= kMaxNotCompared);
417 }
418 }
419 std::printf("d3d12_residency_test: OK\n");
420 return 0;
421}
diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp
index 503492610..1d51c9e70 100644
--- a/runtime/test/d3d12_set0_compute_test.cpp
+++ b/runtime/test/d3d12_set0_compute_test.cpp
@@ -16,6 +16,7 @@
16// GLSL written to the translator's contract. 16// GLSL written to the translator's contract.
17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). 17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
18#include "shader_fixture_path.h" 18#include "shader_fixture_path.h"
19#include "test_temp_dir.h"
19#include "vk_test_device.h" 20#include "vk_test_device.h"
20#include "d3d12_test_shaders.h" 21#include "d3d12_test_shaders.h"
21#include "../shims/d3d12_com.h" 22#include "../shims/d3d12_com.h"
@@ -68,10 +69,10 @@ int main() {
68 // set-0 bindings for the shader, as the translator does for one that samples. 69 // set-0 bindings for the shader, as the translator does for one that samples.
69 const auto program = fssm_program({0x43530003, 0xbf810000}); 70 const auto program = fssm_program({0x43530003, 0xbf810000});
70 const auto container = shader_container(program); 71 const auto container = shader_container(program);
71 const auto library = std::filesystem::temp_directory_path() / "leonida_set0_compute_test"; 72 const testfiles::ScratchDir scratch("leonida_set0_compute_test");
72 std::filesystem::create_directories(library); 73 const auto& library = scratch.path();
73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV), library / "cs_set0_sample.spv", 74 EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV),
74 std::filesystem::copy_options::overwrite_existing); 75 library / "cs_set0_sample.spv"));
75 { 76 {
76 std::ofstream index(library / "index.json", std::ios::binary); 77 std::ofstream index(library / "index.json", std::ios::binary);
77 index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program) 78 index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program)
@@ -309,7 +310,6 @@ int main() {
309 fence.reset(); 310 fence.reset();
310 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); 311 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
311 } 312 }
312 std::filesystem::remove_all(library);
313 313
314 // Runs 0, 1 and 3 against the textures; run 2 is the fallback image, whose colour the test does not fix: it 314 // Runs 0, 1 and 3 against the textures; run 2 is the fallback image, whose colour the test does not fix: it
315 // must be one colour everywhere, which neither texture gives. 315 // must be one colour everywhere, which neither texture gives.
diff --git a/runtime/test/d3d12_shader_cache_test.cpp b/runtime/test/d3d12_shader_cache_test.cpp
index 8f6a68288..bc4b2704d 100644
--- a/runtime/test/d3d12_shader_cache_test.cpp
+++ b/runtime/test/d3d12_shader_cache_test.cpp
@@ -28,7 +28,7 @@ struct Ref {
28 T* operator->() const { return p; } 28 T* operator->() const { return p; }
29}; 29};
30 30
31int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_in_params) { 31int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool is_vulkan_layer) {
32 // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a} 32 // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a}
33 const GUID id1 = {0x7c83f2a1, 0x4b5e, 0x4d19, {0x9a, 0x32, 0x1f, 0x2e, 0x3d, 0x4c, 0x5b, 0x6a}}; 33 const GUID id1 = {0x7c83f2a1, 0x4b5e, 0x4d19, {0x9a, 0x32, 0x1f, 0x2e, 0x3d, 0x4c, 0x5b, 0x6a}};
34 const GUID id2 = {0x1b74e9d0, 0x2c3a, 0x4f81, {0x8e, 0x11, 0x5a, 0x6b, 0x7c, 0x8d, 0x9e, 0x0f}}; 34 const GUID id2 = {0x1b74e9d0, 0x2c3a, 0x4f81, {0x8e, 0x11, 0x5a, 0x6b, 0x7c, 0x8d, 0x9e, 0x0f}};
@@ -42,9 +42,9 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
42 42
43 // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE). 43 // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE).
44 // Passing nullptr for SAL _In_/_Inout_ parameters (pDesc, pKey, pValue, pValueSize) is undefined 44 // Passing nullptr for SAL _In_/_Inout_ parameters (pDesc, pKey, pValue, pValueSize) is undefined
45 // behaviour on older in-box Windows D3D12 runtimes (e.g. Win11 23H2 22621.5415 AVs), so those 45 // behaviour on older in-box Windows D3D12 runtimes, so those null-pointer guards are exercised
46 // null-pointer guards are exercised only on the Vulkan layer. 46 // only on the Vulkan layer.
47 if (test_null_in_params) { 47 if (is_vulkan_layer) {
48 EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG); 48 EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG);
49 } 49 }
50 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE); 50 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE);
@@ -81,16 +81,16 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
81 UINT sz = sizeof(out_v); 81 UINT sz = sizeof(out_v);
82 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); 82 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
83 EXPECT(sz == sizeof(out_v)); 83 EXPECT(sz == sizeof(out_v));
84 if (test_null_in_params) { 84 if (is_vulkan_layer) {
85 EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG); 85 EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG);
86 } 86 }
87 EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG); 87 EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG);
88 if (test_null_in_params) { 88 if (is_vulkan_layer) {
89 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG); 89 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG);
90 EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG); 90 EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG);
91 } 91 }
92 EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG); 92 EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG);
93 if (test_null_in_params) { 93 if (is_vulkan_layer) {
94 EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG); 94 EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG);
95 } 95 }
96 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG); 96 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG);
@@ -118,17 +118,21 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
118 EXPECT(s2->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1); 118 EXPECT(s2->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1);
119 119
120 // Different Identifier does not see k1. 120 // Different Identifier does not see k1.
121 // Older in-box Windows D3D12 runtimes (e.g. Win11 23H2 d3d12.dll 10.0.22621.5415) AV (0xC0000005)
122 // when releasing a D3D12_SHADER_CACHE_MODE_MEMORY session after SetDeleteOnDestroy(), so exercise
123 // SetDeleteOnDestroy() on MODE_MEMORY only on the Vulkan layer; MODE_MEMORY still discards on final
124 // release on both runtimes.
121 D3D12_SHADER_CACHE_SESSION_DESC desc2 = desc; 125 D3D12_SHADER_CACHE_SESSION_DESC desc2 = desc;
122 desc2.Identifier = id2; 126 desc2.Identifier = id2;
123 Ref<ID3D12ShaderCacheSession> other; 127 Ref<ID3D12ShaderCacheSession> other;
124 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc2, IID_PPV_ARGS(&other.p))) && other.p); 128 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc2, IID_PPV_ARGS(&other.p))) && other.p);
125 sz = sizeof(out_v); 129 sz = sizeof(out_v);
126 EXPECT(other->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); 130 EXPECT(other->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
127 other->SetDeleteOnDestroy(); 131 if (is_vulkan_layer) other->SetDeleteOnDestroy();
128 other.reset(); 132 other.reset();
129 133
130 // Marking s1 delete-on-destroy keeps data alive while s2 is still open, then deletes once s2 releases. 134 // Releasing s1 keeps data alive while s2 is still open, then discards once s2 releases.
131 s1->SetDeleteOnDestroy(); 135 if (is_vulkan_layer) s1->SetDeleteOnDestroy();
132 s1.reset(); 136 s1.reset();
133 sz = sizeof(out_v); 137 sz = sizeof(out_v);
134 out_v = 0; 138 out_v = 0;
@@ -139,7 +143,7 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_
139 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s3.p))) && s3.p); 143 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s3.p))) && s3.p);
140 sz = sizeof(out_v); 144 sz = sizeof(out_v);
141 EXPECT(s3->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); 145 EXPECT(s3->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
142 s3->SetDeleteOnDestroy(); 146 if (is_vulkan_layer) s3->SetDeleteOnDestroy();
143 s3.reset(); 147 s3.reset();
144 148
145 // 4. ShaderCacheControl invalid-argument checks (same on host and layer). 149 // 4. ShaderCacheControl invalid-argument checks (same on host and layer).
diff --git a/runtime/test/d3d12_sparse_queue_family_test.cpp b/runtime/test/d3d12_sparse_queue_family_test.cpp
new file mode 100644
index 000000000..04caee442
--- /dev/null
+++ b/runtime/test/d3d12_sparse_queue_family_test.cpp
@@ -0,0 +1,175 @@
1// Synthetic D3D12 reserved-buffer mapping on DIRECT/COPY/COMPUTE queues, with GPU readback.
2#include <windows.h>
3#include <d3d12.h>
4#include <dxgi1_6.h>
5#include "../shims/d3d12_com.h"
6#include <wrl/client.h>
7#include <algorithm>
8#include <cstdint>
9#include <cstdio>
10#include <cstring>
11#include <stdexcept>
12#include <string>
13
14using Microsoft::WRL::ComPtr;
15constexpr UINT64 PAGE_BYTES = 65536, BUFFER_BYTES = 2 * PAGE_BYTES;
16
17static void ok(HRESULT hr, const char* where) {
18 if (FAILED(hr)) {
19 std::printf("FAIL %s hr=0x%08lx\n", where, static_cast<unsigned long>(hr));
20 throw std::runtime_error(where);
21 }
22}
23static unsigned char pattern(size_t n) {
24 return static_cast<unsigned char>((n * 131u + (n >> 7u) * 17u + 29u) & 255u);
25}
26static D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
27 D3D12_RESOURCE_DESC d{};
28 d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
29 d.Alignment = 0;
30 d.Width = bytes;
31 d.Height = 1;
32 d.DepthOrArraySize = 1;
33 d.MipLevels = 1;
34 d.Format = DXGI_FORMAT_UNKNOWN;
35 d.SampleDesc.Count = 1;
36 d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
37 return d;
38}
39static ComPtr<ID3D12Resource> committed(ID3D12Device* dev, UINT64 bytes,
40 D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state) {
41 ComPtr<ID3D12Resource> res;
42 D3D12_HEAP_PROPERTIES hp{};
43 hp.Type = type;
44 auto desc = buffer_desc(bytes);
45 ok(dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
46 IID_PPV_ARGS(&res)), "CreateCommittedResource");
47 return res;
48}
49static ComPtr<ID3D12CommandQueue> make_queue(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE type) {
50 D3D12_COMMAND_QUEUE_DESC desc{};
51 desc.Type = type;
52 ComPtr<ID3D12CommandQueue> q;
53 ok(dev->CreateCommandQueue(&desc, IID_PPV_ARGS(&q)), "CreateCommandQueue");
54 return q;
55}
56struct CopyList {
57 ComPtr<ID3D12CommandAllocator> alloc;
58 ComPtr<ID3D12GraphicsCommandList> list;
59};
60static CopyList copy_list(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE type,
61 ID3D12Resource* dst, ID3D12Resource* src, UINT64 bytes) {
62 CopyList cl;
63 ok(dev->CreateCommandAllocator(type, IID_PPV_ARGS(&cl.alloc)), "CreateCommandAllocator");
64 ok(dev->CreateCommandList(0, type, cl.alloc.Get(), nullptr, IID_PPV_ARGS(&cl.list)),
65 "CreateCommandList");
66 cl.list->CopyBufferRegion(dst, 0, src, 0, bytes);
67 ok(cl.list->Close(), "Close command list");
68 return cl;
69}
70
71static bool run_case(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE map_type,
72 ID3D12CommandQueue* direct, ID3D12CommandQueue* copy,
73 ID3D12CommandQueue* compute, const char* label) {
74 ID3D12CommandQueue* mapper = map_type == D3D12_COMMAND_LIST_TYPE_DIRECT ? direct :
75 map_type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? compute : copy;
76
77 D3D12_HEAP_DESC hdesc{};
78 hdesc.SizeInBytes = PAGE_BYTES;
79 hdesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
80 hdesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
81 hdesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
82 ComPtr<ID3D12Heap> heap;
83 ok(dev->CreateHeap(&hdesc, IID_PPV_ARGS(&heap)), "CreateHeap(one tile)");
84 ComPtr<ID3D12Resource> sparse;
85 auto desc = buffer_desc(BUFFER_BYTES);
86 ok(dev->CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
87 IID_PPV_ARGS(&sparse)), "CreateReservedResource(buffer)");
88 UINT total_tiles = 0;
89 dev->GetResourceTiling(sparse.Get(), &total_tiles, nullptr, nullptr, nullptr, 0, nullptr);
90 std::printf("case=%s reserved_tiles=%u mapping_queue=%d\n", label, total_tiles, int(map_type));
91 if (total_tiles != 2) throw std::runtime_error("unexpected reserved-buffer tile count");
92
93 auto upload = committed(dev, PAGE_BYTES, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ);
94 auto readback = committed(dev, BUFFER_BYTES, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST);
95 unsigned char* host = nullptr;
96 D3D12_RANGE empty{0, 0};
97 ok(upload->Map(0, &empty, reinterpret_cast<void**>(&host)), "Upload Map");
98 for (size_t i = 0; i < PAGE_BYTES; ++i) host[i] = pattern(i);
99 D3D12_RANGE written{0, size_t(PAGE_BYTES)};
100 upload->Unmap(0, &written);
101
102 ComPtr<ID3D12Fence> fence;
103 ok(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "CreateFence");
104 D3D12_TILED_RESOURCE_COORDINATE coord{};
105 D3D12_TILE_REGION_SIZE region{};
106 region.NumTiles = 1;
107 region.UseBox = FALSE;
108 D3D12_TILE_RANGE_FLAGS range_flags = D3D12_TILE_RANGE_FLAG_NONE;
109 UINT heap_start = 0, range_count = 1;
110 mapper->UpdateTileMappings(sparse.Get(), 1, &coord, &region, heap.Get(),
111 1, &range_flags, &heap_start, &range_count, D3D12_TILE_MAPPING_FLAG_NONE);
112 ok(mapper->Signal(fence.Get(), 1), "mapper Signal 1");
113
114 auto write = copy_list(dev, D3D12_COMMAND_LIST_TYPE_COPY, sparse.Get(), upload.Get(), PAGE_BYTES);
115 ok(copy->Wait(fence.Get(), 1), "copy Wait 1");
116 ID3D12CommandList* write_lists[] = {write.list.Get()};
117 copy->ExecuteCommandLists(1, write_lists);
118 ok(copy->Signal(fence.Get(), 2), "copy Signal 2");
119
120 auto read = copy_list(dev, D3D12_COMMAND_LIST_TYPE_COMPUTE, readback.Get(), sparse.Get(), BUFFER_BYTES);
121 ok(compute->Wait(fence.Get(), 2), "compute Wait 2");
122 ID3D12CommandList* read_lists[] = {read.list.Get()};
123 compute->ExecuteCommandLists(1, read_lists);
124 ok(compute->Signal(fence.Get(), 3), "compute Signal 3");
125
126 HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
127 if (!done) throw std::runtime_error("CreateEventW failed");
128 ok(fence->SetEventOnCompletion(3, done), "SetEventOnCompletion");
129 DWORD wait = WaitForSingleObject(done, 15000);
130 CloseHandle(done);
131 if (wait != WAIT_OBJECT_0) throw std::runtime_error("GPU fence timeout");
132
133 D3D12_RANGE read_range{0, size_t(BUFFER_BYTES)};
134 unsigned char* data = nullptr;
135 ok(readback->Map(0, &read_range, reinterpret_cast<void**>(&data)), "Readback Map");
136 size_t wrong_mapped = 0, wrong_unmapped = 0;
137 for (size_t i = 0; i < PAGE_BYTES; ++i) wrong_mapped += data[i] != pattern(i);
138 for (size_t i = PAGE_BYTES; i < BUFFER_BYTES; ++i) wrong_unmapped += data[i] != 0;
139 readback->Unmap(0, &empty);
140 const bool passed = wrong_mapped == 0 && wrong_unmapped == 0;
141 std::printf("RESULT %s %s mapped_mismatch=%zu/65536 unmapped_nonzero=%zu/65536\n",
142 label, passed ? "PASS" : "FAIL", wrong_mapped, wrong_unmapped);
143 return passed;
144}
145
146int main() {
147 try {
148 ComPtr<ID3D12Device> device;
149 ok(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)),
150 "Leonida create_vulkan_device_standalone");
151 if (!rt::d3d12::device_sparse_buffer_tiles(device.Get())) {
152 std::puts("SKIP Leonida sparse_buffer_tiles not supported");
153 return 77;
154 }
155 std::puts("LEONIDA Vulkan-layer test; independent D3D12 API surface, direct->copy->compute queues");
156 auto direct = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT);
157 auto copy = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_COPY);
158 auto compute = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_COMPUTE);
159 bool all_pass = true;
160 all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT,
161 direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_DIRECT_COPY_COMPUTE");
162 all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_COPY,
163 direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_COPY_COPY_COMPUTE");
164 all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_COMPUTE,
165 direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_COMPUTE_COPY_COMPUTE");
166 const HRESULT removed = device->GetDeviceRemovedReason();
167 std::printf("DEVICE_REMOVED_HRESULT=0x%08lx\n", static_cast<unsigned long>(removed));
168 all_pass &= SUCCEEDED(removed);
169 std::printf("LAYER_FINAL %s\n", all_pass ? "PASS" : "FAIL");
170 return all_pass ? 0 : 1;
171 } catch (const std::exception& e) {
172 std::fprintf(stderr, "LAYER_FATAL: %s\n", e.what());
173 return 2;
174 }
175}
diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp
index 58a649437..d7466b781 100644
--- a/runtime/test/d3d12_state_map_test.cpp
+++ b/runtime/test/d3d12_state_map_test.cpp
@@ -660,6 +660,21 @@ int main() {
660 CHECK(!resizable_bar(VkPhysicalDeviceMemoryProperties{})); 660 CHECK(!resizable_bar(VkPhysicalDeviceMemoryProperties{}));
661 } 661 }
662 662
663 // D3D-299: a texture (required 0, preferred DEVICE_LOCAL) in host memory has spilled; the arena (required
664 // HOST_VISIBLE | HOST_COHERENT, preferred DEVICE_LOCAL) in host memory has not, and neither has anything that
665 // got DEVICE_LOCAL or never asked for it.
666 {
667 constexpr VkMemoryPropertyFlags local = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
668 constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
669 CHECK(spilled_to_host(0, local, host));
670 CHECK(spilled_to_host(0, local, 0));
671 CHECK(!spilled_to_host(0, local, local));
672 CHECK(!spilled_to_host(0, local, local | host));
673 CHECK(!spilled_to_host(host, local, host));
674 CHECK(!spilled_to_host(host, 0, host));
675 CHECK(!spilled_to_host(0, 0, host));
676 }
677
663 // Memory type choice. Heaps as an RTX 3090 without Resizable BAR reports them: VRAM, system memory, and the 678 // Memory type choice. Heaps as an RTX 3090 without Resizable BAR reports them: VRAM, system memory, and the
664 // 214 MiB BAR heap that holds the only DEVICE_LOCAL | HOST_VISIBLE type. 679 // 214 MiB BAR heap that holds the only DEVICE_LOCAL | HOST_VISIBLE type.
665 { 680 {
diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp
index 4894f70e2..abc6f2bd0 100644
--- a/runtime/test/d3d12_subgroup_test.cpp
+++ b/runtime/test/d3d12_subgroup_test.cpp
@@ -10,6 +10,7 @@
10// Each case also prints a control run with the layer's size request switched off, to show what the request changes 10// Each case also prints a control run with the layer's size request switched off, to show what the request changes
11// on this GPU; the control is not judged. No game data. Set LEONIDA_VK_VALIDATION=1 to run under 11// on this GPU; the control is not judged. No game data. Set LEONIDA_VK_VALIDATION=1 to run under
12// VK_LAYER_KHRONOS_validation; validation errors fail the test. 12// VK_LAYER_KHRONOS_validation; validation errors fail the test.
13#include "test_temp_dir.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "../shims/d3d12_com.h" 15#include "../shims/d3d12_com.h"
15#include "../src/shader_library.h" 16#include "../src/shader_library.h"
@@ -313,14 +314,14 @@ struct LibraryEntry {
313 314
314// A translator-style folder with the entries' modules, every entry keyed by the fixture program's hash. 315// A translator-style folder with the entries' modules, every entry keyed by the fixture program's hash.
315std::filesystem::path make_library(const std::string& tag, const std::vector<LibraryEntry>& entries) { 316std::filesystem::path make_library(const std::string& tag, const std::vector<LibraryEntry>& entries) {
316 const auto dir = std::filesystem::temp_directory_path() / ("leonida_subgroup_" + tag); 317 const auto dir = testfiles::process_temp_dir("leonida_subgroup_" + tag);
317 std::filesystem::remove_all(dir); 318 std::filesystem::remove_all(dir);
318 std::filesystem::create_directories(dir); 319 std::filesystem::create_directories(dir);
319 std::ofstream index(dir / "index.json", std::ios::binary); 320 std::ofstream index(dir / "index.json", std::ios::binary);
320 index << "{"; 321 index << "{";
321 bool first = true; 322 bool first = true;
322 for (const LibraryEntry& e : entries) { 323 for (const LibraryEntry& e : entries) {
323 std::filesystem::copy_file(e.spv, dir / (e.name + ".spv"), std::filesystem::copy_options::overwrite_existing); 324 testfiles::copy_file(e.spv, dir / (e.name + ".spv")); // a missing module is reported, and the PSO fails
324 index << (first ? "" : ",\n") << "\"" << e.name << "\": {\"stage\": \"" << e.stage << "\", \"fssm_sha256\": \"" 325 index << (first ? "" : ",\n") << "\"" << e.name << "\": {\"stage\": \"" << e.stage << "\", \"fssm_sha256\": \""
325 << leonida::sha256_hex(fixture_fssm()) << "\", \"bindings\": [], \"push_constant_bytes\": 144, " 326 << leonida::sha256_hex(fixture_fssm()) << "\", \"bindings\": [], \"push_constant_bytes\": 144, "
326 << e.tail << "}"; 327 << e.tail << "}";
diff --git a/runtime/test/d3d12_typeless_families_test.cpp b/runtime/test/d3d12_typeless_families_test.cpp
index 936fbbbee..b6fe4ea86 100644
--- a/runtime/test/d3d12_typeless_families_test.cpp
+++ b/runtime/test/d3d12_typeless_families_test.cpp
@@ -10,6 +10,7 @@
10// A view format the layer does not map yet (its CheckFeatureSupport gives no RENDER_TARGET) is reported and skipped, 10// A view format the layer does not map yet (its CheckFeatureSupport gives no RENDER_TARGET) is reported and skipped,
11// so the R8 family and the 16-bit integer and normalized formats are covered as soon as their mapping lands. 11// so the R8 family and the 16-bit integer and normalized formats are covered as soon as their mapping lands.
12// Synthetic data only. LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation. 12// Synthetic data only. LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation.
13#include "test_temp_dir.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "host_wine.h" 15#include "host_wine.h"
15#include "../shims/d3d12_com.h" 16#include "../shims/d3d12_com.h"
@@ -260,12 +261,12 @@ int main() {
260 const auto vs_container = d3d12test::shader_container(vs_program); 261 const auto vs_container = d3d12test::shader_container(vs_program);
261 const auto ps_float_container = d3d12test::shader_container(ps_float_program); 262 const auto ps_float_container = d3d12test::shader_container(ps_float_program);
262 const auto ps_uint_container = d3d12test::shader_container(ps_uint_program); 263 const auto ps_uint_container = d3d12test::shader_container(ps_uint_program);
263 const auto library = std::filesystem::temp_directory_path() / "leonida_typeless_families_test"; 264 const testfiles::ScratchDir scratch("leonida_typeless_families_test");
264 std::filesystem::create_directories(library); 265 const auto& library = scratch.path();
265 const auto overwrite = std::filesystem::copy_options::overwrite_existing; 266 if (!testfiles::copy_file(LEONIDA_TYPELESS_VS_SPV, library / "vs.spv") ||
266 std::filesystem::copy_file(LEONIDA_TYPELESS_VS_SPV, library / "vs.spv", overwrite); 267 !testfiles::copy_file(LEONIDA_TYPELESS_PS_FLOAT_SPV, library / "ps_float.spv") ||
267 std::filesystem::copy_file(LEONIDA_TYPELESS_PS_FLOAT_SPV, library / "ps_float.spv", overwrite); 268 !testfiles::copy_file(LEONIDA_TYPELESS_PS_UINT_SPV, library / "ps_uint.spv"))
268 std::filesystem::copy_file(LEONIDA_TYPELESS_PS_UINT_SPV, library / "ps_uint.spv", overwrite); 269 return 1;
269 { 270 {
270 std::ofstream index(library / "index.json", std::ios::binary); 271 std::ofstream index(library / "index.json", std::ios::binary);
271 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 272 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index c16ecd6a7..f7a1ed319 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -867,6 +867,56 @@ int compare_allocation_info(ID3D12Device* ours) {
867 if (empty_a.SizeInBytes != empty_b.SizeInBytes || empty_a.Alignment != empty_b.Alignment) 867 if (empty_a.SizeInBytes != empty_b.SizeInBytes || empty_a.Alignment != empty_b.Alignment)
868 mismatch("no resources", empty_a, empty_b); 868 mismatch("no resources", empty_a, empty_b);
869 869
870 // A visible mask above 1 names a node a single-node adapter does not have: the host answers the invalid
871 // allocation (size UINT64_MAX, 64 KiB alignment), for one resource and for none, through GetResourceAllocationInfo
872 // and its 1 and 2 variants, and leaves the per-resource array as it was.
873 {
874 Ref<ID3D12Device4> ours4, host4;
875 Ref<ID3D12Device8> ours8_mask, host8_mask;
876 ours->QueryInterface(IID_PPV_ARGS(&ours4.p));
877 host->QueryInterface(IID_PPV_ARGS(&host4.p));
878 ours->QueryInterface(IID_PPV_ARGS(&ours8_mask.p));
879 host->QueryInterface(IID_PPV_ARGS(&host8_mask.p));
880 const D3D12_RESOURCE_DESC buffer = buffer_desc(256);
881 D3D12_RESOURCE_DESC1 buffer1{};
882 buffer1.Dimension = buffer.Dimension;
883 buffer1.Width = buffer.Width;
884 buffer1.Height = buffer1.DepthOrArraySize = buffer1.MipLevels = 1;
885 buffer1.SampleDesc.Count = 1;
886 buffer1.Layout = buffer.Layout;
887 const auto same_info = [](const D3D12_RESOURCE_ALLOCATION_INFO& x, const D3D12_RESOURCE_ALLOCATION_INFO& y) {
888 return x.SizeInBytes == y.SizeInBytes && x.Alignment == y.Alignment;
889 };
890 for (const UINT mask : {0u, 1u, 2u, 3u, 0x80000000u}) {
891 char name[64];
892 std::snprintf(name, sizeof(name), "visible mask 0x%x", mask);
893 for (const UINT count : {0u, 1u}) {
894 const D3D12_RESOURCE_DESC* descs = count ? &buffer : nullptr;
895 const auto ia = ours->GetResourceAllocationInfo(mask, count, descs);
896 const auto ib = host->GetResourceAllocationInfo(mask, count, descs);
897 if (!same_info(ia, ib)) mismatch(name, ia, ib);
898 }
899 if (ours4.p && host4.p) {
900 const D3D12_RESOURCE_ALLOCATION_INFO1 sentinel{0xdead, 0xbeef, 0xcafe};
901 D3D12_RESOURCE_ALLOCATION_INFO1 each_a = sentinel, each_b = sentinel;
902 const auto ia = ours4->GetResourceAllocationInfo1(mask, 1, &buffer, &each_a);
903 const auto ib = host4->GetResourceAllocationInfo1(mask, 1, &buffer, &each_b);
904 if (!same_info(ia, ib) || each_a.Offset != each_b.Offset || each_a.SizeInBytes != each_b.SizeInBytes ||
905 each_a.Alignment != each_b.Alignment)
906 mismatch("visible mask, GetResourceAllocationInfo1", ia, ib);
907 }
908 if (ours8_mask.p && host8_mask.p) {
909 const D3D12_RESOURCE_ALLOCATION_INFO1 sentinel{0xdead, 0xbeef, 0xcafe};
910 D3D12_RESOURCE_ALLOCATION_INFO1 each_a = sentinel, each_b = sentinel;
911 const auto ia = ours8_mask->GetResourceAllocationInfo2(mask, 1, &buffer1, &each_a);
912 const auto ib = host8_mask->GetResourceAllocationInfo2(mask, 1, &buffer1, &each_b);
913 if (!same_info(ia, ib) || each_a.Offset != each_b.Offset || each_a.SizeInBytes != each_b.SizeInBytes ||
914 each_a.Alignment != each_b.Alignment)
915 mismatch("visible mask, GetResourceAllocationInfo2", ia, ib);
916 }
917 }
918 }
919
870 Ref<ID3D12Device8> ours8; 920 Ref<ID3D12Device8> ours8;
871 // MULTISAMPLE_QUALITY_LEVELS with TILED_RESOURCE: the same answers as the host, except 128-bit formats at 4x, 921 // MULTISAMPLE_QUALITY_LEVELS with TILED_RESOURCE: the same answers as the host, except 128-bit formats at 4x,
872 // which the AMD drivers refuse and WARP and NVIDIA report (and GetResourceAllocationInfo allocates here). 922 // which the AMD drivers refuse and WARP and NVIDIA report (and GetResourceAllocationInfo allocates here).
@@ -1968,6 +2018,7 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn
1968 }; 2018 };
1969 constexpr UINT size = 4, pitch = 256, slot = 1024; 2019 constexpr UINT size = 4, pitch = 256, slot = 1024;
1970 int failures = 0; 2020 int failures = 0;
2021 unsigned host_compared = 0, host_lacking = 0;
1971 const auto fail = [&](DXGI_FORMAT format, const char* what) { 2022 const auto fail = [&](DXGI_FORMAT format, const char* what) {
1972 if (failures++ < 16) std::fprintf(stderr, "new format %d: %s\n", int(format), what); 2023 if (failures++ < 16) std::fprintf(stderr, "new format %d: %s\n", int(format), what);
1973 }; 2024 };
@@ -2041,17 +2092,21 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn
2041 } 2092 }
2042 if (host.p) { 2093 if (host.p) {
2043 // A host runtime older than the format has nothing to match: A4B4G4R4_UNORM is not in Windows 10's D3D12, 2094 // A host runtime older than the format has nothing to match: A4B4G4R4_UNORM is not in Windows 10's D3D12,
2044 // which reports no 2D texture support for it and refuses it. Compare only where the host itself says it 2095 // which answers the query with an error (E_FAIL on Windows 10 build 19045, E_INVALIDARG on another 19041
2045 // has the format, so a host that reports it and still refuses the texture fails as before. 2096 // host) or reports no 2D texture, and refuses the texture. Compare only where the host itself says it has
2097 // the format, so a host that reports it and still refuses the texture fails as before. The answer is
2098 // printed, so an unexpected code stays visible.
2046 D3D12_FEATURE_DATA_FORMAT_SUPPORT host_support{format}; 2099 D3D12_FEATURE_DATA_FORMAT_SUPPORT host_support{format};
2047 const bool host_has_format = 2100 const HRESULT query = host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support,
2048 SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support, 2101 sizeof(host_support));
2049 sizeof(host_support))) && 2102 const bool host_has_format = SUCCEEDED(query) && (host_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
2050 (host_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
2051 if (!host_has_format) { 2103 if (!host_has_format) {
2052 std::printf("new format %d: the host runtime has no such 2D texture (e.g. Windows 10), " 2104 ++host_lacking;
2053 "host comparison skipped\n", int(format)); 2105 std::printf("new format %d: the host runtime has no such 2D texture (FORMAT_SUPPORT answered %08lx, "
2106 "e.g. Windows 10), host comparison skipped\n",
2107 int(format), static_cast<unsigned long>(query));
2054 } else { 2108 } else {
2109 ++host_compared;
2055 Ref<ID3D12Resource> native; 2110 Ref<ID3D12Resource> native;
2056 if (FAILED(host->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, 2111 if (FAILED(host->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
2057 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, 2112 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
@@ -2172,9 +2227,12 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn
2172 } 2227 }
2173 upload->Unmap(0, nullptr); 2228 upload->Unmap(0, nullptr);
2174 readback->Unmap(0, nullptr); 2229 readback->Unmap(0, nullptr);
2230 char compared[64] = "";
2231 if (host.p) std::snprintf(compared, sizeof(compared), " (host compared on %u, host lacks %u)", host_compared,
2232 host_lacking);
2175 std::printf("new formats: %u of %zu created and copied both ways bit for bit%s, %u render-target clears " 2233 std::printf("new formats: %u of %zu created and copied both ways bit for bit%s, %u render-target clears "
2176 "matched the host, A4B4G4R4 render target %s, %d failures\n", 2234 "matched the host, A4B4G4R4 render target %s, %d failures\n",
2177 round_trips, std::size(formats), host.p ? " (host compared)" : "", clears_matched, 2235 round_trips, std::size(formats), compared, clears_matched,
2178 a4_target ? (a4_cleared == 4 ? "cleared to R, G, B and A" : "cleared wrong") : "not reported, skipped", 2236 a4_target ? (a4_cleared == 4 ? "cleared to R, G, B and A" : "cleared wrong") : "not reported, skipped",
2179 failures); 2237 failures);
2180 return failures; 2238 return failures;
@@ -2236,8 +2294,8 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2236 D3D12_FEATURE_DATA_D3D12_OPTIONS16 o16{}; 2294 D3D12_FEATURE_DATA_D3D12_OPTIONS16 o16{};
2237 D3D12_FEATURE_DATA_D3D12_OPTIONS18 o18{}; 2295 D3D12_FEATURE_DATA_D3D12_OPTIONS18 o18{};
2238 D3D12_FEATURE_DATA_D3D12_OPTIONS19 o19{}; 2296 D3D12_FEATURE_DATA_D3D12_OPTIONS19 o19{};
2239 D3D12_FEATURE_DATA_D3D12_OPTIONS20 o20{}; 2297 rt::d3d12::compat::FeatureDataOptions20 o20{};
2240 D3D12_FEATURE_DATA_D3D12_OPTIONS21 o21{}; 2298 rt::d3d12::compat::FeatureDataOptions21 o21{};
2241 2299
2242 query_ours(std::pair{"OPTIONS2", D3D12_FEATURE_D3D12_OPTIONS2}, o2); 2300 query_ours(std::pair{"OPTIONS2", D3D12_FEATURE_D3D12_OPTIONS2}, o2);
2243 query_ours(std::pair{"OPTIONS3", D3D12_FEATURE_D3D12_OPTIONS3}, o3); 2301 query_ours(std::pair{"OPTIONS3", D3D12_FEATURE_D3D12_OPTIONS3}, o3);
@@ -2252,14 +2310,14 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2252 query_ours(std::pair{"OPTIONS16", D3D12_FEATURE_D3D12_OPTIONS16}, o16); 2310 query_ours(std::pair{"OPTIONS16", D3D12_FEATURE_D3D12_OPTIONS16}, o16);
2253 query_ours(std::pair{"OPTIONS18", D3D12_FEATURE_D3D12_OPTIONS18}, o18); 2311 query_ours(std::pair{"OPTIONS18", D3D12_FEATURE_D3D12_OPTIONS18}, o18);
2254 query_ours(std::pair{"OPTIONS19", D3D12_FEATURE_D3D12_OPTIONS19}, o19); 2312 query_ours(std::pair{"OPTIONS19", D3D12_FEATURE_D3D12_OPTIONS19}, o19);
2255 query_ours(std::pair{"OPTIONS20", D3D12_FEATURE_D3D12_OPTIONS20}, o20); 2313 query_ours(std::pair{"OPTIONS20", rt::d3d12::compat::kFeatureOptions20}, o20);
2256 query_ours(std::pair{"OPTIONS21", D3D12_FEATURE_D3D12_OPTIONS21}, o21); 2314 query_ours(std::pair{"OPTIONS21", rt::d3d12::compat::kFeatureOptions21}, o21);
2257 2315
2258 D3D12_FEATURE_DATA_SHADER_CACHE shader_cache{}; 2316 D3D12_FEATURE_DATA_SHADER_CACHE shader_cache{};
2259 D3D12_FEATURE_DATA_EXISTING_HEAPS existing_heaps{}; 2317 D3D12_FEATURE_DATA_EXISTING_HEAPS existing_heaps{};
2260 D3D12_FEATURE_DATA_CROSS_NODE cross_node{}; 2318 D3D12_FEATURE_DATA_CROSS_NODE cross_node{};
2261 D3D12_FEATURE_DATA_DISPLAYABLE displayable{}; 2319 D3D12_FEATURE_DATA_DISPLAYABLE displayable{};
2262 D3D12_FEATURE_DATA_PREDICATION predication{}; 2320 rt::d3d12::compat::FeatureSupportFlag predication{};
2263 rt::d3d12::compat::FeatureSupportFlag driver_state{}; 2321 rt::d3d12::compat::FeatureSupportFlag driver_state{};
2264 rt::d3d12::compat::FeatureSupportFlag bypass_hash{}; 2322 rt::d3d12::compat::FeatureSupportFlag bypass_hash{};
2265 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT prot_support{}; 2323 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT prot_support{};
@@ -2272,7 +2330,7 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2272 query_ours(std::pair{"EXISTING_HEAPS", D3D12_FEATURE_EXISTING_HEAPS}, existing_heaps); 2330 query_ours(std::pair{"EXISTING_HEAPS", D3D12_FEATURE_EXISTING_HEAPS}, existing_heaps);
2273 query_ours(std::pair{"CROSS_NODE", D3D12_FEATURE_CROSS_NODE}, cross_node); 2331 query_ours(std::pair{"CROSS_NODE", D3D12_FEATURE_CROSS_NODE}, cross_node);
2274 query_ours(std::pair{"DISPLAYABLE", D3D12_FEATURE_DISPLAYABLE}, displayable); 2332 query_ours(std::pair{"DISPLAYABLE", D3D12_FEATURE_DISPLAYABLE}, displayable);
2275 query_ours(std::pair{"PREDICATION", D3D12_FEATURE_PREDICATION}, predication); 2333 query_ours(std::pair{"PREDICATION", rt::d3d12::compat::kFeaturePredication}, predication);
2276 query_ours(std::pair{"APPLICATION_SPECIFIC_DRIVER_STATE", 2334 query_ours(std::pair{"APPLICATION_SPECIFIC_DRIVER_STATE",
2277 rt::d3d12::compat::kFeatureApplicationSpecificDriverState}, 2335 rt::d3d12::compat::kFeatureApplicationSpecificDriverState},
2278 driver_state); 2336 driver_state);
@@ -2341,11 +2399,11 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2341 o19.MaxViewDescriptorHeapSize != D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2 || 2399 o19.MaxViewDescriptorHeapSize != D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2 ||
2342 o19.ComputeOnlyCustomHeapSupported) 2400 o19.ComputeOnlyCustomHeapSupported)
2343 fail("OPTIONS19 mismatch"); 2401 fail("OPTIONS19 mismatch");
2344 if (o20.ComputeOnlyWriteWatchSupported || o20.RecreateAtTier != D3D12_RECREATE_AT_TIER_NOT_SUPPORTED) 2402 if (o20.ComputeOnlyWriteWatchSupported || o20.RecreateAtTier != rt::d3d12::compat::kRecreateAtTierNotSupported)
2345 fail("OPTIONS20 unexpected support"); 2403 fail("OPTIONS20 unexpected support");
2346 if (o21.WorkGraphsTier != D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED || 2404 if (o21.WorkGraphsTier != rt::d3d12::compat::kWorkGraphsTierNotSupported ||
2347 o21.ExecuteIndirectTier != D3D12_EXECUTE_INDIRECT_TIER_1_0 || o21.SampleCmpGradientAndBiasSupported || 2405 o21.ExecuteIndirectTier != rt::d3d12::compat::kExecuteIndirectTier1_0 ||
2348 o21.ExtendedCommandInfoSupported) 2406 o21.SampleCmpGradientAndBiasSupported || o21.ExtendedCommandInfoSupported)
2349 fail("OPTIONS21 unexpected support"); 2407 fail("OPTIONS21 unexpected support");
2350 2408
2351 // Verify OPTIONS19.AnisoFilterWithPointMipSupported follows VulkanDeviceInfo::sampler_anisotropy. 2409 // Verify OPTIONS19.AnisoFilterWithPointMipSupported follows VulkanDeviceInfo::sampler_anisotropy.
@@ -2448,8 +2506,9 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2448 if (FAILED(rt::d3d12::create_vulkan_device(no_pred_info, IID_PPV_ARGS(&no_pred.p)))) { 2506 if (FAILED(rt::d3d12::create_vulkan_device(no_pred_info, IID_PPV_ARGS(&no_pred.p)))) {
2449 fail("failed to create conditional_rendering=false device"); 2507 fail("failed to create conditional_rendering=false device");
2450 } else { 2508 } else {
2451 D3D12_FEATURE_DATA_PREDICATION pred_off{TRUE}; 2509 rt::d3d12::compat::FeatureSupportFlag pred_off{TRUE};
2452 if (FAILED(no_pred->CheckFeatureSupport(D3D12_FEATURE_PREDICATION, &pred_off, sizeof(pred_off))) || 2510 if (FAILED(no_pred->CheckFeatureSupport(rt::d3d12::compat::kFeaturePredication, &pred_off,
2511 sizeof(pred_off))) ||
2453 pred_off.Supported != FALSE) 2512 pred_off.Supported != FALSE)
2454 fail("PREDICATION did not become FALSE when conditional_rendering is off"); 2513 fail("PREDICATION did not become FALSE when conditional_rendering is off");
2455 } 2514 }
@@ -2629,13 +2688,13 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2629 check_bool(n, "ComputeOnlyCustomHeapSupported", a.ComputeOnlyCustomHeapSupported, 2688 check_bool(n, "ComputeOnlyCustomHeapSupported", a.ComputeOnlyCustomHeapSupported,
2630 b.ComputeOnlyCustomHeapSupported); 2689 b.ComputeOnlyCustomHeapSupported);
2631 }); 2690 });
2632 compare_host("OPTIONS20", D3D12_FEATURE_D3D12_OPTIONS20, o20, 2691 compare_host("OPTIONS20", rt::d3d12::compat::kFeatureOptions20, o20,
2633 [&](const char* n, const auto& a, const auto& b) { 2692 [&](const char* n, const auto& a, const auto& b) {
2634 check_bool(n, "ComputeOnlyWriteWatchSupported", a.ComputeOnlyWriteWatchSupported, 2693 check_bool(n, "ComputeOnlyWriteWatchSupported", a.ComputeOnlyWriteWatchSupported,
2635 b.ComputeOnlyWriteWatchSupported); 2694 b.ComputeOnlyWriteWatchSupported);
2636 check_tier(n, "RecreateAtTier", int(a.RecreateAtTier), int(b.RecreateAtTier)); 2695 check_tier(n, "RecreateAtTier", int(a.RecreateAtTier), int(b.RecreateAtTier));
2637 }); 2696 });
2638 compare_host("OPTIONS21", D3D12_FEATURE_D3D12_OPTIONS21, o21, 2697 compare_host("OPTIONS21", rt::d3d12::compat::kFeatureOptions21, o21,
2639 [&](const char* n, const auto& a, const auto& b) { 2698 [&](const char* n, const auto& a, const auto& b) {
2640 check_tier(n, "WorkGraphsTier", int(a.WorkGraphsTier), int(b.WorkGraphsTier)); 2699 check_tier(n, "WorkGraphsTier", int(a.WorkGraphsTier), int(b.WorkGraphsTier));
2641 check_tier(n, "ExecuteIndirectTier", int(a.ExecuteIndirectTier), int(b.ExecuteIndirectTier)); 2700 check_tier(n, "ExecuteIndirectTier", int(a.ExecuteIndirectTier), int(b.ExecuteIndirectTier));
@@ -2666,7 +2725,7 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2666 check_tier(n, "SharedResourceCompatibilityTier", int(a.SharedResourceCompatibilityTier), 2725 check_tier(n, "SharedResourceCompatibilityTier", int(a.SharedResourceCompatibilityTier),
2667 int(b.SharedResourceCompatibilityTier)); 2726 int(b.SharedResourceCompatibilityTier));
2668 }); 2727 });
2669 compare_host("PREDICATION", D3D12_FEATURE_PREDICATION, predication, 2728 compare_host("PREDICATION", rt::d3d12::compat::kFeaturePredication, predication,
2670 [&](const char* n, const auto& a, const auto& b) { 2729 [&](const char* n, const auto& a, const auto& b) {
2671 check_bool(n, "Supported", a.Supported, b.Supported); 2730 check_bool(n, "Supported", a.Supported, b.Supported);
2672 }); 2731 });
@@ -2883,6 +2942,35 @@ HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uui
2883 return released(device->CreateFence(0, flags, riid, &out), &out); 2942 return released(device->CreateFence(0, flags, riid, &out), &out);
2884} 2943}
2885 2944
2945HRESULT command_allocator(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type, bool output = true,
2946 REFIID riid = __uuidof(ID3D12CommandAllocator)) {
2947 void* out = nullptr;
2948 return released(device->CreateCommandAllocator(type, riid, output ? &out : nullptr), &out);
2949}
2950
2951// CreateCommandList with a fresh allocator of `allocator_type` (or none when it is -2).
2952HRESULT command_list(ID3D12Device* device, UINT node_mask, D3D12_COMMAND_LIST_TYPE type,
2953 int allocator_type, bool output = true) {
2954 void* allocator = nullptr;
2955 if (allocator_type != -2)
2956 device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(allocator_type), __uuidof(ID3D12CommandAllocator),
2957 &allocator);
2958 void* out = nullptr;
2959 const HRESULT hr = device->CreateCommandList(node_mask, type, static_cast<ID3D12CommandAllocator*>(allocator),
2960 nullptr, __uuidof(ID3D12GraphicsCommandList), output ? &out : nullptr);
2961 released(S_OK, &allocator);
2962 return released(hr, &out);
2963}
2964
2965HRESULT command_list1(ID3D12Device* device, UINT node_mask, D3D12_COMMAND_LIST_TYPE type, bool output = true) {
2966 Ref<ID3D12Device4> device4;
2967 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device4.p)))) return E_NOINTERFACE;
2968 void* out = nullptr;
2969 return released(device4->CreateCommandList1(node_mask, type, D3D12_COMMAND_LIST_FLAG_NONE,
2970 __uuidof(ID3D12GraphicsCommandList), output ? &out : nullptr),
2971 &out);
2972}
2973
2886// A 64 KiB heap description for the CreateHeap cases (D3D-238). 2974// A 64 KiB heap description for the CreateHeap cases (D3D-238).
2887D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT}, 2975D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT},
2888 D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) { 2976 D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) {
@@ -2977,6 +3065,19 @@ bool host_ray_tracing(ID3D12Device* host) {
2977 o5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED; 3065 o5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED;
2978} 3066}
2979 3067
3068// Windows 10's runtime (no ID3D12Device10) still checks a buffer's initial state and refuses a HARDWARE_PROTECTED
3069// heap, where newer runtimes and the layer accept them (measured on Windows 10 22H2 build 19045.5737). For a case
3070// marked windows10_refuses only that pair is excused: the layer's S_OK against the host's E_INVALIDARG, on a host
3071// without ID3D12Device10. Any other difference, and any difference on a newer host, is still a mismatch.
3072bool windows10_refusal(const char* name, ID3D12Device* host, HRESULT ours, HRESULT theirs) {
3073 if (ours != S_OK || theirs != E_INVALIDARG) return false;
3074 Ref<ID3D12Device10> newer;
3075 if (SUCCEEDED(host->QueryInterface(IID_PPV_ARGS(&newer.p)))) return false;
3076 std::printf("invalid arguments %s: Windows 10's runtime refuses it (ours 0x%08lx, host 0x%08lx)\n", name, ours,
3077 theirs);
3078 return true;
3079}
3080
2980int compare_invalid_arguments(ID3D12Device* ours) { 3081int compare_invalid_arguments(ID3D12Device* ours) {
2981 Ref<ID3D12Device> host; 3082 Ref<ID3D12Device> host;
2982 if (!create_host_device(host)) return -1; 3083 if (!create_host_device(host)) return -1;
@@ -2985,6 +3086,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2985 const char* name; 3086 const char* name;
2986 InvalidCase call; 3087 InvalidCase call;
2987 bool (*comparable)(ID3D12Device*) = nullptr; 3088 bool (*comparable)(ID3D12Device*) = nullptr;
3089 bool windows10_refuses = false;
2988 }; 3090 };
2989 const auto device10 = [](ID3D12Device* d) { 3091 const auto device10 = [](ID3D12Device* d) {
2990 Ref<ID3D12Device10> newer; 3092 Ref<ID3D12Device10> newer;
@@ -3094,13 +3196,14 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3094 {"committed: texture in RESOLVE_DEST state", [](ID3D12Device* d) { 3196 {"committed: texture in RESOLVE_DEST state", [](ID3D12Device* d) {
3095 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_RESOLVE_DEST); 3197 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_RESOLVE_DEST);
3096 }}, 3198 }},
3199 // A buffer's initial state: Windows 10's runtime refuses these two, newer ones accept them, as the layer does.
3097 {"committed: buffer in state 0x80000000", [](ID3D12Device* d) { 3200 {"committed: buffer in state 0x80000000", [](ID3D12Device* d) {
3098 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATES(0x80000000u)); 3201 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATES(0x80000000u));
3099 }}, 3202 }, nullptr, true},
3100 {"committed: buffer in RENDER_TARGET | UNORDERED_ACCESS state", [](ID3D12Device* d) { 3203 {"committed: buffer in RENDER_TARGET | UNORDERED_ACCESS state", [](ID3D12Device* d) {
3101 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), 3204 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256),
3102 D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS); 3205 D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
3103 }}, 3206 }, nullptr, true},
3104 {"committed: buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) { 3207 {"committed: buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) {
3105 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), 3208 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256),
3106 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE); 3209 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE);
@@ -3835,6 +3938,98 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3835 {"command queue: high priority", [](ID3D12Device* d) { 3938 {"command queue: high priority", [](ID3D12Device* d) {
3836 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_HIGH}); 3939 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_HIGH});
3837 }}, 3940 }},
3941 // Command allocators and lists (video list types are only created here, not compared: the host hands out
3942 // a video list, which is not an ID3D12GraphicsCommandList). Types past VIDEO_ENCODE and nodes other than 0
3943 // are refused first; a null output is then E_UNEXPECTED.
3944 {"command allocator: type direct", [](ID3D12Device* d) {
3945 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(0));
3946 }},
3947 {"command allocator: type bundle", [](ID3D12Device* d) {
3948 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(1));
3949 }},
3950 {"command allocator: type compute", [](ID3D12Device* d) {
3951 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(2));
3952 }},
3953 {"command allocator: type copy", [](ID3D12Device* d) {
3954 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(3));
3955 }},
3956 {"command allocator: type video encode", [](ID3D12Device* d) {
3957 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(6));
3958 }},
3959 {"command allocator: type 7", [](ID3D12Device* d) { return command_allocator(d, D3D12_COMMAND_LIST_TYPE(7)); }},
3960 {"command allocator: type 99", [](ID3D12Device* d) {
3961 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(99));
3962 }},
3963 {"command allocator: type -1", [](ID3D12Device* d) {
3964 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(-1));
3965 }},
3966 {"command allocator: null output", [](ID3D12Device* d) {
3967 return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, false);
3968 }},
3969 {"command allocator: null output, type 99", [](ID3D12Device* d) {
3970 return command_allocator(d, D3D12_COMMAND_LIST_TYPE(99), false);
3971 }},
3972 {"command allocator: null output, wrong interface", [](ID3D12Device* d) {
3973 return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, false, __uuidof(ID3D12Fence));
3974 }},
3975 {"command allocator: wrong interface", [](ID3D12Device* d) {
3976 return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, true, __uuidof(ID3D12Fence));
3977 }},
3978 {"command list: direct", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0); }},
3979 {"command list: bundle", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_BUNDLE, 1); }},
3980 {"command list: node mask 1", [](ID3D12Device* d) {
3981 return command_list(d, 1, D3D12_COMMAND_LIST_TYPE_DIRECT, 0);
3982 }},
3983 {"command list: node mask 2", [](ID3D12Device* d) {
3984 return command_list(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, 0);
3985 }},
3986 {"command list: node mask 3", [](ID3D12Device* d) {
3987 return command_list(d, 3, D3D12_COMMAND_LIST_TYPE_DIRECT, 0);
3988 }},
3989 {"command list: compute allocator", [](ID3D12Device* d) {
3990 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 2);
3991 }},
3992 {"command list: no allocator", [](ID3D12Device* d) {
3993 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, -2);
3994 }},
3995 {"command list: type 99", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE(99), 0); }},
3996 {"command list: null output", [](ID3D12Device* d) {
3997 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, false);
3998 }},
3999 {"command list: null output, node mask 2", [](ID3D12Device* d) {
4000 return command_list(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, false);
4001 }},
4002 {"command list: null output, no allocator", [](ID3D12Device* d) {
4003 return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, -2, false);
4004 }},
4005 {"command list1: type direct", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(0)); }},
4006 {"command list1: type bundle", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(1)); }},
4007 {"command list1: type compute", [](ID3D12Device* d) {
4008 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(2));
4009 }},
4010 {"command list1: type copy", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(3)); }},
4011 {"command list1: type 7", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(7)); }},
4012 {"command list1: type 99", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(99)); }},
4013 // NONE (-1): Windows 10's runtime (19045, no ID3D12Device10) creates the list and Windows 11's refuses it
4014 // (measured on #2297), so it is compared only on a host with ID3D12Device10.
4015 {"command list1: type -1", [](ID3D12Device* d) {
4016 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(-1));
4017 }, +device10},
4018 {"command list1: node mask 1", [](ID3D12Device* d) {
4019 return command_list1(d, 1, D3D12_COMMAND_LIST_TYPE_DIRECT);
4020 }},
4021 {"command list1: node mask 2", [](ID3D12Device* d) {
4022 return command_list1(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT);
4023 }},
4024 {"command list1: null output", [](ID3D12Device* d) {
4025 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, false);
4026 }},
4027 {"command list1: null output, node mask 2", [](ID3D12Device* d) {
4028 return command_list1(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, false);
4029 }},
4030 {"command list1: null output, type 99", [](ID3D12Device* d) {
4031 return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(99), false);
4032 }},
3838 // CreateCommandSignature (no root signature). A null description faults in the host runtime, so it is not 4033 // CreateCommandSignature (no root signature). A null description faults in the host runtime, so it is not
3839 // compared. 4034 // compared.
3840 {"command signature: null output", [](ID3D12Device* d) { 4035 {"command signature: null output", [](ID3D12Device* d) {
@@ -4004,6 +4199,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
4004 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 4199 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
4005 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 4200 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
4006 if (a == b) continue; 4201 if (a == b) continue;
4202 if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue;
4007 if (c.comparable && !c.comparable(host.p)) { 4203 if (c.comparable && !c.comparable(host.p)) {
4008 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name, 4204 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
4009 a, b); 4205 a, b);
@@ -4074,6 +4270,7 @@ int compare_heap_neighbours(ID3D12Device* ours) {
4074 struct Case { 4270 struct Case {
4075 const char* name; 4271 const char* name;
4076 InvalidCase call; 4272 InvalidCase call;
4273 bool windows10_refuses = false;
4077 }; 4274 };
4078 static const Case cases[] = { 4275 static const Case cases[] = {
4079 {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }}, 4276 {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }},
@@ -4100,15 +4297,16 @@ int compare_heap_neighbours(ID3D12Device* ours) {
4100 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS)); 4297 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS));
4101 }}, 4298 }},
4102 // The D3D12_HEAP_FLAGS documentation calls it unsupported, but the host accepts it (RTX 4070 SUPER and 4299 // The D3D12_HEAP_FLAGS documentation calls it unsupported, but the host accepts it (RTX 4070 SUPER and
4103 // UHD 770, @CowBoYdu76). 4300 // UHD 770, @CowBoYdu76). Windows 10's runtime refuses it, as it refuses the committed case above.
4104 {"heap: HARDWARE_PROTECTED", [](ID3D12Device* d) { 4301 {"heap: HARDWARE_PROTECTED", [](ID3D12Device* d) {
4105 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_HARDWARE_PROTECTED)); 4302 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_HARDWARE_PROTECTED));
4106 }}, 4303 }, true},
4107 }; 4304 };
4108 int mismatches = 0; 4305 int mismatches = 0;
4109 for (const Case& c : cases) { 4306 for (const Case& c : cases) {
4110 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 4307 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
4111 if (a == b) continue; 4308 if (a == b) continue;
4309 if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue;
4112 ++mismatches; 4310 ++mismatches;
4113 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); 4311 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
4114 } 4312 }
@@ -4126,6 +4324,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4126 const char* name; 4324 const char* name;
4127 InvalidCase call; 4325 InvalidCase call;
4128 bool (*comparable)(ID3D12Device*) = nullptr; 4326 bool (*comparable)(ID3D12Device*) = nullptr;
4327 bool windows10_refuses = false;
4129 }; 4328 };
4130 static const Case cases[] = { 4329 static const Case cases[] = {
4131 // The standalone device has acceleration structures (XDXR, or KHR with LEONIDA_RT_AS=khr) and accepts a UAV 4330 // The standalone device has acceleration structures (XDXR, or KHR with LEONIDA_RT_AS=khr) and accepts a UAV
@@ -4339,7 +4538,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4339 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD; 4538 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4340 a.state = D3D12_RESOURCE_STATE_COPY_DEST; 4539 a.state = D3D12_RESOURCE_STATE_COPY_DEST;
4341 return placed(d, buffer_desc(256), a); 4540 return placed(d, buffer_desc(256), a);
4342 }}, 4541 }, nullptr, true},
4343 {"placed: upload buffer with ALLOW_UNORDERED_ACCESS", [](ID3D12Device* d) { 4542 {"placed: upload buffer with ALLOW_UNORDERED_ACCESS", [](ID3D12Device* d) {
4344 auto desc = buffer_desc(256); 4543 auto desc = buffer_desc(256);
4345 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; 4544 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
@@ -4359,12 +4558,12 @@ int compare_placed_reserved(ID3D12Device* ours) {
4359 a.heap.Properties.Type = D3D12_HEAP_TYPE_READBACK; 4558 a.heap.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4360 a.state = D3D12_RESOURCE_STATE_GENERIC_READ; 4559 a.state = D3D12_RESOURCE_STATE_GENERIC_READ;
4361 return placed(d, buffer_desc(256), a); 4560 return placed(d, buffer_desc(256), a);
4362 }}, 4561 }, nullptr, true},
4363 {"placed: default buffer in state 0x80000000", [](ID3D12Device* d) { 4562 {"placed: default buffer in state 0x80000000", [](ID3D12Device* d) {
4364 PlacedArgs a; 4563 PlacedArgs a;
4365 a.state = D3D12_RESOURCE_STATES(0x80000000u); 4564 a.state = D3D12_RESOURCE_STATES(0x80000000u);
4366 return placed(d, buffer_desc(256), a); 4565 return placed(d, buffer_desc(256), a);
4367 }}, 4566 }, nullptr, true},
4368 {"placed: depth texture in DEPTH_WRITE", [](ID3D12Device* d) { 4567 {"placed: depth texture in DEPTH_WRITE", [](ID3D12Device* d) {
4369 PlacedArgs a; 4568 PlacedArgs a;
4370 a.state = D3D12_RESOURCE_STATE_DEPTH_WRITE; 4569 a.state = D3D12_RESOURCE_STATE_DEPTH_WRITE;
@@ -4460,7 +4659,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4460 }}, 4659 }},
4461 {"reserved: buffer in state 0x80000000", [](ID3D12Device* d) { 4660 {"reserved: buffer in state 0x80000000", [](ID3D12Device* d) {
4462 return reserved(d, buffer_desc(64 * 1024), D3D12_RESOURCE_STATES(0x80000000u)); 4661 return reserved(d, buffer_desc(64 * 1024), D3D12_RESOURCE_STATES(0x80000000u));
4463 }}, 4662 }, nullptr, true},
4464 {"reserved: texture", [](ID3D12Device* d) { 4663 {"reserved: texture", [](ID3D12Device* d) {
4465 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE))); 4664 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)));
4466 }}, 4665 }},
@@ -4544,6 +4743,7 @@ int compare_placed_reserved(ID3D12Device* ours) {
4544 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 4743 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
4545 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 4744 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
4546 if (a == b) continue; 4745 if (a == b) continue;
4746 if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue;
4547 if (c.comparable && !c.comparable(host.p)) { 4747 if (c.comparable && !c.comparable(host.p)) {
4548 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name, 4748 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
4549 a, b); 4749 a, b);
@@ -5284,7 +5484,9 @@ int main() {
5284 EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device1.p)))); 5484 EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device1.p))));
5285 const D3D12_RESIDENCY_PRIORITY priorities[] = {D3D12_RESIDENCY_PRIORITY_MAXIMUM, 5485 const D3D12_RESIDENCY_PRIORITY priorities[] = {D3D12_RESIDENCY_PRIORITY_MAXIMUM,
5286 D3D12_RESIDENCY_PRIORITY(D3D12_RESIDENCY_PRIORITY_LOW + 5)}; 5486 D3D12_RESIDENCY_PRIORITY(D3D12_RESIDENCY_PRIORITY_LOW + 5)};
5287 EXPECT(device1->SetResidencyPriority(2, pageables, priorities) == S_OK); 5487 // Only committed resources and heaps take a priority, as on the host runtime (d3d12_residency_test): a
5488 // fence and an allocator don't.
5489 EXPECT(device1->SetResidencyPriority(2, pageables, priorities) == E_INVALIDARG);
5288 EXPECT(device1->SetResidencyPriority(0, nullptr, nullptr) == S_OK); 5490 EXPECT(device1->SetResidencyPriority(0, nullptr, nullptr) == S_OK);
5289 EXPECT(device1->SetResidencyPriority(1, pageables, nullptr) == E_INVALIDARG); 5491 EXPECT(device1->SetResidencyPriority(1, pageables, nullptr) == E_INVALIDARG);
5290 EXPECT(device1->SetResidencyPriority(1, nullptr, priorities) == E_INVALIDARG); 5492 EXPECT(device1->SetResidencyPriority(1, nullptr, priorities) == E_INVALIDARG);
@@ -5296,8 +5498,9 @@ int main() {
5296 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, residency.p, 9) == 5498 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, residency.p, 9) ==
5297 S_OK); 5499 S_OK);
5298 EXPECT(residency->GetCompletedValue() == 9); 5500 EXPECT(residency->GetCompletedValue() == 9);
5299 // Refused calls leave the fence alone. 5501 // A null fence is accepted (the host runtime's answer) and signals nothing; refused calls leave the fence
5300 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, pageables, nullptr, 11) == E_INVALIDARG); 5502 // alone.
5503 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, pageables, nullptr, 11) == S_OK);
5301 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, residency.p, 11) == 5504 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, residency.p, 11) ==
5302 E_INVALIDARG); 5505 E_INVALIDARG);
5303 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, pageables, residency.p, 11) == 5506 EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, pageables, residency.p, 11) ==
@@ -6271,7 +6474,7 @@ int main() {
6271 UINT64 frequency = 0; 6474 UINT64 frequency = 0;
6272 EXPECT(SUCCEEDED(queue->GetTimestampFrequency(&frequency)) && frequency >= 1'000'000); 6475 EXPECT(SUCCEEDED(queue->GetTimestampFrequency(&frequency)) && frequency >= 1'000'000);
6273 EXPECT(queue->GetTimestampFrequency(nullptr) == E_INVALIDARG); 6476 EXPECT(queue->GetTimestampFrequency(nullptr) == E_INVALIDARG);
6274 Ref<ID3D12QueryHeap> occlusion, timestamps, statistics, refused; 6477 Ref<ID3D12QueryHeap> occlusion, timestamps, statistics, so, refused;
6275 D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0}; 6478 D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0};
6276 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p)))); 6479 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p))));
6277 // A null output is E_UNEXPECTED, as on the host runtime (compare_invalid_arguments, "query heap:"). 6480 // A null output is E_UNEXPECTED, as on the host runtime (compare_invalid_arguments, "query heap:").
@@ -6284,16 +6487,20 @@ int main() {
6284 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&timestamps.p)))); 6487 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&timestamps.p))));
6285 query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0}; 6488 query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0};
6286 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); 6489 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p);
6287 query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 1, 0}; // no stream output path yet 6490 // The layer has no stream output, so stream-output statistics heaps are made without a Vulkan pool and
6288 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && !refused.p); 6491 // every query reads zero (D3D-302).
6492 query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0};
6493 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p))));
6289 query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0}; 6494 query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0};
6290 if (d.pipeline_statistics_query) 6495 if (d.pipeline_statistics_query)
6291 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&statistics.p)))); 6496 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&statistics.p))));
6292 else 6497 else
6293 std::printf("pipeline statistics: no pipelineStatisticsQuery, skipped\n"); 6498 std::printf("pipeline statistics: no pipelineStatisticsQuery, skipped\n");
6294 6499
6295 // Readback layout: timestamps at 0, occlusion at 64, statistics at 256, the second run's at 1024. 6500 // Readback layout: timestamps at 0, occlusion at 64, statistics at 256, stream output at 512, the second
6296 constexpr UINT64 ts_at = 0, occlusion_at = 64, statistics_at = 256, again_at = 1024; 6501 // run's at 1024.
6502 constexpr UINT64 ts_at = 0, occlusion_at = 64, statistics_at = 256, so_at = 512, again_at = 1024;
6503 static_assert(sizeof(D3D12_QUERY_DATA_SO_STATISTICS) == 16);
6297 const auto u64 = [&](UINT64 offset) { 6504 const auto u64 = [&](UINT64 offset) {
6298 UINT64 value; 6505 UINT64 value;
6299 std::memcpy(&value, down + offset, sizeof(value)); 6506 std::memcpy(&value, down + offset, sizeof(value));
@@ -6303,15 +6510,21 @@ int main() {
6303 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); 6510 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
6304 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); 6511 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0);
6305 if (statistics.p) list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); 6512 if (statistics.p) list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0);
6513 // Two streams at once, inside the statistics query and crossing the occlusion one: none of them is a
6514 // Vulkan query, so none overlaps.
6515 list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0);
6516 list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1);
6306 // A rectangle clear runs in a render pass inside a query; clears count no samples. 6517 // A rectangle clear runs in a render pass inside a query; clears count no samples.
6307 device->CreateRenderTargetView(rt_resource.p, &rtv_desc, rtv1); // the resolve test reused it 6518 device->CreateRenderTargetView(rt_resource.p, &rtv_desc, rtv1); // the resolve test reused it
6308 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); 6519 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0);
6309 barrier = transition(rt_resource.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); 6520 barrier = transition(rt_resource.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
6310 list->ResourceBarrier(1, &barrier); 6521 list->ResourceBarrier(1, &barrier);
6311 list->ClearRenderTargetView(rtv1, red, 1, &square); 6522 list->ClearRenderTargetView(rtv1, red, 1, &square);
6523 list->EndQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0);
6312 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); 6524 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0);
6313 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); 6525 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1);
6314 list->CopyBufferRegion(readback.p, 8192, upload.p, 0, 32768); 6526 list->CopyBufferRegion(readback.p, 8192, upload.p, 0, 32768);
6527 list->EndQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1);
6315 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); 6528 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1);
6316 if (statistics.p) list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); 6529 if (statistics.p) list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0);
6317 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 1); 6530 list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 1);
@@ -6322,6 +6535,8 @@ int main() {
6322 if (statistics.p) 6535 if (statistics.p)
6323 list->ResolveQueryData(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 2, readback.p, 6536 list->ResolveQueryData(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 2, readback.p,
6324 statistics_at); 6537 statistics_at);
6538 list->ResolveQueryData(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0, 1, readback.p, so_at);
6539 list->ResolveQueryData(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1, 2, readback.p, so_at + 16); // 2: never
6325 EXPECT(list->Close() == S_OK); 6540 EXPECT(list->Close() == S_OK);
6326 queue->ExecuteCommandLists(1, lists); 6541 queue->ExecuteCommandLists(1, lists);
6327 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 6542 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
@@ -6334,6 +6549,8 @@ int main() {
6334 for (UINT i = 0; i < 4; ++i) EXPECT(u64(occlusion_at + 8 * i) == 0); 6549 for (UINT i = 0; i < 4; ++i) EXPECT(u64(occlusion_at + 8 * i) == 0);
6335 for (UINT i = 0; statistics.p && i < 22; ++i) EXPECT(u64(statistics_at + 8 * i) == 0); 6550 for (UINT i = 0; statistics.p && i < 22; ++i) EXPECT(u64(statistics_at + 8 * i) == 0);
6336 EXPECT(u64(statistics.p ? statistics_at + 176 : statistics_at) == 0xcdcdcdcdcdcdcdcdull); // not past it 6551 EXPECT(u64(statistics.p ? statistics_at + 176 : statistics_at) == 0xcdcdcdcdcdcdcdcdull); // not past it
6552 for (UINT i = 0; i < 6; ++i) EXPECT(u64(so_at + 8 * i) == 0); // written and needed, three queries
6553 EXPECT(u64(so_at + 48) == 0xcdcdcdcdcdcdcdcdull); // not past them
6337 6554
6338 // A second execution reuses timestamp 0 (reset before it is written again) and resolves timestamp 1, 6555 // A second execution reuses timestamp 0 (reset before it is written again) and resolves timestamp 1,
6339 // which keeps the result of the first execution. 6556 // which keeps the result of the first execution.
@@ -6393,6 +6610,12 @@ int main() {
6393 [&] { list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 3, 2, readback.p, 0); })); 6610 [&] { list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 3, 2, readback.p, 0); }));
6394 EXPECT(refuse(S_OK, R::invalid_query, // a type the heap does not hold 6611 EXPECT(refuse(S_OK, R::invalid_query, // a type the heap does not hold
6395 [&] { list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); })); 6612 [&] { list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); }));
6613 EXPECT(refuse(S_OK, R::invalid_query, [&] { // a stream-output query in an occlusion heap
6614 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1, 0);
6615 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1, 0);
6616 }));
6617 EXPECT(refuse(E_INVALIDARG, R::invalid_query, // a stream-output query begun and never ended
6618 [&] { list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2, 0); }));
6396 EXPECT(refuse(S_OK, R::invalid_query, // into a texture 6619 EXPECT(refuse(S_OK, R::invalid_query, // into a texture
6397 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, rt_resource.p, 0); })); 6620 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, rt_resource.p, 0); }));
6398 EXPECT(refuse(S_OK, R::invalid_query, // past the end of the buffer 6621 EXPECT(refuse(S_OK, R::invalid_query, // past the end of the buffer
@@ -6498,6 +6721,45 @@ int main() {
6498 } 6721 }
6499 } 6722 }
6500 6723
6724 // D3D-71: a default-heap buffer outside the arena (this device has none) starts zeroed, as D3D12 committed
6725 // resources do. Its memory is first dirtied through an earlier buffer, which is then released so the next
6726 // allocation is likely to reuse it. CREATE_NOT_ZEROED skips the fill; a copy into the same list still lands.
6727 {
6728 constexpr UINT64 bytes = 4096;
6729 const D3D12_HEAP_PROPERTIES default_buffer_heap{D3D12_HEAP_TYPE_DEFAULT};
6730 std::memset(up, 0xab, std::size_t(bytes));
6731 {
6732 Ref<ID3D12Resource> dirty;
6733 EXPECT(SUCCEEDED(create(default_buffer_heap, buffer_desc(bytes), D3D12_RESOURCE_STATE_COMMON, dirty)));
6734 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
6735 list->CopyBufferRegion(dirty.p, 0, upload.p, 0, bytes);
6736 EXPECT(list->Close() == S_OK);
6737 queue->ExecuteCommandLists(1, lists);
6738 EXPECT(submit_and_wait());
6739 }
6740 Ref<ID3D12Resource> fresh, not_zeroed;
6741 EXPECT(SUCCEEDED(create(default_buffer_heap, buffer_desc(bytes), D3D12_RESOURCE_STATE_COMMON, fresh)));
6742 const D3D12_RESOURCE_DESC zero_desc = buffer_desc(bytes);
6743 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_buffer_heap, D3D12_HEAP_FLAG_CREATE_NOT_ZEROED,
6744 &zero_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
6745 IID_PPV_ARGS(&not_zeroed.p))));
6746 std::memset(down, 0xcd, std::size_t(2 * bytes));
6747 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
6748 list->CopyBufferRegion(readback.p, 0, fresh.p, 0, bytes);
6749 list->CopyBufferRegion(not_zeroed.p, 0, upload.p, 0, bytes); // written before it is read
6750 auto readable = transition(not_zeroed.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
6751 list->ResourceBarrier(1, &readable);
6752 list->CopyBufferRegion(readback.p, bytes, not_zeroed.p, 0, bytes);
6753 EXPECT(list->Close() == S_OK);
6754 queue->ExecuteCommandLists(1, lists);
6755 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
6756 EXPECT(submit_and_wait());
6757 const std::uint8_t zero[4] = {}, written[4] = {0xab, 0xab, 0xab, 0xab};
6758 for (UINT64 i = 0; i < bytes; i += 4) report("zero-filled buffer byte", UINT(i), down + i, zero, 4);
6759 for (UINT64 i = 0; i < bytes; i += 4)
6760 report("NOT_ZEROED buffer byte after a copy", UINT(i), down + bytes + i, written, 4);
6761 }
6762
6501 // Every child holds the proxy; once they are gone the proxy holds the only reference. 6763 // Every child holds the proxy; once they are gone the proxy holds the only reference.
6502 upload->Unmap(0, nullptr); 6764 upload->Unmap(0, nullptr);
6503 readback->Unmap(0, nullptr); 6765 readback->Unmap(0, nullptr);
diff --git a/runtime/test/dxgi_device_test.cpp b/runtime/test/dxgi_device_test.cpp
new file mode 100644
index 000000000..5b02cb762
--- /dev/null
+++ b/runtime/test/dxgi_device_test.cpp
@@ -0,0 +1,349 @@
1// IDXGIDevice1 on the Xbox-ABI device proxy (d3d12_xs_device.h): the step a GDKX title takes to find its output
2// (docs/d3d12_vulkan.md section 4.5: QueryInterface the device for IDXGIDevice1, GetAdapter, EnumOutputs(0)). Walked
3// on the host PC runtime (WARP, and the first hardware adapter when there is one) and on the Vulkan-backed device:
4// - the PC device behind the proxy has no IDXGIDevice of its own (host runtime), so the proxy's answer is its own;
5// - QueryInterface for IDXGIDevice, IDXGIDevice1 and IDXGIObject gives one pointer, which is not the device's but
6// is the same COM object: one IUnknown, QueryInterface back to ID3D12Device gives the proxy, one reference count;
7// - IDXGIDevice2 and later are refused;
8// - GetAdapter and GetParent(IDXGIAdapter) give the adapter of the device behind the proxy: its LUID is the
9// device's GetAdapterLuid. On the host runtime it is the host's adapter; on the Vulkan device it is the layer's
10// own (rt::dxgi, which stops at IDXGIAdapter3 and whose parent is the layer's factory);
11// - EnumOutputs(0) on that adapter answers S_OK with an output or DXGI_ERROR_NOT_FOUND, never anything else;
12// - null arguments, the frame latency and the GPU thread priority, and private data shared with the device;
13// - a device created as IDXGIDevice1 directly (a title may pass that IID to D3D12XboxCreateDevice): the pointer
14// that comes back is the DXGI one, the proxy behind it is the device's identity (a fence's GetDevice gives it),
15// and the adapter provider still reaches it, so the Vulkan device hands out the layer's adapter there too.
16// Exits 77 when neither a host D3D12 device nor a Vulkan device can be made. No shaders, game data or Xbox DLLs.
17#include "vk_test_device.h"
18#include "../shims/d3d12_com.h"
19#include "../shims/d3d12_xs_device.h"
20
21#include <d3d12.h>
22#include <dxgi1_6.h>
23
24#include <cstdint>
25#include <cstdio>
26#include <cstring>
27
28#define EXPECT(condition) do { \
29 if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", label, __LINE__, #condition); return 1; } \
30} while (0)
31
32namespace {
33
34namespace xs = rt::d3d12_xs;
35
36template <class T>
37struct Ref {
38 T* p = nullptr;
39 Ref() = default;
40 Ref(const Ref&) = delete;
41 Ref& operator=(const Ref&) = delete;
42 ~Ref() { reset(); }
43 void reset() {
44 if (p) p->Release();
45 p = nullptr;
46 }
47 T* operator->() const { return p; }
48};
49
50// {8f3a1c52-6e0b-4d97-b1c4-2a7e9d5f0c36}: a private-data key of this test.
51constexpr GUID kTestData{0x8f3a1c52, 0x6e0b, 0x4d97, {0xb1, 0xc4, 0x2a, 0x7e, 0x9d, 0x5f, 0x0c, 0x36}};
52
53bool same_luid(const LUID& a, const LUID& b) { return a.LowPart == b.LowPart && a.HighPart == b.HighPart; }
54
55// `device` is the device proxy, `real` the device behind it.
56int check_backend(const char* label, ID3D12Device* device, ID3D12Device* real, bool vulkan) {
57 const unsigned long device_refs = xs::device_proxy_ref_count(device);
58
59 // The device behind the proxy: the PC runtime's has no IDXGIDevice, which is why the proxy answers it itself.
60 if (!vulkan) {
61 void* none = reinterpret_cast<void*>(1);
62 EXPECT(real->QueryInterface(__uuidof(IDXGIDevice1), &none) == E_NOINTERFACE && !none);
63 }
64
65 Ref<IDXGIDevice1> dxgi;
66 EXPECT(device->QueryInterface(__uuidof(IDXGIDevice1), reinterpret_cast<void**>(&dxgi.p)) == S_OK && dxgi.p);
67 EXPECT(static_cast<void*>(dxgi.p) != static_cast<void*>(device));
68 EXPECT(xs::device_proxy_from_dxgi_device(dxgi.p) == device && !xs::device_proxy_from_dxgi_device(device));
69 EXPECT(xs::device_proxy_ref_count(device) == device_refs + 1);
70 {
71 // One COM object: every DXGI interface is the same pointer, IUnknown is the device's, and QueryInterface
72 // leads back to the device proxy from each of them.
73 Ref<IDXGIDevice> dxgi0;
74 Ref<IDXGIObject> object;
75 Ref<IUnknown> unknown_a, unknown_b;
76 Ref<ID3D12Device> back;
77 EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgi0.p)) == S_OK);
78 EXPECT(device->QueryInterface(__uuidof(IDXGIObject), reinterpret_cast<void**>(&object.p)) == S_OK);
79 EXPECT(static_cast<void*>(dxgi0.p) == static_cast<void*>(dxgi.p) &&
80 static_cast<void*>(object.p) == static_cast<void*>(dxgi.p));
81 EXPECT(dxgi->QueryInterface(__uuidof(IUnknown), reinterpret_cast<void**>(&unknown_a.p)) == S_OK);
82 EXPECT(device->QueryInterface(__uuidof(IUnknown), reinterpret_cast<void**>(&unknown_b.p)) == S_OK);
83 EXPECT(unknown_a.p == unknown_b.p && static_cast<void*>(unknown_a.p) == static_cast<void*>(device));
84 EXPECT(dxgi->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast<void**>(&back.p)) == S_OK);
85 EXPECT(back.p == device);
86 EXPECT(xs::device_proxy_ref_count(device) == device_refs + 6);
87 // Later DXGI device interfaces, and a null output or IID.
88 void* none = reinterpret_cast<void*>(1);
89 EXPECT(device->QueryInterface(__uuidof(IDXGIDevice2), &none) == E_NOINTERFACE && !none);
90 none = reinterpret_cast<void*>(1);
91 EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice2), &none) == E_NOINTERFACE && !none);
92 EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice1), nullptr) == E_POINTER);
93 }
94 EXPECT(xs::device_proxy_ref_count(device) == device_refs + 1);
95 // AddRef and Release on the DXGI pointer count on the device.
96 EXPECT(dxgi->AddRef() == device_refs + 2 && dxgi->Release() == device_refs + 1);
97
98 // GetAdapter: the adapter of the device behind the proxy.
99 const LUID device_luid = device->GetAdapterLuid();
100 EXPECT(same_luid(device_luid, real->GetAdapterLuid()));
101 Ref<IDXGIAdapter> adapter;
102 EXPECT(dxgi->GetAdapter(&adapter.p) == S_OK && adapter.p);
103 DXGI_ADAPTER_DESC desc{};
104 EXPECT(adapter->GetDesc(&desc) == S_OK && same_luid(desc.AdapterLuid, device_luid));
105 char name[128] = {};
106 WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, name, sizeof(name) - 1, nullptr, nullptr);
107 EXPECT(dxgi->GetAdapter(nullptr) == E_POINTER);
108 {
109 // GetParent is the same adapter by another road, as any interface it has; the device is not its own parent.
110 Ref<IDXGIAdapter> parent;
111 EXPECT(dxgi->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&parent.p)) == S_OK && parent.p);
112 DXGI_ADAPTER_DESC parent_desc{};
113 EXPECT(parent->GetDesc(&parent_desc) == S_OK && same_luid(parent_desc.AdapterLuid, device_luid));
114 void* none = reinterpret_cast<void*>(1);
115 EXPECT(FAILED(dxgi->GetParent(__uuidof(ID3D12Device), &none)) && !none);
116 EXPECT(dxgi->GetParent(__uuidof(IDXGIAdapter), nullptr) == E_POINTER);
117 }
118 {
119 // Whose adapter it is. The layer's own stops at IDXGIAdapter3 and its parent is the layer's factory, which
120 // enumerates exactly that one adapter; the host's is the host DXGI's (IDXGIAdapter4 since Windows 10 1803).
121 Ref<IDXGIAdapter4> adapter4;
122 const HRESULT hr4 = adapter->QueryInterface(__uuidof(IDXGIAdapter4), reinterpret_cast<void**>(&adapter4.p));
123 Ref<IDXGIFactory1> factory;
124 EXPECT(adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory.p)) == S_OK);
125 Ref<IDXGIAdapter> second;
126 const HRESULT second_hr = factory->EnumAdapters(1, &second.p);
127 if (vulkan) {
128 EXPECT(hr4 == E_NOINTERFACE && !adapter4.p);
129 EXPECT(second_hr == DXGI_ERROR_NOT_FOUND && !second.p);
130 }
131 }
132 // The next step of the sequence. Which answer comes back is the adapter's business (a software adapter has no
133 // output; the layer's adapter has none before D3D-313): it is one of the two, and an output only with S_OK.
134 Ref<IDXGIOutput> output;
135 const HRESULT output_hr = adapter->EnumOutputs(0, &output.p);
136 EXPECT((output_hr == S_OK && output.p) || (output_hr == DXGI_ERROR_NOT_FOUND && !output.p));
137
138 // IDXGIDevice1's own state: kept and read back.
139 UINT latency = 0;
140 EXPECT(dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 3);
141 EXPECT(dxgi->SetMaximumFrameLatency(1) == S_OK && dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 1);
142 EXPECT(dxgi->SetMaximumFrameLatency(17) == DXGI_ERROR_INVALID_CALL);
143 EXPECT(dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 1);
144 EXPECT(dxgi->SetMaximumFrameLatency(0) == S_OK && dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 3);
145 EXPECT(dxgi->GetMaximumFrameLatency(nullptr) == E_POINTER);
146 INT priority = 99;
147 EXPECT(dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 0);
148 EXPECT(dxgi->SetGPUThreadPriority(7) == S_OK && dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 7);
149 EXPECT(dxgi->SetGPUThreadPriority(8) == E_INVALIDARG && dxgi->SetGPUThreadPriority(-8) == E_INVALIDARG);
150 EXPECT(dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 7);
151 EXPECT(dxgi->GetGPUThreadPriority(nullptr) == E_POINTER);
152 IDXGISurface* surface = reinterpret_cast<IDXGISurface*>(std::uintptr_t{1});
153 EXPECT(dxgi->CreateSurface(nullptr, 0, 0, nullptr, &surface) == E_NOTIMPL && !surface);
154 EXPECT(dxgi->QueryResourceResidency(nullptr, nullptr, 0) == E_NOTIMPL);
155
156 // Private data set through the DXGI interface is the device's, and the other way round.
157 const std::uint32_t written = 0x12345678;
158 std::uint32_t read = 0;
159 UINT size = sizeof(read);
160 EXPECT(dxgi->SetPrivateData(kTestData, sizeof(written), &written) == S_OK);
161 EXPECT(device->GetPrivateData(kTestData, &size, &read) == S_OK && size == sizeof(read) && read == written);
162 EXPECT(device->SetPrivateData(kTestData, 0, nullptr) == S_OK);
163 size = sizeof(read);
164 EXPECT(FAILED(dxgi->GetPrivateData(kTestData, &size, &read)));
165
166 // The adapter does not keep the device alive, and the device outlives its DXGI pointer's last use.
167 adapter.reset();
168 output.reset();
169 dxgi.reset();
170 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
171 std::printf("%s: IDXGIDevice1 on the device proxy is one COM object with it; GetAdapter and GetParent give \"%s\" "
172 "(%s adapter, the device's LUID); EnumOutputs(0) %s\n",
173 label, name, vulkan ? "the layer's own" : "the host's",
174 output_hr == S_OK ? "gives an output" : "is DXGI_ERROR_NOT_FOUND");
175 return 0;
176}
177
178// The device created as IDXGIDevice1, the way D3D12XboxCreateDevice creates it when a title passes that IID: the
179// proxy over `real` (which takes one reference to it), then set_device_outer with what came back for the Vulkan
180// device. `real` is released by the proxy's last reference.
181int check_direct(const char* label, ID3D12Device* real, bool vulkan) {
182 IDXGIDevice1* dxgi = nullptr;
183 EXPECT(xs::create_device_proxy(real, __uuidof(IDXGIDevice1), reinterpret_cast<void**>(&dxgi)) == S_OK && dxgi);
184 EXPECT(!xs::is_device_proxy(dxgi)); // the DXGI pointer, not the proxy
185 void* const proxy = xs::device_proxy_from_dxgi_device(dxgi);
186 EXPECT(proxy && xs::is_device_proxy(proxy) && xs::device_proxy_primary(dxgi) == proxy &&
187 xs::device_proxy_primary(proxy) == proxy);
188 EXPECT(xs::device_proxy_ref_count(proxy) == 1); // the caller's one reference, held through the DXGI pointer
189 if (vulkan) rt::d3d12::set_device_outer(real, dxgi);
190 {
191 // QueryInterface back to the device gives the proxy, and the device's children name the proxy as their
192 // device: the outer identity is the proxy, not the DXGI pointer that creation returned.
193 Ref<ID3D12Device> device;
194 EXPECT(dxgi->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device.p)) == S_OK);
195 EXPECT(static_cast<void*>(device.p) == proxy && xs::device_proxy_ref_count(proxy) == 2);
196 Ref<ID3D12Fence> fence;
197 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
198 Ref<ID3D12Device> owner;
199 EXPECT(SUCCEEDED(fence->GetDevice(IID_PPV_ARGS(&owner.p))) && static_cast<void*>(owner.p) == proxy);
200 // The adapter: the device's LUID, and on the Vulkan device the layer's own, as on the query path.
201 Ref<IDXGIAdapter> adapter;
202 EXPECT(dxgi->GetAdapter(&adapter.p) == S_OK && adapter.p);
203 DXGI_ADAPTER_DESC desc{};
204 EXPECT(adapter->GetDesc(&desc) == S_OK && same_luid(desc.AdapterLuid, real->GetAdapterLuid()));
205 Ref<IDXGIAdapter4> adapter4;
206 const HRESULT hr4 = adapter->QueryInterface(__uuidof(IDXGIAdapter4), reinterpret_cast<void**>(&adapter4.p));
207 Ref<IDXGIFactory1> factory;
208 EXPECT(adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory.p)) == S_OK);
209 Ref<IDXGIAdapter> second;
210 const HRESULT second_hr = factory->EnumAdapters(1, &second.p);
211 if (vulkan) {
212 EXPECT(hr4 == E_NOINTERFACE && !adapter4.p);
213 EXPECT(second_hr == DXGI_ERROR_NOT_FOUND && !second.p);
214 }
215 }
216 EXPECT(xs::device_proxy_ref_count(proxy) == 1);
217 {
218 // A provider set through the DXGI pointer is the one GetAdapter asks, and one handed something that is not
219 // a proxy is refused (it says so on stderr) instead of leaving the default in place unnoticed.
220 const xs::DxgiAdapterProvider refuse = [](ID3D12Device*, REFIID, void** out) {
221 *out = reinterpret_cast<void*>(std::uintptr_t{1}); // a failing provider's output is not handed on
222 return E_ABORT;
223 };
224 EXPECT(xs::set_device_adapter_provider(dxgi, refuse));
225 IDXGIAdapter* none = reinterpret_cast<IDXGIAdapter*>(std::uintptr_t{1});
226 EXPECT(dxgi->GetAdapter(&none) == E_ABORT && !none);
227 EXPECT(xs::set_device_adapter_provider(proxy, nullptr)); // back to the default (the host's adapter)
228 Ref<IDXGIAdapter> host;
229 EXPECT(dxgi->GetAdapter(&host.p) == S_OK && host.p);
230 void* not_a_proxy = nullptr; // pointer-sized: the helpers read a vtable pointer from what they are given
231 EXPECT(!xs::set_device_adapter_provider(&not_a_proxy, refuse) && !xs::set_device_adapter_provider(real, refuse));
232 EXPECT(!xs::device_proxy_primary(&not_a_proxy) && !xs::device_proxy_primary(nullptr));
233 }
234 EXPECT(dxgi->Release() == 0); // the last reference: the proxy goes, and with it its reference to `real`
235 std::printf("%s: created as IDXGIDevice1: the proxy is the device's identity and the adapter is %s\n", label,
236 vulkan ? "the layer's own" : "the host's");
237 return 0;
238}
239
240int run_host(IDXGIAdapter1* adapter, const char* label) {
241 ID3D12Device* real = nullptr;
242 if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&real)))) {
243 std::printf("%s: no D3D12 device, skipped\n", label);
244 return 77;
245 }
246 real->AddRef(); // for the second proxy below: each proxy takes one reference
247 if (check_direct(label, real, false)) {
248 real->Release();
249 return 1;
250 }
251 real->AddRef(); // the backend's own reference; the proxy takes the other
252 Ref<ID3D12Device> device;
253 if (FAILED(xs::create_device_proxy(real, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device.p)))) {
254 real->Release();
255 real->Release();
256 std::fprintf(stderr, "%s: device proxy creation failed\n", label);
257 return 1;
258 }
259 const int result = check_backend(label, device.p, real, false);
260 device.reset();
261 if (result) return 1;
262 if (real->Release() != 0) {
263 std::fprintf(stderr, "%s: the PC device outlives its proxy\n", label);
264 return 1;
265 }
266 return 0;
267}
268
269} // namespace
270
271// A failure ends the process with a message on stderr, never in a dialog a test run would wait on.
272static void no_dialogs() {
273 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
274 SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
275}
276
277int main() {
278 no_dialogs();
279 std::setvbuf(stdout, nullptr, _IONBF, 0);
280 const char* label = "dxgi_device_test";
281 int ran = 0;
282
283 // Host PC runtime: WARP, then the first hardware adapter. Under Wine the host d3d12.dll is Wine's own, not the
284 // PC runtime the proxy is written against, so only Vulkan runs there.
285 const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr;
286 Ref<IDXGIFactory4> factory;
287 if (wine) std::printf("host D3D12: under Wine, skipped\n");
288 if (!wine && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) {
289 Ref<IDXGIAdapter1> warp;
290 if (SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) {
291 const int r = run_host(warp.p, "host WARP");
292 if (r == 1) return 1;
293 ran += r == 0;
294 }
295 for (UINT i = 0;; ++i) {
296 Ref<IDXGIAdapter1> adapter;
297 if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break;
298 DXGI_ADAPTER_DESC1 desc{};
299 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
300 const int r = run_host(adapter.p, "host hardware adapter");
301 if (r == 1) return 1;
302 ran += r == 0;
303 break;
304 }
305 }
306
307 // The Vulkan-backed device, the way D3D12XboxCreateDevice hands it out with LEONIDA_D3D12=vulkan.
308 vktest::Device d;
309 if (d.create()) {
310 label = "Vulkan";
311 rt::d3d12::VulkanDeviceInfo info{};
312 info.get_instance_proc = d.instance_proc;
313 info.instance = d.instance;
314 info.physical = d.physical;
315 info.device = d.device;
316 info.queue = d.queue;
317 info.queue_family = d.family;
318 ID3D12Device* inner = nullptr;
319 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
320 inner->AddRef(); // the backend's own reference; the proxy takes the other
321 ID3D12Device* device = nullptr;
322 EXPECT(SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device))));
323 rt::d3d12::set_device_outer(inner, device);
324 const int result = check_backend(label, device, inner, true);
325 device->Release();
326 if (result) return 1;
327 EXPECT(inner->Release() == 0); // nothing the adapter or the factory made kept the layer's device alive
328 // A second device on the same Vulkan device, created as IDXGIDevice1.
329 ID3D12Device* direct = nullptr;
330 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&direct))));
331 direct->AddRef(); // the backend's own reference; the proxy takes the other
332 if (check_direct(label, direct, true)) return 1;
333 EXPECT(direct->Release() == 0);
334 ++ran;
335 if (d.validation_errors()) {
336 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
337 return 1;
338 }
339 } else {
340 std::printf("Vulkan: no device, skipped\n");
341 }
342
343 if (!ran) {
344 std::printf("SKIP dxgi_device_test: neither a host D3D12 device nor a Vulkan device\n");
345 return 77;
346 }
347 std::printf("dxgi_device_test: %d backend(s) passed\n", ran);
348 return 0;
349}
diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp
new file mode 100644
index 000000000..13da2028e
--- /dev/null
+++ b/runtime/test/dxgi_swapchain_count_test.cpp
@@ -0,0 +1,354 @@
1// Synthetic regression test for the DXGI swapchain buffer-count contract (D3D-389), with no GPU and no
2// window: VulkanSwapchain (runtime/shims/dxgi_swapchain.h) runs on a fake Vulkan function table, so
3// vkGetSwapchainImagesKHR can report more images than the app's requested BufferCount.
4//
5// DXGI rule: GetDesc/GetDesc1 report the BufferCount the app created with, and GetCurrentBackBufferIndex is
6// always below it, one stable resource per index. The shim must not expose images the driver added above
7// minImageCount, and must hide a caps.minImageCount above the request. When the native count differs, the
8// exposed buffers form an offscreen ring; each present blits the current slot into the acquired native image.
9#include "../shims/dxgi_swapchain.h"
10
11#include <cstdint>
12#include <cstdio>
13#include <cstring>
14#include <mutex>
15#include <vector>
16
17namespace {
18
19constexpr std::uintptr_t kSurface = 0x5100;
20constexpr std::uintptr_t kSwapchain = 0x5101;
21constexpr std::uintptr_t kFence = 0x5102;
22constexpr std::uintptr_t kPool = 0x5103;
23constexpr std::uintptr_t kCmd = 0x5104;
24constexpr std::uintptr_t kNativeBase = 0x6000;
25constexpr std::uintptr_t kOffscreenBase = 0x7000;
26
27struct Fake {
28 std::uint32_t min_image_count = 2;
29 std::uint32_t max_image_count = 0;
30 std::uint32_t returned_images = 2;
31 std::uint32_t create_min_image_count = 0;
32 std::uint32_t acquire_cursor = 0;
33 std::uint32_t last_acquired = 0;
34 std::uint32_t presented_image = UINT32_MAX;
35 VkImage blit_src = VK_NULL_HANDLE;
36 VkImage blit_dst = VK_NULL_HANDLE;
37 unsigned presents = 0;
38 unsigned created_offscreen = 0;
39};
40Fake g;
41
42VkImage native_image(std::uint32_t i) {
43 return reinterpret_cast<VkImage>(static_cast<std::uintptr_t>(kNativeBase + i));
44}
45
46template <typename T>
47PFN_vkVoidFunction as_function(T fn) {
48 return reinterpret_cast<PFN_vkVoidFunction>(fn);
49}
50
51VKAPI_ATTR VkResult VKAPI_CALL create_win32_surface(VkInstance, const VkWin32SurfaceCreateInfoKHR*,
52 const VkAllocationCallbacks*, VkSurfaceKHR* out) {
53 if (out) *out = reinterpret_cast<VkSurfaceKHR>(kSurface);
54 return VK_SUCCESS;
55}
56VKAPI_ATTR void VKAPI_CALL destroy_surface(VkInstance, VkSurfaceKHR, const VkAllocationCallbacks*) {}
57VKAPI_ATTR VkResult VKAPI_CALL surface_support(VkPhysicalDevice, std::uint32_t, VkSurfaceKHR, VkBool32* out) {
58 if (out) *out = VK_TRUE;
59 return VK_SUCCESS;
60}
61VKAPI_ATTR VkResult VKAPI_CALL surface_caps(VkPhysicalDevice, VkSurfaceKHR, VkSurfaceCapabilitiesKHR* caps) {
62 if (!caps) return VK_ERROR_INITIALIZATION_FAILED;
63 std::memset(caps, 0, sizeof(*caps));
64 caps->minImageCount = g.min_image_count;
65 caps->maxImageCount = g.max_image_count;
66 caps->currentExtent = {64, 64};
67 caps->minImageExtent = {1, 1};
68 caps->maxImageExtent = {4096, 4096};
69 caps->supportedUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
70 VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
71 caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
72 return VK_SUCCESS;
73}
74VKAPI_ATTR VkResult VKAPI_CALL surface_formats(VkPhysicalDevice, VkSurfaceKHR, std::uint32_t* count,
75 VkSurfaceFormatKHR* formats) {
76 if (!count) return VK_ERROR_INITIALIZATION_FAILED;
77 if (formats && *count) {
78 formats[0].format = VK_FORMAT_B8G8R8A8_UNORM;
79 formats[0].colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
80 }
81 *count = 1;
82 return VK_SUCCESS;
83}
84VKAPI_ATTR VkResult VKAPI_CALL surface_present_modes(VkPhysicalDevice, VkSurfaceKHR, std::uint32_t* count,
85 VkPresentModeKHR* modes) {
86 if (!count) return VK_ERROR_INITIALIZATION_FAILED;
87 if (modes && *count) modes[0] = VK_PRESENT_MODE_FIFO_KHR;
88 *count = 1;
89 return VK_SUCCESS;
90}
91VKAPI_ATTR void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties* props) {
92 std::memset(props, 0, sizeof(*props));
93 props->memoryTypeCount = 1;
94 props->memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
95 props->memoryHeapCount = 1;
96 props->memoryHeaps[0].size = 1ull << 30;
97 props->memoryHeaps[0].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
98}
99VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice, const VkSwapchainCreateInfoKHR* info,
100 const VkAllocationCallbacks*, VkSwapchainKHR* out) {
101 if (!info || !out) return VK_ERROR_INITIALIZATION_FAILED;
102 g.create_min_image_count = info->minImageCount;
103 *out = reinterpret_cast<VkSwapchainKHR>(kSwapchain);
104 return VK_SUCCESS;
105}
106VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice, VkSwapchainKHR, const VkAllocationCallbacks*) {}
107VKAPI_ATTR VkResult VKAPI_CALL get_images(VkDevice, VkSwapchainKHR, std::uint32_t* count, VkImage* images) {
108 if (!count) return VK_ERROR_INITIALIZATION_FAILED;
109 if (images) {
110 for (std::uint32_t i = 0; i < g.returned_images && i < *count; ++i) images[i] = native_image(i);
111 }
112 *count = g.returned_images;
113 return VK_SUCCESS;
114}
115VKAPI_ATTR VkResult VKAPI_CALL acquire_next_image(VkDevice, VkSwapchainKHR, std::uint64_t, VkSemaphore, VkFence,
116 std::uint32_t* out) {
117 if (!out || g.returned_images == 0) return VK_ERROR_INITIALIZATION_FAILED;
118 g.last_acquired = g.acquire_cursor % g.returned_images;
119 ++g.acquire_cursor;
120 *out = g.last_acquired;
121 return VK_SUCCESS;
122}
123VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue, const VkPresentInfoKHR* info) {
124 if (!info || info->swapchainCount != 1 || !info->pImageIndices) return VK_ERROR_INITIALIZATION_FAILED;
125 g.presented_image = info->pImageIndices[0];
126 ++g.presents;
127 return VK_SUCCESS;
128}
129VKAPI_ATTR VkResult VKAPI_CALL create_fence(VkDevice, const VkFenceCreateInfo*, const VkAllocationCallbacks*,
130 VkFence* out) {
131 if (out) *out = reinterpret_cast<VkFence>(kFence);
132 return VK_SUCCESS;
133}
134VKAPI_ATTR void VKAPI_CALL destroy_fence(VkDevice, VkFence, const VkAllocationCallbacks*) {}
135VKAPI_ATTR VkResult VKAPI_CALL wait_for_fences(VkDevice, std::uint32_t, const VkFence*, VkBool32, std::uint64_t) {
136 return VK_SUCCESS;
137}
138VKAPI_ATTR VkResult VKAPI_CALL reset_fences(VkDevice, std::uint32_t, const VkFence*) { return VK_SUCCESS; }
139VKAPI_ATTR VkResult VKAPI_CALL device_wait_idle(VkDevice) { return VK_SUCCESS; }
140VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo*, const VkAllocationCallbacks*,
141 VkImage* out) {
142 if (!out) return VK_ERROR_INITIALIZATION_FAILED;
143 *out = reinterpret_cast<VkImage>(static_cast<std::uintptr_t>(kOffscreenBase + g.created_offscreen++));
144 return VK_SUCCESS;
145}
146VKAPI_ATTR void VKAPI_CALL destroy_image(VkDevice, VkImage, const VkAllocationCallbacks*) {}
147VKAPI_ATTR void VKAPI_CALL image_mem_req(VkDevice, VkImage, VkMemoryRequirements* req) {
148 std::memset(req, 0, sizeof(*req));
149 req->size = 4096;
150 req->alignment = 1;
151 req->memoryTypeBits = 1;
152}
153VKAPI_ATTR VkResult VKAPI_CALL alloc_mem(VkDevice, const VkMemoryAllocateInfo*, const VkAllocationCallbacks*,
154 VkDeviceMemory* out) {
155 if (out) *out = reinterpret_cast<VkDeviceMemory>(kOffscreenBase);
156 return VK_SUCCESS;
157}
158VKAPI_ATTR void VKAPI_CALL free_mem(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) {}
159VKAPI_ATTR VkResult VKAPI_CALL bind_image_mem(VkDevice, VkImage, VkDeviceMemory, VkDeviceSize) {
160 return VK_SUCCESS;
161}
162VKAPI_ATTR VkResult VKAPI_CALL create_cmd_pool(VkDevice, const VkCommandPoolCreateInfo*,
163 const VkAllocationCallbacks*, VkCommandPool* out) {
164 if (out) *out = reinterpret_cast<VkCommandPool>(kPool);
165 return VK_SUCCESS;
166}
167VKAPI_ATTR void VKAPI_CALL destroy_cmd_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {}
168VKAPI_ATTR VkResult VKAPI_CALL alloc_cmd_bufs(VkDevice, const VkCommandBufferAllocateInfo*,
169 VkCommandBuffer* out) {
170 if (out) *out = reinterpret_cast<VkCommandBuffer>(kCmd);
171 return VK_SUCCESS;
172}
173VKAPI_ATTR VkResult VKAPI_CALL reset_cmd_buf(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; }
174VKAPI_ATTR VkResult VKAPI_CALL begin_cmd_buf(VkCommandBuffer, const VkCommandBufferBeginInfo*) {
175 return VK_SUCCESS;
176}
177VKAPI_ATTR VkResult VKAPI_CALL end_cmd_buf(VkCommandBuffer) { return VK_SUCCESS; }
178VKAPI_ATTR void VKAPI_CALL cmd_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, std::uint32_t,
179 const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*,
180 std::uint32_t, const VkImageMemoryBarrier*) {}
181VKAPI_ATTR void VKAPI_CALL cmd_blit(VkCommandBuffer, VkImage src, VkImageLayout, VkImage dst, VkImageLayout,
182 std::uint32_t, const VkImageBlit*, VkFilter) {
183 g.blit_src = src;
184 g.blit_dst = dst;
185}
186VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) {
187 return VK_SUCCESS;
188}
189
190struct Entry {
191 const char* name;
192 PFN_vkVoidFunction fn;
193};
194const Entry kEntries[] = {
195 {"vkCreateWin32SurfaceKHR", as_function(create_win32_surface)},
196 {"vkDestroySurfaceKHR", as_function(destroy_surface)},
197 {"vkGetPhysicalDeviceSurfaceSupportKHR", as_function(surface_support)},
198 {"vkGetPhysicalDeviceSurfaceCapabilitiesKHR", as_function(surface_caps)},
199 {"vkGetPhysicalDeviceSurfaceFormatsKHR", as_function(surface_formats)},
200 {"vkGetPhysicalDeviceSurfacePresentModesKHR", as_function(surface_present_modes)},
201 {"vkGetPhysicalDeviceMemoryProperties", as_function(memory_properties)},
202 {"vkCreateSwapchainKHR", as_function(create_swapchain)},
203 {"vkDestroySwapchainKHR", as_function(destroy_swapchain)},
204 {"vkGetSwapchainImagesKHR", as_function(get_images)},
205 {"vkAcquireNextImageKHR", as_function(acquire_next_image)},
206 {"vkQueuePresentKHR", as_function(queue_present)},
207 {"vkCreateFence", as_function(create_fence)},
208 {"vkDestroyFence", as_function(destroy_fence)},
209 {"vkWaitForFences", as_function(wait_for_fences)},
210 {"vkResetFences", as_function(reset_fences)},
211 {"vkDeviceWaitIdle", as_function(device_wait_idle)},
212 {"vkCreateImage", as_function(create_image)},
213 {"vkDestroyImage", as_function(destroy_image)},
214 {"vkGetImageMemoryRequirements", as_function(image_mem_req)},
215 {"vkAllocateMemory", as_function(alloc_mem)},
216 {"vkFreeMemory", as_function(free_mem)},
217 {"vkBindImageMemory", as_function(bind_image_mem)},
218 {"vkCreateCommandPool", as_function(create_cmd_pool)},
219 {"vkDestroyCommandPool", as_function(destroy_cmd_pool)},
220 {"vkAllocateCommandBuffers", as_function(alloc_cmd_bufs)},
221 {"vkResetCommandBuffer", as_function(reset_cmd_buf)},
222 {"vkBeginCommandBuffer", as_function(begin_cmd_buf)},
223 {"vkEndCommandBuffer", as_function(end_cmd_buf)},
224 {"vkCmdPipelineBarrier", as_function(cmd_barrier)},
225 {"vkCmdBlitImage", as_function(cmd_blit)},
226 {"vkQueueSubmit", as_function(queue_submit)},
227};
228
229PFN_vkVoidFunction lookup(const char* name) {
230 for (const Entry& entry : kEntries)
231 if (name && std::strcmp(name, entry.name) == 0) return entry.fn;
232 return nullptr;
233}
234
235VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance_proc(VkInstance, const char* name) { return lookup(name); }
236VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device_proc(VkDevice, const char* name) { return lookup(name); }
237
238int fail(const char* what) {
239 std::fprintf(stderr, "FAIL: %s\n", what);
240 return 1;
241}
242
243// Requests `requested` buffers while faking `native` images and a surface minimum of `minimum`.
244int run_case(const char* label, std::uint32_t requested, std::uint32_t native, std::uint32_t minimum,
245 bool expect_offscreen) {
246 g = Fake{};
247 g.min_image_count = minimum;
248 g.returned_images = native;
249 std::mutex mutex;
250 leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1),
251 reinterpret_cast<VkPhysicalDevice>(2), get_device_proc,
252 reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex);
253 if (!swapchain.create(reinterpret_cast<HWND>(static_cast<std::uintptr_t>(1)), 64, 64,
254 VK_FORMAT_B8G8R8A8_UNORM, requested))
255 return fail("VulkanSwapchain::create");
256
257 // GetDesc/GetDesc1 read image_count(): the app's request, never the native count.
258 if (swapchain.image_count() != requested) {
259 std::fprintf(stderr, "FAIL: %s: exposed BufferCount %u, requested %u (native %u)\n", label,
260 swapchain.image_count(), requested, native);
261 return 1;
262 }
263 const std::uint32_t expected_min = minimum > requested ? minimum : requested;
264 if (g.create_min_image_count != expected_min) {
265 std::fprintf(stderr, "FAIL: %s: vkCreateSwapchainKHR minImageCount %u, expected %u\n", label,
266 g.create_min_image_count, expected_min);
267 return 1;
268 }
269 if (swapchain.is_offscreen() != expect_offscreen)
270 return fail(expect_offscreen ? "expected the offscreen ring" : "expected direct native images");
271
272 if (expect_offscreen) {
273 if (g.created_offscreen != requested) return fail("offscreen ring size != requested BufferCount");
274 std::vector<VkImage> exposed;
275 for (std::uint32_t i = 0; i < requested; ++i) {
276 const leonida::ResourceBinding binding = swapchain.resource_binding(i);
277 if (!binding.image || binding.presentable) return fail("offscreen backbuffer binding is not offscreen");
278 if (binding.image != swapchain.image(i)) return fail("binding/image disagree");
279 for (VkImage other : exposed)
280 if (other == binding.image) return fail("two exposed backbuffers share one image");
281 exposed.push_back(binding.image);
282 }
283 if (swapchain.current_back_buffer_index() >= requested)
284 return fail("initial current index out of range");
285
286 std::uint32_t index = 0;
287 if (!swapchain.acquire_next_image(index)) return fail("first acquire");
288 constexpr unsigned kFrames = 20;
289 for (unsigned frame = 0; frame < kFrames; ++frame) {
290 const std::uint32_t current = swapchain.current_back_buffer_index();
291 if (current >= requested) return fail("GetCurrentBackBufferIndex >= BufferCount");
292 if (current != frame % requested) return fail("current index does not cycle over the exposed ring");
293 const std::uint32_t acquired = g.last_acquired;
294 g.blit_src = g.blit_dst = VK_NULL_HANDLE;
295 g.presented_image = UINT32_MAX;
296 if (!swapchain.present(current)) return fail("present");
297 if (g.blit_src != exposed[current]) return fail("present did not blit the current backbuffer");
298 if (g.blit_dst != native_image(acquired)) return fail("present blitted to the wrong acquired image");
299 if (g.presented_image != acquired) return fail("presented an image other than the acquired one");
300 if (frame + 1 < kFrames && !swapchain.acquire_next_image(index)) return fail("acquire");
301 }
302 // ResizeBuffers(count=0) keeps the exposed BufferCount, not the native image count.
303 if (!swapchain.resize(64, 64)) return fail("resize");
304 if (swapchain.image_count() != requested) return fail("resize(count=0) changed the exposed BufferCount");
305 if (!swapchain.is_offscreen()) return fail("resize dropped the offscreen ring");
306 return 0;
307 }
308
309 // Direct path: exposed index and native image index are the same, and nothing is blitted.
310 if (swapchain.current_back_buffer_index() != 0) return fail("direct initial index");
311 std::uint32_t index = 0;
312 if (!swapchain.acquire_next_image(index)) return fail("direct first acquire");
313 for (unsigned frame = 0; frame < 9; ++frame) {
314 const std::uint32_t current = swapchain.current_back_buffer_index();
315 if (current >= requested) return fail("direct GetCurrentBackBufferIndex >= BufferCount");
316 if (current != g.last_acquired) return fail("direct current index is not the acquired image");
317 if (swapchain.resource_binding(current).image != native_image(current))
318 return fail("direct binding is not the native image");
319 g.blit_src = g.blit_dst = VK_NULL_HANDLE;
320 g.presented_image = UINT32_MAX;
321 if (!swapchain.present(current)) return fail("direct present");
322 if (g.blit_src || g.blit_dst) return fail("direct present took the blit path");
323 if (g.presented_image != current) return fail("direct present index");
324 if (frame + 1 < 9 && !swapchain.acquire_next_image(index)) return fail("direct acquire");
325 }
326 return 0;
327}
328
329struct Case {
330 const char* label;
331 std::uint32_t requested;
332 std::uint32_t native;
333 std::uint32_t minimum;
334 bool offscreen;
335};
336
337} // namespace
338
339int main() {
340 const Case cases[] = {
341 // Vulkan returns more images than minImageCount: the app asked for 2 and must see 2.
342 {"driver returns 4 for BufferCount 2", 2, 4, 2, true},
343 // The surface minimum exceeds the request (2): still expose the app's 2.
344 {"minImageCount 3 for BufferCount 2", 2, 3, 3, true},
345 // Control: the app asks for more than minImageCount; native and exposed counts agree, no blit.
346 {"BufferCount 3 above minImageCount 2", 3, 3, 2, false},
347 };
348 for (const Case& c : cases) {
349 if (const int result = run_case(c.label, c.requested, c.native, c.minimum, c.offscreen)) return result;
350 }
351 std::printf("dxgi_swapchain_count_test: PASS (3 cases: extra native images, min above request, "
352 "request above min)\n");
353 return 0;
354}
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index ca1491153..1ef864ff1 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -16,6 +16,7 @@
16#include <cstdio> 16#include <cstdio>
17#include <cstdlib> 17#include <cstdlib>
18#include <cstring> 18#include <cstring>
19#include <iterator>
19#include <vector> 20#include <vector>
20 21
21namespace { 22namespace {
@@ -91,8 +92,220 @@ bool check_statistics_disjoint(IDXGISwapChain* swapchain) {
91 return swapchain->GetFrameStatistics(&stats) == S_OK; 92 return swapchain->GetFrameStatistics(&stats) == S_OK;
92} 93}
93 94
95// Counts references: AddRef/Release of the private-data interface are observable through refs.
96struct CountedUnknown final : IUnknown {
97 ULONG refs = 1;
98 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void** out) override {
99 if (out) *out = nullptr;
100 return E_NOINTERFACE;
101 }
102 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
103 ULONG STDMETHODCALLTYPE Release() override { return --refs; }
104};
105
106// IDXGIObject private data (Microsoft: IDXGIObject::SetPrivateData / SetPrivateDataInterface / GetPrivateData):
107// the bytes are copied, an interface is held with a reference until it is replaced or removed, and the same GUID
108// replaces the entry. Returns null on success or the failing step.
109const char* check_private_data(IDXGIObject* object) {
110 static constexpr GUID key{0x6c2c5b0e, 0x4d9a, 0x4f43, {0x9e, 0x1b, 0x3a, 0x57, 0x0c, 0x91, 0x2d, 0x44}};
111 UINT size = 99;
112 if (object->GetPrivateData(key, &size, nullptr) != DXGI_ERROR_NOT_FOUND) return "GetPrivateData before any Set";
113 std::uint32_t value = 0x12345678u;
114 if (object->SetPrivateData(key, sizeof(value), &value) != S_OK) return "SetPrivateData";
115 value = 0; // SetPrivateData copies
116 size = 0;
117 if (object->GetPrivateData(key, &size, nullptr) != S_OK || size != sizeof(value)) return "GetPrivateData size query";
118 std::uint32_t read = 0;
119 size = sizeof(read);
120 if (object->GetPrivateData(key, &size, &read) != S_OK || size != sizeof(read) || read != 0x12345678u)
121 return "GetPrivateData did not return the stored bytes";
122 std::uint16_t too_small = 0;
123 size = sizeof(too_small);
124 if (object->GetPrivateData(key, &size, &too_small) != DXGI_ERROR_MORE_DATA || size != sizeof(read))
125 return "GetPrivateData with a small buffer should be DXGI_ERROR_MORE_DATA and report the size";
126 CountedUnknown counted;
127 if (object->SetPrivateDataInterface(key, &counted) != S_OK || counted.refs != 2) return "SetPrivateDataInterface";
128 IUnknown* got = nullptr;
129 size = sizeof(got);
130 if (object->GetPrivateData(key, &size, &got) != S_OK || got != &counted || counted.refs != 3)
131 return "GetPrivateData did not return the interface with a reference added";
132 got->Release();
133 if (object->SetPrivateData(key, sizeof(read), &read) != S_OK || counted.refs != 1)
134 return "SetPrivateData with the same GUID should release the held interface";
135 if (object->SetPrivateDataInterface(key, &counted) != S_OK || counted.refs != 2) return "SetPrivateDataInterface again";
136 if (object->SetPrivateDataInterface(key, nullptr) != S_OK || counted.refs != 1)
137 return "SetPrivateDataInterface(null) should remove the entry and release the interface";
138 size = 99;
139 if (object->GetPrivateData(key, &size, nullptr) != DXGI_ERROR_NOT_FOUND) return "GetPrivateData after removal";
140 return nullptr;
141}
142
94} // namespace 143} // namespace
95 144
145
146// CreateSwapChainForHwnd on a guarded call: a host runtime that faults on a case reports it instead of ending the test.
147HRESULT create_guarded(IDXGIFactory4* factory, IUnknown* queue, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc,
148 IDXGISwapChain1** out) {
149 __try {
150 return factory->CreateSwapChainForHwnd(queue, hwnd, desc, nullptr, nullptr, out);
151 } __except (EXCEPTION_EXECUTE_HANDLER) {
152 return HRESULT(0xC0000005);
153 }
154}
155
156// CreateSwapChainForHwnd with descriptions D3D12 refuses (and the valid ones next to them), against the host runtime's
157// DXGI: each case gets its own window on each side, and the HRESULTs must match. Returns the number of mismatches,
158// or -1 without a host D3D12 device.
159int compare_swap_chain_arguments(IDXGIFactory4* ours, ID3D12Device* our_device, ID3D12CommandQueue* our_queue) {
160 using CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
161 using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
162 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
163 const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
164 const auto create_device = d3d12 ? reinterpret_cast<CreateDevice>(
165 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
166 : nullptr;
167 const auto create_factory = dxgi ? reinterpret_cast<CreateFactory2>(
168 reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory2")))
169 : nullptr;
170 ID3D12Device* host_device = nullptr;
171 IDXGIFactory4* host_factory = nullptr;
172 ID3D12CommandQueue* host_queue = nullptr;
173 const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
174 if (!create_device || !create_factory ||
175 FAILED(create_device(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host_device))) ||
176 FAILED(create_factory(0, IID_PPV_ARGS(&host_factory))) ||
177 FAILED(host_device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&host_queue)))) {
178 if (host_factory) host_factory->Release();
179 if (host_device) host_device->Release();
180 return -1;
181 }
182 DXGI_SWAP_CHAIN_DESC1 base{};
183 base.Width = 64;
184 base.Height = 64;
185 base.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
186 base.SampleDesc.Count = 1;
187 base.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
188 base.BufferCount = 2;
189 base.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
190 enum class Pass { queue, null_queue, device, null_window, null_desc, null_out };
191 struct Case {
192 const char* name;
193 DXGI_SWAP_CHAIN_DESC1 desc;
194 Pass pass = Pass::queue;
195 };
196 const auto with = [&](void (*edit)(DXGI_SWAP_CHAIN_DESC1&)) {
197 DXGI_SWAP_CHAIN_DESC1 d = base;
198 edit(d);
199 return d;
200 };
201 const Case cases[] = {
202 {"valid", base},
203 {"flip sequential, 3 buffers", with([](DXGI_SWAP_CHAIN_DESC1& d) {
204 d.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
205 d.BufferCount = 3;
206 })},
207 {"effect DISCARD", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; })},
208 {"effect SEQUENTIAL", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL; })},
209 {"effect 99", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT(99); })},
210 {"scaling NONE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING_NONE; })},
211 {"scaling ASPECT_RATIO_STRETCH",
212 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING_ASPECT_RATIO_STRETCH; })},
213 {"scaling 7", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING(7); })},
214 {"alpha IGNORE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_IGNORE; })},
215 {"alpha PREMULTIPLIED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED; })},
216 {"alpha STRAIGHT", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_STRAIGHT; })},
217 {"alpha 9", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE(9); })},
218 {"flag NONPREROTATED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_NONPREROTATED; })},
219 {"flag ALLOW_MODE_SWITCH",
220 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; })},
221 {"flag GDI_COMPATIBLE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE; })},
222 {"flag DISPLAY_ONLY", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY; })},
223 {"flag FRAME_LATENCY_WAITABLE_OBJECT", with([](DXGI_SWAP_CHAIN_DESC1& d) {
224 d.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
225 })},
226 {"flag FOREGROUND_LAYER",
227 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER; })},
228 {"flag HW_PROTECTED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_HW_PROTECTED; })},
229 {"flag ALLOW_TEARING", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; })},
230 {"flag 0x1000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x1000; })},
231 {"flag 0x2000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x2000; })},
232 {"flag 0x4000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x4000; })},
233 {"flag 0x80000000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x80000000u; })},
234 {"usage 0", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = 0; })},
235 {"usage SHADER_INPUT", with([](DXGI_SWAP_CHAIN_DESC1& d) {
236 d.BufferUsage = DXGI_USAGE_SHADER_INPUT | DXGI_USAGE_RENDER_TARGET_OUTPUT;
237 })},
238 {"usage SHARED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_SHARED; })},
239 {"usage READ_ONLY", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_READ_ONLY; })},
240 {"usage DISCARD_ON_PRESENT",
241 with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_DISCARD_ON_PRESENT; })},
242 {"usage UNORDERED_ACCESS", with([](DXGI_SWAP_CHAIN_DESC1& d) {
243 d.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_UNORDERED_ACCESS;
244 })},
245 {"16384 x 16", with([](DXGI_SWAP_CHAIN_DESC1& d) {
246 d.Width = 16384;
247 d.Height = 16;
248 })},
249 {"width 16385", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Width = 16385; })},
250 {"height 16385", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Height = 16385; })},
251 {"one buffer", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferCount = 1; })},
252 {"MSAA 4", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SampleDesc.Count = 4; })},
253 {"width 16385 and MSAA 4", with([](DXGI_SWAP_CHAIN_DESC1& d) {
254 d.Width = 16385;
255 d.SampleDesc.Count = 4;
256 })},
257 {"width 16385 and one buffer", with([](DXGI_SWAP_CHAIN_DESC1& d) {
258 d.Width = 16385;
259 d.BufferCount = 1;
260 })},
261 {"width 16385 and format UNKNOWN", with([](DXGI_SWAP_CHAIN_DESC1& d) {
262 d.Width = 16385;
263 d.Format = DXGI_FORMAT_UNKNOWN;
264 })},
265 {"height 16385 and format BC1", with([](DXGI_SWAP_CHAIN_DESC1& d) {
266 d.Height = 16385;
267 d.Format = DXGI_FORMAT_BC1_UNORM;
268 })},
269 {"width 16385 and effect DISCARD", with([](DXGI_SWAP_CHAIN_DESC1& d) {
270 d.Width = 16385;
271 d.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
272 })},
273 {"null queue", base, Pass::null_queue},
274 {"a device, not a queue", base, Pass::device},
275 {"null window", base, Pass::null_window},
276 {"null description", base, Pass::null_desc},
277 {"null output", base, Pass::null_out},
278 };
279 int mismatches = 0;
280 for (const Case& c : cases) {
281 HRESULT result[2];
282 for (int side = 0; side < 2; ++side) {
283 IDXGIFactory4* factory = side ? host_factory : ours;
284 IUnknown* queue = side ? static_cast<IUnknown*>(host_queue) : static_cast<IUnknown*>(our_queue);
285 if (c.pass == Pass::null_queue) queue = nullptr;
286 if (c.pass == Pass::device) queue = side ? static_cast<IUnknown*>(host_device) : our_device;
287 HWND hwnd = create_test_window(64, 64);
288 IDXGISwapChain1* chain = nullptr;
289 result[side] = create_guarded(factory, queue, c.pass == Pass::null_window ? nullptr : hwnd,
290 c.pass == Pass::null_desc ? nullptr : &c.desc,
291 c.pass == Pass::null_out ? nullptr : &chain);
292 if (chain) chain->Release();
293 if (hwnd) DestroyWindow(hwnd);
294 }
295 if (result[0] != result[1]) {
296 ++mismatches;
297 std::fprintf(stderr, "CreateSwapChainForHwnd %s: ours 0x%08lx, host 0x%08lx\n", c.name,
298 static_cast<unsigned long>(result[0]), static_cast<unsigned long>(result[1]));
299 }
300 }
301 std::printf("CreateSwapChainForHwnd: %zu descriptions compared with the host runtime, %d mismatches\n",
302 std::size(cases), mismatches);
303 host_queue->Release();
304 host_factory->Release();
305 host_device->Release();
306 return mismatches;
307}
308
96int main() { 309int main() {
97 const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); 310 const PFN_vkGetInstanceProcAddr gipa = load_vulkan();
98 if (!gipa) { 311 if (!gipa) {
@@ -286,6 +499,11 @@ int main() {
286 return fail("queue/alloc/cl/fence"); 499 return fail("queue/alloc/cl/fence");
287 cl->Close(); 500 cl->Close();
288 501
502 // Before the test's own swap chain: the host comparison creates and releases its own windows and chains.
503 const int argument_mismatches = compare_swap_chain_arguments(factory, dev, queue);
504 if (argument_mismatches < 0) std::printf("CreateSwapChainForHwnd: no host D3D12 device to compare with, skipped\n");
505 if (argument_mismatches > 0) return fail("CreateSwapChainForHwnd answers differ from the host runtime");
506
289 DXGI_SWAP_CHAIN_DESC1 scd{}; 507 DXGI_SWAP_CHAIN_DESC1 scd{};
290 scd.Width = 128; 508 scd.Width = 128;
291 scd.Height = 128; 509 scd.Height = 128;
@@ -327,6 +545,16 @@ int main() {
327 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3"); 545 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3");
328 sc1->Release(); 546 sc1->Release();
329 547
548 // DXGI reports the BufferCount the app created with, never a larger native/Vulkan image count (D3D-389).
549 {
550 DXGI_SWAP_CHAIN_DESC1 created_desc{};
551 DXGI_SWAP_CHAIN_DESC created_desc0{};
552 if (FAILED(sc->GetDesc1(&created_desc)) || created_desc.BufferCount != scd.BufferCount)
553 return fail("GetDesc1 BufferCount is not the requested count");
554 if (FAILED(sc->GetDesc(&created_desc0)) || created_desc0.BufferCount != scd.BufferCount)
555 return fail("GetDesc BufferCount is not the requested count");
556 }
557
330 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification"); 558 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification");
331 559
332 ID3D12Device* got_device = nullptr; 560 ID3D12Device* got_device = nullptr;
@@ -401,6 +629,7 @@ int main() {
401 return 1; 629 return 1;
402 } 630 }
403 const UINT idx = sc->GetCurrentBackBufferIndex(); 631 const UINT idx = sc->GetCurrentBackBufferIndex();
632 if (idx >= cur_desc.BufferCount) return fail("GetCurrentBackBufferIndex >= BufferCount");
404 ID3D12Resource* bb = nullptr; 633 ID3D12Resource* bb = nullptr;
405 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer"); 634 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer");
406 635
@@ -610,6 +839,7 @@ int main() {
610 return fail("GetDesc1 did not preserve 37x19 R10G10B10A2_UNORM"); 839 return fail("GetDesc1 did not preserve 37x19 R10G10B10A2_UNORM");
611 840
612 const UINT idx = sc->GetCurrentBackBufferIndex(); 841 const UINT idx = sc->GetCurrentBackBufferIndex();
842 if (idx >= d10.BufferCount) return fail("GetCurrentBackBufferIndex >= BufferCount (10-bit)");
613 ID3D12Resource* bb = nullptr; 843 ID3D12Resource* bb = nullptr;
614 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer (10-bit)"); 844 if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer (10-bit)");
615 const D3D12_RESOURCE_DESC bb_desc = bb->GetDesc(); 845 const D3D12_RESOURCE_DESC bb_desc = bb->GetDesc();
@@ -822,6 +1052,16 @@ int main() {
822 return fail("Non-waitable SetMaximumFrameLatency should return DXGI_ERROR_INVALID_CALL"); 1052 return fail("Non-waitable SetMaximumFrameLatency should return DXGI_ERROR_INVALID_CALL");
823 } 1053 }
824 1054
1055 // IDXGIObject private data on the swapchain, the factory and an adapter.
1056 {
1057 if (const char* step = check_private_data(sc)) return fail(step);
1058 if (const char* step = check_private_data(factory)) return fail(step);
1059 IDXGIAdapter1* pd_adapter = nullptr;
1060 if (FAILED(factory->EnumAdapters1(0, &pd_adapter)) || !pd_adapter) return fail("EnumAdapters1(0) for private data");
1061 if (const char* step = check_private_data(pd_adapter)) return fail(step);
1062 pd_adapter->Release();
1063 }
1064
825 // IDXGIFactory4 adapter enumeration, IDXGIAdapter3 descriptors, EnumAdapterByLuid, and QueryVideoMemoryInfo. 1065 // IDXGIFactory4 adapter enumeration, IDXGIAdapter3 descriptors, EnumAdapterByLuid, and QueryVideoMemoryInfo.
826 { 1066 {
827 IDXGIAdapter1* adapter1 = nullptr; 1067 IDXGIAdapter1* adapter1 = nullptr;
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index f51dd32e0..58233ee98 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -571,6 +571,52 @@ int main() {
571 "CreateFile2 refuses a path above GAME:"); 571 "CreateFile2 refuses a path above GAME:");
572 if (h_esc != INVALID_HANDLE_VALUE) ::CloseHandle(h_esc); 572 if (h_esc != INVALID_HANDLE_VALUE) ::CloseHandle(h_esc);
573 573
574 // MAXIMUM_ALLOWED asks for every right the file grants, write included, without naming one. Such an open of
575 // a package file is a write-open: it gets the overlay copy, so a write through the handle cannot reach the
576 // package. CreateFileW, CreateFileA and CreateFile2 share the rule. The write is shorter than the file, so
577 // the bytes after it show the overlay copy started as the package file's contents (OPEN_EXISTING keeps them).
578 {
579 write_path(package / "data" / "max_w.txt", "pkg-max");
580 write_path(package / "data" / "max_a.txt", "pkg-max");
581 write_path(package / "data" / "max_2.txt", "pkg-max");
582 const auto write_through = [](HANDLE h) {
583 if (h == INVALID_HANDLE_VALUE) return false;
584 DWORD written = 0;
585 const BOOL ok = ::WriteFile(h, "OV", 2, &written, nullptr);
586 ::CloseHandle(h);
587 return ok != FALSE && written == 2;
588 };
589 check(write_through(create_w(L"GAME:\\data\\max_w.txt", MAXIMUM_ALLOWED, 0, nullptr, OPEN_EXISTING, 0,
590 nullptr)),
591 "CreateFileW(MAXIMUM_ALLOWED, OPEN_EXISTING) opens a package file for writing");
592 check(read_path(package / "data" / "max_w.txt") == "pkg-max",
593 "a write through a MAXIMUM_ALLOWED handle does not reach the package (CreateFileW)");
594 check(read_path(overlay / "data" / "max_w.txt") == "OVg-max",
595 "the write through a MAXIMUM_ALLOWED handle is in the overlay copy (CreateFileW)");
596
597 check(write_through(create_a("GAME:\\data\\max_a.txt", MAXIMUM_ALLOWED | GENERIC_READ, 0, nullptr,
598 OPEN_EXISTING, 0, nullptr)),
599 "CreateFileA(MAXIMUM_ALLOWED | GENERIC_READ, OPEN_EXISTING) opens a package file for writing");
600 check(read_path(package / "data" / "max_a.txt") == "pkg-max" &&
601 read_path(overlay / "data" / "max_a.txt") == "OVg-max",
602 "the write goes to the overlay and not the package (CreateFileA)");
603
604 check(write_through(create2(L"GAME:\\data\\max_2.txt", MAXIMUM_ALLOWED, 0, OPEN_EXISTING, &ext)),
605 "CreateFile2(MAXIMUM_ALLOWED, OPEN_EXISTING) opens a package file for writing");
606 check(read_path(package / "data" / "max_2.txt") == "pkg-max" &&
607 read_path(overlay / "data" / "max_2.txt") == "OVg-max",
608 "the write goes to the overlay and not the package (CreateFile2)");
609
610 // A plain read still opens the package file in place: no overlay copy appears for it.
611 write_path(package / "data" / "max_read.txt", "pkg-max");
612 const HANDLE h_plain = create_w(L"GAME:\\data\\max_read.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
613 OPEN_EXISTING, 0, nullptr);
614 check(h_plain != INVALID_HANDLE_VALUE && read_handle(h_plain) == "pkg-max" &&
615 !std::filesystem::exists(overlay / "data" / "max_read.txt"),
616 "a GENERIC_READ open is still a read: no overlay copy is made");
617 if (h_plain != INVALID_HANDLE_VALUE) ::CloseHandle(h_plain);
618 }
619
574 // FindFirstFileExW merges package + overlay and honours FindExInfoBasic & FindExSearchLimitToDirectories. 620 // FindFirstFileExW merges package + overlay and honours FindExInfoBasic & FindExSearchLimitToDirectories.
575 WIN32_FIND_DATAW fd{}; 621 WIN32_FIND_DATAW fd{};
576 std::vector<std::wstring> basic_names; 622 std::vector<std::wstring> basic_names;
diff --git a/runtime/test/fixtures/d3d12_xs_stub.cpp b/runtime/test/fixtures/d3d12_xs_stub.cpp
new file mode 100644
index 000000000..e60c9b388
--- /dev/null
+++ b/runtime/test/fixtures/d3d12_xs_stub.cpp
@@ -0,0 +1,10 @@
1// Link-time stand-in for the console's d3d12_xs.dll, so tiny_frame.exe gets a real import of
2// D3D12XboxCreateDevice. Under `gta6rt --run` the shim registry answers the import and this DLL never loads; it is
3// built into a folder the loader does not search. Test code, not game content.
4#include <windows.h>
5#include <unknwn.h>
6
7extern "C" HRESULT __stdcall D3D12XboxCreateDevice(IUnknown*, const void*, const IID*, void** out) {
8 if (out) *out = nullptr;
9 return E_FAIL;
10}
diff --git a/runtime/test/fixtures/d3d12_xs_stub.def b/runtime/test/fixtures/d3d12_xs_stub.def
new file mode 100644
index 000000000..608feffc1
--- /dev/null
+++ b/runtime/test/fixtures/d3d12_xs_stub.def
@@ -0,0 +1,3 @@
1LIBRARY d3d12_xs
2EXPORTS
3 D3D12XboxCreateDevice
diff --git a/runtime/test/fixtures/dll_thread_calls.cpp b/runtime/test/fixtures/dll_thread_calls.cpp
index 4f4d73eb8..4d50229c5 100644
--- a/runtime/test/fixtures/dll_thread_calls.cpp
+++ b/runtime/test/fixtures/dll_thread_calls.cpp
@@ -4,6 +4,15 @@
4// data. 4// data.
5#include <windows.h> 5#include <windows.h>
6 6
7#ifdef __MSVC_RUNTIME_CHECKS
8// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB
9// leaves these unresolved (LNK1120). The checks have nothing to check here, so they do nothing.
10extern "C" {
11void __cdecl _RTC_InitBase() {}
12void __cdecl _RTC_Shutdown() {}
13}
14#endif
15
7extern "C" BOOL WINAPI dll_thread_calls_main(HINSTANCE instance, DWORD reason, LPVOID) { 16extern "C" BOOL WINAPI dll_thread_calls_main(HINSTANCE instance, DWORD reason, LPVOID) {
8 if (reason == DLL_PROCESS_ATTACH) return DisableThreadLibraryCalls(instance); 17 if (reason == DLL_PROCESS_ATTACH) return DisableThreadLibraryCalls(instance);
9 return TRUE; 18 return TRUE;
diff --git a/runtime/test/fixtures/gameinput_host.cpp b/runtime/test/fixtures/gameinput_host.cpp
new file mode 100644
index 000000000..f28945045
--- /dev/null
+++ b/runtime/test/fixtures/gameinput_host.cpp
@@ -0,0 +1,43 @@
1// A DLL that does what a title's input code does first: GameInputCreate, a timestamp, a gamepad reading. It uses the
2// Windows SDK's public GameInput.h and links against the SDK's gameinput.lib, so GameInputCreate is imported from
3// GameInput.dll (by ordinal) like any title's import. Built without the CRT: DllMain does nothing and the exports call
4// only GameInput. gameinput_host_test maps it with the loader. No game data.
5#include <windows.h>
6
7#include <GameInput.h>
8
9extern "C" BOOL WINAPI gameinput_host_main(HINSTANCE, DWORD, LPVOID) { return TRUE; }
10
11#ifdef __MSVC_RUNTIME_CHECKS
12// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB
13// leaves these three unresolved (LNK1120). The checks have nothing to check here, so they do nothing.
14extern "C" {
15void __cdecl _RTC_InitBase() {}
16void __cdecl _RTC_Shutdown() {}
17void __fastcall _RTC_CheckStackVars(void*, void*) {}
18}
19#endif
20
21// Returns 1 when the library was created. reading_hr is S_OK with a gamepad attached and
22// GAMEINPUT_E_READING_NOT_FOUND without one (E_FAIL when the library was not created); state_ok is 1 when
23// GetGamepadState succeeded on a reading.
24extern "C" __declspec(dllexport) int gameinput_host_probe(long* create_hr, unsigned long long* timestamp,
25 long* reading_hr, int* state_ok) {
26 IGameInput* input = nullptr;
27 IGameInputReading* reading = nullptr;
28 const HRESULT hr = GameInputCreate(&input);
29 *create_hr = hr;
30 *timestamp = 0;
31 *reading_hr = E_FAIL; // not S_OK: a failed GameInputCreate must not look like an attached gamepad
32 *state_ok = 0;
33 if (FAILED(hr) || !input) return 0;
34 *timestamp = input->GetCurrentTimestamp();
35 *reading_hr = input->GetCurrentReading(GameInputKindGamepad, nullptr, &reading);
36 if (SUCCEEDED(*reading_hr) && reading) {
37 GameInputGamepadState state;
38 *state_ok = reading->GetGamepadState(&state) ? 1 : 0;
39 reading->Release();
40 }
41 input->Release();
42 return 1;
43}
diff --git a/runtime/test/fixtures/tiny_atexit.cpp b/runtime/test/fixtures/tiny_atexit.cpp
new file mode 100644
index 000000000..fbe071e7f
--- /dev/null
+++ b/runtime/test/fixtures/tiny_atexit.cpp
@@ -0,0 +1,92 @@
1// A stand-in program for `gta6rt --run`: atexit handlers, static destructors and the ways a program ends.
2// Test code, not game content. check_atexit.cmake runs it natively and through the loader with each mode below
3// and compares the lines it prints.
4// return main returns: handlers and static destructors run, in reverse order of registration
5// exit exit(7): the same
6// _exit _exit(8): no handlers, no destructors
7// quick_exit quick_exit(9): no atexit handlers, no destructors
8// ExitProcess ExitProcess(10): no handlers, no destructors
9// cexit _cexit() runs every handler and returns; main then returns 11
10// c_exit _c_exit() runs none and returns; main then returns 12, and exit runs them all
11// concurrent_exit a second thread calls _exit(7) while exit(7) runs a handler: it waits for them all
12// One handler registers another while the handlers run: it must still run, next.
13#include <windows.h>
14#include <process.h> // _cexit, _c_exit
15
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19
20namespace {
21
22void say(const char* what) {
23 std::printf("tiny_atexit: %s\n", what);
24 std::fflush(stdout); // every line reaches the pipe before any way out, natively and under the loader
25}
26
27struct Tracer {
28 const char* name;
29 explicit Tracer(const char* n) : name(n) {
30 std::printf("tiny_atexit: ctor %s\n", name);
31 std::fflush(stdout);
32 }
33 ~Tracer() {
34 std::printf("tiny_atexit: dtor %s\n", name);
35 std::fflush(stdout);
36 }
37};
38Tracer g_first("first");
39Tracer g_second("second");
40
41void handler_one() { say("atexit one"); }
42void handler_two() { say("atexit two"); }
43void handler_late() { say("atexit late"); }
44void handler_registers() {
45 say("atexit registers late");
46 std::atexit(handler_late);
47}
48
49// concurrent_exit: while exit() runs this handler on the main thread, a second thread calls _exit(). The CRT lets
50// it go once the handlers are done, so either call may set the exit code: both use 7.
51HANDLE g_slow_started = nullptr;
52void handler_slow() {
53 say("slow handler started");
54 SetEvent(g_slow_started);
55 Sleep(300);
56 say("slow handler done");
57}
58DWORD WINAPI quick_exit_thread(void*) {
59 WaitForSingleObject(g_slow_started, INFINITE);
60 _exit(7);
61}
62
63} // namespace
64
65int main(int argc, char** argv) {
66 const char* mode = argc > 1 ? argv[1] : "return";
67 std::atexit(handler_one);
68 std::atexit(handler_registers);
69 std::atexit(handler_two);
70 say("main");
71 if (!std::strcmp(mode, "concurrent_exit")) {
72 g_slow_started = CreateEventW(nullptr, TRUE, FALSE, nullptr);
73 std::atexit(handler_slow);
74 CloseHandle(CreateThread(nullptr, 0, quick_exit_thread, nullptr, 0, nullptr));
75 std::exit(7);
76 }
77 if (!std::strcmp(mode, "exit")) std::exit(7);
78 if (!std::strcmp(mode, "_exit")) _exit(8);
79 if (!std::strcmp(mode, "quick_exit")) std::quick_exit(9);
80 if (!std::strcmp(mode, "ExitProcess")) ExitProcess(10);
81 if (!std::strcmp(mode, "cexit")) {
82 _cexit();
83 say("after _cexit");
84 return 11;
85 }
86 if (!std::strcmp(mode, "c_exit")) {
87 _c_exit();
88 say("after _c_exit");
89 return 12;
90 }
91 return 3;
92}
diff --git a/runtime/test/fixtures/tiny_frame.cpp b/runtime/test/fixtures/tiny_frame.cpp
new file mode 100644
index 000000000..c30f7cc5c
--- /dev/null
+++ b/runtime/test/fixtures/tiny_frame.cpp
@@ -0,0 +1,166 @@
1// A stand-in title for `gta6rt --run` that reaches the D3D12 layer the way a title does: it imports
2// d3d12_xs.dll!D3D12XboxCreateDevice (from a link-time stub; the shim registry answers it) and then does the least
3// a title does before its first frame, on the device that call returns: a direct queue, an allocator, a command
4// list, a fence, an RTV heap whose start handle is read in the console shape (the 8-byte handle in RAX, heap slot 9),
5// a committed render target, a clear, a copy into a readback buffer, Signal and a fence wait, Map, and a check of
6// every pixel. It then returns from main with the device, the queue and the fence still alive, as a title's exit
7// does. With LEONIDA_D3D12=vulkan (check_tiny_frame.py sets it) that device is the Vulkan-backed one, so this is the
8// loader, the game thread, the Xbox-ABI proxies and the Vulkan device in one process. Hand-written test code, public
9// D3D12 API only; no game data and no shader.
10#include <windows.h>
11#include <d3d12.h>
12
13#include <cstdint>
14#include <cstdio>
15#include <cstring>
16
17extern "C" __declspec(dllimport) HRESULT __stdcall D3D12XboxCreateDevice(IUnknown* adapter, const void* params,
18 const IID* riid, void** device);
19
20namespace {
21
22int g_failures = 0;
23
24bool check(bool ok, const char* what) {
25 std::printf("tiny_frame: %s %s\n", ok ? "PASS" : "FAIL", what);
26 if (!ok) ++g_failures;
27 return ok;
28}
29
30int finish() {
31 std::printf("tiny_frame: %s\n", g_failures ? "FAILED" : "OK");
32 std::fflush(stdout);
33 return g_failures ? 1 : 0;
34}
35
36// Descriptor-heap slot 9 on the console returns the handle in RAX (docs/d3d12_vulkan.md section 7); the PC header's
37// GetCPUDescriptorHandleForHeapStart returns it through a hidden pointer, which the heap proxy does not serve.
38using HeapStartFn = std::uint64_t(__stdcall*)(void* heap);
39
40constexpr UINT kWidth = 8, kHeight = 4;
41
42} // namespace
43
44int main() {
45 std::setvbuf(stdout, nullptr, _IONBF, 0);
46
47 // The entry point's second argument is a block the shim logs and does not interpret; a title passes its own.
48 std::uint32_t params[24] = {};
49 const IID device_iid = __uuidof(ID3D12Device);
50 ID3D12Device* device = nullptr;
51 HRESULT hr = D3D12XboxCreateDevice(nullptr, params, &device_iid, reinterpret_cast<void**>(&device));
52 if (!check(hr == S_OK && device, "D3D12XboxCreateDevice returns a device")) {
53 std::printf("tiny_frame: hr=0x%08lx\n", static_cast<unsigned long>(hr));
54 return finish();
55 }
56
57 ID3D12CommandQueue* queue = nullptr;
58 ID3D12CommandAllocator* allocator = nullptr;
59 ID3D12GraphicsCommandList* list = nullptr;
60 ID3D12Fence* fence = nullptr;
61 D3D12_COMMAND_QUEUE_DESC queue_desc{};
62 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
63 check(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue))) && queue, "a direct command queue");
64 check(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) &&
65 allocator, "a command allocator");
66 if (allocator)
67 check(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, nullptr,
68 IID_PPV_ARGS(&list))) && list, "a command list");
69 check(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))) && fence, "a fence");
70
71 ID3D12DescriptorHeap* rtv_heap = nullptr;
72 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
73 heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
74 heap_desc.NumDescriptors = 1;
75 check(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap))) && rtv_heap, "an RTV heap");
76 if (!queue || !list || !fence || !rtv_heap) return finish();
77 const std::uint64_t start = reinterpret_cast<HeapStartFn>((*reinterpret_cast<void***>(rtv_heap))[9])(rtv_heap);
78 check(start != 0, "the heap's start handle comes back in RAX (heap slot 9)");
79 const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(start)};
80
81 D3D12_HEAP_PROPERTIES default_heap{}, readback_heap{};
82 default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
83 readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
84 D3D12_RESOURCE_DESC target_desc{};
85 target_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
86 target_desc.Width = kWidth;
87 target_desc.Height = kHeight;
88 target_desc.DepthOrArraySize = 1;
89 target_desc.MipLevels = 1;
90 target_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
91 target_desc.SampleDesc.Count = 1;
92 target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
93 ID3D12Resource* target = nullptr;
94 check(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &target_desc,
95 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
96 IID_PPV_ARGS(&target))) && target, "a committed render target");
97
98 D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{};
99 UINT rows = 0;
100 UINT64 row_bytes = 0, total = 0;
101 device->GetCopyableFootprints(&target_desc, 0, 1, 0, &placed, &rows, &row_bytes, &total);
102 check(rows == kHeight && row_bytes == kWidth * 4 && placed.Footprint.RowPitch >= kWidth * 4 && total != 0,
103 "GetCopyableFootprints describes the target");
104 D3D12_RESOURCE_DESC buffer_desc{};
105 buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
106 buffer_desc.Width = total ? total : 4096;
107 buffer_desc.Height = 1;
108 buffer_desc.DepthOrArraySize = 1;
109 buffer_desc.MipLevels = 1;
110 buffer_desc.SampleDesc.Count = 1;
111 buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
112 ID3D12Resource* readback = nullptr;
113 check(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc,
114 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
115 IID_PPV_ARGS(&readback))) && readback, "a readback buffer");
116 if (!target || !readback) return finish();
117
118 device->CreateRenderTargetView(target, nullptr, rtv);
119 const FLOAT colour[4] = {64.0f / 255.0f, 128.0f / 255.0f, 191.0f / 255.0f, 1.0f};
120 list->ClearRenderTargetView(rtv, colour, 0, nullptr);
121 D3D12_RESOURCE_BARRIER barrier{};
122 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
123 barrier.Transition.pResource = target;
124 barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
125 barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
126 barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
127 list->ResourceBarrier(1, &barrier);
128 D3D12_TEXTURE_COPY_LOCATION from{}, to{};
129 from.pResource = target;
130 from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
131 to.pResource = readback;
132 to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
133 to.PlacedFootprint = placed;
134 list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
135 check(SUCCEEDED(list->Close()), "the list closes");
136 ID3D12CommandList* lists[] = {list};
137 queue->ExecuteCommandLists(1, lists);
138
139 HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
140 check(SUCCEEDED(queue->Signal(fence, 1)), "Signal");
141 check(done && SUCCEEDED(fence->SetEventOnCompletion(1, done)) && WaitForSingleObject(done, 30000) == WAIT_OBJECT_0,
142 "the fence reaches the signalled value");
143 check(fence->GetCompletedValue() >= 1, "GetCompletedValue is past the signal");
144 if (done) CloseHandle(done);
145
146 void* bytes = nullptr;
147 if (check(SUCCEEDED(readback->Map(0, nullptr, &bytes)) && bytes, "Map of the readback buffer")) {
148 const std::uint8_t want[4] = {64, 128, 191, 255};
149 unsigned wrong = 0;
150 for (UINT y = 0; y < kHeight; ++y)
151 for (UINT x = 0; x < kWidth; ++x)
152 wrong += std::memcmp(static_cast<const std::uint8_t*>(bytes) + placed.Offset +
153 y * placed.Footprint.RowPitch + x * 4, want, 4) != 0;
154 check(wrong == 0, "all 32 pixels are the clear colour (64, 128, 191, 255)");
155 readback->Unmap(0, nullptr);
156 }
157
158 // What a frame owns is released; the device, the queue and the fence stay alive across the return from main, so
159 // the run ends through the CRT's exit with the layer still up.
160 readback->Release();
161 target->Release();
162 rtv_heap->Release();
163 list->Release();
164 allocator->Release();
165 return finish();
166}
diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp
index b37307369..9b4ad4e90 100644
--- a/runtime/test/fixtures/tiny_gdk_load.cpp
+++ b/runtime/test/fixtures/tiny_gdk_load.cpp
@@ -98,8 +98,9 @@ int main() {
98 reinterpret_cast<Close>(vtable[17])(obj, queue); 98 reinterpret_cast<Close>(vtable[17])(obj, queue);
99 reinterpret_cast<Release>(vtable[2])(obj); 99 reinterpret_cast<Release>(vtable[2])(obj);
100 100
101 // A class not served (an id no runtime class has) is refused, with the out pointer cleared. 101 // A class not served (an id no runtime class has) is refused, with the out pointer cleared: XGameSaveImpl
102 const GUID unserved = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; 102 // (xgameruntime include/xgamesave.idl), which is not served yet.
103 const GUID unserved = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}};
103 void* out = reinterpret_cast<void*>(1); 104 void* out = reinterpret_cast<void*>(1);
104 hr = query(&unserved, unserved, &out); 105 hr = query(&unserved, unserved, &out);
105 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr) 106 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr)
diff --git a/runtime/test/fixtures/tiny_tls_cb_only.cpp b/runtime/test/fixtures/tiny_tls_cb_only.cpp
index d8062c073..e8f80010a 100644
--- a/runtime/test/fixtures/tiny_tls_cb_only.cpp
+++ b/runtime/test/fixtures/tiny_tls_cb_only.cpp
@@ -2,6 +2,15 @@
2// and SizeOfZeroFill == 0 while providing a TLS callback (no CRT .tls section). Ordinary test code, not game data. 2// and SizeOfZeroFill == 0 while providing a TLS callback (no CRT .tls section). Ordinary test code, not game data.
3#include <windows.h> 3#include <windows.h>
4 4
5#ifdef __MSVC_RUNTIME_CHECKS
6// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB
7// leaves these unresolved (LNK1120). The checks have nothing to check here, so they do nothing.
8extern "C" {
9void __cdecl _RTC_InitBase() {}
10void __cdecl _RTC_Shutdown() {}
11}
12#endif
13
5namespace { 14namespace {
6 15
7ULONG g_tls_index = 0; 16ULONG g_tls_index = 0;
diff --git a/runtime/test/gameinput_host_test.cpp b/runtime/test/gameinput_host_test.cpp
new file mode 100644
index 000000000..cdd071055
--- /dev/null
+++ b/runtime/test/gameinput_host_test.cpp
@@ -0,0 +1,90 @@
1// The host GameInput path: mapped code that imports GameInputCreate from GameInput.dll, with no GameInput shim.
2//
3// docs/gameinput.md: without the SDL3 shim, the loader binds GameInputCreate to the host's GameInput.dll. This checks
4// that path with a synthetic DLL (test/fixtures/gameinput_host.cpp) mapped by rt::Loader:
5// - its GameInput.dll import binds to the host's copy (this test links no shim table, so it cannot be a shim);
6// - GameInputCreate succeeds from mapped code, and the library answers GetCurrentTimestamp;
7// - GetCurrentReading says either "reading" or "no reading found": no crash, no other error. With a gamepad attached
8// GetGamepadState must succeed on the reading; the test passes with or without one.
9// Skips (exit 77) only where Windows itself cannot load GameInput.dll (asked before mapping, with LoadLibraryExW).
10// When the DLL is there, an import that binds to nothing is a failure, not a skip. No game files.
11#include <windows.h>
12
13#include <cstdio>
14#include <filesystem>
15#include <stdexcept>
16#include <string>
17
18#include "pe_loader.h"
19
20namespace {
21
22using ProbeFn = int (*)(long*, unsigned long long*, long*, int*);
23constexpr unsigned long kReadingNotFound = 0x838A0003UL; // GAMEINPUT_E_READING_NOT_FOUND
24
25int g_failures = 0;
26
27void check(bool ok, const std::string& what) {
28 std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str());
29 std::fflush(stdout);
30 if (!ok) ++g_failures;
31}
32
33} // namespace
34
35int main(int argc, char** argv) {
36 if (argc != 2) {
37 std::fprintf(stderr, "usage: gameinput_host_test <gameinput_host.dll>\n");
38 return 2;
39 }
40 const std::filesystem::path fixture = argv[1];
41
42 // Decide the skip from the machine, not from the loader's answer: a broken host binding must fail the test.
43 HMODULE const host_gameinput = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
44 if (!host_gameinput) {
45 const DWORD error = GetLastError();
46 if (error == ERROR_MOD_NOT_FOUND || error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) {
47 std::printf("SKIP: no GameInput.dll on this machine\n");
48 return 77;
49 }
50 std::printf("FAIL GameInput.dll is present but does not load (error %lu)\n", static_cast<unsigned long>(error));
51 return 1;
52 }
53
54 try {
55 rt::Loader loader(fixture.parent_path());
56 rt::Module& m = loader.load(fixture);
57
58 // The SDK's import library imports by ordinal, so match the DLL name, not the function name.
59 rt::Binding binding = rt::Binding::Unimplemented;
60 int seen = 0;
61 for (const auto& r : m.imports)
62 if (rt::lower(r.dll) == "gameinput.dll") {
63 binding = r.binding;
64 ++seen;
65 }
66 check(seen == 1 && binding == rt::Binding::Host, "the GameInput.dll import binds to the host's copy");
67
68 loader.initialise();
69 const auto probe = reinterpret_cast<ProbeFn>(m.exports.at("gameinput_host_probe"));
70 long create_hr = -1, reading_hr = -1;
71 unsigned long long timestamp = 0;
72 int state_ok = 0;
73 const int created = probe(&create_hr, &timestamp, &reading_hr, &state_ok);
74 std::printf(" create hr=0x%08lX, timestamp=%llu, reading hr=0x%08lX\n", static_cast<unsigned long>(create_hr),
75 timestamp, static_cast<unsigned long>(reading_hr));
76 check(created == 1 && create_hr == 0, "GameInputCreate succeeds from mapped code");
77 check(timestamp != 0, "GetCurrentTimestamp returns a time");
78 const bool pad = created == 1 && reading_hr == 0;
79 check(pad || static_cast<unsigned long>(reading_hr) == kReadingNotFound,
80 "GetCurrentReading says either 'reading' or 'no reading found'");
81 std::printf(" gamepad reading: %s\n", pad ? "yes (a gamepad is attached)" : "none (no gamepad attached)");
82 if (pad) check(state_ok == 1, "GetGamepadState succeeds on a real reading");
83 } catch (const std::exception& e) {
84 std::printf("FAIL unexpected exception: %s\n", e.what());
85 ++g_failures;
86 }
87 FreeLibrary(host_gameinput);
88 std::printf("gameinput_host_test: %s (%d failures)\n", g_failures ? "FAILED" : "OK", g_failures);
89 return g_failures ? 1 : 0;
90}
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index 1389b8f6d..679adf19f 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -6,7 +6,8 @@
6// without trigger motors. The test covers enumeration and device callbacks, readings and their button/axis mapping, 6// without trigger motors. The test covers enumeration and device callbacks, readings and their button/axis mapping,
7// UI navigation, the guide button, rumble and trigger rumble as SDL receives them, the DualSense effect bytes for 7// UI navigation, the guide button, rumble and trigger rumble as SDL receives them, the DualSense effect bytes for
8// each LEONIDA_DS_TRIGGERS mode, the lightbar, a dispatcher, unplug/replug, reading history, 8// each LEONIDA_DS_TRIGGERS mode, the lightbar, a dispatcher, unplug/replug, reading history,
9// and identification of two or three otherwise indistinguishable pads. No game data. 9// identification of two or three otherwise indistinguishable pads, and which kind of device was used last
10// (active_input, LEONIDA_PROMPTS). No game data.
10#include <windows.h> 11#include <windows.h>
11 12
12#include <SDL3/SDL.h> 13#include <SDL3/SDL.h>
@@ -794,6 +795,156 @@ void test_keyboard_pad(IGameInput* input) {
794 rt::gameinput::set_cursor_source(nullptr); 795 rt::gameinput::set_cursor_source(nullptr);
795} 796}
796 797
798// active_input(): which kind of device the player used last. Virtual pads with a DualSense, a DualShock 4 and an Xbox
799// pad's vendor and product id (SDL takes the gamepad type from them) plus the keyboard pad; first with no wait
800// between changes (LEONIDA_PROMPTS_SWITCH_MS=0), then with the default 300 ms window on the real clock, then a family
801// forced by LEONIDA_PROMPTS.
802void test_active_input() {
803 using leonida::InputFamily;
804 const auto family = [] { return rt::gameinput::active_input().family; };
805 const auto generation = [] { return rt::gameinput::active_input().generation; };
806
807 set_env("LEONIDA_PROMPTS", nullptr);
808 set_env("LEONIDA_PROMPTS_SWITCH_MS", "0");
809 rt::gameinput::reload_config();
810 rt::gameinput::poll();
811 check(!rt::gameinput::active_input().forced, "active input: not forced without LEONIDA_PROMPTS");
812
813 Pad ds, ds4, xbox;
814 attach(ds, "Leonida virtual DualSense", 0x054C, 0x0CE6, false);
815 attach(ds4, "Leonida virtual DualShock 4", 0x054C, 0x09CC, false);
816 attach(xbox, "Leonida virtual Xbox pad", 0x045E, 0x0B12, true);
817 SDL_SetJoystickVirtualButton(ds.js, SDL_GAMEPAD_BUTTON_SOUTH, true); // held while it connects
818 const uint64_t at_connect = generation();
819 rt::gameinput::poll();
820 check(rt::gameinput::connected_count() == 3, "active input: three pads open");
821 check(generation() == at_connect, "active input: connecting pads (one with a button held) changes nothing");
822
823 auto press = [](Pad& p, SDL_GamepadButton b) {
824 SDL_SetJoystickVirtualButton(p.js, b, true);
825 rt::gameinput::poll();
826 SDL_SetJoystickVirtualButton(p.js, b, false);
827 rt::gameinput::poll();
828 };
829 SDL_SetJoystickVirtualButton(ds.js, SDL_GAMEPAD_BUTTON_SOUTH, false); // the held button, let go
830 rt::gameinput::poll();
831 check(generation() == at_connect, "active input: letting go of a button is not input");
832
833 // The tests before this one leave whichever pad they used last; an Xbox press makes the start known.
834 press(xbox, SDL_GAMEPAD_BUTTON_SOUTH);
835 check(family() == InputFamily::Xbox, "active input: the Xbox pad in use");
836 const uint64_t g0 = generation();
837
838 press(ds, SDL_GAMEPAD_BUTTON_SOUTH);
839 check(family() == InputFamily::PlayStation5 && generation() == g0 + 1, "active input: DualSense press");
840 press(ds4, SDL_GAMEPAD_BUTTON_EAST);
841 check(family() == InputFamily::PlayStation4 && generation() == g0 + 2, "active input: DualShock 4 press");
842
843 // Stick drift on the Xbox pad (0.18) is not input; the stick pushed over is.
844 SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 6000);
845 rt::gameinput::poll();
846 check(family() == InputFamily::PlayStation4 && generation() == g0 + 2, "active input: stick drift changes nothing");
847 SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 32767);
848 rt::gameinput::poll();
849 check(family() == InputFamily::Xbox && generation() == g0 + 3, "active input: Xbox stick pushed over");
850 SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 0);
851 rt::gameinput::poll();
852
853 // Buttons GameInput's gamepad state leaves out count too: the DualSense touchpad.
854 press(ds, SDL_GAMEPAD_BUTTON_TOUCHPAD);
855 check(family() == InputFamily::PlayStation5 && generation() == g0 + 4, "active input: DualSense touchpad click");
856 // A trigger pulled on the DualShock 4.
857 SDL_SetJoystickVirtualAxis(ds4.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 32767);
858 rt::gameinput::poll();
859 check(family() == InputFamily::PlayStation4 && generation() == g0 + 5, "active input: DualShock 4 trigger pull");
860 SDL_SetJoystickVirtualAxis(ds4.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, -32768);
861 rt::gameinput::poll();
862
863 // The keyboard pad: a key, and the mouse through the keyboard pad's right stick.
864 rt::gameinput::set_keyboard_source(fake_key_down, fake_focus);
865 rt::gameinput::set_cursor_source(fake_cursor);
866 std::memset(g_keys, 0, sizeof g_keys);
867 g_cursor_x = g_cursor_y = 0;
868 set_env("LEONIDA_KEYBOARD_PAD", "always");
869 rt::gameinput::reload_config();
870 rt::gameinput::poll(); // attaches the keyboard pad
871 rt::gameinput::poll(); // opens it: its first sample is the baseline
872 check(rt::gameinput::connected_count() == 4 && generation() == g0 + 5,
873 "active input: the keyboard pad connecting changes nothing");
874 g_keys[VK_RETURN] = true;
875 rt::gameinput::poll();
876 g_keys[VK_RETURN] = false;
877 rt::gameinput::poll();
878 check(family() == InputFamily::Keyboard && generation() == g0 + 6, "active input: Enter on the keyboard pad");
879 press(xbox, SDL_GAMEPAD_BUTTON_SOUTH);
880 check(family() == InputFamily::Xbox && generation() == g0 + 7, "active input: back to the Xbox pad");
881 g_cursor_x += 1; // a 1-count jitter stays well inside the stick radius
882 rt::gameinput::poll();
883 check(family() == InputFamily::Xbox, "active input: mouse jitter changes nothing");
884 g_cursor_x += 20; // a real movement pushes the right stick past the radius
885 rt::gameinput::poll();
886 check(family() == InputFamily::Keyboard && generation() == g0 + 8, "active input: mouse movement");
887 for (int i = 0; i < 80; ++i) rt::gameinput::poll(); // the stick falls back to rest
888
889 // The default window on the real clock: a second change within 300 ms of the last is ignored.
890 set_env("LEONIDA_PROMPTS_SWITCH_MS", nullptr);
891 rt::gameinput::reload_config();
892 check(rt::gameinput::config().prompts_switch_ms == 300, "active input: 300 ms by default");
893 Sleep(350);
894 press(ds, SDL_GAMEPAD_BUTTON_NORTH);
895 check(family() == InputFamily::PlayStation5 && generation() == g0 + 9, "active input: DualSense after the window");
896 press(xbox, SDL_GAMEPAD_BUTTON_WEST);
897 check(family() == InputFamily::PlayStation5 && generation() == g0 + 9,
898 "active input: an Xbox press right after a change is ignored");
899 Sleep(350);
900 press(xbox, SDL_GAMEPAD_BUTTON_WEST);
901 check(family() == InputFamily::Xbox && generation() == g0 + 10,
902 "active input: the Xbox press once the window passed");
903
904 // LEONIDA_PROMPTS forces a family; tracking goes on underneath and takes over again when it is cleared.
905 set_env("LEONIDA_PROMPTS_SWITCH_MS", "0");
906 set_env("LEONIDA_PROMPTS", "keyboard");
907 rt::gameinput::reload_config();
908 rt::gameinput::poll();
909 check(family() == InputFamily::Keyboard && rt::gameinput::active_input().forced && generation() == g0 + 11,
910 "active input: LEONIDA_PROMPTS=keyboard");
911 press(ds, SDL_GAMEPAD_BUTTON_SOUTH);
912 check(family() == InputFamily::Keyboard && generation() == g0 + 11,
913 "active input: forced, a DualSense press shows nothing");
914 set_env("LEONIDA_PROMPTS", "PlayStation"); // case does not matter
915 rt::gameinput::reload_config();
916 rt::gameinput::poll();
917 check(family() == InputFamily::PlayStation5 && rt::gameinput::active_input().forced && generation() == g0 + 12,
918 "active input: LEONIDA_PROMPTS=PlayStation (any case) is PlayStation 5");
919 set_env("LEONIDA_PROMPTS", "ps4");
920 rt::gameinput::reload_config();
921 rt::gameinput::poll();
922 check(family() == InputFamily::PlayStation4 && generation() == g0 + 13, "active input: LEONIDA_PROMPTS=ps4");
923 set_env("LEONIDA_PROMPTS", "nonsense"); // warns and follows the devices
924 rt::gameinput::reload_config();
925 rt::gameinput::poll();
926 check(!rt::gameinput::active_input().forced && family() == InputFamily::PlayStation5 && generation() == g0 + 14,
927 "active input: an unknown LEONIDA_PROMPTS follows the devices (the DualSense pressed while forced)");
928 set_env("LEONIDA_PROMPTS", "playstation");
929 rt::gameinput::reload_config();
930 rt::gameinput::poll();
931 check(family() == InputFamily::PlayStation5 && rt::gameinput::active_input().forced && generation() == g0 + 14,
932 "active input: forcing the family already in use changes no generation");
933
934 // Clean up: everything off and unplugged.
935 set_env("LEONIDA_PROMPTS", nullptr);
936 set_env("LEONIDA_PROMPTS_SWITCH_MS", nullptr);
937 set_env("LEONIDA_KEYBOARD_PAD", nullptr);
938 rt::gameinput::reload_config();
939 detach(ds);
940 detach(ds4);
941 detach(xbox);
942 rt::gameinput::poll();
943 check(rt::gameinput::connected_count() == 0, "active input: all pads closed at the end");
944 rt::gameinput::set_keyboard_source(nullptr, nullptr);
945 rt::gameinput::set_cursor_source(nullptr);
946}
947
797bool same_id(const AppLocalDeviceId& a, const AppLocalDeviceId& b) { return std::memcmp(&a, &b, sizeof a) == 0; } 948bool same_id(const AppLocalDeviceId& a, const AppLocalDeviceId& b) { return std::memcmp(&a, &b, sizeof a) == 0; }
798 949
799// The id the shim derives from SDL: the GUID, then two FNV-1a hashes of "s:" serial, "p:" path or nothing, with 950// The id the shim derives from SDL: the GUID, then two FNV-1a hashes of "s:" serial, "p:" path or nothing, with
@@ -1815,6 +1966,7 @@ int main() {
1815 rt::gameinput::poll(); 1966 rt::gameinput::poll();
1816 check(rt::gameinput::connected_count() == 0, "all pads closed after detaching"); 1967 check(rt::gameinput::connected_count() == 0, "all pads closed after detaching");
1817 1968
1969 test_active_input();
1818 test_twins(input); 1970 test_twins(input);
1819 test_keyboard_pad(input); 1971 test_keyboard_pad(input);
1820 test_motion(input); 1972 test_motion(input);
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index 48724afae..523180ee7 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -362,6 +362,15 @@ int main() {
362 .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true}); 362 .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true});
363 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); 363 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST);
364 CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE); 364 CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE);
365 // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border,
366 // W is free; min and mag filter agree (VUID ...-01072).
367 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
368 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
369 info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter);
370 info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror,
371 .min_filter = Filter::bilinear, .unnormalized = true});
372 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER &&
373 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST);
365 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); 374 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT);
366 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE); 375 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE);
367 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); 376 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
diff --git a/runtime/test/glsl/cs_indirect_dispatch_count.comp b/runtime/test/glsl/cs_indirect_dispatch_count.comp
new file mode 100644
index 000000000..234575467
--- /dev/null
+++ b/runtime/test/glsl/cs_indirect_dispatch_count.comp
@@ -0,0 +1,17 @@
1#version 460
2// Synthetic translated-shader stand-in: root UAV s0:s1, plus the 144-byte user-data contract.
3#extension GL_EXT_buffer_reference : require
4#extension GL_EXT_buffer_reference_uvec2 : require
5layout(local_size_x = 1) in;
6layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; };
7layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc;
8uvec2 add64(uvec2 a, uvec2 b) {
9 uint carry;
10 uint lo = uaddCarry(a.x, b.x, carry);
11 return uvec2(lo, a.y + b.y + carry);
12}
13void main() {
14 Words result = Words(add64(pc.heap_base, uvec2(pc.s[0], pc.s[1])));
15 atomicAdd(result.w[0], 1u);
16 atomicAdd(result.w[1], gl_WorkGroupID.x + 1u);
17}
diff --git a/runtime/test/glsl/cs_wave_probe.comp b/runtime/test/glsl/cs_wave_probe.comp
new file mode 100644
index 000000000..d18987908
--- /dev/null
+++ b/runtime/test/glsl/cs_wave_probe.comp
@@ -0,0 +1,31 @@
1#version 450
2// vk_compute_test's subgroup probe (cs_wave_probe_spv.h). Where the device can't pin a compute subgroup size
3// (MoltenVK: requiredSubgroupSizeStages is 0), vk_compute_test runs this first, with the test shader's local size
4// and pipeline flags, and checks what each invocation reports: its subgroup's size, its lane and subgroup number,
5// and how many lanes a ballot of the whole subgroup counts. The ballot is the real width: MoltenVK's MSL declares
6// SubgroupSize as the constant 32, while the lane, the subgroup number and simd_ballot come from the hardware.
7// Four words per invocation at base + 16 * gl_LocalInvocationIndex, the buffer address in the first push-constant
8// words (s0, s1), so the probe fits the 128-byte push-constant layout of --pc-tail-ubo as well as the 144-byte one.
9#extension GL_EXT_buffer_reference : require
10#extension GL_EXT_buffer_reference_uvec2 : require
11#extension GL_KHR_shader_subgroup_basic : require
12#extension GL_KHR_shader_subgroup_ballot : require
13
14layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in;
15
16layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words {
17 uint w[];
18};
19
20layout(push_constant) uniform UserData {
21 uvec2 base;
22} pc;
23
24void main() {
25 Words o = Words(pc.base);
26 const uint i = gl_LocalInvocationIndex * 4u;
27 o.w[i + 0u] = gl_SubgroupSize;
28 o.w[i + 1u] = gl_SubgroupInvocationID;
29 o.w[i + 2u] = gl_SubgroupID;
30 o.w[i + 3u] = subgroupBallotBitCount(subgroupBallot(true));
31}
diff --git a/runtime/test/glsl/gs_depth.geom b/runtime/test/glsl/gs_depth.geom
new file mode 100644
index 000000000..0661c7acf
--- /dev/null
+++ b/runtime/test/glsl/gs_depth.geom
@@ -0,0 +1,15 @@
1#version 460
2// A pass-through geometry shader with the interface of a translated one (docs/design.md, "Geometry shaders":
3// triangles in, a triangle strip out), for d3d12_depth24_draw_test: a VS + GS pipeline without a pixel shader still
4// gets the built-in D24 depth stage. It reads no input but the position and writes none but gl_Position.
5
6layout(triangles) in;
7layout(triangle_strip, max_vertices = 3) out;
8
9void main() {
10 for (int i = 0; i < 3; ++i) {
11 gl_Position = gl_in[i].gl_Position;
12 EmitVertex();
13 }
14 EndPrimitive();
15}
diff --git a/runtime/test/glsl/ps_depth_empty.frag b/runtime/test/glsl/ps_depth_empty.frag
new file mode 100644
index 000000000..8bc5bce70
--- /dev/null
+++ b/runtime/test/glsl/ps_depth_empty.frag
@@ -0,0 +1,11 @@
1#version 460
2// A pixel shader with no outputs, for d3d12_depth24_draw_test: it stands in for a translated shader in a pipeline
3// with no render target, so the layer's D24 depth edit (src/depth24_fragment.h) runs on a shader it did not build.
4
5layout(push_constant) uniform UserData {
6 uint s[32];
7 uvec2 heap_base;
8 uvec2 code_base;
9} pc;
10
11void main() {}
diff --git a/runtime/test/glsl/ps_depth_write.frag b/runtime/test/glsl/ps_depth_write.frag
new file mode 100644
index 000000000..959d1dd9d
--- /dev/null
+++ b/runtime/test/glsl/ps_depth_write.frag
@@ -0,0 +1,13 @@
1#version 460
2// A pixel shader that writes its own depth (SV_Depth), for d3d12_depth24_draw_test: s2 is the depth it writes. On a
3// D24 target the value is stored quantised to 24 bits, and D3D applies no depth bias to it.
4
5layout(push_constant) uniform UserData {
6 uint s[32];
7 uvec2 heap_base;
8 uvec2 code_base;
9} pc;
10
11void main() {
12 gl_FragDepth = uintBitsToFloat(pc.s[2]);
13}
diff --git a/runtime/test/glsl/vs_depth.vert b/runtime/test/glsl/vs_depth.vert
new file mode 100644
index 000000000..de1d6ee40
--- /dev/null
+++ b/runtime/test/glsl/vs_depth.vert
@@ -0,0 +1,16 @@
1#version 460
2// A full-screen triangle at a chosen depth, written to the translator's runtime contract (docs/design.md, "User
3// data"), for d3d12_depth24_draw_test: s0 is the depth at the centre and s1 how much it changes per unit of clip-space
4// x, so s1 = 0 gives a flat triangle and anything else a constant slope across the target.
5
6layout(push_constant) uniform UserData {
7 uint s[32];
8 uvec2 heap_base;
9 uvec2 code_base;
10} pc;
11
12void main() {
13 const vec2 corner = vec2(float(gl_VertexIndex & 2), float((gl_VertexIndex << 1) & 2));
14 const vec2 xy = corner * 2.0 - 1.0;
15 gl_Position = vec4(xy, uintBitsToFloat(pc.s[0]) + uintBitsToFloat(pc.s[1]) * xy.x, 1.0);
16}
diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h
new file mode 100644
index 000000000..53aa61f2d
--- /dev/null
+++ b/runtime/test/large_module_gate.h
@@ -0,0 +1,179 @@
1// How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget.
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement.
8//
9// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
10// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
11// large module.
12#pragma once
13
14#include <algorithm>
15#include <condition_variable>
16#include <cstdint>
17#include <cstdio>
18#include <mutex>
19#include <string>
20
21#ifdef _WIN32
22#ifndef NOMINMAX
23#define NOMINMAX
24#endif
25#include <windows.h>
26#endif
27#if defined(__GLIBC__)
28#include <malloc.h>
29#endif
30
31namespace leonida {
32
33inline constexpr uint64_t kBytesPerSpirvByte = 512;
34
35inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
36
37#if defined(__linux__)
38// The first unsigned number in a file ("max" and unreadable files give no value).
39inline bool read_u64_file(const std::string& path, uint64_t& value) {
40 std::FILE* f = std::fopen(path.c_str(), "r");
41 if (!f) return false;
42 unsigned long long v = 0;
43 const bool ok = std::fscanf(f, "%llu", &v) == 1;
44 std::fclose(f);
45 value = v;
46 return ok;
47}
48
49// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
50// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
51inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
52 const std::string& cgroup_root = "/sys/fs/cgroup") {
53 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
54 if (!f) return UINT64_MAX;
55 char line[4096];
56 std::string rel;
57 while (std::fgets(line, sizeof(line), f)) {
58 std::string l(line);
59 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
60 rel = l.substr(3);
61 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
62 break;
63 }
64 }
65 std::fclose(f);
66 uint64_t room = UINT64_MAX;
67 for (std::string dir = rel; !dir.empty() && dir != "/";) {
68 uint64_t max = 0, current = 0;
69 if (read_u64_file(cgroup_root + dir + "/memory.max", max) &&
70 read_u64_file(cgroup_root + dir + "/memory.current", current))
71 room = std::min(room, max > current ? max - current : 0);
72 const auto slash = dir.find_last_of('/');
73 dir = slash == std::string::npos ? std::string() : dir.substr(0, slash);
74 }
75 return room;
76}
77#endif
78
79// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
80inline uint64_t available_memory_bytes() {
81#ifdef _WIN32
82 MEMORYSTATUSEX status{};
83 status.dwLength = sizeof(status);
84 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
85#elif defined(__linux__)
86 std::FILE* f = std::fopen("/proc/meminfo", "r");
87 if (!f) return 0;
88 char line[256];
89 unsigned long long kb = 0;
90 bool found = false;
91 while (std::fgets(line, sizeof(line), f))
92 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
93 std::fclose(f);
94 if (!found) return 0;
95 const uint64_t room = cgroup_memory_room();
96 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
97#else
98 return 0;
99#endif
100}
101
102// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
103inline void release_free_memory() {
104#if defined(__GLIBC__)
105 malloc_trim(0);
106#endif
107}
108
109// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
110// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
111class LargeModuleGate {
112public:
113 LargeModuleGate(uint64_t budget, unsigned max_inflight)
114 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
115
116 bool admits(uint64_t estimate) const {
117 std::lock_guard<std::mutex> g(mu_);
118 return admits_locked(estimate);
119 }
120 void enter(uint64_t estimate) {
121 std::unique_lock<std::mutex> l(mu_);
122 cv_.wait(l, [&] { return admits_locked(estimate); });
123 used_ += estimate;
124 ++inflight_;
125 }
126 void leave(uint64_t estimate) {
127 {
128 std::lock_guard<std::mutex> g(mu_);
129 used_ -= estimate;
130 --inflight_;
131 }
132 cv_.notify_all();
133 }
134 unsigned inflight() const {
135 std::lock_guard<std::mutex> g(mu_);
136 return inflight_;
137 }
138 uint64_t budget() const { return budget_; }
139 unsigned max_inflight() const { return max_inflight_; }
140
141 // Holds a place from construction until destruction (or release()), then hands freed memory back.
142 class Ticket {
143 public:
144 Ticket() = default;
145 Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); }
146 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
147 Ticket& operator=(Ticket&& o) noexcept {
148 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
149 return *this;
150 }
151 Ticket(const Ticket&) = delete;
152 Ticket& operator=(const Ticket&) = delete;
153 ~Ticket() { release(); }
154 void release() {
155 if (!gate_) return;
156 gate_->leave(estimate_);
157 gate_ = nullptr;
158 release_free_memory();
159 }
160 private:
161 LargeModuleGate* gate_ = nullptr;
162 uint64_t estimate_ = 0;
163 };
164
165private:
166 bool admits_locked(uint64_t estimate) const {
167 if (inflight_ == 0) return true;
168 return inflight_ < max_inflight_ && used_ + estimate <= budget_;
169 }
170
171 const uint64_t budget_;
172 const unsigned max_inflight_;
173 mutable std::mutex mu_;
174 std::condition_variable cv_;
175 uint64_t used_ = 0;
176 unsigned inflight_ = 0;
177};
178
179} // namespace leonida
diff --git a/runtime/test/large_module_gate_test.cpp b/runtime/test/large_module_gate_test.cpp
new file mode 100644
index 000000000..ed8d18a0c
--- /dev/null
+++ b/runtime/test/large_module_gate_test.cpp
@@ -0,0 +1,159 @@
1// vk_pipeline_check's memory budget for large modules (large_module_gate.h), without a Vulkan device.
2#include "large_module_gate.h"
3
4#include <atomic>
5#include <string>
6#ifndef _WIN32
7#include <unistd.h>
8#endif
9#include <chrono>
10#include <cstdio>
11#include <thread>
12#include <vector>
13
14#define CHECK(condition) do { \
15 if (!(condition)) { \
16 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
17 return 1; \
18 } \
19} while (0)
20
21using leonida::LargeModuleGate;
22
23static int budget_and_count() {
24 LargeModuleGate gate(10, 3);
25 CHECK(gate.admits(4));
26 gate.enter(4);
27 CHECK(gate.admits(4));
28 gate.enter(4);
29 CHECK(!gate.admits(4)); // 12 > 10
30 CHECK(gate.admits(2)); // 10 fits exactly
31 gate.enter(2);
32 CHECK(!gate.admits(0)); // three in: max_inflight
33 gate.leave(4);
34 CHECK(gate.admits(4));
35 gate.leave(4);
36 gate.leave(2);
37 CHECK(gate.inflight() == 0);
38 return 0;
39}
40
41static int oversized_module_still_gets_in_alone() {
42 // Before: a module whose estimate exceeds the whole budget would wait forever.
43 LargeModuleGate gate(10, 4);
44 CHECK(gate.admits(100));
45 gate.enter(100);
46 CHECK(!gate.admits(1)); // nothing joins it
47 gate.leave(100);
48 CHECK(gate.admits(1));
49 return 0;
50}
51
52static int max_inflight_zero_means_one() {
53 LargeModuleGate gate(100, 0);
54 CHECK(gate.max_inflight() == 1);
55 gate.enter(1);
56 CHECK(!gate.admits(1));
57 gate.leave(1);
58 return 0;
59}
60
61static int ticket_releases() {
62 LargeModuleGate gate(10, 2);
63 {
64 LargeModuleGate::Ticket a(gate, 6);
65 CHECK(gate.inflight() == 1);
66 LargeModuleGate::Ticket moved = std::move(a); // the moved-from ticket must not leave twice
67 CHECK(gate.inflight() == 1);
68 LargeModuleGate::Ticket b;
69 b = LargeModuleGate::Ticket(gate, 4);
70 CHECK(gate.inflight() == 2);
71 b.release();
72 CHECK(gate.inflight() == 1);
73 }
74 CHECK(gate.inflight() == 0);
75 return 0;
76}
77
78static int threads_never_exceed_the_budget() {
79 constexpr uint64_t kBudget = 10;
80 LargeModuleGate gate(kBudget, 3);
81 std::atomic<uint64_t> used{0};
82 std::atomic<unsigned> in{0};
83 std::atomic<bool> over{false};
84 std::vector<std::thread> threads;
85 for (int t = 0; t < 8; ++t) {
86 threads.emplace_back([&, t] {
87 for (int i = 0; i < 200; ++i) {
88 const uint64_t est = 1 + uint64_t((t + i) % 5); // 1..5
89 LargeModuleGate::Ticket ticket(gate, est);
90 const uint64_t u = used += est;
91 const unsigned n = ++in;
92 if (n > 3 || (n > 1 && u > kBudget)) over = true;
93 std::this_thread::sleep_for(std::chrono::microseconds(50));
94 --in;
95 used -= est;
96 }
97 });
98 }
99 for (auto& th : threads) th.join();
100 CHECK(!over);
101 CHECK(gate.inflight() == 0);
102 return 0;
103}
104
105static int estimate_and_memory_query() {
106 CHECK(leonida::large_module_estimate(4u << 20) == (uint64_t(4) << 20) * leonida::kBytesPerSpirvByte);
107#if defined(__linux__) || defined(_WIN32)
108 CHECK(leonida::available_memory_bytes() > 0); // Linux: MemAvailable; Windows: ullAvailPhys
109#endif
110 leonida::release_free_memory(); // must be callable anywhere
111 return 0;
112}
113
114#if defined(__linux__)
115#include <filesystem>
116#include <fstream>
117
118static void write_file(const std::filesystem::path& p, const char* text) {
119 std::filesystem::create_directories(p.parent_path());
120 std::ofstream(p) << text;
121}
122
123static int cgroup_limits_are_read_up_the_tree() {
124 // Before: only MemAvailable was read, so under systemd-run -p MemoryMax=... (or in a container) the budget was
125 // the whole machine's and the checker could be killed by its own cgroup.
126 namespace fs = std::filesystem;
127 const fs::path root = fs::temp_directory_path() / ("lmg_test_" + std::to_string(::getpid()));
128 fs::remove_all(root);
129 write_file(root / "self", "0::/user.slice/app.scope\n");
130 write_file(root / "cg/user.slice/memory.max", "10000\n");
131 write_file(root / "cg/user.slice/memory.current", "4000\n"); // room 6000
132 write_file(root / "cg/user.slice/app.scope/memory.max", "max\n"); // no limit of its own
133 write_file(root / "cg/user.slice/app.scope/memory.current", "3000\n");
134 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 6000);
135 write_file(root / "cg/user.slice/app.scope/memory.max", "5000\n"); // room 2000, the tighter one
136 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 2000);
137 write_file(root / "cg/user.slice/app.scope/memory.current", "7000\n"); // over its limit: no room
138 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 0);
139 write_file(root / "self", "12:memory:/legacy\n"); // cgroup v1 only: no limit read
140 CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == UINT64_MAX);
141 CHECK(leonida::cgroup_memory_room((root / "missing").string(), (root / "cg").string()) == UINT64_MAX);
142 fs::remove_all(root);
143 return 0;
144}
145#endif
146
147int main() {
148#if defined(__linux__)
149 if (int r = cgroup_limits_are_read_up_the_tree()) return r;
150#endif
151 if (int r = budget_and_count()) return r;
152 if (int r = oversized_module_still_gets_in_alone()) return r;
153 if (int r = max_inflight_zero_means_one()) return r;
154 if (int r = ticket_releases()) return r;
155 if (int r = threads_never_exceed_the_budget()) return r;
156 if (int r = estimate_and_memory_query()) return r;
157 std::puts("large_module_gate: ok");
158 return 0;
159}
diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp
index 58aae185b..7a4e10cfd 100644
--- a/runtime/test/loader_test.cpp
+++ b/runtime/test/loader_test.cpp
@@ -8,6 +8,7 @@
8#include <intrin.h> 8#include <intrin.h>
9 9
10#include <algorithm> 10#include <algorithm>
11#include <atomic>
11#include <chrono> 12#include <chrono>
12#include <cstdio> 13#include <cstdio>
13#include <cstdlib> 14#include <cstdlib>
@@ -16,6 +17,7 @@
16#include <fstream> 17#include <fstream>
17#include <stdexcept> 18#include <stdexcept>
18#include <string> 19#include <string>
20#include <thread>
19#include <vector> 21#include <vector>
20 22
21#include "../shims/shims.h" 23#include "../shims/shims.h"
@@ -1166,6 +1168,58 @@ void test_unwind_registration() {
1166 1168
1167// An export whose address-table entry is past SizeOfImage (not a forwarder: outside the export directory) is 1169// An export whose address-table entry is past SizeOfImage (not a forwarder: outside the export directory) is
1168// refused instead of being stored as base + rva, a pointer outside the mapping. 1170// refused instead of being stored as base + rva, a pointer outside the mapping.
1171// The address-to-module lookup the shim registry uses (on every C++ throw from a mapped image, and for trace and
1172// stop lines) runs on whatever thread asks, while another thread may be inside load(). It used to walk the Loader's
1173// module vector with no lock while load() appended to it. Without the fix this fails for certain only under
1174// AddressSanitizer; here it checks that every answer given during 300 loads is right.
1175void test_lookup_during_loads() {
1176 const char* what = "the address lookup is right while another thread loads modules";
1177 try {
1178 rt::Loader loader(g_dir);
1179 auto first = make_image();
1180 auto* first_nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(first.data() + 0x80);
1181 first_nt->OptionalHeader.ImageBase = 0x200000000ull;
1182 rt::Module& anchor = loader.load(write_image(first));
1183 const uint64_t inside = reinterpret_cast<uint64_t>(anchor.base) + 0x1004;
1184
1185 std::atomic<bool> stop{false};
1186 std::atomic<unsigned> lookups{0}, wrong{0};
1187 std::thread reader([&] {
1188 while (!stop.load()) {
1189 uint64_t base = 0;
1190 if (!rt::shims::mapped_image_base(inside, base) || base != reinterpret_cast<uint64_t>(anchor.base))
1191 ++wrong;
1192 if (rt::shims::module_offset(inside).find("+0x1004") == std::string::npos) ++wrong;
1193 uint64_t none = 0;
1194 if (rt::shims::mapped_image_base(0x10, none)) ++wrong; // in no image
1195 ++lookups;
1196 }
1197 });
1198 unsigned loaded = 0;
1199 for (unsigned i = 1; i <= 300; ++i) {
1200 auto img = make_image();
1201 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(img.data() + 0x80);
1202 nt->OptionalHeader.ImageBase = 0x200000000ull + i * 0x10000ull;
1203 rt::Module& m = loader.load(write_image(img));
1204 uint64_t base = 0;
1205 if (rt::shims::mapped_image_base(reinterpret_cast<uint64_t>(m.base) + 0x1000, base) &&
1206 base == reinterpret_cast<uint64_t>(m.base))
1207 ++loaded;
1208 }
1209 while (lookups.load() < 1000) std::this_thread::yield();
1210 stop = true;
1211 reader.join();
1212 if (wrong.load())
1213 failed(what, std::to_string(wrong.load()) + " wrong answers in " + std::to_string(lookups.load()) + " lookups");
1214 else if (loaded != 300)
1215 failed(what, "only " + std::to_string(loaded) + " of 300 new modules were found by address");
1216 else
1217 pass(what);
1218 } catch (const std::exception& e) {
1219 failed(what, e.what());
1220 }
1221}
1222
1169void test_export_bounds() { 1223void test_export_bounds() {
1170 auto outside = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); 1224 auto outside = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000);
1171 nt_of(outside)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sizeof(IMAGE_EXPORT_DIRECTORY); 1225 nt_of(outside)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sizeof(IMAGE_EXPORT_DIRECTORY);
@@ -1273,6 +1327,7 @@ int main() {
1273 test_export_bounds(); 1327 test_export_bounds();
1274 test_tls_directory_count(); 1328 test_tls_directory_count();
1275 test_unwind_registration(); 1329 test_unwind_registration();
1330 test_lookup_during_loads();
1276 } catch (const std::exception& e) { 1331 } catch (const std::exception& e) {
1277 // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process. 1332 // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process.
1278 failed("writing the test images", e.what()); 1333 failed("writing the test images", e.what());
diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp
index 2259cf5d3..75feecf15 100644
--- a/runtime/test/queue_proxy_test.cpp
+++ b/runtime/test/queue_proxy_test.cpp
@@ -1017,12 +1017,15 @@ int run_runner_child(const char* mode, unsigned long bytes) {
1017int check_child_runner() { 1017int check_child_runner() {
1018 const char* label = "child runner"; 1018 const char* label = "child runner";
1019 ChildResult report; 1019 ChildResult report;
1020 ChildRun run = run_self(L"--child-flood 0", 30000); 1020 ChildRun run;
1021 EXPECT(run.end == ChildEnd::exited && run.exit_code == 0 && parse_diff_report(run.tail, report)); 1021 // The first two successful starts and the first failed start make Windows load and cache their persistent process
1022 EXPECT(report.ran == 1 && report.hr == 0 && report.removed == 0 && report.validation == 0); 1022 // handles (on Windows 11 26200, a second CreateProcessW caches the HKCU root key and a failed CreateProcessW keeps
1023 // The first start and the first failed start make Windows load what it keeps for them (a failed CreateProcessW 1023 // 41-42 AppCompat/PCA handles; later starts add none). Warm up both before reading handles_before.
1024 // leaves 42 handles the first time on Windows 11 26200, none on every later one): both run once before the handle 1024 for (int warmup = 0; warmup < 2; ++warmup) {
1025 // count is taken, and every case after it must leave the count as it was. 1025 run = run_self(L"--child-flood 0", 30000);
1026 EXPECT(run.end == ChildEnd::exited && run.exit_code == 0 && parse_diff_report(run.tail, report));
1027 EXPECT(report.ran == 1 && report.hr == 0 && report.removed == 0 && report.validation == 0);
1028 }
1026 std::fprintf(stderr, "child runner: the next four errors are expected\n"); 1029 std::fprintf(stderr, "child runner: the next four errors are expected\n");
1027 const std::wstring missing = self_path() + L".missing.exe"; 1030 const std::wstring missing = self_path() + L".missing.exe";
1028 run = run_process(missing.c_str(), L"", 5000); 1031 run = run_process(missing.c_str(), L"", 5000);
diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp
index f3eb316c1..8de50299e 100644
--- a/runtime/test/replay_cpu_bench.cpp
+++ b/runtime/test/replay_cpu_bench.cpp
@@ -31,6 +31,7 @@
31#include <functional> 31#include <functional>
32#include <iterator> 32#include <iterator>
33#include <map> 33#include <map>
34#include <memory>
34#include <new> 35#include <new>
35#include <string> 36#include <string>
36#include <tuple> 37#include <tuple>
@@ -276,11 +277,13 @@ bool uav_clear(CommandList& list, std::uint32_t index) {
276bool draw(CommandList& list, std::uint32_t index, bool indexed) { 277bool draw(CommandList& list, std::uint32_t index, bool indexed) {
277 Draw d{}; 278 Draw d{};
278 d.pipeline = Scene::pipeline_id; 279 d.pipeline = Scene::pipeline_id;
279 d.render_targets = {color_view}; 280 auto views = std::make_shared<DrawViews>(); // out of line since D3D-391
281 views->render_targets = {color_view};
280 d.depth = depth_view; 282 d.depth = depth_view;
281 const std::uint64_t base = Scene::geometry_va + (index % 256) * 65536ull; 283 const std::uint64_t base = Scene::geometry_va + (index % 256) * 65536ull;
282 d.vertex_buffers[0] = {base, 24576, 12}; // by input slot, inlined since D3D-289 284 views->vertex_buffers[0] = {base, 24576, 12}; // by input slot
283 d.vertex_buffers[1] = {base + 24576, 16384, 8}; 285 views->vertex_buffers[1] = {base + 24576, 16384, 8};
286 d.views = std::move(views);
284 if (indexed) d.index = {base + 40960, 6144, 57}; 287 if (indexed) d.index = {base + 40960, 6144, 57};
285 d.topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST 288 d.topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST
286 d.viewport = {0, 0, 1920, 1080, 0, 1}; 289 d.viewport = {0, 0, 1920, 1080, 0, 1};
@@ -577,7 +580,9 @@ int main(int argc, char** argv) {
577 CommandList earlier, later; 580 CommandList earlier, later;
578 Draw plain{}; 581 Draw plain{};
579 plain.pipeline = Scene::bare_id; 582 plain.pipeline = Scene::bare_id;
580 plain.render_targets = {color_view}; 583 auto plain_views = std::make_shared<DrawViews>();
584 plain_views->render_targets = {color_view};
585 plain.views = std::move(plain_views);
581 plain.topology = 4; 586 plain.topology = 4;
582 plain.viewport = {0, 0, 1920, 1080, 0, 1}; 587 plain.viewport = {0, 0, 1920, 1080, 0, 1};
583 plain.scissor = {0, 0, 1920, 1080}; 588 plain.scissor = {0, 0, 1920, 1080};
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp
index df4e22718..e4a513676 100644
--- a/runtime/test/replay_query_predication_test.cpp
+++ b/runtime/test/replay_query_predication_test.cpp
@@ -5,7 +5,7 @@
5// how resolves inside a pipeline-statistics query are replayed; cases 7 and 8 cover the other helper dispatches 5// how resolves inside a pipeline-statistics query are replayed; cases 7 and 8 cover the other helper dispatches
6// and their no-pool fallback (D3D-162). Cases 9 to 13 check overlapping queries: statistics over statistics, binary 6// and their no-pool fallback (D3D-162). Cases 9 to 13 check overlapping queries: statistics over statistics, binary
7// inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics 7// inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics
8// queries, and the single-list refusal (D3D-252). No GPU or game data. 8// queries, and the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). No GPU or game data.
9#include "../src/vulkan_replay.h" 9#include "../src/vulkan_replay.h"
10#include <cstdint> 10#include <cstdint>
11#include <cstdio> 11#include <cstdio>
@@ -571,6 +571,54 @@ int main() {
571 expect(trace.events.empty(), "no segment pool: nothing was emitted for the refused list"); 571 expect(trace.events.empty(), "no segment pool: nothing was emitted for the refused list");
572 } 572 }
573 573
574 // 14. D3D-399, the single-list replay() with a segment pool: the list case 13 refuses replays as on the batched
575 // path, and so does case 10's occlusion pair. The pools are created to the planned size and handed to `keep`.
576 {
577 Trace trace;
578 g_trace = &trace;
579 std::vector<std::pair<VkQueryType, std::uint32_t>> created;
580 ReplayFunctions pooled = vk;
581 pooled.create_segment_pool = [&](VkQueryType type, std::uint32_t count) {
582 created.emplace_back(type, count);
583 auto pool = std::make_shared<OcclusionSegmentPool>();
584 pool->pool = handle<VkQueryPool>(type == VK_QUERY_TYPE_OCCLUSION ? 8 : 9);
585 pool->destroy = mock_destroy_pool;
586 return std::shared_ptr<const OcclusionSegmentPool>(pool);
587 };
588 CommandList statistics_list; // case 13's list
589 expect(statistics_list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record pooled begin 0");
590 expect(statistics_list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "record pooled begin 1");
591 expect(statistics_list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record pooled end 0");
592 expect(statistics_list.end_query({6, d3d12_query::pipeline_statistics, 1}), "record pooled end 1");
593 expect(statistics_list.close(), "close pooled statistics list");
594 CommandList occlusion_list; // case 10's list
595 expect(occlusion_list.begin_query({1, d3d12_query::occlusion, 0}), "record pooled occlusion begin");
596 expect(occlusion_list.begin_query({1, d3d12_query::binary_occlusion, 1}), "record pooled binary begin");
597 expect(occlusion_list.end_query({1, d3d12_query::binary_occlusion, 1}), "record pooled binary end");
598 expect(occlusion_list.end_query({1, d3d12_query::occlusion, 0}), "record pooled occlusion end");
599 expect(occlusion_list.resolve_queries({1, d3d12_query::occlusion, 0, 1, 1, 0}), "record pooled resolve");
600 expect(occlusion_list.close(), "close pooled occlusion list");
601 expect(replay(statistics_list, VK_NULL_HANDLE, resolve, pooled) == ReplayResult::unsupported &&
602 replay(occlusion_list, VK_NULL_HANDLE, resolve, vk) == ReplayResult::unsupported &&
603 created.empty() && trace.events.empty(),
604 "pooled: without `keep` or a pool both lists are still refused and no pool is made");
605 std::vector<std::shared_ptr<const OcclusionSegmentPool>> keep;
606 const auto r0 = replay(statistics_list, VK_NULL_HANDLE, resolve, pooled, nullptr, &keep);
607 const auto r1 = replay(occlusion_list, VK_NULL_HANDLE, resolve, pooled, nullptr, &keep);
608 expect(r0 == ReplayResult::success && r1 == ReplayResult::success,
609 "pooled: overlapping statistics and occlusion queries replay on the single-list path");
610 const std::vector<std::pair<VkQueryType, std::uint32_t>> sizes{{VK_QUERY_TYPE_PIPELINE_STATISTICS, 3},
611 {VK_QUERY_TYPE_OCCLUSION, 3}};
612 expect(created == sizes, "pooled: one pool of each type, sized to the planned segments");
613 expect(keep.size() == 2, "pooled: both pools are handed to the caller");
614 const std::vector<std::string> want{"begin_query 9:0", "end_query 9:0", "begin_query 9:1",
615 "end_query 9:1", "begin_query 9:2", "end_query 9:2",
616 "begin_query 8:0", "end_query 8:0", "begin_query 8:1",
617 "end_query 8:1", "begin_query 8:2", "end_query 8:2",
618 "sum_occlusion 8:0+3"};
619 expect(trace.events == want, "pooled: the same segments and sums as the batched path");
620 }
621
574 if (failures) return 1; 622 if (failures) return 1;
575 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); 623 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches");
576 return 0; 624 return 0;
diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp
index 261004328..a5d90c141 100644
--- a/runtime/test/root_signature_oracle_test.cpp
+++ b/runtime/test/root_signature_oracle_test.cpp
@@ -25,6 +25,13 @@ void check(bool condition, const char* what) {
25 if (!condition) ++g_failures; 25 if (!condition) ++g_failures;
26} 26}
27 27
28// One line per assertion: "case: what", so a failure names the signature and the field instead of just "false".
29void check_named(bool condition, const char* name, const char* what) {
30 char line[256];
31 std::snprintf(line, sizeof(line), "%s: %s", name, what);
32 check(condition, line);
33}
34
28struct Blobs { 35struct Blobs {
29 ID3DBlob* blob = nullptr; 36 ID3DBlob* blob = nullptr;
30 ID3DBlob* error = nullptr; 37 ID3DBlob* error = nullptr;
@@ -70,6 +77,41 @@ bool parse_blob(ID3DBlob* blob, rt::rootsig::RootSignature& model) {
70 return true; 77 return true;
71} 78}
72 79
80// Parses and logs "case: parses"; false means the caller must not index the model (that segfaulted CI).
81bool parse_checked(ID3DBlob* blob, const char* name, rt::rootsig::RootSignature& model) {
82 const bool parsed = parse_blob(blob, model);
83 check_named(parsed, name, "parses");
84 return parsed;
85}
86
87// Serializes one synthetic desc and, on failure, prints the runtime's own complaint: that text is what tells a
88// rejected flag apart from a rejected layout.
89bool serialize_desc(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc, Blobs& out, const char* name) {
90 const HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &out.blob, &out.error);
91 check_named(hr == S_OK, name, "Microsoft serializer accepts it");
92 if (hr != S_OK) {
93 if (out.error != nullptr) {
94 std::printf("serializer error: %s\n",
95 static_cast<const char*>(out.error->GetBufferPointer()));
96 }
97 return false;
98 }
99 return true;
100}
101
102// Every field of one static sampler, plus whether this root-signature version carries the 1.2 flags dword.
103bool same_sampler(const rt::rootsig::StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) {
104 return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) &&
105 got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) &&
106 got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy &&
107 got.comparison_func == uint32_t(want.ComparisonFunc) &&
108 got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD &&
109 got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister &&
110 got.register_space == want.RegisterSpace &&
111 got.visibility == static_cast<rt::rootsig::Visibility>(want.ShaderVisibility) &&
112 got.flags == (flags ? uint32_t(want.Flags) : 0u);
113}
114
73} // namespace 115} // namespace
74 116
75int main() { 117int main() {
@@ -115,7 +157,9 @@ int main() {
115 model.params[0].num_values == 4 && 157 model.params[0].num_values == 4 &&
116 model.params[0].visibility == Visibility::Vertex, 158 model.params[0].visibility == Visibility::Vertex,
117 "oracle constants match"); 159 "oracle constants match");
118 check(model.params[1].type == ParamType::Descriptor, 160 check(model.params[1].type == ParamType::Descriptor &&
161 model.params[1].descriptor_register == 2 &&
162 model.params[1].descriptor_space == 0,
119 "oracle CBV matches"); 163 "oracle CBV matches");
120 const PackResult packed = pack(model); 164 const PackResult packed = pack(model);
121 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords"); 165 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords");
@@ -213,17 +257,6 @@ int main() {
213 params1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; 257 params1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
214 params1[1].Descriptor = {5, 1, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE}; 258 params1[1].Descriptor = {5, 1, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE};
215 259
216 const auto same_sampler = [](const StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) {
217 return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) &&
218 got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) &&
219 got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy &&
220 got.comparison_func == uint32_t(want.ComparisonFunc) &&
221 got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD &&
222 got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister &&
223 got.register_space == want.RegisterSpace &&
224 got.visibility == static_cast<Visibility>(want.ShaderVisibility) &&
225 got.flags == (flags ? uint32_t(want.Flags) : 0u);
226 };
227 // Ranges as the model should hold them: 1.0 has no range flags (0 in the model); 1.1 and 1.2 use range1. 260 // Ranges as the model should hold them: 1.0 has no range flags (0 in the model); 1.1 and 1.2 use range1.
228 const auto same_ranges = [&](const std::vector<DescriptorRange>& got, bool range_flags) { 261 const auto same_ranges = [&](const std::vector<DescriptorRange>& got, bool range_flags) {
229 if (got.size() != 2) return false; 262 if (got.size() != 2) return false;
@@ -242,19 +275,10 @@ int main() {
242 bool sampler_flags) { 275 bool sampler_flags) {
243 const bool range_flags = version != Version::V1_0; 276 const bool range_flags = version != Version::V1_0;
244 Blobs out; 277 Blobs out;
245 char what[160]; 278 if (!serialize_desc(d, out, name)) return;
246 const HRESULT result = D3D12SerializeVersionedRootSignature(&d, &out.blob, &out.error);
247 std::snprintf(what, sizeof(what), "%s: Microsoft serializer accepts it", name);
248 check(result == S_OK, what);
249 if (result != S_OK) {
250 if (out.error) std::printf("serializer error: %s\n", static_cast<const char*>(out.error->GetBufferPointer()));
251 return;
252 }
253 RootSignature got; 279 RootSignature got;
254 std::snprintf(what, sizeof(what), "%s: parses", name); 280 if (!parse_checked(out.blob, name, got)) return;
255 const bool parsed = parse_blob(out.blob, got); 281 char what[160];
256 check(parsed, what);
257 if (!parsed) return;
258 std::snprintf(what, sizeof(what), "%s: version, a two-range table, a root SRV and two samplers", name); 282 std::snprintf(what, sizeof(what), "%s: version, a two-range table, a root SRV and two samplers", name);
259 check(got.version == version && got.params.size() == 2 && got.params[0].type == ParamType::Table && 283 check(got.version == version && got.params.size() == 2 && got.params[0].type == ParamType::Table &&
260 got.params[0].ranges.size() == 2 && got.params[0].ranges[0].range_type == 0 && 284 got.params[0].ranges.size() == 2 && got.params[0].ranges[0].range_type == 0 &&
@@ -291,6 +315,300 @@ int main() {
291 v11.Desc_1_1 = {2, params1, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; 315 v11.Desc_1_1 = {2, params1, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE};
292 serialize(v11, Version::V1_1, "1.1 with static samplers", false); 316 serialize(v11, Version::V1_1, "1.1 with static samplers", false);
293 317
318 // An empty signature (no parameters, no samplers) is legal and is the shape of a bindless compute signature.
319 // It proves the header's count and offset words are believed when both are zero instead of being read as a
320 // truncated table, and the canonical codec has a model to keep.
321 D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty11{};
322 empty11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
323 empty11.Desc_1_1 = {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
324 {
325 Blobs out;
326 RootSignature got;
327 if (serialize_desc(empty11, out, "1.1 empty") && parse_checked(out.blob, "1.1 empty", got)) {
328 check_named(got.version == Version::V1_1 && got.params.empty() && got.static_samplers.empty() &&
329 got.flags == 0,
330 "1.1 empty", "version 1.1, no parameters, no samplers, flags 0");
331 const std::vector<uint8_t> bytes = encode_canonical(got);
332 const DecodeResult again = decode_canonical(bytes.data(), bytes.size());
333 check_named(again.ok && again.sig.params.empty() && again.sig.static_samplers.empty() &&
334 again.sig.flags == 0,
335 "1.1 empty", "canonical codec round-trips the empty model");
336 }
337 }
338
339 // Every root-signature flag that a signature with no parameters can legally carry, in one blob. A graphics
340 // signature sets ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT and a bindless one sets the heap-direct bits, so a parser
341 // that read the flags from the wrong header word would pick the other binding model without failing anywhere
342 // else. There are no parameters because the DENY_* bits are invalid next to a parameter any of those stages
343 // can see.
344 const uint32_t every_pc_flag =
345 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
346 D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS |
347 D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
348 D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
349 D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
350 D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS |
351 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT |
352 D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED |
353 D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
354 D3D12_VERSIONED_ROOT_SIGNATURE_DESC flagged11{};
355 flagged11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
356 flagged11.Desc_1_1 = {0, nullptr, 0, nullptr, static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(every_pc_flag)};
357 {
358 Blobs out;
359 RootSignature got;
360 if (serialize_desc(flagged11, out, "1.1 with every root-signature flag") &&
361 parse_checked(out.blob, "1.1 with every root-signature flag", got)) {
362 check_named(got.flags == every_pc_flag, "1.1 with every root-signature flag",
363 "the whole PC flag word round-trips (heap-direct bits included)");
364 const std::vector<uint8_t> bytes = encode_canonical(got);
365 const DecodeResult again = decode_canonical(bytes.data(), bytes.size());
366 check_named(again.ok && again.sig.flags == every_pc_flag, "1.1 with every root-signature flag",
367 "canonical codec keeps the flag word");
368 }
369 }
370
371 // A 1.0 signature with all three root view types and a table last. A root UAV opens most compute signatures,
372 // 1.0 root views have no flags dword, and the table last means its payload cannot be found by a fixed stride.
373 D3D12_DESCRIPTOR_RANGE view_range =
374 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 4, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND};
375 D3D12_ROOT_PARAMETER view_params[4]{};
376 view_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
377 view_params[0].Descriptor = {2, 3};
378 view_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
379 view_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
380 view_params[1].Descriptor = {5, 1};
381 view_params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
382 view_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
383 view_params[2].Descriptor = {7, 2};
384 view_params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
385 view_params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
386 view_params[3].DescriptorTable = {1, &view_range};
387 view_params[3].ShaderVisibility = D3D12_SHADER_VISIBILITY_GEOMETRY;
388 D3D12_VERSIONED_ROOT_SIGNATURE_DESC views10{};
389 views10.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
390 views10.Desc_1_0 = {4, view_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
391 {
392 Blobs out;
393 RootSignature got;
394 if (serialize_desc(views10, out, "1.0 root CBV, SRV and UAV with a table last") &&
395 parse_checked(out.blob, "1.0 root CBV, SRV and UAV with a table last", got)) {
396 check_named(got.params.size() == 4 &&
397 got.params[0].type == ParamType::Descriptor &&
398 got.params[0].descriptor_register == 2 && got.params[0].descriptor_space == 3 &&
399 uint32_t(got.params[0].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_ALL) &&
400 got.params[1].type == ParamType::Descriptor &&
401 got.params[1].descriptor_register == 5 && got.params[1].descriptor_space == 1 &&
402 uint32_t(got.params[1].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_VERTEX) &&
403 got.params[2].type == ParamType::Descriptor &&
404 got.params[2].descriptor_register == 7 && got.params[2].descriptor_space == 2 &&
405 uint32_t(got.params[2].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_PIXEL),
406 "1.0 root CBV, SRV and UAV with a table last",
407 "each root view type keeps its register, space and stage");
408 check_named(got.params.size() == 4 && got.params[3].type == ParamType::Table &&
409 uint32_t(got.params[3].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_GEOMETRY) &&
410 got.params[3].ranges.size() == 1 &&
411 got.params[3].ranges[0].range_type == 0 &&
412 got.params[3].ranges[0].num_descriptors == 4 &&
413 got.params[3].ranges[0].offset_in_table == kRangeOffsetAppend,
414 "1.0 root CBV, SRV and UAV with a table last",
415 "the table after three views keeps its range");
416 const PackResult packed_views = pack(got);
417 check_named(packed_views.ok && packed_views.dword_count == 8,
418 "1.0 root CBV, SRV and UAV with a table last",
419 "three views and a table use 8 user dwords in parameter order");
420 }
421 }
422
423 // 64 constants is the largest legal root-constant parameter and exactly fills the 64-dword D3D12 budget. It is
424 // legal D3D12 and impossible for the console's 32 user SGPRs, so the parse must recover all 64 and pack must
425 // refuse the signature by name instead of truncating every draw at 32.
426 D3D12_ROOT_PARAMETER1 huge_constants[1]{};
427 huge_constants[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
428 huge_constants[0].Constants = {0, 1, 64};
429 huge_constants[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
430 D3D12_VERSIONED_ROOT_SIGNATURE_DESC constants64{};
431 constants64.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
432 constants64.Desc_1_1 = {1, huge_constants, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
433 {
434 Blobs out;
435 RootSignature got;
436 if (serialize_desc(constants64, out, "1.1 with 64 root constants") &&
437 parse_checked(out.blob, "1.1 with 64 root constants", got)) {
438 check_named(got.params.size() == 1 && got.params[0].type == ParamType::Constants &&
439 got.params[0].num_values == 64 && got.params[0].shader_register == 0 &&
440 got.params[0].register_space == 1,
441 "1.1 with 64 root constants",
442 "all 64 constant dwords and the non-zero space survive");
443 const PackResult packed_huge = pack(got);
444 check_named(!packed_huge.ok && packed_huge.error.find("spill") != std::string::npos,
445 "1.1 with 64 root constants",
446 "pack refuses 64 constants as spill instead of truncating");
447 }
448 }
449
450 // All eight D3D12 shader-visibility values in one signature, with the constant registers in descending order.
451 // The existing cases only reach ALL, VERTEX and PIXEL; a game with amplification and mesh shaders binds root
452 // parameters to stages 6 and 7, which no oracle case had put through the serializer before.
453 const D3D12_SHADER_VISIBILITY stages[8] = {
454 D3D12_SHADER_VISIBILITY_ALL, D3D12_SHADER_VISIBILITY_VERTEX, D3D12_SHADER_VISIBILITY_HULL,
455 D3D12_SHADER_VISIBILITY_DOMAIN, D3D12_SHADER_VISIBILITY_GEOMETRY, D3D12_SHADER_VISIBILITY_PIXEL,
456 D3D12_SHADER_VISIBILITY_AMPLIFICATION, D3D12_SHADER_VISIBILITY_MESH};
457 D3D12_ROOT_PARAMETER1 staged_params[8]{};
458 for (int i = 0; i < 8; ++i) {
459 staged_params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
460 staged_params[i].Constants = {static_cast<UINT>(7 - i), 0, 1};
461 staged_params[i].ShaderVisibility = stages[i];
462 }
463 D3D12_VERSIONED_ROOT_SIGNATURE_DESC staged11{};
464 staged11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
465 staged11.Desc_1_1 = {8, staged_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
466 {
467 Blobs out;
468 RootSignature got;
469 if (serialize_desc(staged11, out, "1.1 with all eight visibilities") &&
470 parse_checked(out.blob, "1.1 with all eight visibilities", got)) {
471 bool stages_match = got.params.size() == 8;
472 for (uint32_t i = 0; stages_match && i < 8; ++i) {
473 stages_match = got.params[i].type == ParamType::Constants &&
474 got.params[i].num_values == 1 &&
475 got.params[i].shader_register == 7 - i &&
476 uint32_t(got.params[i].visibility) == uint32_t(stages[i]);
477 }
478 check_named(stages_match, "1.1 with all eight visibilities",
479 "every stage value keeps its parameter and the descending registers stay in order");
480 const PackResult packed_stages = pack(got);
481 check_named(packed_stages.ok && packed_stages.dword_count == 8,
482 "1.1 with all eight visibilities",
483 "eight single-dword constants pack in parameter order");
484 }
485 }
486
487 // Every descriptor range type, with an unbounded SRV range and a non-zero base register and space on each.
488 // Bindless signatures declare "all descriptors from here on" with NumDescriptors == UINT_MAX, and D3D12 forces
489 // sampler ranges into a table of their own (the serializer rejects a mixed table), so the signature carries two
490 // tables; a parser that treated UINT_MAX as an error or a signed count would lose the tail of every bindless
491 // table.
492 D3D12_DESCRIPTOR_RANGE1 resource_ranges[3] = {
493 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0xFFFFFFFFu, 0, 1,
494 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND},
495 {D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 2, 3, D3D12_DESCRIPTOR_RANGE_FLAG_NONE, 0},
496 {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 8, 1, 2,
497 static_cast<D3D12_DESCRIPTOR_RANGE_FLAGS>(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE |
498 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE),
499 16}};
500 D3D12_DESCRIPTOR_RANGE1 sampler_range = {
501 D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 4, 1, 4, D3D12_DESCRIPTOR_RANGE_FLAG_NONE,
502 D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND};
503 D3D12_ROOT_PARAMETER1 range_params[2]{};
504 range_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
505 range_params[0].DescriptorTable = {3, resource_ranges};
506 range_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
507 range_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
508 range_params[1].DescriptorTable = {1, &sampler_range};
509 range_params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
510 D3D12_VERSIONED_ROOT_SIGNATURE_DESC ranges11{};
511 ranges11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
512 ranges11.Desc_1_1 = {2, range_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
513 {
514 Blobs out;
515 RootSignature got;
516 if (serialize_desc(ranges11, out, "1.1 with all four range types") &&
517 parse_checked(out.blob, "1.1 with all four range types", got)) {
518 if (got.params.size() != 2 || got.params[0].ranges.size() != 3 ||
519 got.params[1].ranges.size() != 1) {
520 check_named(false, "1.1 with all four range types", "two tables: three resources, one sampler");
521 } else {
522 const std::vector<DescriptorRange>& ranges = got.params[0].ranges;
523 check_named(ranges[0].range_type == 0 && ranges[0].num_descriptors == 0xFFFFFFFFu &&
524 ranges[0].base_shader_register == 0 && ranges[0].register_space == 1 &&
525 ranges[0].flags == D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE &&
526 ranges[0].offset_in_table == kRangeOffsetAppend,
527 "1.1 with all four range types",
528 "unbounded SRV range keeps UINT_MAX, its space, flags and appended offset");
529 check_named(ranges[1].range_type == 2 && ranges[1].num_descriptors == 1 &&
530 ranges[1].base_shader_register == 2 && ranges[1].register_space == 3 &&
531 ranges[1].flags == 0 && ranges[1].offset_in_table == 0,
532 "1.1 with all four range types",
533 "CBV range keeps base 2 space 3 and an explicit table offset of 0");
534 check_named(ranges[2].range_type == 1 && ranges[2].num_descriptors == 8 &&
535 ranges[2].base_shader_register == 1 && ranges[2].register_space == 2 &&
536 ranges[2].flags ==
537 uint32_t(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE |
538 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE) &&
539 ranges[2].offset_in_table == 16,
540 "1.1 with all four range types",
541 "UAV range keeps the combined data and descriptor flags before offset 16");
542 check_named(got.params[1].ranges[0].range_type == 3 &&
543 got.params[1].ranges[0].num_descriptors == 4 &&
544 got.params[1].ranges[0].base_shader_register == 1 &&
545 got.params[1].ranges[0].register_space == 4 &&
546 got.params[1].ranges[0].offset_in_table == kRangeOffsetAppend,
547 "1.1 with all four range types",
548 "the sampler table keeps its own range, base register and space");
549 const std::vector<uint8_t> bytes = encode_canonical(got);
550 const DecodeResult again = decode_canonical(bytes.data(), bytes.size());
551 check_named(again.ok && again.sig.params.size() == 2 &&
552 again.sig.params[0].ranges.size() == 3 &&
553 again.sig.params[0].ranges[0].num_descriptors == 0xFFFFFFFFu &&
554 again.sig.params[0].ranges[2].flags ==
555 uint32_t(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE |
556 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE) &&
557 again.sig.params[1].ranges.size() == 1 &&
558 again.sig.params[1].ranges[0].range_type == 3,
559 "1.1 with all four range types",
560 "canonical codec keeps the unbounded count, the flags and the second table");
561 }
562 }
563 }
564
565 // A shadow sampler: comparison filter, MIRROR_ONCE addressing, a non-zero min LOD and GEOMETRY visibility. The
566 // existing samplers are anisotropic and point-clamp, so no comparison filter or MIRROR_ONCE value reached the
567 // parser; the single root constant beside it uses a non-zero register and space, which the first case cannot
568 // distinguish from a swapped register/space read.
569 D3D12_STATIC_SAMPLER_DESC1 shadow_sampler{};
570 shadow_sampler.Filter = D3D12_FILTER_COMPARISON_ANISOTROPIC;
571 shadow_sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE;
572 shadow_sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE;
573 shadow_sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE;
574 shadow_sampler.MipLODBias = 0.25f;
575 shadow_sampler.MaxAnisotropy = 16;
576 shadow_sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL;
577 shadow_sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
578 shadow_sampler.MinLOD = 0.5f;
579 shadow_sampler.MaxLOD = 12.0f;
580 shadow_sampler.ShaderRegister = 9;
581 shadow_sampler.RegisterSpace = 5;
582 shadow_sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_GEOMETRY;
583 const D3D12_STATIC_SAMPLER_DESC shadow_sampler0 = {
584 shadow_sampler.Filter, shadow_sampler.AddressU, shadow_sampler.AddressV, shadow_sampler.AddressW,
585 shadow_sampler.MipLODBias, shadow_sampler.MaxAnisotropy, shadow_sampler.ComparisonFunc,
586 shadow_sampler.BorderColor, shadow_sampler.MinLOD, shadow_sampler.MaxLOD, shadow_sampler.ShaderRegister,
587 shadow_sampler.RegisterSpace, shadow_sampler.ShaderVisibility};
588 D3D12_ROOT_PARAMETER1 shadow_params[1]{};
589 shadow_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
590 shadow_params[0].Constants = {3, 2, 1};
591 shadow_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
592 D3D12_VERSIONED_ROOT_SIGNATURE_DESC shadow11{};
593 shadow11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
594 shadow11.Desc_1_1 = {1, shadow_params, 1, &shadow_sampler0, D3D12_ROOT_SIGNATURE_FLAG_NONE};
595 {
596 Blobs out;
597 RootSignature got;
598 if (serialize_desc(shadow11, out, "1.1 with a comparison sampler") &&
599 parse_checked(out.blob, "1.1 with a comparison sampler", got)) {
600 check_named(got.params.size() == 1 && got.params[0].type == ParamType::Constants &&
601 got.params[0].num_values == 1 && got.params[0].shader_register == 3 &&
602 got.params[0].register_space == 2,
603 "1.1 with a comparison sampler",
604 "one constant at b3 space 2 keeps every field");
605 check_named(got.static_samplers.size() == 1 &&
606 same_sampler(got.static_samplers[0], shadow_sampler, false),
607 "1.1 with a comparison sampler",
608 "comparison filter, MIRROR_ONCE, GEOMETRY and every other sampler field round-trip");
609 }
610 }
611
294 // The 1.2 cases below need a host that serializes 1.2. Windows 10's built-in d3d12.dll stops at 1.1 and rejects 612 // The 1.2 cases below need a host that serializes 1.2. Windows 10's built-in d3d12.dll stops at 1.1 and rejects
295 // even an empty 1.2 description; their sampler flags have no 1.1 form, so they are skipped there. 613 // even an empty 1.2 description; their sampler flags have no 1.1 form, so they are skipped there.
296 D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty12{}; 614 D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty12{};
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index 85d7a2b6a..ba8b4f9e2 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -2,6 +2,7 @@
2// Huffman blocks, compressed from synthetic data with Python's zlib), the JSON reader, FSSM extraction from a 2// Huffman blocks, compressed from synthetic data with Python's zlib), the JSON reader, FSSM extraction from a
3// synthetic DXBC container, and index lookup by content hash. No game data. 3// synthetic DXBC container, and index lookup by content hash. No game data.
4#include "../src/shader_library.h" 4#include "../src/shader_library.h"
5#include "test_temp_dir.h"
5 6
6#include <cstdio> 7#include <cstdio>
7#include <filesystem> 8#include <filesystem>
@@ -343,7 +344,8 @@ int main() {
343 CHECK(fssm_program(container({{dynamic, 600}, {fixed, 25}})) == bytes("hello hello hello leonida")); 344 CHECK(fssm_program(container({{dynamic, 600}, {fixed, 25}})) == bytes("hello hello hello leonida"));
344 345
345 // An index with one findable shader, one without a hash, and the module next to it. 346 // An index with one findable shader, one without a hash, and the module next to it.
346 const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test"; 347 const testfiles::ScratchDir scratch("leonida_shader_library_test");
348 const auto& dir = scratch.path();
347 std::filesystem::create_directories(dir); 349 std::filesystem::create_directories(dir);
348 const std::string hash = sha256_hex(skewed(600)); 350 const std::string hash = sha256_hex(skewed(600));
349 const std::string hash2 = sha256_hex(bytes("another program")); 351 const std::string hash2 = sha256_hex(bytes("another program"));
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index b002201c9..ec9251dfa 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -16,8 +16,9 @@ are also what a shader reads through s_getpc_b64 (the code base) at that offset.
16The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this 16The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this
17doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container). 17doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container).
18The comment at the top of each .asm says which test program to run on the result and what it should print. 18The comment at the top of each .asm says which test program to run on the result and what it should print.
19With LEONIDA_FMA=khr (or glsl), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs 19With LEONIDA_FMA=khr (or glsl, or exact), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs
20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl. 20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77), --fma glsl, or --fma exact
21(a single rounding built from plain f32 ops, for a driver that splits GLSL Fma and has no VK_KHR_shader_fma).
21With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and 22With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and
22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). 23each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py).
23Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR 24Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR
@@ -164,7 +165,7 @@ def translate_tests(work, names):
164 cmd.append("--wave64-emulate") 165 cmd.append("--wave64-emulate")
165 if os.environ.get("LEONIDA_BARY_FALLBACK") == "1": # raw barycentrics without VK_KHR_fragment_shader_barycentric 166 if os.environ.get("LEONIDA_BARY_FALLBACK") == "1": # raw barycentrics without VK_KHR_fragment_shader_barycentric
166 cmd.append("--bary-fallback") 167 cmd.append("--bary-fallback")
167 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr"): # fused multiply-add as GLSL Fma (default) or OpFmaKHR 168 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma (default), OpFmaKHR, or emulated
168 cmd += ["--fma", os.environ["LEONIDA_FMA"]] 169 cmd += ["--fma", os.environ["LEONIDA_FMA"]]
169 if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": # f16 interpolation without PerVertexKHR (MoltenVK) 170 if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": # f16 interpolation without PerVertexKHR (MoltenVK)
170 cmd.append("--f16-interp-fallback") 171 cmd.append("--f16-interp-fallback")
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 330af9f4f..de286fa77 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -163,6 +163,8 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
163BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE]), 163BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE]),
164 ("cs_smem_bounds", [0, 0x5eed0010, 0x5eed000c, 0, 0x5eed000c, 0x5eed0010, 0, 0]), 164 ("cs_smem_bounds", [0, 0x5eed0010, 0x5eed000c, 0, 0x5eed000c, 0x5eed0010, 0, 0]),
165 ("cs_smem_stride_align", [0x5eed0010, 0, 0, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0004]), 165 ("cs_smem_stride_align", [0x5eed0010, 0, 0, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0004]),
166 # SHADER-328: a constant SGPR offset gives what the run-time one gives (no 32-bit wrap)
167 ("cs_smem_sconst_off", [0, 0x5eed0018, 0x5eed0018, 0x5eed0014]),
166 ("cs_smem_sload_neg", [0x5eed0004, 0x5eed0000, 0x5eed0004, 0x5eed0004, 0x5eed0008, 0x5eed000c, 168 ("cs_smem_sload_neg", [0x5eed0004, 0x5eed0000, 0x5eed0004, 0x5eed0004, 0x5eed0008, 0x5eed000c,
167 0xeeeeeeee, 0xeeeeeeee]), 169 0xeeeeeeee, 0xeeeeeeee]),
168 ("cs_buf_tail", [0, 0x5eed000c, 0x5eed0008, 0x5eed000c, 0, 0, 0x5eed0010, 0]), 170 ("cs_buf_tail", [0, 0x5eed000c, 0x5eed0008, 0x5eed000c, 0, 0, 0x5eed0010, 0]),
@@ -364,6 +366,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
364 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), 366 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000),
365 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) 367 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers)
366 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000), 368 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000),
369 # far branches: s_getpc/s_add|s_sub/s_addc|s_subb/s_setpc forward, backward loops, conditional (.asm header)
370 "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000b),
367 # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers) 371 # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers)
368 "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba), 372 "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba),
369 "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9), 373 "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9),
@@ -533,6 +537,19 @@ def run(*cmd, env=None):
533 return r.returncode, r.stdout + r.stderr 537 return r.returncode, r.stdout + r.stderr
534 538
535 539
540def run_readback(path, launch, *args, **kwargs):
541 """Require this invocation to write its framebuffer before comparing it."""
542 path = Path(path)
543 try:
544 path.unlink(missing_ok=True)
545 except OSError as err:
546 return 1, f"could not remove the previous readback {path.name}: {err}"
547 code, output = launch(*args, **kwargs)
548 if code == 0 and not path.is_file():
549 return 1, f"{output.rstrip()}\nmissing readback: {path.name}".lstrip()
550 return code, output
551
552
536def failure(code, output, lines): 553def failure(code, output, lines):
537 details = "\n".join(output.strip().splitlines()[-lines:]) 554 details = "\n".join(output.strip().splitlines()[-lines:])
538 return f"exit {code}: {details or 'no test output'}" 555 return f"exit {code}: {details or 'no test output'}"
@@ -643,11 +660,11 @@ def mesh_v5_test(tools, spirv, raw):
643 fs = Path(spirv) / "fs_passthru.spv" 660 fs = Path(spirv) / "fs_passthru.spv"
644 if not fs.is_file(): 661 if not fs.is_file():
645 return "missing fs_passthru.spv" 662 return "missing fs_passthru.spv"
646 code, out = run(os.path.join(tools, "vk_harness" + EXE), shader, fs, raw, "--mesh-group-readback", "2", "3", "4", 663 code, out = run_readback(raw, run, os.path.join(tools, "vk_harness" + EXE), shader, fs, raw,
647 env=mesh_env(spirv, "ms_v5_workgroup")) 664 "--mesh-group-readback", "2", "3", "4", env=mesh_env(spirv, "ms_v5_workgroup"))
648 if code == UNSUPPORTED: 665 if code == UNSUPPORTED:
649 return Skip("SKIP (mesh shading unavailable)") 666 return Skip("SKIP (mesh shading unavailable)")
650 if code or not raw.is_file(): 667 if code:
651 return failure(code, out, 3) 668 return failure(code, out, 3)
652 return check_mesh_v5(raw.read_bytes()) 669 return check_mesh_v5(raw.read_bytes())
653 670
@@ -688,7 +705,9 @@ def narrow_subgroup_skip(out):
688 705
689def unpinned_subgroup_skip(out): 706def unpinned_subgroup_skip(out):
690 """A Skip when vk_compute_test says the VKC_SUBGROUP_SIZE it was given can't be pinned on this device, else None. 707 """A Skip when vk_compute_test says the VKC_SUBGROUP_SIZE it was given can't be pinned on this device, else None.
691 Output without the line (an older vk_compute_test) is judged as before.""" 708 Output without the line (an older vk_compute_test) is judged as before. "compute subgroup size: 32 (observed: ...)"
709 (MoltenVK: not requirable, but its probe saw 32 lanes) is judged, and "observed wrong" comes with exit 1, a
710 failure."""
692 m = re.search(r"^compute subgroup size: (\d+) not available$", out, re.MULTILINE) 711 m = re.search(r"^compute subgroup size: (\d+) not available$", out, re.MULTILINE)
693 if m: 712 if m:
694 return Skip(f"SKIP (the device can't run this shader at {m.group(1)} lanes on request)") 713 return Skip(f"SKIP (the device can't run this shader at {m.group(1)} lanes on request)")
@@ -939,14 +958,17 @@ def bindless_test(tools, spirv, pixel="ps_tex"):
939# Samples with a16 coordinates after whole-VGPR arguments (gradients, a bias, a clamp). On the 8x8 gradient every 958# Samples with a16 coordinates after whole-VGPR arguments (gradients, a bias, a clamp). On the 8x8 gradient every
940# pixel must be the texel its own (u, v) reads. ps_texture_grad_cl_a16 draws on the two-mip texture instead, where its 959# pixel must be the texel its own (u, v) reads. ps_texture_grad_cl_a16 draws on the two-mip texture instead, where its
941# clamp picks mip 0 left of x = 32 and mip 1 from there on. 960# clamp picks mip 0 left of x = 32 and mip 1 from there on.
942GRADIENT_TESTS = ("ps_texture_grad_a16", "ps_texture_bias_a16", "ps_texture_grad_cl_a16") 961GRADIENT_TESTS = ("ps_texture_grad_a16", "ps_texture_bias_a16", "ps_texture_grad_cl_a16", "ps_texture_cl", "ps_texture_b_cl")
962# ps_texture_cl / ps_texture_b_cl (image_sample_cl / _b_cl) draw on the two-mip texture too: the left half reads mip 0 (red,
963# the top-left quadrant), the right half mip 1 (cyan) where the clamp is 1.
964CLAMP_TESTS = ("ps_texture_cl", "ps_texture_b_cl")
943 965
944 966
945def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_grad_a16") -> str: 967def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_grad_a16") -> str:
946 """Check every pixel of one of the GRADIENT_TESTS samples.""" 968 """Check every pixel of one of the GRADIENT_TESTS samples."""
947 vs = os.path.join(spirv, "vs_ids.spv") 969 vs = os.path.join(spirv, "vs_ids.spv")
948 fs = os.path.join(spirv, name + ".spv") 970 fs = os.path.join(spirv, name + ".spv")
949 two_mip = name == "ps_texture_grad_cl_a16" 971 two_mip = name == "ps_texture_grad_cl_a16" or name in CLAMP_TESTS
950 with tempfile.TemporaryDirectory(prefix="leonida-texture-") as tmp: 972 with tempfile.TemporaryDirectory(prefix="leonida-texture-") as tmp:
951 raw = Path(tmp) / "pixels.raw" 973 raw = Path(tmp) / "pixels.raw"
952 code, out = run(os.path.join(tools, "vk_texture_test" + EXE), vs, fs, raw, 974 code, out = run(os.path.join(tools, "vk_texture_test" + EXE), vs, fs, raw,
@@ -963,7 +985,9 @@ def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_gr
963 first = "" 985 first = ""
964 for index, pixel in enumerate(struct.iter_unpack("<4f", data)): 986 for index, pixel in enumerate(struct.iter_unpack("<4f", data)):
965 x, y = index % 64, index // 64 987 x, y = index % 64, index // 64
966 if two_mip: # mip 1 (cyan) where the clamp is 1, else mip 0's red and blue quadrants 988 if name in CLAMP_TESTS: # mip 1 (cyan) where the clamp is 1, else mip 0's top-left quadrant (red)
989 want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0)
990 elif two_mip: # mip 1 (cyan) where the clamp is 1, else mip 0's red and blue quadrants
967 want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) if y < 32 else (0.0, 0.0, 1.0, 1.0) 991 want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) if y < 32 else (0.0, 0.0, 1.0, 1.0)
968 else: 992 else:
969 want = (32 * (x // 8) / 255, 32 * (y // 8) / 255, 128 / 255, 1.0) 993 want = (32 * (x // 8) / 255, 32 * (y // 8) / 255, 128 / 255, 1.0)
diff --git a/runtime/test/shaders/cs_bvh.asm b/runtime/test/shaders/cs_bvh.asm
index 92caa125f..465816a6c 100644
--- a/runtime/test/shaders/cs_bvh.asm
+++ b/runtime/test/shaders/cs_bvh.asm
@@ -1,6 +1,8 @@
1; image_bvh64_intersect_ray emulation: vk_compute_test writes an AMD-format BVH into the heap (box32 root 0x100 -> triangle 1; image_bvh64_intersect_ray emulation: vk_compute_test writes an AMD-format BVH into the heap (box32 root 0x100 -> triangle
2; z=10 node 0x40, triangle z=5 node 0x48, missed box, NaN box). Ray (0.25,0.25,0) +z. Run: vk_compute_test cs_bvh.spv 1 bvh 2; z=10 node 0x40, triangle z=5 node 0x48, missed box, box 0x68 with a NaN min.x). Ray (0.25,0.25,0) +z. Run:
3; -> box result 0x48 0x40 0xffffffff 0xffffffff (sorted), triangle result -10 -1 -0.25 -0.25 (t = 10, bary 0.25/0.25). 3; vk_compute_test cs_bvh.spv 1 bvh
4; -> box result 0x68 0x48 0x40 0xffffffff (sorted; RDNA2 skips the NaN plane and enters box 0x68 at t = 0, SHADER-650),
5; triangle result -10 -1 -0.25 -0.25 (t = 10, bary 0.25/0.25).
4v_cmpx_eq_u32_e32 0, v0 6v_cmpx_eq_u32_e32 0, v0
5v_mov_b32_e32 v1, 0x25 7v_mov_b32_e32 v1, 0x25
6v_mov_b32_e32 v2, 0 8v_mov_b32_e32 v2, 0
diff --git a/runtime/test/shaders/cs_bvh32.asm b/runtime/test/shaders/cs_bvh32.asm
index c73f6cd9d..4fe0f78e0 100644
--- a/runtime/test/shaders/cs_bvh32.asm
+++ b/runtime/test/shaders/cs_bvh32.asm
@@ -2,13 +2,15 @@
2; is 11 dwords: node, ray extent (t max), origin xyz, direction xyz, inverse direction xyz. The 64-bit form has the 2; is 11 dwords: node, ray extent (t max), origin xyz, direction xyz, inverse direction xyz. The 64-bit form has the
3; node's high dword after the low one, so read with that layout every operand here would be one register off. 3; node's high dword after the low one, so read with that layout every operand here would be one register off.
4; Same scene and ray as cs_bvh.asm: vk_compute_test writes an AMD-format BVH into the heap (box32 root at 0x100 -> 4; Same scene and ray as cs_bvh.asm: vk_compute_test writes an AMD-format BVH into the heap (box32 root at 0x100 ->
5; triangle z=10 node 0x40, triangle z=5 node 0x48, a box the ray misses, a NaN box). Ray origin (0.25, 0.25, 0), 5; triangle z=10 node 0x40, triangle z=5 node 0x48, a box the ray misses, a box with a NaN min.x). Ray origin
6; direction +z, t max 100. Run: vk_compute_test cs_bvh32.spv 1 bvh 6; (0.25, 0.25, 0), direction +z, t max 100. Run: vk_compute_test cs_bvh32.spv 1 bvh
7; Expected, from the "Ray tracing" row of docs/design.md (one traversal step, RADV's software box and triangle tests): 7; Expected, from the "Ray tracing" row of docs/design.md (one traversal step; the box test as measured on RDNA2,
8; SHADER-650, and RADV's software triangle test):
8; box node 0x25 (address 0x100 >> 3 | type 5): along +z the ray enters a box that contains its x and y at the 9; box node 0x25 (address 0x100 >> 3 | type 5): along +z the ray enters a box that contains its x and y at the
9; box's near z, so child 0x40 (z = 10) at 10 and child 0x48 (z = 5) at 5. The third box lies at x in [5, 6], which 10; box's near z, so child 0x40 (z = 10) at 10 and child 0x48 (z = 5) at 5. The third box lies at x in [5, 6], which
10; the ray never reaches, and the fourth has a NaN corner: both give 0xffffffff. box_sort_enable (descriptor bit 63, 11; the ray never reaches: 0xffffffff. The fourth (0x68) has min.x = NaN; the hardware skips a NaN plane, so the box
11; set in s5) orders the children by entry distance: out[0..3] = 0x48 0x40 0xffffffff 0xffffffff. 12; is x <= 1, y and z in [0, 1], which the ray is in at t = 0. box_sort_enable (descriptor bit 63, set in s5) orders
13; the children by entry distance clamped to 0: out[0..3] = 0x68 0x48 0x40 0xffffffff (native gfx1030 gives the same).
12; triangle node 0x40 (address 0x200, vertices (0,0,10) (1,0,10) (0,1,10)): the ray runs along z, so the vertices 14; triangle node 0x40 (address 0x200, vertices (0,0,10) (1,0,10) (0,1,10)): the ray runs along z, so the vertices
13; relative to the origin project onto xy unsheared: A = (-0.25, -0.25), B = (0.75, -0.25), C = (-0.25, 0.75). The 15; relative to the origin project onto xy unsheared: A = (-0.25, -0.25), B = (0.75, -0.25), C = (-0.25, 0.75). The
14; edge functions are u = Cx By - Cy Bx = -0.5, v = Ax Cy - Ay Cx = -0.25 and w = Bx Ay - By Ax = -0.25, all of one 16; edge functions are u = Cx By - Cy Bx = -0.5, v = Ax Cy - Ay Cx = -0.25 and w = Bx Ay - By Ax = -0.25, all of one
diff --git a/runtime/test/shaders/cs_smem_sconst_off.asm b/runtime/test/shaders/cs_smem_sconst_off.asm
new file mode 100644
index 000000000..1da78df89
--- /dev/null
+++ b/runtime/test/shaders/cs_smem_sconst_off.asm
@@ -0,0 +1,47 @@
1; SHADER-328: an s_buffer_load SGPR offset the translator can see as a constant gives what the same offset gives at run
2; time. The rule (docs/design.md, Scalar/buffer memory): off = zext(soffset & ~3) + (imm & ~3) in 64 bits, and the
3; dword is 0 when off + 4 > limit. #1686 folded a constant soffset as a 32-bit sum, so 0xfffffffc + 20 wrapped to 16
4; and read data; gfx1036 (tools/hw_oracle, #1686) reads 0.
5; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X and byte 0x60 with
6; 4, then loads through a V# it builds itself (base 0x40, stride 0, NUM_RECORDS 0x40, word3 0x31016fac):
7; s_buffer_load_dword s24, s8=-4 offset:20 (constant) -> 0xfffffffc + 0x14 > 0x40: 0 (32-bit wrap: 0x5eed0010)
8; s_buffer_load_dword s25, s9=4 offset:20 (from heap 0x60) -> run time, in range: 0x5eed0018, as s26
9; s_buffer_load_dword s26, s10=4 offset:20 (constant) -> 0x18: 0x5eed0018
10; s_buffer_load_dword s27, s11=0x10 offset:4 (constant) -> 0x14: 0x5eed0014
11; and writes s24..s27 to out[0..3]. The run-time load stays in range: an out-of-range run-time sOFF (-4) made llvmpipe
12; (Mesa 26.0.8) do the guarded load anyway and segfault (#1938 review); the CPU tests cover that path.
13; Run: vk_compute_test cs_smem_sconst_off.spv 1 dump -> out[0..3] = 0x00000000 0x5eed0018 0x5eed0018 0x5eed0014.
14v_cmpx_eq_u32_e32 0, v0
15v_mov_b32 v1, 0x5eed0000
16v_mov_b32 v2, 0x5eed0004
17v_mov_b32 v3, 0x5eed0008
18v_mov_b32 v4, 0x5eed000c
19buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64
20v_mov_b32 v1, 0x5eed0010
21v_mov_b32 v2, 0x5eed0014
22v_mov_b32 v3, 0x5eed0018
23v_mov_b32 v4, 0x5eed001c
24buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80
25v_mov_b32 v5, 4
26buffer_store_dword v5, off, s[0:3], 0 offset:96
27s_waitcnt vmcnt(0)
28s_mov_b32 s4, 0x40
29s_mov_b32 s5, 0
30s_mov_b32 s6, 0x40
31s_mov_b32 s7, 0x31016fac
32s_mov_b32 s8, -4
33s_buffer_load_dword s9, s[0:3], 0x60
34s_mov_b32 s10, 4
35s_mov_b32 s11, 0x10
36s_waitcnt lgkmcnt(0)
37s_buffer_load_dword s24, s[4:7], s8 offset:0x14
38s_buffer_load_dword s25, s[4:7], s9 offset:0x14
39s_buffer_load_dword s26, s[4:7], s10 offset:0x14
40s_buffer_load_dword s27, s[4:7], s11 offset:0x4
41s_waitcnt lgkmcnt(0)
42v_mov_b32 v1, s24
43v_mov_b32 v2, s25
44v_mov_b32 v3, s26
45v_mov_b32 v4, s27
46buffer_store_dwordx4 v[1:4], off, s[0:3], 0
47s_endpgm
diff --git a/runtime/test/shaders/ps_far_branch.asm b/runtime/test/shaders/ps_far_branch.asm
new file mode 100644
index 000000000..15f807291
--- /dev/null
+++ b/runtime/test/shaders/ps_far_branch.asm
@@ -0,0 +1,321 @@
1; Far branches: the idiom s_getpc_b64 s[a:a+1]; s_add_u32 sa, sa, K; s_addc_u32 sa+1, sa+1, 0|-1; s_setpc_b64 s[a:a+1] (and the
2; s_sub_u32/s_subb_u32 form), which jumps beyond the +-32K dwords an s_branch reaches. docs/design.md "Far branches": the
3; translator folds the four instructions into one branch. RDNA2 ISA: S_GETPC_B64 returns the address of the next
4; instruction; S_ADD_U32 / S_ADDC_U32 add K to that 64-bit address (carry through SCC; the high word is 0 for a forward
5; K and 0xffffffff, as -1, with K = 2^32 - |K| for a backward one; S_SUB_U32 / S_SUBB_U32 subtract |K|); S_SETPC_B64
6; sets PC. K is in bytes from the instruction after s_getpc. The block between a far branch and its target holds
7; "poison" ORs that must never run, and 40 s_nop (4 bytes each, 160 bytes) so that K > 64 is a 32-bit literal.
8; Sizes (bytes): s_nop 4, s_or_b32 with an inline constant 4, with a literal 8, s_add_u32/s_sub_u32/s_cmp with a literal 8.
9; x (s10 = 1 to start): two forward far branches, one through s[4:5], one through s[8:9]:
10; K = add (8) + addc (4) + setpc (4) + poison s_or literal (8) + 40 nops (160) = 184 = 0xb8, landing on "s_or s10, 2";
11; the poison ORs 0x100 / 0x200 are skipped, the targets OR 2 and 4: x = 1 | 2 | 4 = 0x00000007.
12; y (s11 = 0): a backward loop with s_sub_u32 / s_subb_u32 (hi = 0). The body is s_add_u32 s11, 1 (4) + 40 nops (160) +
13; s_cmp_ge_u32 s11, 3 (4) + s_cbranch_scc1 (4) + s_getpc (4) = 176 bytes from the loop top to the instruction after
14; s_getpc, so K = 176 = 0xb0. The far branch back is taken after iterations 1 and 2 and not after iteration 3
15; (scc = 1 jumps over it), so s11 counts 3; then s_or s11, 0x10: y = 0x00000013.
16; z (s12 = 0): a backward loop with s_add_u32 K / s_addc_u32 -1, K = -180 = 0xffffff4c: body s_add_u32 s12, 0x10 (4) +
17; 40 nops (160) + s_cmp_ge_u32 s12, 0x50 (literal, 8) + s_cbranch_scc1 (4) + s_getpc (4) = 180. s12 steps by 0x10 and
18; the loop leaves when s12 >= 0x50, after 5 iterations (the far branch back taken 4 times): s12 = 0x50, then
19; s_or s12, 1: z = 0x00000051.
20; w (s13 = 0): a far forward branch behind a conditional branch that skips it (s_cbranch_scc0 over the 5 dwords of the
21; sequence), run twice. First scc = (s13 == 1) = 0: the sequence is skipped, the code after it runs: s13 |= 1, then
22; the target ORs 2 (K = 8+4+4 + 4 + 160 = 180 = 0xb4), s13 = 3. Second scc = (s13 == 3) = 1: the sequence runs, it
23; jumps over "s_or s13, 4" and the nops to the target: s13 |= 8: w = 0x0000000b.
24; A translation that folded a far branch to the wrong target runs a poison OR (x gains 0x300), repeats or skips a
25; loop iteration (y, z), or mishandles the conditional case (w). The loops count on s11/s12, so a wrong target shows
26; as a different count, not just a hang.
27; Expected mrt0 bits: 0x00000007, 0x00000013, 0x00000051, 0x0000000b
28s_mov_b32 s10, 1
29s_getpc_b64 s[4:5]
30s_add_u32 s4, s4, 184
31s_addc_u32 s5, s5, 0
32s_setpc_b64 s[4:5]
33s_or_b32 s10, s10, 0x100
34s_nop 0
35s_nop 0
36s_nop 0
37s_nop 0
38s_nop 0
39s_nop 0
40s_nop 0
41s_nop 0
42s_nop 0
43s_nop 0
44s_nop 0
45s_nop 0
46s_nop 0
47s_nop 0
48s_nop 0
49s_nop 0
50s_nop 0
51s_nop 0
52s_nop 0
53s_nop 0
54s_nop 0
55s_nop 0
56s_nop 0
57s_nop 0
58s_nop 0
59s_nop 0
60s_nop 0
61s_nop 0
62s_nop 0
63s_nop 0
64s_nop 0
65s_nop 0
66s_nop 0
67s_nop 0
68s_nop 0
69s_nop 0
70s_nop 0
71s_nop 0
72s_nop 0
73s_nop 0
74s_or_b32 s10, s10, 2
75s_getpc_b64 s[8:9]
76s_add_u32 s8, s8, 184
77s_addc_u32 s9, s9, 0
78s_setpc_b64 s[8:9]
79s_or_b32 s10, s10, 0x200
80s_nop 0
81s_nop 0
82s_nop 0
83s_nop 0
84s_nop 0
85s_nop 0
86s_nop 0
87s_nop 0
88s_nop 0
89s_nop 0
90s_nop 0
91s_nop 0
92s_nop 0
93s_nop 0
94s_nop 0
95s_nop 0
96s_nop 0
97s_nop 0
98s_nop 0
99s_nop 0
100s_nop 0
101s_nop 0
102s_nop 0
103s_nop 0
104s_nop 0
105s_nop 0
106s_nop 0
107s_nop 0
108s_nop 0
109s_nop 0
110s_nop 0
111s_nop 0
112s_nop 0
113s_nop 0
114s_nop 0
115s_nop 0
116s_nop 0
117s_nop 0
118s_nop 0
119s_nop 0
120s_or_b32 s10, s10, 4
121s_mov_b32 s11, 0
122s_add_u32 s11, s11, 1
123s_nop 0
124s_nop 0
125s_nop 0
126s_nop 0
127s_nop 0
128s_nop 0
129s_nop 0
130s_nop 0
131s_nop 0
132s_nop 0
133s_nop 0
134s_nop 0
135s_nop 0
136s_nop 0
137s_nop 0
138s_nop 0
139s_nop 0
140s_nop 0
141s_nop 0
142s_nop 0
143s_nop 0
144s_nop 0
145s_nop 0
146s_nop 0
147s_nop 0
148s_nop 0
149s_nop 0
150s_nop 0
151s_nop 0
152s_nop 0
153s_nop 0
154s_nop 0
155s_nop 0
156s_nop 0
157s_nop 0
158s_nop 0
159s_nop 0
160s_nop 0
161s_nop 0
162s_nop 0
163s_cmp_ge_u32 s11, 3
164s_cbranch_scc1 5
165s_getpc_b64 s[6:7]
166s_sub_u32 s6, s6, 176
167s_subb_u32 s7, s7, 0
168s_setpc_b64 s[6:7]
169s_or_b32 s11, s11, 0x10
170s_mov_b32 s12, 0
171s_add_u32 s12, s12, 0x10
172s_nop 0
173s_nop 0
174s_nop 0
175s_nop 0
176s_nop 0
177s_nop 0
178s_nop 0
179s_nop 0
180s_nop 0
181s_nop 0
182s_nop 0
183s_nop 0
184s_nop 0
185s_nop 0
186s_nop 0
187s_nop 0
188s_nop 0
189s_nop 0
190s_nop 0
191s_nop 0
192s_nop 0
193s_nop 0
194s_nop 0
195s_nop 0
196s_nop 0
197s_nop 0
198s_nop 0
199s_nop 0
200s_nop 0
201s_nop 0
202s_nop 0
203s_nop 0
204s_nop 0
205s_nop 0
206s_nop 0
207s_nop 0
208s_nop 0
209s_nop 0
210s_nop 0
211s_nop 0
212s_cmp_ge_u32 s12, 0x50
213s_cbranch_scc1 5
214s_getpc_b64 s[8:9]
215s_add_u32 s8, s8, 0xffffff4c
216s_addc_u32 s9, s9, -1
217s_setpc_b64 s[8:9]
218s_or_b32 s12, s12, 1
219s_mov_b32 s13, 0
220s_cmp_eq_u32 s13, 1
221s_cbranch_scc0 5
222s_getpc_b64 s[4:5]
223s_add_u32 s4, s4, 180
224s_addc_u32 s5, s5, 0
225s_setpc_b64 s[4:5]
226s_or_b32 s13, s13, 1
227s_nop 0
228s_nop 0
229s_nop 0
230s_nop 0
231s_nop 0
232s_nop 0
233s_nop 0
234s_nop 0
235s_nop 0
236s_nop 0
237s_nop 0
238s_nop 0
239s_nop 0
240s_nop 0
241s_nop 0
242s_nop 0
243s_nop 0
244s_nop 0
245s_nop 0
246s_nop 0
247s_nop 0
248s_nop 0
249s_nop 0
250s_nop 0
251s_nop 0
252s_nop 0
253s_nop 0
254s_nop 0
255s_nop 0
256s_nop 0
257s_nop 0
258s_nop 0
259s_nop 0
260s_nop 0
261s_nop 0
262s_nop 0
263s_nop 0
264s_nop 0
265s_nop 0
266s_nop 0
267s_or_b32 s13, s13, 2
268s_cmp_eq_u32 s13, 3
269s_cbranch_scc0 5
270s_getpc_b64 s[4:5]
271s_add_u32 s4, s4, 180
272s_addc_u32 s5, s5, 0
273s_setpc_b64 s[4:5]
274s_or_b32 s13, s13, 4
275s_nop 0
276s_nop 0
277s_nop 0
278s_nop 0
279s_nop 0
280s_nop 0
281s_nop 0
282s_nop 0
283s_nop 0
284s_nop 0
285s_nop 0
286s_nop 0
287s_nop 0
288s_nop 0
289s_nop 0
290s_nop 0
291s_nop 0
292s_nop 0
293s_nop 0
294s_nop 0
295s_nop 0
296s_nop 0
297s_nop 0
298s_nop 0
299s_nop 0
300s_nop 0
301s_nop 0
302s_nop 0
303s_nop 0
304s_nop 0
305s_nop 0
306s_nop 0
307s_nop 0
308s_nop 0
309s_nop 0
310s_nop 0
311s_nop 0
312s_nop 0
313s_nop 0
314s_nop 0
315s_or_b32 s13, s13, 8
316v_mov_b32_e32 v10, s10
317v_mov_b32_e32 v11, s11
318v_mov_b32_e32 v12, s12
319v_mov_b32_e32 v13, s13
320exp mrt0 v10, v11, v12, v13 done vm
321s_endpgm
diff --git a/runtime/test/shaders/ps_m2_literal.asm b/runtime/test/shaders/ps_m2_literal.asm
new file mode 100644
index 000000000..f77ef197f
--- /dev/null
+++ b/runtime/test/shaders/ps_m2_literal.asm
@@ -0,0 +1,21 @@
1; M2 literal sampler: ps_m2.asm with its S# built from immediates instead of loaded from the sampler table, as game
2; shaders do (docs/design.md, Literal samplers): CLAMP_LAST_TEXEL on all axes, bilinear min/mag, point mip, MAX_LOD
3; 12. No heap slot names this S#, so the layer registers it when a pipeline uses the shader; otherwise the shader's
4; hash lookup finds the fallback sampler. Run: d3d12_m2_textured_test.
5; s[0:1] = console VA of the SRV table's first slot (the T#). attr0.xy = (u, v). mrt0 = the sampled texel.
6; fssm-at: 0x10
7; fssm-data: 0x324d5350 0x4c544c20
8s_load_dwordx8 s[8:15], s[0:1], 0x0
9s_movk_i32 s16, 0x92
10s_mov_b32 s17, 0xc00000
11s_mov_b32 s18, 0x14500000
12s_mov_b32 s19, 0
13s_waitcnt lgkmcnt(0)
14v_interp_p1_f32_e32 v2, v0, attr0.x
15v_interp_p2_f32_e32 v2, v1, attr0.x
16v_interp_p1_f32_e32 v3, v0, attr0.y
17v_interp_p2_f32_e32 v3, v1, attr0.y
18image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
19s_waitcnt vmcnt(0)
20exp mrt0 v4, v5, v6, v7 done vm
21s_endpgm
diff --git a/runtime/test/shaders/ps_sample_c.asm b/runtime/test/shaders/ps_sample_c.asm
new file mode 100644
index 000000000..8d6616cdc
--- /dev/null
+++ b/runtime/test/shaders/ps_sample_c.asm
@@ -0,0 +1,25 @@
1; Depth-compare sampling with implicit LOD: image_sample_c of an 8x8 D32 texture whose texel x holds depth (x + 0.5) / 8,
2; reference 0.5 against a LESS_OR_EQUAL compare sampler (S# DEPTH_COMPARE_FUNC 3 at s[16:19]), at u, v from attr0 (a
3; pixel shader, so the LOD comes from the derivatives: OpImageSampleDrefImplicitLod). Address v[4:6] = (z-compare,
4; u, v). The same sample without and with d16; the d16 result (an f16 in the low half) is widened with v_cvt_f32_f16.
5; The one-level texture makes the LOD 0 whatever the derivatives. mrt0 = (f32 result, widened d16 result, u, v).
6; Run: vk_texture_test dref_c -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0
7v_interp_p1_f32_e32 v2, v0, attr0.x
8v_interp_p2_f32_e32 v2, v1, attr0.x
9v_interp_p1_f32_e32 v3, v0, attr0.y
10v_interp_p2_f32_e32 v3, v1, attr0.y
11v_mov_b32_e32 v4, 0.5
12v_mov_b32_e32 v5, v2
13v_mov_b32_e32 v6, v3
14s_load_dwordx8 s[8:15], s[0:1], 0x0
15s_waitcnt lgkmcnt(0)
16s_mov_b32 s16, 0x3092
17s_mov_b32 s17, 0xc00000
18s_mov_b32 s18, 0x14500000
19s_mov_b32 s19, 0
20image_sample_c v9, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
21image_sample_c v10, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16
22s_waitcnt vmcnt(0)
23v_cvt_f32_f16_e32 v11, v10
24exp mrt0 v9, v11, v2, v3 done vm
25s_endpgm
diff --git a/runtime/test/shaders/ps_sample_c_b.asm b/runtime/test/shaders/ps_sample_c_b.asm
new file mode 100644
index 000000000..ad86f20df
--- /dev/null
+++ b/runtime/test/shaders/ps_sample_c_b.asm
@@ -0,0 +1,25 @@
1; Depth-compare sampling with a LOD bias: image_sample_c_b, as ps_sample_c with the bias 1.0 in front of the z-compare
2; (address v[4:7] = bias, z-compare 0.5, u, v). A bias read as the reference (1.0 compares false everywhere) or the
3; reference as the bias would change every result; on the one-level texture the bias itself has no other effect.
4; mrt0 = (f32 result, widened d16 result, u, v).
5; Run: vk_texture_test dref_c_b -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0
6v_interp_p1_f32_e32 v2, v0, attr0.x
7v_interp_p2_f32_e32 v2, v1, attr0.x
8v_interp_p1_f32_e32 v3, v0, attr0.y
9v_interp_p2_f32_e32 v3, v1, attr0.y
10v_mov_b32_e32 v4, 1.0
11v_mov_b32_e32 v5, 0.5
12v_mov_b32_e32 v6, v2
13v_mov_b32_e32 v7, v3
14s_load_dwordx8 s[8:15], s[0:1], 0x0
15s_waitcnt lgkmcnt(0)
16s_mov_b32 s16, 0x3092
17s_mov_b32 s17, 0xc00000
18s_mov_b32 s18, 0x14500000
19s_mov_b32 s19, 0
20image_sample_c_b v9, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
21image_sample_c_b v10, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16
22s_waitcnt vmcnt(0)
23v_cvt_f32_f16_e32 v11, v10
24exp mrt0 v9, v11, v2, v3 done vm
25s_endpgm
diff --git a/runtime/test/shaders/ps_texture_b_cl.asm b/runtime/test/shaders/ps_texture_b_cl.asm
new file mode 100644
index 000000000..ba8970667
--- /dev/null
+++ b/runtime/test/shaders/ps_texture_b_cl.asm
@@ -0,0 +1,23 @@
1; image_sample_b_cl: as ps_texture_cl with a LOD bias of 0.0 in front of the coordinates (address v[3:6] = bias,
2; u / 4, v / 4, clamp), so the bias and the clamp each have to come from their own VGPR. Left half mip 0 (red), right
3; half mip 1 (cyan). A bias read from the clamp's register (1.0) would still give cyan on the right but also move the
4; left half to mip 1; the clamp read as the bias would never clamp.
5v_interp_p1_f32_e32 v2, v0, attr0.x
6v_interp_p2_f32_e32 v2, v1, attr0.x
7v_interp_p1_f32_e32 v3, v0, attr0.y
8v_interp_p2_f32_e32 v3, v1, attr0.y
9s_load_dwordx8 s[8:15], s[0:1], 0x0
10s_waitcnt lgkmcnt(0)
11s_mov_b32 s16, 0x92
12s_mov_b32 s17, 0xc00000
13s_mov_b32 s18, 0x14500000
14s_mov_b32 s19, 0
15v_cmp_le_f32_e32 vcc_lo, 0.5, v2
16v_mul_f32_e32 v4, 0.25, v2
17v_mul_f32_e32 v5, 0.25, v3
18v_mov_b32_e32 v3, 0
19v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo
20image_sample_b_cl v[8:11], v[3:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
21s_waitcnt vmcnt(0)
22exp mrt0 v8, v9, v10, v11 done vm
23s_endpgm
diff --git a/runtime/test/shaders/ps_texture_cl.asm b/runtime/test/shaders/ps_texture_cl.asm
new file mode 100644
index 000000000..932427c9d
--- /dev/null
+++ b/runtime/test/shaders/ps_texture_cl.asm
@@ -0,0 +1,23 @@
1; image_sample_cl on vk_texture_test's two-mip texture (--two-mip: 128x128 quadrants, solid cyan mip 1) drawn on 64x64:
2; the coordinates are u / 4, v / 4, so the unclamped LOD is -1 (mip 0, the top-left quadrant, red). The min-LOD clamp
3; after the coordinates is 0.0 left of x = 32 and 1.0 from there on: the left half must read mip 0 (red), the right half
4; mip 1 (cyan). A clamp read from the wrong register, or ignored, makes the right half red too.
5; Address v[4:6] = (u / 4, v / 4, clamp); MinLod on an implicit-LOD sample (OpImageSampleImplicitLod ... MinLod).
6v_interp_p1_f32_e32 v2, v0, attr0.x
7v_interp_p2_f32_e32 v2, v1, attr0.x
8v_interp_p1_f32_e32 v3, v0, attr0.y
9v_interp_p2_f32_e32 v3, v1, attr0.y
10s_load_dwordx8 s[8:15], s[0:1], 0x0
11s_waitcnt lgkmcnt(0)
12s_mov_b32 s16, 0x92
13s_mov_b32 s17, 0xc00000
14s_mov_b32 s18, 0x14500000
15s_mov_b32 s19, 0
16v_cmp_le_f32_e32 vcc_lo, 0.5, v2
17v_mul_f32_e32 v4, 0.25, v2
18v_mul_f32_e32 v5, 0.25, v3
19v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo
20image_sample_cl v[8:11], v[4:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
21s_waitcnt vmcnt(0)
22exp mrt0 v8, v9, v10, v11 done vm
23s_endpgm
diff --git a/runtime/test/shaders/ps_w64_a_discard.asm b/runtime/test/shaders/ps_w64_a_discard.asm
new file mode 100644
index 000000000..b8f4c16a5
--- /dev/null
+++ b/runtime/test/shaders/ps_w64_a_discard.asm
@@ -0,0 +1,65 @@
1; SHADER-10 tier A (docs/design.md, "Wave64 graphics: partition invariance"): the early exit of a pixel kill. A wave64
2; pixel shader whose 32-lane halves can lose every pixel while the other half lives on gives the same image when its
3; 64 lanes are cut into two 32-lane subgroups. x = floor(u * 64), y = floor(v * 64) are the pixel's coordinates on
4; the 64x64 target (u, v = attr0.xy of vs_ids), so every expected word is a function of (x, y) and not of the lane
5; the pixel landed on.
6; Three kills, each `s_andn2_b64 live, live, <kill mask>` then `s_cbranch_scc0` to its own exit block, which only
7; sets EXEC from the (empty) live mask, exports null with done vm and ends (an exit shared by several kills reads a
8; mask redefined behind the earlier votes: tier C tainted-exec, a stale scalar). The run side narrows EXEC into the
9; whole quads of the live mask (s_wqm_b64, s_and_b64 exec) and never widens it.
10; (1) x < 30, through v_cmpx (EXEC = the pixels to kill); (2) y >= 50, through VCC; (3) x % 4 == 3 and y odd
11; ((y & 1) * 4 + (x & 3) == 7), through VCC.
12; The first two discard large regions: whole waves and, at x = 30 and y = 50, halves whose pixels are all dead
13; next to halves that live (for a wave tiled as 8x8 cut into 8x4 or 4x8 halves, among others).
14; Before the export EXEC is narrowed to the live mask itself, so the helper lanes of the quads are discarded.
15; Live pixel: r0 = 7 * y + x, r1 = 1, r2 = 2000 + y, r3 = x % 4 + 1. A discarded pixel keeps the harness clear
16; value, -1.0f in every word (0xbf800000).
17; Run: vk_harness vs_ids.spv ps_w64_a_discard.spv out.raw, once with VKH_SUBGROUP_SIZE=64 and once with 32: the two
18; images must be equal (and equal to the expected words). Output is raw bits (r0, r1, r2, r3) per pixel.
19; mattr: +wavefrontsize64,-wavefrontsize32
20v_interp_p1_f32_e32 v2, v0, attr0.x
21v_interp_p2_f32_e32 v2, v1, attr0.x
22v_interp_p1_f32_e32 v3, v0, attr0.y
23v_interp_p2_f32_e32 v3, v1, attr0.y
24v_mul_f32_e32 v2, 0x42800000, v2
25v_mul_f32_e32 v3, 0x42800000, v3
26v_cvt_u32_f32_e32 v2, v2
27v_cvt_u32_f32_e32 v3, v3
28s_mov_b64 s[10:11], exec
29s_mov_b64 s[20:21], exec
30v_cmpx_gt_u32_e32 30, v2
31s_andn2_b64 s[20:21], s[20:21], exec
32s_cbranch_scc0 34
33s_wqm_b64 s[22:23], s[20:21]
34s_and_b64 exec, s[10:11], s[22:23]
35v_cmp_lt_u32_e32 vcc, 49, v3
36s_andn2_b64 s[20:21], s[20:21], vcc
37s_cbranch_scc0 25
38s_wqm_b64 s[22:23], s[20:21]
39s_and_b64 exec, exec, s[22:23]
40v_and_b32_e32 v4, 3, v2
41v_and_b32_e32 v5, 1, v3
42v_lshlrev_b32_e32 v5, 2, v5
43v_add_nc_u32_e32 v5, v5, v4
44v_cmp_eq_u32_e32 vcc, 7, v5
45s_andn2_b64 s[20:21], s[20:21], vcc
46s_cbranch_scc0 12
47s_wqm_b64 s[22:23], s[20:21]
48s_and_b64 exec, exec, s[22:23]
49v_mul_u32_u24_e32 v6, 7, v3
50v_add_nc_u32_e32 v6, v6, v2
51v_mov_b32_e32 v7, 1
52v_add_nc_u32_e32 v8, 0x7d0, v3
53v_add_nc_u32_e32 v9, 1, v4
54s_and_b64 exec, exec, s[20:21]
55exp mrt0 v6, v7, v8, v9 done vm
56s_endpgm
57s_mov_b64 exec, s[20:21]
58exp null off, off, off, off done vm
59s_endpgm
60s_mov_b64 exec, s[20:21]
61exp null off, off, off, off done vm
62s_endpgm
63s_mov_b64 exec, s[20:21]
64exp null off, off, off, off done vm
65s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index cea4f29c0..64aa532b7 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -63,6 +63,16 @@ def _a_skip(i):
63 return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 < 2), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1) 63 return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 < 2), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1)
64 64
65 65
66CLEAR = 0xBF800000 # the harness clears the target to -1.0f: the words of a pixel no shader wrote
67
68
69def _a_discard(i):
70 x, y = _x(i), _y(i)
71 if x < 30 or y >= 50 or (x % 4 == 3 and y % 2 == 1):
72 return (CLEAR,) * 4
73 return (7 * y + x, 1, 2000 + y, x % 4 + 1)
74
75
66def _b_waterfall(i): 76def _b_waterfall(i):
67 x, y = _x(i), _y(i) 77 x, y = _x(i), _y(i)
68 a = x % 4 + 4 * (y % 4) 78 a = x % 4 + 4 * (y % 4)
@@ -169,6 +179,7 @@ FIXTURES = {
169 "ps_w64_a_permlane": ("A", _a_permlane, {}), 179 "ps_w64_a_permlane": ("A", _a_permlane, {}),
170 "ps_w64_a_swizzle": ("A", _a_swizzle, {}), 180 "ps_w64_a_swizzle": ("A", _a_swizzle, {}),
171 "ps_w64_a_bpermute": ("A", _a_bpermute, {}), 181 "ps_w64_a_bpermute": ("A", _a_bpermute, {}),
182 "ps_w64_a_discard": ("A", _a_discard, {}),
172 "ps_w64_b_waterfall": ("B", _b_waterfall, {}), 183 "ps_w64_b_waterfall": ("B", _b_waterfall, {}),
173 "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}), 184 "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}),
174 "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}), 185 "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}),
diff --git a/runtime/test/test_runtime_types.cpp b/runtime/test/test_runtime_types.cpp
index 1a0b5ed2a..a71deb000 100644
--- a/runtime/test/test_runtime_types.cpp
+++ b/runtime/test/test_runtime_types.cpp
@@ -525,18 +525,27 @@ void test_xmem_working_set_statistics_abi_layout() {
525 check(ok != FALSE && pmc.WorkingSetSize > 0, 525 check(ok != FALSE && pmc.WorkingSetSize > 0,
526 "GetProcessMemoryInfo succeeds and returns non-zero WorkingSetSize"); 526 "GetProcessMemoryInfo succeeds and returns non-zero WorkingSetSize");
527 527
528 // Verify FidelityFX / XMem layout contract: 528 // Verify FidelityFX / XMem layout contract (RT-220):
529 // stats[0..7] = 0 (unknown/reserved), stats[8..15] = WorkingSetSize (uint64_t) 529 // The measured FSR sites establish argument shape, kind and the +8 working-set read; +0's title-total memory
530 // limit is inferred from other Series implementations (xcl, xbox-emulator).
531 // stats[0..7] = TotalMemoryLimit (uint64_t), stats[8..15] = WorkingSetSize (uint64_t)
530 alignas(64) uint8_t stats[64]; 532 alignas(64) uint8_t stats[64];
531 std::memset(stats, 0xA5, sizeof(stats)); 533 std::memset(stats, 0xA5, sizeof(stats));
532 534
533 std::memset(stats, 0, 16); 535 std::memset(stats, 0, 16);
536 MEMORYSTATUSEX ms{sizeof(ms)};
537 uint64_t total_memory = 12ULL * 1024 * 1024 * 1024;
538 if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) {
539 total_memory = ms.ullTotalPhys;
540 }
541 std::memcpy(stats + 0, &total_memory, sizeof(total_memory));
534 const uint64_t working_set = static_cast<uint64_t>(pmc.WorkingSetSize); 542 const uint64_t working_set = static_cast<uint64_t>(pmc.WorkingSetSize);
535 std::memcpy(stats + 8, &working_set, sizeof(working_set)); 543 std::memcpy(stats + 8, &working_set, sizeof(working_set));
536 544
537 uint64_t prefix0 = 0; 545 uint64_t prefix0 = 0;
538 std::memcpy(&prefix0, stats, sizeof(prefix0)); 546 std::memcpy(&prefix0, stats, sizeof(prefix0));
539 check(prefix0 == 0, "Working set statistics prefix at +0 is 0"); 547 check(prefix0 == total_memory && prefix0 >= working_set,
548 "Working set statistics total memory at +0 holds title memory limit >= working set");
540 549
541 uint64_t extracted_ws = 0; 550 uint64_t extracted_ws = 0;
542 std::memcpy(&extracted_ws, stats + 8, sizeof(extracted_ws)); 551 std::memcpy(&extracted_ws, stats + 8, sizeof(extracted_ws));
diff --git a/runtime/test/test_temp_dir.h b/runtime/test/test_temp_dir.h
new file mode 100644
index 000000000..3601f35d0
--- /dev/null
+++ b/runtime/test/test_temp_dir.h
@@ -0,0 +1,67 @@
1// Scratch folders for tests that write files (a translator-style shader library, an index) under the temp directory.
2//
3// The folder name carries the process id. Under one fixed name, every copy of a test running at the same time (ctest
4// -j, or two suites sharing one Wine prefix or one TMPDIR) used the same folder, and one copy's remove_all deleted the
5// modules another copy was still loading: with four copies of d3d12_compute at once, 6 of 40 runs failed at PSO
6// creation or in copy_file, while 125 runs one at a time all passed (Apple M3 Max, MoltenVK 1.4.3 under Wine 11).
7#pragma once
8
9#include <cstdio>
10#include <filesystem>
11#include <string>
12#include <string_view>
13#include <system_error>
14
15#ifdef _WIN32
16#include <process.h>
17#else
18#include <unistd.h>
19#endif
20
21namespace testfiles {
22
23// <temp>/<name>_<pid>: a folder no other running process uses.
24inline std::filesystem::path process_temp_dir(std::string_view name) {
25#ifdef _WIN32
26 const long pid = long(_getpid());
27#else
28 const long pid = long(getpid());
29#endif
30 return std::filesystem::temp_directory_path() / (std::string(name) + "_" + std::to_string(pid));
31}
32
33// process_temp_dir(name), emptied and created on construction (a crashed run may have left the same name behind) and
34// removed with its contents on destruction, so early returns don't leave one folder per failed run.
35class ScratchDir {
36public:
37 explicit ScratchDir(std::string_view name) : path_(process_temp_dir(name)) {
38 std::error_code ec;
39 std::filesystem::remove_all(path_, ec);
40 std::filesystem::create_directories(path_, ec);
41 if (ec) std::fprintf(stderr, "cannot create %s: %s\n", path_.string().c_str(), ec.message().c_str());
42 }
43 ~ScratchDir() {
44 std::error_code ec;
45 std::filesystem::remove_all(path_, ec);
46 }
47 ScratchDir(const ScratchDir&) = delete;
48 ScratchDir& operator=(const ScratchDir&) = delete;
49
50 const std::filesystem::path& path() const { return path_; }
51
52private:
53 std::filesystem::path path_;
54};
55
56// Copies `from` (a file the build compiled into the test, LEONIDA_TEST_*_SPV) to `to`, overwriting it. Returns false
57// and says why when it can't: std::filesystem::copy_file would throw instead, and the uncaught exception ends the
58// test without a message (abort; exit code 3 under Wine), which reads as a crash rather than a missing file.
59inline bool copy_file(const std::filesystem::path& from, const std::filesystem::path& to) {
60 std::error_code ec;
61 std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
62 if (ec) std::fprintf(stderr, "cannot copy %s to %s: %s\n", from.string().c_str(), to.string().c_str(),
63 ec.message().c_str());
64 return !ec;
65}
66
67} // namespace testfiles
diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp
index cf32f094b..9769e70be 100644
--- a/runtime/test/vk_command_replay_test.cpp
+++ b/runtime/test/vk_command_replay_test.cpp
@@ -7,7 +7,8 @@
7// Part F (D3D-26) runs immediate buffer writes, atomic copies and discards. Part G copies one subresource twice in one 7// Part F (D3D-26) runs immediate buffer writes, atomic copies and discards. Part G copies one subresource twice in one
8// list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour 8// list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour
9// and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth 9// and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth
10// rectangle (MIN) and checks that the texels around it keep their values. 10// rectangle (MIN) and checks that the texels around it keep their values. Part J copies between disjoint regions
11// of one texture subresource.
11// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. 12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test.
12#include "vk_test_device.h" 13#include "vk_test_device.h"
13#include "../src/vulkan_replay.h" 14#include "../src/vulkan_replay.h"
@@ -1188,6 +1189,82 @@ int part_i(vktest::Device& d) {
1188 return 0; 1189 return 0;
1189} 1190}
1190 1191
1192int part_j(vktest::Device& d) {
1193 constexpr std::uint32_t width = 4, height = 2, pitch = texture_data_pitch_alignment;
1194 constexpr VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
1195 const VkImage image = d.image(format, width, height, 1, 0);
1196 void* upload_data = nullptr;
1197 const VkBuffer upload = d.buffer(pitch * height, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &upload_data);
1198 void* readback_data = nullptr;
1199 const VkBuffer readback = d.buffer(width * height * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback_data);
1200 EXPECT(image && upload && readback);
1201 for (std::uint32_t y = 0; y < height; ++y)
1202 std::memcpy(static_cast<std::uint8_t*>(upload_data) + pitch * y, (y ? green : red).data(), 4);
1203
1204 constexpr ResourceId image_id = 40, upload_id = 41;
1205 ResourceBinding image_binding{}, upload_binding{};
1206 image_binding.image = image;
1207 image_binding.format = format;
1208 image_binding.width = width;
1209 image_binding.height = height;
1210 upload_binding.buffer = upload;
1211 upload_binding.size = pitch * height;
1212 const auto resolve = [&](ResourceId id) -> const ResourceBinding* {
1213 if (id == image_id) return &image_binding;
1214 if (id == upload_id) return &upload_binding;
1215 return nullptr;
1216 };
1217 LayoutTracker tracker;
1218 tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_UNDEFINED);
1219 ReplayFunctions vk{};
1220 vk.pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
1221 vk.pipeline_barrier2 = d.fn<PFN_vkCmdPipelineBarrier2>("vkCmdPipelineBarrier2");
1222 vk.clear_color_image = d.fn<PFN_vkCmdClearColorImage>("vkCmdClearColorImage");
1223 vk.copy_buffer = d.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
1224 vk.copy_image_to_buffer = d.fn<PFN_vkCmdCopyImageToBuffer>("vkCmdCopyImageToBuffer");
1225 vk.copy_buffer_to_image = d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage");
1226 vk.copy_image = d.fn<PFN_vkCmdCopyImage>("vkCmdCopyImage");
1227
1228 namespace a = d3d12_access;
1229 namespace l = d3d12_layout;
1230 namespace y = d3d12_sync;
1231 const CopyLocation texture{image_id, false, 0, 0, 0, 0, 0, 0};
1232 const CopyLocation footprint{upload_id, true, 0, 0, 1, height, 1, pitch};
1233 const CopyBox column{0, 0, 0, 1, height, 1};
1234 const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0};
1235 CommandList first;
1236 EXPECT(first.copy_texture({texture, 2, 0, 0, texture, true, column}));
1237 EXPECT(first.close());
1238 CommandList list;
1239 EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_dest,
1240 l::common, l::copy_dest, image_id, all, 0}));
1241 EXPECT(list.copy_texture({texture, 0, 0, 0, footprint, false, {}}));
1242 EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source | a::copy_dest,
1243 l::copy_dest, l::common, image_id, all, 0}));
1244 EXPECT(list.copy_texture({texture, 1, 0, 0, texture, true, column})); // touching edges, not overlapping
1245 EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source,
1246 l::common, l::copy_source, image_id, all, 0}));
1247 EXPECT(list.close());
1248 CommandList overlap;
1249 EXPECT(overlap.copy_texture({texture, 1, 0, 0, texture, true, {0, 0, 0, 2, height, 1}}));
1250 EXPECT(overlap.close());
1251 EXPECT(d.run([&](VkCommandBuffer cb) {
1252 if (replay(overlap, cb, resolve, vk, &tracker) != ReplayResult::invalid_copy) return false;
1253 if (replay(first, cb, resolve, vk, &tracker) != ReplayResult::success ||
1254 tracker.layout(image_id, 0) != VK_IMAGE_LAYOUT_GENERAL) return false;
1255 if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false;
1256 d.read_back(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, width, height, 1,
1257 readback, 0);
1258 return true;
1259 }));
1260 const auto* pixels = static_cast<const std::uint8_t*>(readback_data);
1261 for (std::uint32_t y = 0; y < height; ++y)
1262 for (std::uint32_t x = 0; x < width; ++x)
1263 expect_rgba("J self-copy", pixels, y * width + x, x < 2 ? (y ? green : red) : Rgba{});
1264 std::printf("J: disjoint same-subresource copies, overlapping copy rejected\n");
1265 return 0;
1266}
1267
1191} // namespace 1268} // namespace
1192 1269
1193int main() { 1270int main() {
@@ -1199,7 +1276,7 @@ int main() {
1199 } 1276 }
1200 EXPECT(status == vktest::DeviceStatus::ready); 1277 EXPECT(status == vktest::DeviceStatus::ready);
1201 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || 1278 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) ||
1202 part_g(device) || part_h(device) || part_i(device)) 1279 part_g(device) || part_h(device) || part_i(device) || part_j(device))
1203 return 1; 1280 return 1;
1204 if (g_mismatches) return 1; 1281 if (g_mismatches) return 1;
1205 if (device.validation_errors()) { 1282 if (device.validation_errors()) {
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp
index 69e3bd014..f962cdff6 100644
--- a/runtime/test/vk_compute_test.cpp
+++ b/runtime/test/vk_compute_test.cpp
@@ -11,6 +11,11 @@
11// and before the dispatch, so a program can read prepared inputs (a root table, descriptors, data) from the heap. 11// and before the dispatch, so a program can read prepared inputs (a root table, descriptors, data) from the heap.
12// The file must fit in the buffer (raise VKC_OUT_WORDS); bytes past it keep the fill. 12// The file must fit in the buffer (raise VKC_OUT_WORDS); bytes past it keep the fill.
13// --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77. 13// --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77.
14// VKC_SUBGROUP_SIZE=N (env): run at N lanes. Where the device can't require a compute subgroup size but N is its
15// default subgroupSize (MoltenVK: 32, and requiredSubgroupSizeStages 0), the size is still fixed for a SPIR-V 1.5
16// module (no varying subgroup size); cs_wave_probe.comp then checks, with the test's local size and flags, that every
17// subgroup is N lanes wide (by its lane numbers and a ballot), or the test fails (exit 1) without running; N-lane
18// subgroups not in invocation order print "not available", as a size that can't be pinned does.
14// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#, 19// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#,
15// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS. 20// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS.
16// Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes). 21// Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes).
@@ -20,6 +25,7 @@
20#include "vk_device_pick.h" 25#include "vk_device_pick.h"
21#include "vk_shader_fma.h" 26#include "vk_shader_fma.h"
22#include "vk_pc_tail.h" 27#include "vk_pc_tail.h"
28#include "cs_wave_probe_spv.h"
23 29
24#include <cctype> 30#include <cctype>
25#include <cmath> 31#include <cmath>
@@ -54,6 +60,37 @@ static bool parse_u32(const char*& s, uint32_t& v) {
54 return true; 60 return true;
55} 61}
56 62
63// The module's SPIR-V version and the OpExecutionMode LocalSize of its GLCompute entry point "main", the one the
64// pipeline is made from. All zero when there is none (no such entry point, or LocalSizeId), and then the size is
65// unknown: nothing that needs it (the subgroup probe, full subgroups) is done.
66static uint32_t spirv_local_size(const std::vector<char>& code, uint32_t local[3]) {
67 local[0] = local[1] = local[2] = 0;
68 const std::size_t n = code.size() / 4;
69 std::vector<uint32_t> w(n);
70 if (n) std::memcpy(w.data(), code.data(), n * 4);
71 if (n < 5 || w[0] != 0x07230203u) return 0;
72 constexpr uint32_t kOpEntryPoint = 15, kOpExecutionMode = 16, kGLCompute = 5, kLocalSize = 17;
73 uint32_t main_id = 0;
74 bool have_main = false;
75 for (std::size_t i = 5; i < n;) {
76 const uint32_t len = w[i] >> 16, op = w[i] & 0xFFFFu;
77 if (!len || i + len > n) break;
78 // OpEntryPoint model id "name" ...: the name is a nul-terminated string packed little-endian into words.
79 if (op == kOpEntryPoint && len >= 4 && w[i + 1] == kGLCompute) {
80 const char* name = reinterpret_cast<const char*>(&w[i + 3]);
81 if (std::strncmp(name, "main", 4 * (len - 3)) == 0 && std::memchr(name, 0, 4 * (len - 3))) {
82 main_id = w[i + 2];
83 have_main = true;
84 }
85 }
86 if (op == kOpExecutionMode && len == 6 && have_main && w[i + 1] == main_id && w[i + 2] == kLocalSize) {
87 local[0] = w[i + 3]; local[1] = w[i + 4]; local[2] = w[i + 5];
88 }
89 i += len;
90 }
91 return w[1];
92}
93
57static bool next_item(const char*& s) { 94static bool next_item(const char*& s) {
58 if (!*s) return true; 95 if (!*s) return true;
59 return *s++ == ',' && *s; 96 return *s++ == ',' && *s;
@@ -110,6 +147,10 @@ int main(int argc, char** argv) {
110 } 147 }
111 out_words = uint32_t(n); 148 out_words = uint32_t(n);
112 } 149 }
150 std::ifstream f(argv[1], std::ios::binary);
151 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
152 uint32_t local[3];
153 const uint32_t spirv_version = spirv_local_size(code, local);
113 gipa = load_vulkan(); 154 gipa = load_vulkan();
114 if (!gipa) return 1; 155 if (!gipa) return 1;
115#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name)) 156#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name))
@@ -166,19 +207,31 @@ int main(int argc, char** argv) {
166 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n"); 207 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n");
167 return 77; 208 return 77;
168 } 209 }
169 std::ifstream f(argv[1], std::ios::binary);
170 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
171 const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64 210 const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64
172 if (needs_float64 && !f2q.features.shaderFloat64) { 211 if (needs_float64 && !f2q.features.shaderFloat64) {
173 std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]); 212 std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]);
174 return 77; 213 return 77;
175 } 214 }
215 // A size the device can't require but runs anyway: one min..max range (fixed), or its default subgroupSize in a
216 // module below SPIR-V 1.6 (Vulkan "Varying Subgroup Size": SubgroupSize then always equals subgroupSize), which
217 // cs_wave_probe checks before the test runs (observed). Full subgroups where local size X is a multiple of
218 // maxSubgroupSize (VUID-VkPipelineShaderStageCreateInfo-flags-02759).
219 const bool fixed = req_sg && sgProps.minSubgroupSize == sgProps.maxSubgroupSize && subgroup.subgroupSize == req_sg;
220 const uint32_t local_total = local[0] * local[1] * local[2];
221 // The probe itself needs subgroup operations in compute: the basic built-ins and a ballot.
222 const bool probe_runs = (subgroup.supportedStages & VK_SHADER_STAGE_COMPUTE_BIT) &&
223 (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) &&
224 (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT);
225 const bool observed = req_sg && !require_wave64 && !can_request_size && !fixed && probe_runs &&
226 subgroup.subgroupSize == req_sg && spirv_version && spirv_version < 0x00010600u &&
227 local_total && local_total <= 1024;
228 const bool observed_full = observed && f13q.computeFullSubgroups && local[0] % sgProps.maxSubgroupSize == 0;
176 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 229 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
177 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 230 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
178 f12.bufferDeviceAddress = VK_TRUE; 231 f12.bufferDeviceAddress = VK_TRUE;
179 if (f13q.subgroupSizeControl || require_wave64) { 232 if (f13q.subgroupSizeControl || require_wave64) {
180 f13.subgroupSizeControl = f13q.subgroupSizeControl; 233 f13.subgroupSizeControl = f13q.subgroupSizeControl;
181 f13.computeFullSubgroups = require_wave64 ? VK_TRUE : VK_FALSE; 234 f13.computeFullSubgroups = require_wave64 || observed_full ? VK_TRUE : VK_FALSE;
182 f12.pNext = &f13; 235 f12.pNext = &f13;
183 } 236 }
184 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 237 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
@@ -242,7 +295,7 @@ int main(int argc, char** argv) {
242 if (!std::strcmp(argv[3], "bvh")) { 295 if (!std::strcmp(argv[3], "bvh")) {
243 // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a 296 // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a
244 // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray 297 // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray
245 // misses, and an inactive (NaN) box. Node id = address >> 3 | type. 298 // misses, and a box with a NaN min.x that RDNA2 still enters at t = 0 (SHADER-650). Node id = address >> 3 | type.
246 auto f32 = [&](uint32_t at, float v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); }; 299 auto f32 = [&](uint32_t at, float v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); };
247 auto u32 = [&](uint32_t at, uint32_t v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); }; 300 auto u32 = [&](uint32_t at, uint32_t v) { std::memcpy(static_cast<char*>(map) + at, &v, 4); };
248 u32(0x100, 0x40); u32(0x104, 0x48); u32(0x108, 0x60); u32(0x10C, 0x68); 301 u32(0x100, 0x40); u32(0x104, 0x48); u32(0x108, 0x60); u32(0x10C, 0x68);
@@ -290,7 +343,7 @@ int main(int argc, char** argv) {
290 reqSg.requiredSubgroupSize = req_sg; 343 reqSg.requiredSubgroupSize = req_sg;
291 if (can_request_size) 344 if (can_request_size)
292 cpi.stage.pNext = &reqSg; 345 cpi.stage.pNext = &reqSg;
293 if (require_wave64) 346 if (require_wave64 || observed_full)
294 cpi.stage.flags = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT; 347 cpi.stage.flags = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT;
295 cpi.layout = pl; 348 cpi.layout = pl;
296 VkPipeline pipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &pipe)); 349 VkPipeline pipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &pipe));
@@ -298,9 +351,8 @@ int main(int argc, char** argv) {
298 else if (req_sg) { 351 else if (req_sg) {
299 // VKC_SUBGROUP_SIZE: say whether the pipeline really runs at that size, so a runner can skip a test the device 352 // VKC_SUBGROUP_SIZE: say whether the pipeline really runs at that size, so a runner can skip a test the device
300 // can't pin instead of judging words from whatever size the driver picked (#774). 353 // can't pin instead of judging words from whatever size the driver picked (#774).
301 const bool fixed = sgProps.minSubgroupSize == sgProps.maxSubgroupSize && subgroup.subgroupSize == req_sg;
302 if (can_request_size || fixed) std::printf("compute subgroup size: %u\n", req_sg); 354 if (can_request_size || fixed) std::printf("compute subgroup size: %u\n", req_sg);
303 else std::printf("compute subgroup size: %u not available\n", req_sg); 355 else if (!observed) std::printf("compute subgroup size: %u not available\n", req_sg);
304 } 356 }
305 357
306 pc[0] = 0; pc[1] = 0; pc[2] = 0xFFFFFFFFu; pc[3] = 0x31016FACu; // V#: base 0, stride 0, num_records max, OOB_SELECT 3 (raw) 358 pc[0] = 0; pc[1] = 0; pc[2] = 0xFFFFFFFFu; pc[3] = 0x31016FACu; // V#: base 0, stride 0, num_records max, OOB_SELECT 3 (raw)
@@ -311,6 +363,95 @@ int main(int argc, char** argv) {
311 VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; 363 VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
312 cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; 364 cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1;
313 VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); 365 VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd));
366 if (observed) {
367 // cs_wave_probe with the test's local size and flags, one group, four words per invocation in its own buffer.
368 VkBufferCreateInfo pbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
369 pbi.size = VkDeviceSize(local_total) * 16;
370 pbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
371 VkBuffer pbuf; CHECK(vkCreateBuffer(dev, &pbi, nullptr, &pbuf));
372 VkMemoryRequirements pmr; vkGetBufferMemoryRequirements(dev, pbuf, &pmr);
373 VkMemoryAllocateInfo pmai = mai;
374 pmai.allocationSize = pmr.size;
375 VkDeviceMemory pmem; CHECK(vkAllocateMemory(dev, &pmai, nullptr, &pmem));
376 CHECK(vkBindBufferMemory(dev, pbuf, pmem, 0));
377 void* pmap; CHECK(vkMapMemory(dev, pmem, 0, pbi.size, 0, &pmap));
378 std::memset(pmap, 0xEE, size_t(pbi.size));
379 VkBufferDeviceAddressInfo pbai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
380 pbai.buffer = pbuf;
381 const uint64_t paddr = vkGetBufferDeviceAddress(dev, &pbai);
382 VkShaderModuleCreateInfo psmi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
383 psmi.codeSize = sizeof(leonida::vk_test::cs_wave_probe_spirv);
384 psmi.pCode = leonida::vk_test::cs_wave_probe_spirv;
385 VkShaderModule psm; CHECK(vkCreateShaderModule(dev, &psmi, nullptr, &psm));
386 const VkSpecializationMapEntry entries[3] = {{0, 0, 4}, {1, 4, 4}, {2, 8, 4}};
387 const VkSpecializationInfo spec{3, entries, sizeof(local), local};
388 VkComputePipelineCreateInfo pcpi = cpi;
389 pcpi.flags = 0;
390 pcpi.stage.module = psm;
391 pcpi.stage.pSpecializationInfo = &spec;
392 VkPipeline ppipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pcpi, nullptr, &ppipe));
393 const uint32_t ppc[2] = {uint32_t(paddr), uint32_t(paddr >> 32)}; // cs_wave_probe's buffer address
394 VkCommandBuffer pcmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &pcmd));
395 VkCommandBufferBeginInfo pcbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
396 CHECK(vkBeginCommandBuffer(pcmd, &pcbi));
397 vkCmdBindPipeline(pcmd, VK_PIPELINE_BIND_POINT_COMPUTE, ppipe);
398 vkCmdPushConstants(pcmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ppc), ppc);
399 vkCmdDispatch(pcmd, 1, 1, 1);
400 VkMemoryBarrier pread{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
401 pread.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
402 pread.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
403 vkCmdPipelineBarrier(pcmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0,
404 1, &pread, 0, nullptr, 0, nullptr);
405 CHECK(vkEndCommandBuffer(pcmd));
406 VkSubmitInfo psi{VK_STRUCTURE_TYPE_SUBMIT_INFO};
407 psi.commandBufferCount = 1; psi.pCommandBuffers = &pcmd;
408 CHECK(vkQueueSubmit(q, 1, &psi, VK_NULL_HANDLE));
409 CHECK(vkQueueWaitIdle(q));
410 // Width first, from what each invocation reports: every subgroup has N lanes (one may have the rest of a
411 // group that isn't a multiple of N), each lane once, and a ballot of the subgroup counts them all. A wrong
412 // width fails the test. Then the order: the translator takes a wave32 lane as LocalInvocationIndex % N, so
413 // invocation l must be lane l % N of subgroup l / N. Vulkan doesn't promise that mapping; where it differs,
414 // the size is reported as not available, as on a device that can't give N at all (the runners skip).
415 const uint32_t* pw = static_cast<const uint32_t*>(pmap);
416 const uint32_t subgroups = (local_total + req_sg - 1) / req_sg, tail = local_total % req_sg;
417 std::vector<uint32_t> count(subgroups, 0), seen(std::size_t(subgroups) * req_sg, 0);
418 std::vector<bool> bad(local_total, false);
419 for (uint32_t l = 0; l < local_total; l++) {
420 const uint32_t* w = pw + 4 * l;
421 if (w[0] == req_sg && w[2] < subgroups && w[1] < req_sg && !seen[std::size_t(w[2]) * req_sg + w[1]]++)
422 count[w[2]]++;
423 else
424 bad[l] = true;
425 }
426 uint32_t wrong = 0, first = 0, misplaced = 0, first_misplaced = 0, partial = 0;
427 for (uint32_t c : count)
428 if (c != req_sg) partial++;
429 for (uint32_t l = 0; l < local_total; l++) {
430 const uint32_t* w = pw + 4 * l;
431 if (bad[l] || w[3] != count[w[2]]) {
432 if (!wrong++) first = l;
433 }
434 if ((w[1] != l % req_sg || w[2] != l / req_sg) && !misplaced++) first_misplaced = l;
435 }
436 if (!wrong && partial > (tail ? 1u : 0u)) wrong = partial; // e.g. two half-filled subgroups
437 if (wrong) {
438 const uint32_t* w = pw + 4 * first;
439 std::printf("compute subgroup size: %u observed wrong in %u of %u invocations; invocation %u has "
440 "SubgroupSize %u, lane %u, subgroup %u, a ballot of %u lanes\n", req_sg, wrong, local_total,
441 first, w[0], w[1], w[2], w[3]);
442 return 1;
443 }
444 if (misplaced) {
445 const uint32_t* w = pw + 4 * first_misplaced;
446 std::fprintf(stderr, "%u-lane subgroups, but not in invocation order: invocation %u is lane %u of "
447 "subgroup %u\n", req_sg, first_misplaced, w[1], w[2]);
448 // As where the size can't be pinned at all: say so, run the test, and let the runner skip it.
449 std::printf("compute subgroup size: %u not available\n", req_sg);
450 } else {
451 std::printf("compute subgroup size: %u (observed: all %u invocations of a %ux%ux%u group%s)\n", req_sg,
452 local_total, local[0], local[1], local[2], observed_full ? ", full subgroups" : "");
453 }
454 }
314 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 455 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
315 CHECK(vkBeginCommandBuffer(cmd, &cbi)); 456 CHECK(vkBeginCommandBuffer(cmd, &cbi));
316 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); 457 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
@@ -432,7 +573,7 @@ int main(int argc, char** argv) {
432 } 573 }
433 } 574 }
434 if (!std::strcmp(argv[3], "bvh")) { 575 if (!std::strcmp(argv[3], "bvh")) {
435 const uint32_t want[8] = {0x48, 0x40, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xC1200000u, 0xBF800000u, 0xBE800000u, 0xBE800000u}; 576 const uint32_t want[8] = {0x68, 0x48, 0x40, 0xFFFFFFFFu, 0xC1200000u, 0xBF800000u, 0xBE800000u, 0xBE800000u};
436 for (int i = 0; i < 8; i++) if (out[i] != want[i]) { if (!bad) first_bad = i; bad++; } 577 for (int i = 0; i < 8; i++) if (out[i] != want[i]) { if (!bad) first_bad = i; bad++; }
437 std::printf("bvh out = %08x %08x %08x %08x | %08x %08x %08x %08x\n", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); 578 std::printf("bvh out = %08x %08x %08x %08x | %08x %08x %08x %08x\n", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]);
438 } 579 }
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index 0312b48a4..a3e886d51 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -3,7 +3,8 @@
3// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash 3// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash
4// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants 4// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants
5// sized from push_constant_bytes, default 144 or 128 with pc_tail): 5// sized from push_constant_bytes, default 144 or 128 with pc_tail):
6// - cs: compute pipeline via vkCreateComputePipelines 6// - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for
7// descriptor-free shaders with the standard push-constant range
7// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) 8// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass)
8// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py) 9// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py)
9// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders 10// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders
@@ -11,7 +12,11 @@
11// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every 12// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every
12// 10 minutes and at the end 13// 10 minutes and at the end
13// --jobs N compile on up to N worker threads (default: half the hardware threads) 14// --jobs N compile on up to N worker threads (default: half the hardware threads)
14// --large-module-bytes N compile modules larger than N bytes alone (default: 4194304; 0 disables isolation) 15// --large-module-bytes N modules larger than N bytes are "large" (default: 4194304; 0 disables the gate)
16// --large-parallel N how many large modules may be in the driver at once: 0 (default) = as many as fit 3/4 of
17// the memory available at start, at large_module_gate.h's estimate per module, up to --jobs, with the
18// small ones compiling alongside; 1 = each large module alone, the other threads waiting (the
19// behaviour before; also what 0 falls back to when the available memory can't be read)
15// --start I --count N check only index entries [I, I+N) (sorted by name) 20// --start I --count N check only index entries [I, I+N) (sorted by name)
16// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running 21// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running
17// --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip) 22// --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip)
@@ -30,8 +35,10 @@
30// --inflight-file F keep the modules that are in the driver in F, one "name<TAB>phase" line each (phase: module 35// --inflight-file F keep the modules that are in the driver in F, one "name<TAB>phase" line each (phase: module
31// while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check 36// while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check
32// can tell which module was there when the process died. F is rewritten when a module over 37// can tell which module was there when the process died. F is rewritten when a module over
33// --large-module-bytes enters or leaves the driver (it is alone then, so F names exactly it) and by 38// --large-module-bytes enters or leaves the driver (with --large-parallel 1 it is alone then, so F
34// the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage reads it. 39// names exactly it; otherwise F names every module in flight and make_game.py retries each alone)
40// and by the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage
41// reads it.
35// --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted 42// --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted
36// as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F 43// as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F
37// after a crash, so the next run checks everything else instead of dying on the same module. 44// after a crash, so the next run checks everything else instead of dying on the same module.
@@ -42,9 +49,12 @@
42#include "vk_device_pick.h" 49#include "vk_device_pick.h"
43#include "pipeline_cache_file.h" 50#include "pipeline_cache_file.h"
44#include "pipeline_cache_snapshot.h" 51#include "pipeline_cache_snapshot.h"
52#include "large_module_gate.h"
45#include "../src/spirv_words.h" 53#include "../src/spirv_words.h"
54#include "../src/subgroup_size.h"
46 55
47#include <algorithm> 56#include <algorithm>
57#include <array>
48#include <atomic> 58#include <atomic>
49#include <cctype> 59#include <cctype>
50#include <charconv> 60#include <charconv>
@@ -90,6 +100,10 @@ struct ShaderMeta {
90 uint32_t lds_bytes = 0; 100 uint32_t lds_bytes = 0;
91 uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144) 101 uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144)
92 uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0 102 uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0
103 bool no_set0_bindings = false;
104 bool wave64 = false;
105 std::array<uint32_t, 3> local_size{1, 1, 1};
106 std::string wave64_exchange;
93 bool writes_depth = false; 107 bool writes_depth = false;
94 bool needs_maintenance8 = false; 108 bool needs_maintenance8 = false;
95 std::vector<std::string> features; 109 std::vector<std::string> features;
@@ -222,6 +236,22 @@ struct JsonParser {
222 if (!error) fail("unterminated u32 array"); 236 if (!error) fail("unterminated u32 array");
223 return out; 237 return out;
224 } 238 }
239 void parse_local_size(std::array<uint32_t, 3>& out) {
240 if (!consume('[')) { skip_value(); return; }
241 for (size_t dim = 0; !error && i < s.size(); ++dim) {
242 if (consume(']')) return;
243 const char* start = s.data() + i;
244 skip_value();
245 if (dim < out.size()) {
246 char* end = nullptr;
247 const double size = std::strtod(start, &end);
248 out[dim] = end == s.data() + i && size >= 0 && size <= UINT32_MAX ? uint32_t(size) : 0;
249 }
250 if (consume(']')) return;
251 if (!consume(',')) { fail("expected ',' or ']' in local size"); return; }
252 }
253 if (!error) fail("unterminated local size");
254 }
225 std::vector<std::string> parse_str_array() { 255 std::vector<std::string> parse_str_array() {
226 std::vector<std::string> out; 256 std::vector<std::string> out;
227 if (!consume('[')) { skip_value(); return out; } 257 if (!consume('[')) { skip_value(); return out; }
@@ -318,6 +348,25 @@ struct JsonParser {
318 else if (k == "push_constant_bytes") 348 else if (k == "push_constant_bytes")
319 m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes"); 349 m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes");
320 else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes(); 350 else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes();
351 else if (k == "bindings") {
352 const size_t start = i;
353 m.no_set0_bindings = consume('[') && consume(']');
354 if (!m.no_set0_bindings) {
355 i = start;
356 skip_value();
357 }
358 }
359 else if (k == "wave64") {
360 ws();
361 if (s.compare(i, 4, "true") == 0 || s.compare(i, 5, "false") == 0) m.wave64 = parse_bool();
362 else skip_value();
363 }
364 else if (k == "wave64_exchange") {
365 ws();
366 if (i < s.size() && s[i] == '"') m.wave64_exchange = parse_string();
367 else skip_value();
368 }
369 else if (k == "local_size") parse_local_size(m.local_size);
321 else if (k == "writes_depth") m.writes_depth = parse_bool(); 370 else if (k == "writes_depth") m.writes_depth = parse_bool();
322 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); 371 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool();
323 else if (k == "features") m.features = parse_str_array(); 372 else if (k == "features") m.features = parse_str_array();
@@ -452,6 +501,13 @@ constexpr uint32_t required_push_bytes(uint32_t push_constant_bytes, uint32_t pc
452 return raw > (std::numeric_limits<uint32_t>::max() - 3u) ? raw : ((raw + 3u) & ~3u); 501 return raw > (std::numeric_limits<uint32_t>::max() - 3u) ? raw : ((raw + 3u) & ~3u);
453} 502}
454 503
504constexpr uint32_t runtime_compute_push_bytes = 144; // sizeof(leonida::ShaderUserData)
505
506bool uses_runtime_compute_layout(const ShaderMeta& meta) {
507 return meta.stage == "cs" && meta.no_set0_bindings && !meta.pc_tail_bytes &&
508 required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes) == runtime_compute_push_bytes;
509}
510
455static_assert(required_push_bytes(0, 0) == 144); 511static_assert(required_push_bytes(0, 0) == 144);
456static_assert(required_push_bytes(0, 16) == 128); 512static_assert(required_push_bytes(0, 16) == 128);
457static_assert(required_push_bytes(128, 0) == 128); 513static_assert(required_push_bytes(128, 0) == 128);
@@ -588,7 +644,7 @@ int main(int argc, char** argv) {
588 if (argc < 2) { 644 if (argc < 2) {
589 std::fprintf(stderr, 645 std::fprintf(stderr,
590 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " 646 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] "
591 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] " 647 "[--max-bytes N] [--large-module-bytes N] [--large-parallel N] [--stage all|cs|graphics | --compute-only | --graphics-only] "
592 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] " 648 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] "
593 "[--skip-file F]\n"); 649 "[--skip-file F]\n");
594 return 2; 650 return 2;
@@ -599,6 +655,7 @@ int main(int argc, char** argv) {
599 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); 655 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2);
600 size_t start = 0, count = 0, max_bytes = 0; 656 size_t start = 0, count = 0, max_bytes = 0;
601 size_t large_module_bytes = 4 * 1024 * 1024; 657 size_t large_module_bytes = 4 * 1024 * 1024;
658 unsigned large_parallel = 0; // 0 = by the memory budget
602 double slow = 30.0; 659 double slow = 30.0;
603 std::string stage_filter = "all"; 660 std::string stage_filter = "all";
604 bool cache_feedback = false, isolate = false, iso_child = false; 661 bool cache_feedback = false, isolate = false, iso_child = false;
@@ -640,6 +697,7 @@ int main(int argc, char** argv) {
640 else if (a == "--graphics-only") stage_filter = "graphics"; 697 else if (a == "--graphics-only") stage_filter = "graphics";
641 else if (a == "--max-bytes") valid = number(max_bytes); 698 else if (a == "--max-bytes") valid = number(max_bytes);
642 else if (a == "--large-module-bytes") valid = number(large_module_bytes); 699 else if (a == "--large-module-bytes") valid = number(large_module_bytes);
700 else if (a == "--large-parallel") valid = number(large_parallel);
643 else if (a == "--stats") valid = !(stats_path = value()).empty(); 701 else if (a == "--stats") valid = !(stats_path = value()).empty();
644 else if (a == "--inflight-file") valid = !(inflight_path = value()).empty(); 702 else if (a == "--inflight-file") valid = !(inflight_path = value()).empty();
645 else if (a == "--skip-file") valid = !(skip_path = value()).empty(); 703 else if (a == "--skip-file") valid = !(skip_path = value()).empty();
@@ -726,7 +784,8 @@ int main(int argc, char** argv) {
726 if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string(); 784 if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string();
727 std::vector<std::string> pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter, 785 std::vector<std::string> pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter,
728 "--max-bytes", std::to_string(max_bytes), 786 "--max-bytes", std::to_string(max_bytes),
729 "--large-module-bytes", std::to_string(large_module_bytes)}; 787 "--large-module-bytes", std::to_string(large_module_bytes),
788 "--large-parallel", std::to_string(large_parallel)};
730 if (cache_feedback) pass.push_back("--cache-feedback"); 789 if (cache_feedback) pass.push_back("--cache-feedback");
731 if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path}); 790 if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path});
732 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; }; 791 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; };
@@ -958,15 +1017,33 @@ int main(int argc, char** argv) {
958 dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); 1017 dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data();
959 VkDevice dev; 1018 VkDevice dev;
960 if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } 1019 if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; }
1020 leonida::SubgroupSizeCaps runtime_subgroups;
1021 leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, pd, f13.subgroupSizeControl,
1022 f13.computeFullSubgroups, runtime_subgroups);
961 auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool { 1023 auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool {
962 return f13.subgroupSizeControl && 1024 return f13.subgroupSizeControl &&
963 sg >= sgProps.minSubgroupSize && 1025 sg >= sgProps.minSubgroupSize &&
964 sg <= sgProps.maxSubgroupSize && 1026 sg <= sgProps.maxSubgroupSize &&
965 (sgProps.requiredSubgroupSizeStages & bit); 1027 (sgProps.requiredSubgroupSizeStages & bit);
966 }; 1028 };
1029 auto runtime_compute_subgroup = [&](const ShaderMeta& meta) {
1030 leonida::ShaderEntry entry;
1031 entry.stage = meta.stage;
1032 entry.subgroup_size = meta.subgroup_size;
1033 entry.wave64 = meta.wave64;
1034 entry.wave64_exchange = meta.wave64_exchange;
1035 entry.local_size = meta.local_size;
1036 return leonida::decide_subgroup_size(entry, runtime_subgroups);
1037 };
967 { 1038 {
968 std::map<uint32_t, std::set<std::string>> unforced_by_sg; 1039 std::map<uint32_t, std::set<std::string>> unforced_by_sg;
969 for (const auto& [_, meta] : work) { 1040 for (const auto& [_, meta] : work) {
1041 if (uses_runtime_compute_layout(*meta)) {
1042 const auto request = runtime_compute_subgroup(*meta);
1043 if (request.outcome == leonida::SubgroupOutcome::unavailable)
1044 unforced_by_sg[request.wanted].insert(meta->stage);
1045 continue;
1046 }
970 const VkShaderStageFlagBits bit = stage_bit(meta->stage); 1047 const VkShaderStageFlagBits bit = stage_bit(meta->stage);
971 if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) { 1048 if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) {
972 unforced_by_sg[meta->subgroup_size].insert(meta->stage); 1049 unforced_by_sg[meta->subgroup_size].insert(meta->stage);
@@ -1097,6 +1174,20 @@ int main(int argc, char** argv) {
1097 const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes); 1174 const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes);
1098 return layouts.at({need_pc, meta.pc_tail_bytes != 0}); 1175 return layouts.at({need_pc, meta.pc_tail_bytes != 0});
1099 }; 1176 };
1177 VkPipelineLayout runtime_compute_layout = VK_NULL_HANDLE;
1178 if (runtime_compute_push_bytes <= props.limits.maxPushConstantsSize &&
1179 std::any_of(work.begin(), work.end(), [](const Item& item) {
1180 return uses_runtime_compute_layout(*item.second);
1181 })) {
1182 const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, runtime_compute_push_bytes};
1183 VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
1184 info.pushConstantRangeCount = 1;
1185 info.pPushConstantRanges = &push;
1186 if (VkResult r = vkCreatePipelineLayout(dev, &info, nullptr, &runtime_compute_layout)) {
1187 std::fprintf(stderr, "runtime compute pipeline layout %d\n", r);
1188 return 1;
1189 }
1190 }
1100 VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; 1191 VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
1101 std::vector<char> seed; 1192 std::vector<char> seed;
1102 if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly 1193 if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly
@@ -1136,8 +1227,26 @@ int main(int argc, char** argv) {
1136 work.size(), lo, hi, stage_filter.c_str(), worker_count); 1227 work.size(), lo, hi, stage_filter.c_str(), worker_count);
1137 1228
1138 std::mutex mu; // guards counters, stdout, stub cache and in-flight table 1229 std::mutex mu; // guards counters, stdout, stub cache and in-flight table
1139 std::shared_mutex compile_gate; // large modules exclude other shader and pipeline work 1230 std::shared_mutex compile_gate; // --large-parallel 1: large modules exclude other shader and pipeline work
1140 size_t isolated_modules = 0; 1231 size_t isolated_modules = 0;
1232 // Otherwise large modules share a memory budget and the small ones are never held back (large_module_gate.h).
1233 const uint64_t available_memory = leonida::available_memory_bytes();
1234 const bool large_exclusive = large_parallel == 1 || (large_parallel == 0 && available_memory == 0);
1235 leonida::LargeModuleGate large_gate(
1236 large_parallel == 0 ? available_memory / 4 * 3 : UINT64_MAX,
1237 large_parallel == 0 ? jobs : std::min<unsigned>(large_parallel, jobs));
1238 if (large_module_bytes) {
1239 if (large_exclusive)
1240 std::fprintf(stderr, "large modules (over %zu bytes): one at a time, the other threads waiting\n",
1241 large_module_bytes);
1242 else if (large_parallel == 0)
1243 std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once within %.1f GB "
1244 "(3/4 of the %.1f GB available)\n", large_module_bytes, large_gate.max_inflight(),
1245 large_gate.budget() / 1e9, available_memory / 1e9);
1246 else
1247 std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once\n", large_module_bytes,
1248 large_gate.max_inflight());
1249 }
1141 std::map<std::string, uint32_t> modules_ok, modules_bad, big_skipped; 1250 std::map<std::string, uint32_t> modules_ok, modules_bad, big_skipped;
1142 std::map<std::string, StageStats> stats; 1251 std::map<std::string, StageStats> stats;
1143 std::map<std::string, VkShaderModule> stub_cache; 1252 std::map<std::string, VkShaderModule> stub_cache;
@@ -1234,7 +1343,7 @@ int main(int argc, char** argv) {
1234 VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) { 1343 VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) {
1235 std::lock_guard<std::mutex> g(mu); 1344 std::lock_guard<std::mutex> g(mu);
1236 inflight.erase(std::this_thread::get_id()); 1345 inflight.erase(std::this_thread::get_id());
1237 if (inflight.empty()) write_inflight(); // a large module just finished (it compiles alone) 1346 if (inflight.empty()) write_inflight(); // a large module just finished (alone with --large-parallel 1)
1238 auto& st = stats[stage]; 1347 auto& st = stats[stage];
1239 st.seconds += sec; 1348 st.seconds += sec;
1240 if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; } 1349 if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; }
@@ -1310,12 +1419,18 @@ int main(int argc, char** argv) {
1310 const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes); 1419 const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes);
1311 std::unique_lock exclusive(compile_gate, std::defer_lock); 1420 std::unique_lock exclusive(compile_gate, std::defer_lock);
1312 std::shared_lock parallel(compile_gate, std::defer_lock); 1421 std::shared_lock parallel(compile_gate, std::defer_lock);
1313 if (isolated) exclusive.lock(); 1422 leonida::LargeModuleGate::Ticket large_ticket; // left after the module and its pipeline are gone
1314 else if (large_module_bytes) parallel.lock(); 1423 if (large_exclusive) {
1424 if (isolated) exclusive.lock();
1425 else if (large_module_bytes) parallel.lock();
1426 } else if (isolated) {
1427 large_ticket = leonida::LargeModuleGate::Ticket(large_gate,
1428 leonida::large_module_estimate(file_size));
1429 }
1315 { // in flight from here: vkCreateShaderModule can also take long or die in the driver 1430 { // in flight from here: vkCreateShaderModule can also take long or die in the driver
1316 std::lock_guard<std::mutex> g(mu); 1431 std::lock_guard<std::mutex> g(mu);
1317 inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"}; 1432 inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"};
1318 if (isolated) write_inflight(); // alone in flight: the file names exactly this module 1433 if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1)
1319 } 1434 }
1320 1435
1321 const auto code = leonida::read_spirv_words(f, file_size); 1436 const auto code = leonida::read_spirv_words(f, file_size);
@@ -1338,15 +1453,23 @@ int main(int argc, char** argv) {
1338 if (!miss.empty()) { 1453 if (!miss.empty()) {
1339 record_skip(name, stage, miss); 1454 record_skip(name, stage, miss);
1340 } else { 1455 } else {
1341 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{ 1456 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{};
1342 VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
1343 reqSg.requiredSubgroupSize = meta.subgroup_size;
1344 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; 1457 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
1345 cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; 1458 cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
1346 cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; 1459 cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main";
1347 const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); 1460 bool sg_forced = false;
1348 if (sg_forced) cpi.stage.pNext = &reqSg; 1461 if (uses_runtime_compute_layout(meta)) {
1349 cpi.layout = layout_for(meta); 1462 const auto request = runtime_compute_subgroup(meta);
1463 leonida::apply_subgroup_request(request, reqSg, cpi.stage);
1464 sg_forced = request.size != 0;
1465 cpi.layout = runtime_compute_layout;
1466 } else {
1467 reqSg.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO;
1468 reqSg.requiredSubgroupSize = meta.subgroup_size;
1469 sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT);
1470 if (sg_forced) cpi.stage.pNext = &reqSg;
1471 cpi.layout = layout_for(meta);
1472 }
1350 cpi.flags = capture; 1473 cpi.flags = capture;
1351 // Only whole-pipeline feedback is reported. 1474 // Only whole-pipeline feedback is reported.
1352 VkPipelineCreationFeedback fb{}; 1475 VkPipelineCreationFeedback fb{};
@@ -1357,7 +1480,7 @@ int main(int argc, char** argv) {
1357 { 1480 {
1358 std::lock_guard<std::mutex> g(mu); 1481 std::lock_guard<std::mutex> g(mu);
1359 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; 1482 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
1360 if (isolated) write_inflight(); // alone in flight: the file names exactly this module 1483 if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1)
1361 } 1484 }
1362 VkPipeline p = VK_NULL_HANDLE; 1485 VkPipeline p = VK_NULL_HANDLE;
1363 maybe_simulate_crash(name); 1486 maybe_simulate_crash(name);
@@ -1531,7 +1654,7 @@ int main(int argc, char** argv) {
1531 { 1654 {
1532 std::lock_guard<std::mutex> g(mu); 1655 std::lock_guard<std::mutex> g(mu);
1533 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; 1656 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
1534 if (isolated) write_inflight(); // alone in flight: the file names exactly this module 1657 if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1)
1535 } 1658 }
1536 VkPipeline p = VK_NULL_HANDLE; 1659 VkPipeline p = VK_NULL_HANDLE;
1537 maybe_simulate_crash(name); 1660 maybe_simulate_crash(name);
@@ -1658,7 +1781,8 @@ int main(int argc, char** argv) {
1658 std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size()); 1781 std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size());
1659 } 1782 }
1660 if (isolated_modules) 1783 if (isolated_modules)
1661 std::printf("large modules checked exclusively: %zu (over %zu bytes)\n", isolated_modules, 1784 std::printf("large modules checked %s: %zu (over %zu bytes)\n",
1785 large_exclusive ? "exclusively" : "within the memory budget", isolated_modules,
1662 large_module_bytes); 1786 large_module_bytes);
1663 std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count); 1787 std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count);
1664 const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed 1788 const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index c26703ef5..3834c5c08 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -6,6 +6,7 @@
6// A failed capture fence wait also leaves the caller's outputs untouched. 6// A failed capture fence wait also leaves the caller's outputs untouched.
7// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's 7// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's
8// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks. 8// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks.
9// 4. A swapchain-destroy WSI layer which calls vkDeviceWaitIdle cannot overlap vkQueueSubmit on another thread.
9// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data. 10// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data.
10#ifndef WIN32_LEAN_AND_MEAN 11#ifndef WIN32_LEAN_AND_MEAN
11#define WIN32_LEAN_AND_MEAN 12#define WIN32_LEAN_AND_MEAN
@@ -58,6 +59,8 @@ PFN_vkQueuePresentKHR real_present = nullptr;
58PFN_vkWaitForFences real_wait = nullptr; 59PFN_vkWaitForFences real_wait = nullptr;
59PFN_vkCmdPipelineBarrier real_barrier = nullptr; 60PFN_vkCmdPipelineBarrier real_barrier = nullptr;
60PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; 61PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
62PFN_vkDestroySwapchainKHR real_destroy_swapchain = nullptr;
63PFN_vkDeviceWaitIdle real_device_wait_idle = nullptr;
61 64
62std::atomic<VkResult> fail_next_submit{VK_SUCCESS}; 65std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
63std::atomic<VkResult> fail_next_wait{VK_SUCCESS}; 66std::atomic<VkResult> fail_next_wait{VK_SUCCESS};
@@ -66,9 +69,36 @@ std::atomic<bool> observe_capture{false};
66std::atomic<bool> saw_capture_waw{false}; 69std::atomic<bool> saw_capture_waw{false};
67std::atomic<std::uint32_t> capture_copies{0}; 70std::atomic<std::uint32_t> capture_copies{0};
68std::atomic<std::uint32_t> capture_waw_barriers{0}; 71std::atomic<std::uint32_t> capture_waw_barriers{0};
72std::atomic<bool> check_swapchain_destroy{false};
73std::atomic<bool> destroy_entered{false};
74std::atomic<bool> submit_entered{false};
75std::atomic<bool> overlap_detected{false};
76std::atomic<bool> unexpected_submit_error{false};
77std::mutex destroy_mutex;
78std::condition_variable destroy_cv;
79bool allow_destroy_finish = false;
80
81// Synthetic WSI layer: a destroy hook initiates vkDeviceWaitIdle, as a capture layer may do internally.
82// Holding the hook behind a condition variable makes the concurrency window deterministic rather than dependent
83// on the installed capture software or validation logging overhead. Only the test hook waits on this condition.
84VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice device, VkSwapchainKHR swapchain,
85 const VkAllocationCallbacks* alloc) {
86 if (check_swapchain_destroy.load(std::memory_order_relaxed)) {
87 destroy_entered.store(true, std::memory_order_release);
88 destroy_cv.notify_all();
89 {
90 std::unique_lock lock(destroy_mutex);
91 destroy_cv.wait(lock, [] { return allow_destroy_finish; });
92 }
93 overlap_detected.store(submit_entered.load(std::memory_order_acquire), std::memory_order_release);
94 if (real_device_wait_idle(device) != VK_SUCCESS) unexpected_submit_error.store(true);
95 }
96 real_destroy_swapchain(device, swapchain, alloc);
97}
69 98
70VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, 99VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits,
71 VkFence fence) { 100 VkFence fence) {
101 submit_entered.store(true, std::memory_order_release);
72 const VkResult armed = fail_next_submit.exchange(VK_SUCCESS); 102 const VkResult armed = fail_next_submit.exchange(VK_SUCCESS);
73 if (armed != VK_SUCCESS) return armed; 103 if (armed != VK_SUCCESS) return armed;
74 return real_submit(queue, count, submits, fence); 104 return real_submit(queue, count, submits, fence);
@@ -124,6 +154,7 @@ VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage
124 154
125VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { 155VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
126 const std::string_view n = name; 156 const std::string_view n = name;
157 if (n == "vkDestroySwapchainKHR") return reinterpret_cast<PFN_vkVoidFunction>(destroy_swapchain);
127 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 158 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
128 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present); 159 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
129 if (n == "vkWaitForFences") return reinterpret_cast<PFN_vkVoidFunction>(wait_for_fences); 160 if (n == "vkWaitForFences") return reinterpret_cast<PFN_vkVoidFunction>(wait_for_fences);
@@ -140,6 +171,8 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const
140void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) { 171void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) {
141 real_get_instance = instance_proc; 172 real_get_instance = instance_proc;
142 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr")); 173 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
174 real_destroy_swapchain = reinterpret_cast<PFN_vkDestroySwapchainKHR>(real_get_device(device, "vkDestroySwapchainKHR"));
175 real_device_wait_idle = reinterpret_cast<PFN_vkDeviceWaitIdle>(real_get_device(device, "vkDeviceWaitIdle"));
143 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit")); 176 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
144 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR")); 177 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
145 real_wait = reinterpret_cast<PFN_vkWaitForFences>(real_get_device(device, "vkWaitForFences")); 178 real_wait = reinterpret_cast<PFN_vkWaitForFences>(real_get_device(device, "vkWaitForFences"));
@@ -350,6 +383,59 @@ int main() {
350 EXPECT(!worker_failed.load()); 383 EXPECT(!worker_failed.load());
351 EXPECT(queue.idle() && worker_queue.idle()); 384 EXPECT(queue.idle() && worker_queue.idle());
352 std::printf("presenter sync: concurrent present + queue.execute + tracker mutations ok\n"); 385 std::printf("presenter sync: concurrent present + queue.execute + tracker mutations ok\n");
386
387 // 4. Emulate a WSI capture layer that performs device-idle inside vkDestroySwapchainKHR.
388 // The presenter first enters the destroy hook; a second thread then attempts a real queue submission.
389 // Once the hook is released, that submission must not have entered the Vulkan driver while the hook ran.
390 driver::destroy_entered.store(false);
391 driver::submit_entered.store(false);
392 driver::overlap_detected.store(false);
393 driver::unexpected_submit_error.store(false);
394 {
395 std::lock_guard lock(driver::destroy_mutex);
396 driver::allow_destroy_finish = false;
397 }
398 driver::check_swapchain_destroy.store(true);
399 VkResult recreated = VK_ERROR_UNKNOWN;
400 std::thread destroy_thread([&] { recreated = presenter.present(1, true); });
401 bool entered = false;
402 {
403 std::unique_lock lock(driver::destroy_mutex);
404 entered = driver::destroy_cv.wait_for(lock, std::chrono::seconds(5),
405 [] { return driver::destroy_entered.load(); });
406 }
407 std::atomic<bool> submit_started{false};
408 ReplayResult submit_result = ReplayResult::unsupported;
409 std::thread submit_thread;
410 if (entered) {
411 submit_thread = std::thread([&] {
412 submit_started.store(true);
413 CommandList list;
414 if (!list.clear_render_target({1, 0, 0, 1}, {0.3f, 0.2f, 0.1f, 1.0f}) || !list.close()) return;
415 const CommandList* ptr = &list;
416 submit_result = worker_queue.execute({&ptr, 1});
417 });
418 for (int attempt = 0; attempt < 100 && !submit_started.load(); ++attempt)
419 std::this_thread::sleep_for(std::chrono::milliseconds(1));
420 // Give the competing thread time to reach the submit point if no mutex is protecting destruction.
421 std::this_thread::sleep_for(std::chrono::milliseconds(50));
422 }
423 {
424 std::lock_guard lock(driver::destroy_mutex);
425 driver::allow_destroy_finish = true;
426 }
427 driver::destroy_cv.notify_all();
428 destroy_thread.join();
429 if (submit_thread.joinable()) submit_thread.join();
430 driver::check_swapchain_destroy.store(false);
431 EXPECT(entered);
432 EXPECT(recreated == VK_SUCCESS);
433 EXPECT(submit_started.load());
434 EXPECT(submit_result == ReplayResult::success);
435 EXPECT(!driver::overlap_detected.load());
436 EXPECT(!driver::unexpected_submit_error.load());
437 EXPECT(queue.idle() && worker_queue.idle());
438 std::printf("presenter sync: synthetic WSI device-idle during swapchain destruction serialized ok\n");
353 } 439 }
354 440
355 DestroyWindow(window); 441 DestroyWindow(window);
diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp
index 84289198c..9df720356 100644
--- a/runtime/test/vk_queue_test.cpp
+++ b/runtime/test/vk_queue_test.cpp
@@ -61,7 +61,33 @@ int check_picker() {
61 const auto q = pick_queue_families(f, 0); 61 const auto q = pick_queue_families(f, 0);
62 EXPECT(q.copy == 2); 62 EXPECT(q.copy == 2);
63 } 63 }
64 std::printf("queue family picker: 4 layouts ok\n"); 64 // D3D12 tile mapping is legal on all queue kinds. Dedicated async queues that cannot
65 // bind sparse pages must use the graphics family when sparse buffers are offered.
66 {
67 constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT;
68 const std::array f{fam(G | S), fam(T), fam(C)};
69 const auto preferred = pick_queue_families(f, 0);
70 EXPECT(preferred.compute == 2 && preferred.copy == 1);
71 const auto corrected = sparse_capable_queue_families(f, preferred, true);
72 EXPECT(corrected.direct == 0 && corrected.compute == 0 && corrected.copy == 0);
73 const auto no_sparse = sparse_capable_queue_families(f, preferred, false);
74 EXPECT(no_sparse.compute == 2 && no_sparse.copy == 1);
75 }
76 {
77 constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT;
78 const std::array f{fam(G | S), fam(T | S), fam(C | S)};
79 const auto preferred = pick_queue_families(f, 0);
80 const auto corrected = sparse_capable_queue_families(f, preferred, true);
81 EXPECT(corrected.compute == 2 && corrected.copy == 1); // preserve dedicated queues
82 }
83 {
84 constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT;
85 const std::array f{fam(G | S), fam(T), fam(C | S)};
86 const auto preferred = pick_queue_families(f, 0);
87 const auto corrected = sparse_capable_queue_families(f, preferred, true);
88 EXPECT(corrected.compute == 2 && corrected.copy == 0); // mixed capabilities
89 }
90 std::printf("queue family picker: 7 layouts ok\n");
65 return 0; 91 return 0;
66} 92}
67 93
diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp
new file mode 100644
index 000000000..b5de7bd13
--- /dev/null
+++ b/runtime/test/vk_sandbox.cpp
@@ -0,0 +1,734 @@
1// Real-shader sandbox: draws a tools/sandbox_scene.py scene through two translated game shaders.
2//
3// vk_sandbox <scene.bin> <vs.spv> <ps.spv> --out <image.ppm> [--size W H] [--cam x y z yaw pitch] [--fov deg]
4// vk_sandbox <scene.bin> <vs.spv> <ps.spv> --window [--size W H] [--cam ...] [--mode fly|walk|drive] (Windows only)
5// --window --frames N --out <image.ppm>: test run, the window shows without activation and quits after N frames
6//
7// The pair (chosen by tools/sandbox.py) is a transform VS with POSITION/NORMAL/TEXCOORD inputs and a textured PS, both reading user SGPR 8:
8// a 32-bit pointer (high dword forced to 0) to one table of descriptors in the heap, laid out as the shaders load it:
9// +0x00 V# of the object constants: world rows 0..2 at 0x00/0x10/0x20, translation at 0x30
10// +0x20 T# of the albedo texture (8 dwords)
11// +0x40 V# of the view constants: light direction at 0xa0, view-projection rows at 0x160 (row-vector convention)
12// +0x60 V# of the colour constants: rgba at 0x00
13// Every draw gets its own table and object constants; view and colour constants are shared. The PS samples with the
14// S# literal in its own code, so the sampler is built from those words (gfx10::decode). Nothing here is game data:
15// the scene file and the shaders come from the user's work folder.
16//
17// Window keys (only while the window has focus): WASD move, mouse with the right button held looks, Q/E down/up,
18// Shift faster, 1 fly, 2 walk (eye 1.7 m over the ground under the camera), 3 drive (eye 1.2 m, accelerates),
19// P writes sandbox_shot.ppm, Esc quits.
20#define VK_NO_PROTOTYPES
21#ifdef _WIN32
22#define VK_USE_PLATFORM_WIN32_KHR
23#include <windows.h>
24#endif
25#include "vulkan_loader.h"
26#include "vk_device_pick.h"
27
28#include <algorithm>
29#include <array>
30#include <chrono>
31#include <cmath>
32#include <cstdio>
33#include <cstdlib>
34#include <cstring>
35#include <fstream>
36#include <string>
37#include <unordered_map>
38#include <vector>
39
40#include "../src/descriptor_table.h"
41#include "../src/gfx10_descriptors.h"
42
43static PFN_vkGetInstanceProcAddr gipa;
44#define CHECK(x) \
45 do { \
46 VkResult r_ = (x); \
47 if (r_ != VK_SUCCESS) { \
48 std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \
49 return 1; \
50 } \
51 } while (0)
52
53namespace {
54
55struct Texture { uint32_t w, h; std::vector<uint8_t> rgba; };
56struct Mesh { uint32_t first_vertex, vertex_count, first_index, index_count; };
57struct Draw { uint32_t mesh; int32_t texture; float rows[4][3]; };
58struct Scene {
59 std::vector<Texture> textures;
60 std::vector<Mesh> meshes;
61 std::vector<Draw> draws;
62 std::vector<float> vertices; // 8 floats each
63 std::vector<uint32_t> indices;
64 float center[3];
65};
66
67bool load_scene(const char* path, Scene& s) {
68 std::ifstream f(path, std::ios::binary | std::ios::ate);
69 const uint64_t file_size = f ? uint64_t(f.tellg()) : 0;
70 f.seekg(0);
71 char magic[4];
72 uint32_t hdr[4];
73 if (!f.read(magic, 4) || std::memcmp(magic, "LSB1", 4) || !f.read(reinterpret_cast<char*>(hdr), 16) ||
74 hdr[0] != 1 || !f.read(reinterpret_cast<char*>(s.center), 12))
75 return false;
76 for (uint32_t i = 0; i < hdr[1]; ++i) {
77 Texture t;
78 f.read(reinterpret_cast<char*>(&t.w), 4).read(reinterpret_cast<char*>(&t.h), 4);
79 if (!f || !t.w || !t.h || t.w > 16384 || t.h > 16384 || uint64_t(t.w) * t.h * 4 > file_size) return false;
80 t.rgba.resize(size_t(t.w) * t.h * 4);
81 f.read(reinterpret_cast<char*>(t.rgba.data()), std::streamsize(t.rgba.size()));
82 s.textures.push_back(std::move(t));
83 }
84 for (uint32_t i = 0; i < hdr[2]; ++i) {
85 uint32_t vc = 0, ic = 0;
86 f.read(reinterpret_cast<char*>(&vc), 4).read(reinterpret_cast<char*>(&ic), 4);
87 if (!f || uint64_t(vc) * 32 + uint64_t(ic) * 4 > file_size) return false;
88 Mesh m{uint32_t(s.vertices.size() / 8), vc, uint32_t(s.indices.size()), ic};
89 s.vertices.resize(s.vertices.size() + size_t(vc) * 8);
90 s.indices.resize(s.indices.size() + ic);
91 f.read(reinterpret_cast<char*>(s.vertices.data() + size_t(m.first_vertex) * 8), std::streamsize(vc) * 32);
92 f.read(reinterpret_cast<char*>(s.indices.data() + m.first_index), std::streamsize(ic) * 4);
93 if (!f) return false;
94 for (uint32_t k = 0; k < ic; ++k)
95 if (s.indices[m.first_index + k] >= vc) return false;
96 s.meshes.push_back(m);
97 }
98 for (uint32_t i = 0; i < hdr[3]; ++i) {
99 Draw d;
100 f.read(reinterpret_cast<char*>(&d), sizeof(d));
101 if (!f || d.mesh >= s.meshes.size() || d.texture >= int32_t(s.textures.size())) return false;
102 s.draws.push_back(d);
103 }
104 return bool(f);
105}
106
107std::vector<uint32_t> read_spv(const char* p) {
108 std::ifstream f(p, std::ios::binary);
109 std::vector<char> b((std::istreambuf_iterator<char>(f)), {});
110 std::vector<uint32_t> w(b.size() / 4);
111 std::memcpy(w.data(), b.data(), w.size() * 4);
112 return w;
113}
114
115struct Camera {
116 float pos[3], yaw = 0, pitch = 0, fov = 70, speed = 0;
117 int mode = 0; // 0 fly, 1 walk, 2 drive
118 void forward(float f[3]) const {
119 f[0] = std::cos(pitch) * std::cos(yaw); f[1] = std::cos(pitch) * std::sin(yaw); f[2] = std::sin(pitch);
120 }
121};
122
123// clip = wx*row0 + wy*row1 + wz*row2 + row3 (D3D clip space: y up, z 0..1), stored as 16 floats.
124void view_projection(const Camera& c, float aspect, float out[16]) {
125 float f[3]; c.forward(f);
126 float r[3] = {f[1], -f[0], 0};
127 const float rl = std::sqrt(r[0] * r[0] + r[1] * r[1]);
128 if (rl < 1e-6f) { r[0] = std::sin(c.yaw); r[1] = -std::cos(c.yaw); } else { r[0] /= rl; r[1] /= rl; }
129 const float u[3] = {r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]};
130 const float n = 0.1f, fa = 5000.f, sy = 1.f / std::tan(c.fov * 3.14159265f / 360.f), sx = sy / aspect;
131 const float A = fa / (fa - n), B = -n * fa / (fa - n);
132 // view = (dot(w - p, r), dot(w - p, u), dot(w - p, f)); clip = (vx*sx, vy*sy, vz*A + B, vz)
133 const float* axes[3] = {r, u, f};
134 const float scale[4] = {sx, sy, A, 1};
135 for (int k = 0; k < 4; ++k) {
136 const float* a = axes[k < 3 ? k : 2];
137 for (int j = 0; j < 3; ++j) out[j * 4 + k] = a[j] * scale[k];
138 out[12 + k] = -(a[0] * c.pos[0] + a[1] * c.pos[1] + a[2] * c.pos[2]) * scale[k] + (k == 2 ? B : 0);
139 }
140}
141
142// Ground under a point: highest scene triangle below z + 1 at (x, y), from a 4 m grid built once.
143struct Ground {
144 float cell = 4, x0 = 0, y0 = 0;
145 int nx = 0, ny = 0;
146 std::vector<std::vector<float>> tris; // per cell: 9 floats a triangle
147 void build(const Scene& s) {
148 float lo[2] = {1e30f, 1e30f}, hi[2] = {-1e30f, -1e30f};
149 std::vector<float> all;
150 for (const Draw& d : s.draws) {
151 const Mesh& m = s.meshes[d.mesh];
152 for (uint32_t i = 0; i + 2 < m.index_count; i += 3)
153 for (int k = 0; k < 3; ++k) {
154 const float* v = &s.vertices[size_t(m.first_vertex + s.indices[m.first_index + i + k]) * 8];
155 for (int j = 0; j < 3; ++j) {
156 const float w = v[0] * d.rows[0][j] + v[1] * d.rows[1][j] + v[2] * d.rows[2][j] + d.rows[3][j];
157 all.push_back(w);
158 if (j < 2) { lo[j] = std::min(lo[j], w); hi[j] = std::max(hi[j], w); }
159 }
160 }
161 }
162 if (all.empty()) return;
163 x0 = lo[0]; y0 = lo[1];
164 nx = std::min(4096, int((hi[0] - lo[0]) / cell) + 1); ny = std::min(4096, int((hi[1] - lo[1]) / cell) + 1);
165 tris.assign(size_t(nx) * ny, {});
166 for (size_t t = 0; t < all.size(); t += 9) {
167 const float* p = &all[t];
168 const float ax = std::min({p[0], p[3], p[6]}), bx = std::max({p[0], p[3], p[6]});
169 const float ay = std::min({p[1], p[4], p[7]}), by = std::max({p[1], p[4], p[7]});
170 if (bx - ax > 64 || by - ay > 64) continue; // skip huge sheets (skydomes, water planes)
171 for (int cy = std::max(0, int(std::floor((ay - y0) / cell))); cy <= std::min(ny - 1, int(std::floor((by - y0) / cell))); ++cy)
172 for (int cx = std::max(0, int(std::floor((ax - x0) / cell))); cx <= std::min(nx - 1, int(std::floor((bx - x0) / cell))); ++cx)
173 tris[size_t(cy) * nx + cx].insert(tris[size_t(cy) * nx + cx].end(), p, p + 9);
174 }
175 }
176 bool height(float x, float y, float below, float& out) const {
177 const int cx = int(std::floor((x - x0) / cell)), cy = int(std::floor((y - y0) / cell));
178 if (cx < 0 || cy < 0 || cx >= nx || cy >= ny) return false;
179 bool hit = false;
180 const auto& v = tris[size_t(cy) * nx + cx];
181 for (size_t t = 0; t < v.size(); t += 9) {
182 const float* p = &v[t];
183 const float d = (p[3] - p[0]) * (p[7] - p[1]) - (p[6] - p[0]) * (p[4] - p[1]);
184 if (std::fabs(d) < 1e-9f) continue;
185 const float a = ((p[3] - x) * (p[7] - y) - (p[6] - x) * (p[4] - y)) / d;
186 const float b = ((p[6] - x) * (p[1] - y) - (p[0] - x) * (p[7] - y)) / d;
187 const float c = 1 - a - b;
188 if (a < 0 || b < 0 || c < 0) continue;
189 const float z = a * p[2] + b * p[5] + c * p[8];
190 if (z <= below && (!hit || z > out)) { out = z; hit = true; }
191 }
192 return hit;
193 }
194};
195
196#ifdef _WIN32
197bool g_quit = false, g_look = false;
198int g_mx = 0, g_my = 0, g_dx = 0, g_dy = 0;
199LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM w, LPARAM l) {
200 switch (m) {
201 case WM_CLOSE: g_quit = true; return 0;
202 case WM_RBUTTONDOWN: g_look = true; g_mx = short(LOWORD(l)); g_my = short(HIWORD(l)); SetCapture(h); return 0;
203 case WM_RBUTTONUP: g_look = false; ReleaseCapture(); return 0;
204 case WM_MOUSEMOVE:
205 if (g_look) { const int x = short(LOWORD(l)), y = short(HIWORD(l)); g_dx += x - g_mx; g_dy += y - g_my; g_mx = x; g_my = y; }
206 return 0;
207 }
208 return DefWindowProcW(h, m, w, l);
209}
210#endif
211
212bool write_ppm(const char* path, const uint8_t* bgra_or_rgba, uint32_t w, uint32_t h, bool bgra) {
213 std::ofstream o(path, std::ios::binary);
214 o << "P6\n" << w << " " << h << "\n255\n";
215 for (size_t i = 0; i < size_t(w) * h; ++i) {
216 const uint8_t* p = bgra_or_rgba + i * 4;
217 const char px[3] = {char(p[bgra ? 2 : 0]), char(p[1]), char(p[bgra ? 0 : 2])};
218 o.write(px, 3);
219 }
220 return bool(o);
221}
222
223} // namespace
224
225int main(int argc, char** argv) {
226 if (argc < 4) {
227 std::fprintf(stderr, "usage: vk_sandbox scene.bin vs.spv ps.spv (--out image.ppm | --window) [--size W H] "
228 "[--cam x y z yaw pitch] [--fov deg]\n");
229 return 2;
230 }
231 Scene scene;
232 if (!load_scene(argv[1], scene)) { std::fprintf(stderr, "bad scene file %s\n", argv[1]); return 2; }
233 uint32_t W = 1280, H = 720;
234 const char* out_path = nullptr;
235 bool window = false;
236 int frames = 0; // --frames N: window test run, shown without activation, quits after N frames
237 Camera cam{};
238 cam.pos[0] = scene.center[0] - 40; cam.pos[1] = scene.center[1] - 40; cam.pos[2] = scene.center[2] + 25;
239 cam.yaw = 0.785398f; cam.pitch = -0.35f;
240 for (int i = 4; i < argc; ++i) {
241 if (!std::strcmp(argv[i], "--out") && i + 1 < argc) out_path = argv[++i];
242 else if (!std::strcmp(argv[i], "--window")) window = true;
243 else if (!std::strcmp(argv[i], "--frames") && i + 1 < argc) frames = std::atoi(argv[++i]);
244 else if (!std::strcmp(argv[i], "--mode") && i + 1 < argc) {
245 const char* m = argv[++i];
246 cam.mode = !std::strcmp(m, "walk") ? 1 : !std::strcmp(m, "drive") ? 2 : 0;
247 }
248 else if (!std::strcmp(argv[i], "--size") && i + 2 < argc) { W = std::atoi(argv[++i]); H = std::atoi(argv[++i]); }
249 else if (!std::strcmp(argv[i], "--fov") && i + 1 < argc) cam.fov = float(std::atof(argv[++i]));
250 else if (!std::strcmp(argv[i], "--cam") && i + 5 < argc) {
251 for (int k = 0; k < 3; ++k) cam.pos[k] = float(std::atof(argv[++i]));
252 cam.yaw = float(std::atof(argv[++i])) * 3.14159265f / 180; cam.pitch = float(std::atof(argv[++i])) * 3.14159265f / 180;
253 } else { std::fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; }
254 }
255#ifndef _WIN32
256 if (window) { std::fprintf(stderr, "--window needs Windows\n"); return 2; }
257#endif
258 if (window && frames && !out_path) { std::fprintf(stderr, "--frames needs --out\n"); return 2; }
259 if (!out_path && !window) { std::fprintf(stderr, "give --out or --window\n"); return 2; }
260 std::fprintf(stderr, "scene: %zu draws, %zu meshes, %zu textures, %zu triangles\n", scene.draws.size(),
261 scene.meshes.size(), scene.textures.size(), scene.indices.size() / 3);
262
263 gipa = load_vulkan();
264 if (!gipa) { std::fprintf(stderr, "the Vulkan loader was not found\n"); return 77; }
265 VkInstance inst = VK_NULL_HANDLE;
266#define LI(n) auto n = reinterpret_cast<PFN_##n>(gipa(inst, #n))
267 LI(vkCreateInstance);
268 VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.apiVersion = VK_API_VERSION_1_2;
269 const char* inst_ext[2] = {"VK_KHR_surface", "VK_KHR_win32_surface"};
270 VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; ici.pApplicationInfo = &app;
271 if (window) { ici.enabledExtensionCount = 2; ici.ppEnabledExtensionNames = inst_ext; }
272 if (vkCreateInstance(&ici, nullptr, &inst) != VK_SUCCESS) { std::fprintf(stderr, "unsupported: no Vulkan instance\n"); return 77; }
273 LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties);
274 LI(vkGetPhysicalDeviceMemoryProperties); LI(vkCreateDevice); LI(vkGetDeviceProcAddr);
275 uint32_t n = 0;
276 CHECK(vkEnumeratePhysicalDevices(inst, &n, nullptr));
277 if (!n) { std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); return 77; }
278 std::vector<VkPhysicalDevice> pds(n);
279 CHECK(vkEnumeratePhysicalDevices(inst, &n, pds.data()));
280 VkPhysicalDevice pd = VK_NULL_HANDLE;
281 VkPhysicalDeviceProperties props{};
282 int best = -1;
283 for (auto p : pds) {
284 VkPhysicalDeviceProperties pp; vkGetPhysicalDeviceProperties(p, &pp);
285 if (int r = leonida::vk_test::device_rank(pp.deviceType, pp.vendorID); r > best) { pd = p; props = pp; best = r; }
286 }
287 constexpr uint32_t push_words = 36, push_bytes = push_words * 4;
288 if (props.limits.maxPushConstantsSize < push_bytes) { std::fprintf(stderr, "unsupported: push constants\n"); return 77; }
289 std::fprintf(stderr, "device: %s\n", props.deviceName);
290 uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr);
291 std::vector<VkQueueFamilyProperties> qf(qn); vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data());
292 uint32_t qi = 0;
293 while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi;
294 if (qi == qn) { std::fprintf(stderr, "unsupported: no graphics queue\n"); return 77; }
295
296#ifdef _WIN32
297 HWND hwnd = nullptr;
298 VkSurfaceKHR surface = VK_NULL_HANDLE;
299 if (window) {
300 WNDCLASSW wc{}; wc.lpfnWndProc = wndproc; wc.hInstance = GetModuleHandleW(nullptr); wc.lpszClassName = L"vk_sandbox";
301 wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
302 RegisterClassW(&wc);
303 RECT rc{0, 0, LONG(W), LONG(H)}; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
304 hwnd = CreateWindowExW(0, L"vk_sandbox", L"Leonida real-shader sandbox", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
305 CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, wc.hInstance, nullptr);
306 ShowWindow(hwnd, frames ? SW_SHOWNOACTIVATE : SW_SHOWNORMAL);
307 LI(vkCreateWin32SurfaceKHR);
308 VkWin32SurfaceCreateInfoKHR sci{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR};
309 sci.hinstance = wc.hInstance; sci.hwnd = hwnd;
310 CHECK(vkCreateWin32SurfaceKHR(inst, &sci, nullptr, &surface));
311 }
312#endif
313
314 float prio = 1;
315 VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
316 qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio;
317 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
318 f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE;
319 f12.shaderSampledImageArrayNonUniformIndexing = VK_TRUE;
320 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12;
321 f2.features.shaderInt64 = VK_TRUE;
322 const char* dev_ext[1] = {"VK_KHR_swapchain"};
323 VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
324 dci.pNext = &f2; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci;
325 if (window) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = dev_ext; }
326 VkDevice dev; CHECK(vkCreateDevice(pd, &dci, nullptr, &dev));
327#define LD(n) auto n = reinterpret_cast<PFN_##n>(vkGetDeviceProcAddr(dev, #n))
328 LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory);
329 LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer);
330 LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool);
331 LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline);
332 LD(vkCmdDrawIndexed); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage);
333 LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); LD(vkResetCommandBuffer);
334 LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress);
335 LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets);
336 LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier);
337 LD(vkCmdBindVertexBuffers); LD(vkCmdBindIndexBuffer); LD(vkCmdBlitImage);
338 VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q);
339 VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp);
340 auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) {
341 for (uint32_t i = 0; i < mp.memoryTypeCount; i++)
342 if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i;
343 return 0u;
344 };
345 auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) {
346 VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage;
347 VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); if (r) return r;
348 VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr);
349 VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
350 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.pNext = &fi; ai.allocationSize = mr.size;
351 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
352 VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r;
353 r = vkBindBufferMemory(dev, *b, m, 0); if (r) return r;
354 return vkMapMemory(dev, m, 0, size, 0, map);
355 };
356 auto make_image = [&](uint32_t w, uint32_t h, VkFormat fmt, VkImageUsageFlags usage, VkImageAspectFlags aspect,
357 VkImage* img, VkImageView* view) {
358 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
359 ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {w, h, 1}; ii.mipLevels = 1; ii.arrayLayers = 1;
360 ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = usage;
361 VkResult r = vkCreateImage(dev, &ii, nullptr, img); if (r) return r;
362 VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, *img, &mr);
363 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size;
364 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
365 VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r;
366 r = vkBindImageMemory(dev, *img, m, 0); if (r) return r;
367 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
368 vi.image = *img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; vi.subresourceRange = {aspect, 0, 1, 0, 1};
369 return vkCreateImageView(dev, &vi, nullptr, view);
370 };
371
372 // Heap: the Xbox GPU VA window. 0x1000 view constants, 0x1200 colour constants, then 0x80 per draw: the
373 // descriptor table at +0 (0x70 bytes used) and nothing else; object constants follow all tables.
374 const uint32_t view_va = 0x1000, colour_va = 0x1200, table_va = 0x2000;
375 const uint32_t ndraw = uint32_t(scene.draws.size());
376 const uint32_t object_va = table_va + ndraw * 0x80;
377 const VkDeviceSize heap_bytes = object_va + VkDeviceSize(ndraw) * 0x40 + 0x1000;
378 VkBuffer heap; void* heapp;
379 CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapp));
380 std::memset(heapp, 0, size_t(heap_bytes));
381 auto heap_u32 = [&](uint32_t va) { return reinterpret_cast<uint32_t*>(static_cast<char*>(heapp) + va); };
382 auto heap_f32 = [&](uint32_t va) { return reinterpret_cast<float*>(static_cast<char*>(heapp) + va); };
383 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap;
384 const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai);
385 // A raw V#: base in word0/word1[15:0], stride 0, NUM_RECORDS bytes, OOB_SELECT 3 (raw byte range).
386 auto vsharp = [&](uint32_t at, uint32_t base, uint32_t bytes) {
387 uint32_t* p = heap_u32(at); p[0] = base; p[1] = 0; p[2] = bytes; p[3] = 3u << 28;
388 };
389 // T# keys: unique words per texture with the RGBA8 UNORM format in word 1 (the numeric type the shader reads).
390 const uint32_t fmt_word = leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM) << 20;
391 auto tsharp = [&](uint32_t image) {
392 std::array<uint32_t, 8> t{0x5A000000u | image, fmt_word, 0x7FF7FFu, 0, 0, 0, 0, 0};
393 return t;
394 };
395 const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws
396 leonida::DescriptorTable table(2 * (nimg + 2));
397 for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i);
398 uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S#
399 table.insert(ssharp, 0);
400 for (uint32_t d = 0; d < ndraw; ++d) {
401 const Draw& dr = scene.draws[d];
402 const uint32_t t = table_va + d * 0x80, o = object_va + d * 0x40;
403 vsharp(t + 0x00, o, 0x40);
404 const auto ts = tsharp(dr.texture < 0 ? 0 : uint32_t(dr.texture) + 1);
405 std::memcpy(heap_u32(t + 0x20), ts.data(), 32);
406 vsharp(t + 0x40, view_va, 0x1a0);
407 vsharp(t + 0x60, colour_va, 0x10);
408 float* ob = heap_f32(o);
409 for (int r = 0; r < 4; ++r) for (int j = 0; j < 3; ++j) ob[r * 4 + j] = dr.rows[r][j];
410 }
411 float* colour = heap_f32(colour_va); colour[0] = colour[1] = colour[2] = colour[3] = 1;
412 float* light = heap_f32(view_va + 0xa0);
413 { const float l[3] = {-0.55f, -0.45f, 0.7f}; const float ln = std::sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]);
414 for (int k = 0; k < 3; ++k) light[k] = l[k] / ln; }
415 const auto gpu_table = table.build_gpu_buffer(true);
416 VkBuffer tb; void* tbp;
417 CHECK(make_buffer(gpu_table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp));
418 std::memcpy(tbp, gpu_table.data(), gpu_table.size() * 4);
419
420 // Geometry.
421 VkBuffer vb, ib; void* vbp; void* ibp;
422 CHECK(make_buffer(std::max<size_t>(32, scene.vertices.size() * 4), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &vb, &vbp));
423 CHECK(make_buffer(std::max<size_t>(4, scene.indices.size() * 4), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, &ib, &ibp));
424 std::memcpy(vbp, scene.vertices.data(), scene.vertices.size() * 4);
425 std::memcpy(ibp, scene.indices.data(), scene.indices.size() * 4);
426
427 // Textures.
428 std::vector<VkImage> timg(nimg); std::vector<VkImageView> tview(nimg);
429 VkDeviceSize up_bytes = 4;
430 for (const auto& t : scene.textures) up_bytes += t.rgba.size();
431 VkBuffer up; void* upp;
432 CHECK(make_buffer(up_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up, &upp));
433 std::vector<VkDeviceSize> up_off(nimg);
434 { const uint32_t white = 0xFFFFFFFFu; std::memcpy(upp, &white, 4); VkDeviceSize at = 4;
435 for (uint32_t i = 1; i < nimg; ++i) { up_off[i] = at; std::memcpy(static_cast<char*>(upp) + at, scene.textures[i - 1].rgba.data(), scene.textures[i - 1].rgba.size()); at += scene.textures[i - 1].rgba.size(); } }
436 for (uint32_t i = 0; i < nimg; ++i)
437 CHECK(make_image(i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, VK_FORMAT_R8G8B8A8_UNORM,
438 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &timg[i], &tview[i]));
439 VkSamplerCreateInfo sci = leonida::gfx10::vulkan_sampler(leonida::gfx10::decode(
440 leonida::gfx10::SamplerWords{ssharp[0], ssharp[1], ssharp[2], ssharp[3]}));
441 sci.maxLod = 0; // the scene stores mip 0 only
442 VkSampler smp; CHECK(vkCreateSampler(dev, &sci, nullptr, &smp));
443
444 // Targets: RGBA8 colour + D32 depth.
445 const VkFormat cfmt = VK_FORMAT_R8G8B8A8_UNORM, dfmt = VK_FORMAT_D32_SFLOAT;
446 VkImage rt, dt; VkImageView rtv, dtv;
447 CHECK(make_image(W, H, cfmt, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &rt, &rtv));
448 CHECK(make_image(W, H, dfmt, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, &dt, &dtv));
449 VkAttachmentDescription ad[2]{};
450 ad[0].format = cfmt; ad[0].samples = VK_SAMPLE_COUNT_1_BIT; ad[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
451 ad[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; ad[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
452 ad[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
453 ad[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ad[0].finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
454 ad[1] = ad[0]; ad[1].format = dfmt; ad[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
455 ad[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
456 VkAttachmentReference car{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, dar{1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
457 VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
458 sd.colorAttachmentCount = 1; sd.pColorAttachments = &car; sd.pDepthStencilAttachment = &dar;
459 VkSubpassDependency dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
460 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT};
461 VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
462 rpi.attachmentCount = 2; rpi.pAttachments = ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd;
463 rpi.dependencyCount = 1; rpi.pDependencies = &dep;
464 VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp));
465 VkImageView fbv[2] = {rtv, dtv};
466 VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
467 fbi.renderPass = rp; fbi.attachmentCount = 2; fbi.pAttachments = fbv; fbi.width = W; fbi.height = H; fbi.layers = 1;
468 VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb));
469
470 // Descriptor set: binding 0 images[], 1 samplers[], 2 the descriptor hash table.
471 VkDescriptorSetLayoutBinding b[3]{};
472 b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
473 b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
474 b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
475 VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 3; dli.pBindings = b;
476 VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl));
477 VkDescriptorPoolSize ps[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}};
478 VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 3; dpi.pPoolSizes = ps;
479 VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp));
480 VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl;
481 VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds));
482 std::vector<VkDescriptorImageInfo> iinfo(nimg);
483 for (uint32_t i = 0; i < nimg; ++i) iinfo[i] = {VK_NULL_HANDLE, tview[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
484 VkDescriptorImageInfo sinfo{smp};
485 VkDescriptorBufferInfo tinfo{tb, 0, VK_WHOLE_SIZE};
486 VkWriteDescriptorSet wr[3]{};
487 for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; }
488 wr[0].dstBinding = 0; wr[0].descriptorCount = nimg; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = iinfo.data();
489 wr[1].dstBinding = 1; wr[1].descriptorCount = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &sinfo;
490 wr[2].dstBinding = 2; wr[2].descriptorCount = 1; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tinfo;
491 vkUpdateDescriptorSets(dev, 3, wr, 0, nullptr);
492
493 // Pipeline: the translated VS and PS, vertices (pos, normal, uv) at locations 0..2, depth test, no culling.
494 auto module = [&](const char* p, VkShaderModule* m) {
495 auto code = read_spv(p);
496 if (code.empty()) { std::fprintf(stderr, "cannot read %s\n", p); return VK_ERROR_INITIALIZATION_FAILED; }
497 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data();
498 return vkCreateShaderModule(dev, &smi, nullptr, m);
499 };
500 VkShaderModule vs, fs; CHECK(module(argv[2], &vs)); CHECK(module(argv[3], &fs));
501 VkPipelineShaderStageCreateInfo st[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}};
502 st[0].stage = VK_SHADER_STAGE_VERTEX_BIT; st[0].module = vs; st[0].pName = "main";
503 st[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; st[1].module = fs; st[1].pName = "main";
504 VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes};
505 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
506 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
507 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
508 VkVertexInputBindingDescription vbd{0, 32, VK_VERTEX_INPUT_RATE_VERTEX};
509 VkVertexInputAttributeDescription vad[3]{{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32_SFLOAT, 12},
510 {2, 0, VK_FORMAT_R32G32_SFLOAT, 24}};
511 VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
512 vin.vertexBindingDescriptionCount = 1; vin.pVertexBindingDescriptions = &vbd;
513 vin.vertexAttributeDescriptionCount = 3; vin.pVertexAttributeDescriptions = vad;
514 VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
515 // D3D clip space has y up: a negative-height viewport (Vulkan 1.1) keeps the game's matrices unchanged.
516 VkViewport vp{0, float(H), float(W), -float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}};
517 VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
518 vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = &sc;
519 VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1;
520 VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
521 VkPipelineDepthStencilStateCreateInfo dss{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
522 dss.depthTestEnable = VK_TRUE; dss.depthWriteEnable = VK_TRUE; dss.depthCompareOp = VK_COMPARE_OP_LESS;
523 VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF;
524 VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba;
525 VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
526 gpi.stageCount = 2; gpi.pStages = st; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; gpi.pViewportState = &vps;
527 gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pDepthStencilState = &dss; gpi.pColorBlendState = &cb;
528 gpi.layout = pl; gpi.renderPass = rp;
529 VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe));
530
531 VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi;
532 cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
533 VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool));
534 VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.commandBufferCount = 1;
535 VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd));
536 auto barrier = [&](VkImage img, VkImageLayout from, VkImageLayout to, VkAccessFlags sa, VkAccessFlags da,
537 VkPipelineStageFlags ss, VkPipelineStageFlags dst) {
538 VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
539 ib.oldLayout = from; ib.newLayout = to; ib.image = img; ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
540 ib.srcAccessMask = sa; ib.dstAccessMask = da; ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
541 vkCmdPipelineBarrier(cmd, ss, dst, 0, 0, nullptr, 0, nullptr, 1, &ib);
542 };
543 auto submit = [&]() { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
544 VkResult r = vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE); return r ? r : vkQueueWaitIdle(q); };
545 { // Upload the textures once.
546 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
547 for (uint32_t i = 0; i < nimg; ++i) {
548 barrier(timg[i], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
549 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
550 VkBufferImageCopy c{}; c.bufferOffset = up_off[i]; c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
551 c.imageExtent = {i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, 1};
552 vkCmdCopyBufferToImage(cmd, up, timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c);
553 barrier(timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT,
554 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
555 }
556 CHECK(vkEndCommandBuffer(cmd)); CHECK(submit());
557 }
558 // Records the scene into rt (left in TRANSFER_SRC_OPTIMAL). The caller ends and submits.
559 auto record = [&]() {
560 view_projection(cam, float(W) / float(H), heap_f32(view_va + 0x160));
561 VkClearValue clear[2]{}; clear[0].color = {{0.55f, 0.68f, 0.85f, 1}}; clear[1].depthStencil = {1, 0};
562 VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
563 rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 2; rbi.pClearValues = clear;
564 vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE);
565 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
566 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr);
567 VkDeviceSize zero = 0;
568 vkCmdBindVertexBuffers(cmd, 0, 1, &vb, &zero);
569 vkCmdBindIndexBuffer(cmd, ib, 0, VK_INDEX_TYPE_UINT32);
570 uint32_t pc[push_words] = {};
571 pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32);
572 for (uint32_t d = 0; d < ndraw; ++d) {
573 const Mesh& m = scene.meshes[scene.draws[d].mesh];
574 pc[8] = table_va + d * 0x80; // s8: the descriptor table; s9 (the PS's M0) stays 0
575 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes, pc);
576 vkCmdDrawIndexed(cmd, m.index_count, 1, m.first_index, int32_t(m.first_vertex), 0);
577 }
578 vkCmdEndRenderPass(cmd);
579 };
580 VkBuffer rb; void* rbp;
581 CHECK(make_buffer(VkDeviceSize(W) * H * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb, &rbp));
582 auto read_back = [&]() {
583 VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1};
584 vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc);
585 };
586
587 if (!window) {
588 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
589 record(); read_back();
590 CHECK(vkEndCommandBuffer(cmd)); CHECK(submit());
591 if (!write_ppm(out_path, static_cast<const uint8_t*>(rbp), W, H, false)) { std::fprintf(stderr, "cannot write %s\n", out_path); return 1; }
592 // Coverage: pixels that differ from the clear colour were written by the translated PS.
593 const uint8_t* px = static_cast<const uint8_t*>(rbp);
594 const uint8_t clear_px[3] = {uint8_t(0.55f * 255 + 0.5f), uint8_t(0.68f * 255 + 0.5f), uint8_t(0.85f * 255 + 0.5f)};
595 size_t covered = 0;
596 for (size_t i = 0; i < size_t(W) * H; ++i)
597 covered += std::abs(px[i * 4] - clear_px[0]) > 1 || std::abs(px[i * 4 + 1] - clear_px[1]) > 1 || std::abs(px[i * 4 + 2] - clear_px[2]) > 1;
598 std::printf("vk_sandbox: %u draws, %zu of %u pixels covered -> %s\n", ndraw, covered, W * H, out_path);
599 return 0;
600 }
601
602#ifdef _WIN32
603 LI(vkGetPhysicalDeviceSurfaceCapabilitiesKHR); LI(vkGetPhysicalDeviceSurfaceFormatsKHR); LI(vkGetPhysicalDeviceSurfaceSupportKHR);
604 LD(vkCreateSwapchainKHR); LD(vkDestroySwapchainKHR); LD(vkGetSwapchainImagesKHR); LD(vkAcquireNextImageKHR);
605 LD(vkQueuePresentKHR); LD(vkCreateSemaphore);
606 VkBool32 can_present = VK_FALSE; vkGetPhysicalDeviceSurfaceSupportKHR(pd, qi, surface, &can_present);
607 if (!can_present) { std::fprintf(stderr, "the graphics queue cannot present\n"); return 1; }
608 uint32_t nf = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, nullptr);
609 std::vector<VkSurfaceFormatKHR> sfs(nf); vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, sfs.data());
610 if (sfs.empty()) { std::fprintf(stderr, "the surface has no formats\n"); return 1; }
611 VkSurfaceFormatKHR sf = sfs[0]; // a UNORM format keeps the blit byte-exact with the headless render
612 for (const VkSurfaceFormatKHR& c : sfs)
613 if (c.format == VK_FORMAT_B8G8R8A8_UNORM || c.format == VK_FORMAT_R8G8B8A8_UNORM) { sf = c; break; }
614 VkSwapchainCreateInfoKHR swi{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};
615 VkSwapchainKHR swap = VK_NULL_HANDLE;
616 std::vector<VkImage> simg;
617 // (Re)creates the swapchain for the window's current size; false while it is minimised (extent 0).
618 auto make_swap = [&]() -> int {
619 VkSurfaceCapabilitiesKHR caps;
620 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(pd, surface, &caps) != VK_SUCCESS) return -1;
621 if (!(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) return -1;
622 const VkExtent2D ext = caps.currentExtent.width != 0xFFFFFFFFu ? caps.currentExtent : VkExtent2D{W, H};
623 if (!ext.width || !ext.height) return 0;
624 vkQueueWaitIdle(q);
625 swi.surface = surface; swi.minImageCount = std::max(2u, caps.minImageCount);
626 if (caps.maxImageCount) swi.minImageCount = std::min(swi.minImageCount, caps.maxImageCount);
627 swi.imageFormat = sf.format; swi.imageColorSpace = sf.colorSpace; swi.imageExtent = ext;
628 swi.imageArrayLayers = 1; swi.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; swi.preTransform = caps.currentTransform;
629 swi.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swi.presentMode = VK_PRESENT_MODE_FIFO_KHR; swi.clipped = VK_TRUE;
630 swi.oldSwapchain = swap;
631 VkSwapchainKHR next;
632 if (vkCreateSwapchainKHR(dev, &swi, nullptr, &next) != VK_SUCCESS) return -1;
633 if (swap) vkDestroySwapchainKHR(dev, swap, nullptr);
634 swap = next;
635 uint32_t ns = 0; vkGetSwapchainImagesKHR(dev, swap, &ns, nullptr);
636 simg.resize(ns); vkGetSwapchainImagesKHR(dev, swap, &ns, simg.data());
637 return 1;
638 };
639 if (make_swap() < 0) { std::fprintf(stderr, "cannot create a swapchain (TRANSFER_DST unsupported?)\n"); return 1; }
640 VkSemaphoreCreateInfo semi{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
641 VkSemaphore acquired; CHECK(vkCreateSemaphore(dev, &semi, nullptr, &acquired));
642 Ground ground; ground.build(scene);
643 auto last = std::chrono::steady_clock::now();
644 bool shot_held = false;
645 int frame = 0;
646 while (!g_quit) {
647 MSG msg;
648 while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); }
649 const auto now = std::chrono::steady_clock::now();
650 const float dt = std::min(0.1f, std::chrono::duration<float>(now - last).count()); last = now;
651 const bool focus = GetForegroundWindow() == hwnd;
652 auto key = [&](int vk) { return focus && (GetAsyncKeyState(vk) & 0x8000); };
653 if (key(VK_ESCAPE)) break;
654 if (key('1')) cam.mode = 0; if (key('2')) cam.mode = 1; if (key('3')) cam.mode = 2;
655 cam.yaw -= g_dx * 0.004f; cam.pitch = std::clamp(cam.pitch - g_dy * 0.004f, -1.5f, 1.5f); g_dx = g_dy = 0;
656 float f[3]; cam.forward(f);
657 const float r[2] = {std::sin(cam.yaw), -std::cos(cam.yaw)};
658 const float fwd = float(key('W')) - float(key('S')), side = float(key('D')) - float(key('A'));
659 if (cam.mode == 0) {
660 const float v = (key(VK_SHIFT) ? 60.f : 12.f) * dt;
661 for (int k = 0; k < 3; ++k) cam.pos[k] += f[k] * fwd * v;
662 cam.pos[0] += r[0] * side * v; cam.pos[1] += r[1] * side * v;
663 cam.pos[2] += (float(key('E')) - float(key('Q'))) * v;
664 } else {
665 const float h = std::hypot(f[0], f[1]) > 1e-4f ? std::hypot(f[0], f[1]) : 1;
666 if (cam.mode == 1) cam.speed = fwd * (key(VK_SHIFT) ? 7.f : 2.5f);
667 else { cam.speed += fwd * 12.f * dt; cam.speed *= std::pow(0.6f, dt); cam.yaw -= side * dt * std::clamp(cam.speed / 10.f, -1.f, 1.f); }
668 cam.pos[0] += f[0] / h * cam.speed * dt; cam.pos[1] += f[1] / h * cam.speed * dt;
669 if (cam.mode == 1) { cam.pos[0] += r[0] * side * 2.5f * dt; cam.pos[1] += r[1] * side * 2.5f * dt; }
670 const float eye = cam.mode == 1 ? 1.7f : 1.2f;
671 float gz;
672 if (ground.height(cam.pos[0], cam.pos[1], cam.pos[2] - eye + 0.6f, gz)) cam.pos[2] = gz + eye;
673 }
674 uint32_t idx = 0;
675 if (!swap) { // minimised at start or since the last resize
676 const int made = make_swap();
677 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
678 if (!made) { Sleep(50); continue; }
679 }
680 const VkResult acq = vkAcquireNextImageKHR(dev, swap, UINT64_MAX, acquired, VK_NULL_HANDLE, &idx);
681 if (acq == VK_ERROR_OUT_OF_DATE_KHR) {
682 const int made = make_swap();
683 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
684 if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; Sleep(50); }
685 continue;
686 }
687 if (acq != VK_SUCCESS && acq != VK_SUBOPTIMAL_KHR) { std::fprintf(stderr, "vkAcquireNextImageKHR failed (%d)\n", int(acq)); return 1; }
688 CHECK(vkResetCommandBuffer(cmd, 0));
689 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
690 record();
691 const bool last_frame = frames && ++frame >= frames;
692 const bool shot = (key('P') && !shot_held) || last_frame; shot_held = key('P');
693 if (shot) read_back();
694 barrier(simg[idx], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
695 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
696 VkImageBlit bl{}; bl.srcSubresource = bl.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
697 bl.srcOffsets[1] = {int32_t(W), int32_t(H), 1};
698 bl.dstOffsets[1] = {int32_t(swi.imageExtent.width), int32_t(swi.imageExtent.height), 1};
699 vkCmdBlitImage(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bl, VK_FILTER_LINEAR);
700 barrier(simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, 0,
701 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
702 CHECK(vkEndCommandBuffer(cmd));
703 VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
704 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.waitSemaphoreCount = 1; si.pWaitSemaphores = &acquired;
705 si.pWaitDstStageMask = &wait_stage; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
706 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q));
707 if (shot) {
708 const char* path = last_frame ? out_path : "sandbox_shot.ppm";
709 if (!write_ppm(path, static_cast<const uint8_t*>(rbp), W, H, false)) {
710 std::fprintf(stderr, "cannot write %s\n", path);
711 if (last_frame) return 1;
712 }
713 }
714 VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; pi.swapchainCount = 1; pi.pSwapchains = &swap; pi.pImageIndices = &idx;
715 const VkResult pres = vkQueuePresentKHR(q, &pi);
716 if ((pres == VK_ERROR_OUT_OF_DATE_KHR || pres == VK_SUBOPTIMAL_KHR || acq == VK_SUBOPTIMAL_KHR) && !last_frame) {
717 const int made = make_swap();
718 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
719 if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; }
720 }
721 char title[160];
722 std::snprintf(title, sizeof title, "Leonida real-shader sandbox [%s] %.0f %.0f %.0f %.0f fps", cam.mode == 0 ? "fly" : cam.mode == 1 ? "walk" : "drive",
723 cam.pos[0], cam.pos[1], cam.pos[2], 1.f / std::max(dt, 1e-4f));
724 SetWindowTextA(hwnd, title);
725 if (last_frame) {
726 std::printf("vk_sandbox: window ran %d frames -> %s, camera %.2f %.2f %.2f\n", frame, out_path,
727 cam.pos[0], cam.pos[1], cam.pos[2]);
728 break;
729 }
730 }
731 vkQueueWaitIdle(q);
732#endif
733 return 0;
734}
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index a2191eae3..474264dcf 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -13,6 +13,7 @@
13// (x + 0.5) / 8) and a LESS_OR_EQUAL compare sampler at index 1; both of its results, f32 and d16, must be the 13// (x + 0.5) / 8) and a LESS_OR_EQUAL compare sampler at index 1; both of its results, f32 and d16, must be the
14// 1.0 or 0.0 the reference 0.5 gives against the texel each pixel reads. 14// 1.0 or 0.0 the reference 0.5 gives against the texel each pixel reads.
15// vk_texture_test dref_a16 [out.raw]: the same with ps_sample_c_lz_a16 (16-bit coordinates). 15// vk_texture_test dref_a16 [out.raw]: the same with ps_sample_c_lz_a16 (16-bit coordinates).
16// vk_texture_test dref_c / dref_c_b [out.raw]: the same with ps_sample_c (implicit LOD) / ps_sample_c_b (LOD bias).
16// VKT_HEAP_MB=<n>: size of the heap in MiB (default 64 KiB) 17// VKT_HEAP_MB=<n>: size of the heap in MiB (default 64 KiB)
17// VKT_NEED_MAINTENANCE8=1: the shader has a non-constant texel Offset outside gather (image_sample*_o, see 18// VKT_NEED_MAINTENANCE8=1: the shader has a non-constant texel Offset outside gather (image_sample*_o, see
18// ps_texoff.asm); print "unsupported: ..." and exit 77 when VK_KHR_maintenance8 cannot be enabled. 19// ps_texoff.asm); print "unsupported: ..." and exit 77 when VK_KHR_maintenance8 cannot be enabled.
@@ -72,8 +73,15 @@ int main(int argc, char** argv) {
72 std::string vs_path, fs_path, out_path; 73 std::string vs_path, fs_path, out_path;
73 int ptr_sgpr = 0; 74 int ptr_sgpr = 0;
74 const bool cube = argc >= 2 && !std::strcmp(argv[1], "cube"); 75 const bool cube = argc >= 2 && !std::strcmp(argv[1], "cube");
75 const bool dref_a16 = argc >= 2 && !std::strcmp(argv[1], "dref_a16"); 76 // dref_c / dref_c_b: image_sample_c / image_sample_c_b (implicit LOD, bias), same texture and expected results.
76 const bool dref = dref_a16 || (argc >= 2 && !std::strcmp(argv[1], "dref")); 77 const char* dref_ps = nullptr;
78 if (argc >= 2) {
79 if (!std::strcmp(argv[1], "dref")) dref_ps = "ps_sample_c_lz.spv";
80 else if (!std::strcmp(argv[1], "dref_a16")) dref_ps = "ps_sample_c_lz_a16.spv";
81 else if (!std::strcmp(argv[1], "dref_c")) dref_ps = "ps_sample_c.spv";
82 else if (!std::strcmp(argv[1], "dref_c_b")) dref_ps = "ps_sample_c_b.spv";
83 }
84 const bool dref = dref_ps != nullptr;
77 bool autonomous = false; 85 bool autonomous = false;
78 uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0, 86 uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0,
79 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; 87 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu};
@@ -102,15 +110,14 @@ int main(int argc, char** argv) {
102 return std::string("runtime/build/shaders/spirv/") + name; 110 return std::string("runtime/build/shaders/spirv/") + name;
103 }; 111 };
104 vs_path = find_spv("vs_ids.spv"); 112 vs_path = find_spv("vs_ids.spv");
105 fs_path = find_spv(cube ? "ps_cube_sample.spv" : dref_a16 ? "ps_sample_c_lz_a16.spv" 113 fs_path = find_spv(cube ? "ps_cube_sample.spv" : dref ? dref_ps : "ps_texture_sample.spv");
106 : dref ? "ps_sample_c_lz.spv" : "ps_texture_sample.spv");
107 const int out_arg = cube || dref ? 2 : 1; 114 const int out_arg = cube || dref ? 2 : 1;
108 out_path = argc > out_arg ? argv[out_arg] : "runtime/build/vk_texture_test_out.raw"; 115 out_path = argc > out_arg ? argv[out_arg] : "runtime/build/vk_texture_test_out.raw";
109 ptr_sgpr = 0; 116 ptr_sgpr = 0;
110 if (dref) 117 if (dref)
111 ssharp[0] |= 3u << 12; // the shader's S#: DEPTH_COMPARE_FUNC = LESSEQUAL 118 ssharp[0] |= 3u << 12; // the shader's S#: DEPTH_COMPARE_FUNC = LESSEQUAL
112 } else { 119 } else {
113 std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n"); 120 std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16|dref_c|dref_c_b] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n");
114 return 2; 121 return 2;
115 } 122 }
116 // Word 1 also selects the numeric type when the shader fetches through this key. Word 3 keeps BASE_LEVEL [15:12] 123 // Word 1 also selects the numeric type when the shader fetches through this key. Word 3 keeps BASE_LEVEL [15:12]
@@ -144,18 +151,16 @@ int main(int argc, char** argv) {
144 std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); 151 std::fprintf(stderr, "unsupported: no Vulkan physical device\n");
145 return 77; // a missing device is a skip in every texture-test mode 152 return 77; // a missing device is a skip in every texture-test mode
146 } 153 }
147 VkPhysicalDevice pd = VK_NULL_HANDLE; 154 // LEONIDA_VK_DEVICE picks one GPU on a machine with several, as in the other test programs.
148 VkPhysicalDeviceProperties properties{}; 155 std::vector<VkPhysicalDeviceProperties> candidates(n);
149 int best_rank = -1; 156 for (uint32_t i = 0; i < n; ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]);
150 for (uint32_t i = 0; i < n; ++i) { 157 const size_t chosen = leonida::vk_test::pick_device(candidates);
151 VkPhysicalDeviceProperties p; 158 if (chosen >= n) {
152 vkGetPhysicalDeviceProperties(pds[i], &p); 159 leonida::vk_test::report_no_device();
153 if (const int rank = leonida::vk_test::device_rank(p.deviceType, p.vendorID); rank > best_rank) { 160 return 1;
154 pd = pds[i];
155 properties = p;
156 best_rank = rank;
157 }
158 } 161 }
162 VkPhysicalDevice pd = pds[chosen];
163 VkPhysicalDeviceProperties properties = candidates[chosen];
159 constexpr uint32_t push_words = 36; 164 constexpr uint32_t push_words = 36;
160 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only; the heap base is in a uniform block at set 1 165 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only; the heap base is in a uniform block at set 1
161 // (vk_pc_tail.h), so a 128-byte device runs these tests too. 166 // (vk_pc_tail.h), so a 128-byte device runs these tests too.
@@ -211,7 +216,7 @@ int main(int argc, char** argv) {
211 for (auto& x : exts) m8_on = m8_on || !std::strcmp(x.extensionName, VK_KHR_MAINTENANCE_8_EXTENSION_NAME); 216 for (auto& x : exts) m8_on = m8_on || !std::strcmp(x.extensionName, VK_KHR_MAINTENANCE_8_EXTENSION_NAME);
212 if (m8_on) { 217 if (m8_on) {
213 enable.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); 218 enable.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME);
214 m8.maintenance8 = VK_TRUE; f12.pNext = &m8; 219 m8.maintenance8 = VK_TRUE; f11.pNext = &m8;
215 std::fprintf(stderr, "enabled %s\n", VK_KHR_MAINTENANCE_8_EXTENSION_NAME); 220 std::fprintf(stderr, "enabled %s\n", VK_KHR_MAINTENANCE_8_EXTENSION_NAME);
216 } 221 }
217#endif 222#endif
diff --git a/runtime/test/vulkan13_features_test.cpp b/runtime/test/vulkan13_features_test.cpp
index cf1b4d99c..d0c446495 100644
--- a/runtime/test/vulkan13_features_test.cpp
+++ b/runtime/test/vulkan13_features_test.cpp
@@ -248,11 +248,30 @@ int main() {
248 EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); 248 EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
249 EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); 249 EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2);
250 250
251 const auto* rendering = static_cast<const VkPhysicalDeviceDynamicRenderingFeaturesKHR*>(head);
252 const auto* sync2 = static_cast<const VkPhysicalDeviceSynchronization2FeaturesKHR*>(rendering->pNext);
253 EXPECT(rendering->dynamicRendering == VK_TRUE);
254 EXPECT(sync2->synchronization2 == VK_TRUE);
255
251 std::vector<const char*> exts; 256 std::vector<const char*> exts;
252 v13.add_extensions(exts); 257 v13.add_extensions(exts);
253 EXPECT(exts.size() == 2); 258 EXPECT(exts.size() == 2);
254 EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0); 259 EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0);
255 EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0); 260 EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0);
261
262 // Extensions advertised, but each required feature bit cleared in turn after a successful query.
263 dev.features2_calls = 0;
264 dev.dynamic_rendering = VK_FALSE;
265 dev.synchronization2 = VK_TRUE;
266 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
267 EXPECT(dev.features2_calls == 1);
268 EXPECT(!v13.core && !v13.dynamic_rendering && v13.synchronization2 && !v13.usable());
269
270 dev.dynamic_rendering = VK_TRUE;
271 dev.synchronization2 = VK_FALSE;
272 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
273 EXPECT(dev.features2_calls == 2);
274 EXPECT(!v13.core && v13.dynamic_rendering && !v13.synchronization2 && !v13.usable());
256 } 275 }
257 276
258 // Vulkan 1.2 with only EDS1 (missing EDS2), or both extensions with one feature bit false: EDS stays off. 277 // Vulkan 1.2 with only EDS1 (missing EDS2), or both extensions with one feature bit false: EDS stays off.
@@ -323,6 +342,15 @@ int main() {
323 EXPECT(types[4] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); 342 EXPECT(types[4] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
324 EXPECT(types[5] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); 343 EXPECT(types[5] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2);
325 344
345 const auto* rendering = static_cast<const VkPhysicalDeviceDynamicRenderingFeaturesKHR*>(head);
346 const auto* sync2 = static_cast<const VkPhysicalDeviceSynchronization2FeaturesKHR*>(rendering->pNext);
347 const auto* eds = static_cast<const VkPhysicalDeviceExtendedDynamicStateFeaturesEXT*>(sync2->pNext);
348 const auto* eds2 = static_cast<const VkPhysicalDeviceExtendedDynamicState2FeaturesEXT*>(eds->pNext);
349 EXPECT(rendering->dynamicRendering == VK_TRUE);
350 EXPECT(sync2->synchronization2 == VK_TRUE);
351 EXPECT(eds->extendedDynamicState == VK_TRUE);
352 EXPECT(eds2->extendedDynamicState2 == VK_TRUE);
353
326 std::vector<const char*> exts; 354 std::vector<const char*> exts;
327 chosen.add_extensions(exts); 355 chosen.add_extensions(exts);
328 EXPECT(exts.size() == 4); 356 EXPECT(exts.size() == 4);
@@ -332,6 +360,39 @@ int main() {
332 EXPECT(std::strcmp(exts[3], VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0); 360 EXPECT(std::strcmp(exts[3], VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0);
333 } 361 }
334 362
363 // choose() with a Vulkan 1.3 candidate preserves core=true and subgroup flags after source overwrite.
364 {
365 FakeDevice dev;
366 dev.dynamic_rendering = VK_TRUE;
367 dev.synchronization2 = VK_TRUE;
368 dev.subgroup_size_control = VK_TRUE;
369 dev.compute_full_subgroups = VK_TRUE;
370 g_device = &dev;
371
372 Vulkan13Features candidate;
373 candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr);
374 EXPECT(candidate.core && candidate.usable());
375
376 Vulkan13Features chosen;
377 chosen.choose(candidate);
378 candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions);
379 EXPECT(!candidate.core && !candidate.usable());
380 EXPECT(chosen.core && chosen.usable() && chosen.extended_dynamic_state);
381 EXPECT(chosen.subgroup_size_control && chosen.compute_full_subgroups);
382
383 VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr};
384 void* head = chosen.enable(&tail);
385 const auto* enable13 = static_cast<const VkPhysicalDeviceVulkan13Features*>(head);
386 EXPECT(enable13->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES);
387 EXPECT(enable13->dynamicRendering == VK_TRUE && enable13->synchronization2 == VK_TRUE);
388 EXPECT(enable13->subgroupSizeControl == VK_TRUE && enable13->computeFullSubgroups == VK_TRUE);
389 EXPECT(enable13->pNext == &tail);
390
391 std::vector<const char*> exts;
392 chosen.add_extensions(exts);
393 EXPECT(exts.empty());
394 }
395
335 // device_proc_or_khr resolves core first, then KHR, then EXT, else null. 396 // device_proc_or_khr resolves core first, then KHR, then EXT, else null.
336 { 397 {
337 ProcLookup lookup; 398 ProcLookup lookup;
diff --git a/runtime/test/winhttp_offline_test.cpp b/runtime/test/winhttp_offline_test.cpp
index 4181103fd..f7ea661de 100644
--- a/runtime/test/winhttp_offline_test.cpp
+++ b/runtime/test/winhttp_offline_test.cpp
@@ -10,6 +10,7 @@
10#include <chrono> 10#include <chrono>
11#include <cstdio> 11#include <cstdio>
12#include <cstring> 12#include <cstring>
13#include <vector>
13 14
14#include "shims.h" 15#include "shims.h"
15 16
@@ -84,6 +85,13 @@ double ms_since(std::chrono::steady_clock::time_point start) {
84 return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); 85 return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
85} 86}
86 87
88// HANDLE_CLOSING arrives on the callback thread, so a count read right after WinHttpCloseHandle can be short, and a
89// notification that comes late lands in the next block's count (TEST-721). Waits up to two seconds for `n`.
90bool wait_for_closing(const Seen& s, int n) {
91 for (int i = 0; i < 200 && s.closing.load() < n; ++i) Sleep(10);
92 return s.closing.load() >= n;
93}
94
87} // namespace 95} // namespace
88 96
89int main() { 97int main() {
@@ -256,7 +264,7 @@ int main() {
256 "and HANDLE_CLOSING follows once, after the error"); 264 "and HANDLE_CLOSING follows once, after the error");
257 close(connection); 265 close(connection);
258 close(session); 266 close(session);
259 check(seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once"); 267 check(wait_for_closing(seen, 3) && seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once");
260 } 268 }
261 269
262 // A callback that closes its request while handling the error, as libHttpClient-style code does. 270 // A callback that closes its request while handling the error, as libHttpClient-style code does.
@@ -277,6 +285,8 @@ int main() {
277 seen.close_in_callback = nullptr; 285 seen.close_in_callback = nullptr;
278 close(connection); 286 close(connection);
279 close(session); 287 close(session);
288 check(wait_for_closing(seen, 3) && seen.closing.load() == 3,
289 "the connection and the session report HANDLE_CLOSING before the next block counts its own");
280 } 290 }
281 291
282 // A request closed before its queued failure is delivered gets no error callback, only HANDLE_CLOSING. 292 // A request closed before its queued failure is delivered gets no error callback, only HANDLE_CLOSING.
@@ -300,6 +310,69 @@ int main() {
300 CloseHandle(seen.error_event); 310 CloseHandle(seen.error_event);
301 CloseHandle(seen.closing_event); 311 CloseHandle(seen.closing_event);
302 312
313 // WINHTTP_OPTION_CONTEXT_VALUE is inherited like the callback: a handle starts with the context its parent has
314 // when it is created, and keeps it when the parent's changes later. The host's winhttp.dll gave these values.
315 {
316 struct Event {
317 HINTERNET handle;
318 DWORD status;
319 DWORD_PTR context;
320 };
321 static std::vector<Event> events; // a synchronous session: every callback runs on this thread
322 const WINHTTP_STATUS_CALLBACK record = [](HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID, DWORD) {
323 events.push_back({handle, status, context});
324 };
325 const auto context_of = [&](HINTERNET handle) -> DWORD_PTR {
326 DWORD_PTR value = ~DWORD_PTR{0};
327 DWORD size = sizeof(value);
328 return query_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, &size) ? value : ~DWORD_PTR{0};
329 };
330 const auto set_context = [&](HINTERNET handle, DWORD_PTR value) {
331 return set_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)) != FALSE;
332 };
333 const auto context_at = [&](HINTERNET handle, DWORD status) -> DWORD_PTR {
334 for (const Event& e : events)
335 if (e.handle == handle && e.status == status) return e.context;
336 return ~DWORD_PTR{0};
337 };
338
339 const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0);
340 set_callback(session, record, WINHTTP_CALLBACK_FLAG_HANDLES, 0);
341 check(set_context(session, 7), "WINHTTP_OPTION_CONTEXT_VALUE can be set on a session");
342 const HINTERNET connection = connect(session, L"127.0.0.1", 1, 0);
343 const HINTERNET request = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER,
344 WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
345 check(context_of(connection) == 7 && context_of(request) == 7,
346 "a connection and a request start with the session's context");
347 check(context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == 7 &&
348 context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == 7,
349 "and their HANDLE_CREATED callbacks carry it");
350
351 check(set_context(request, 9) && context_of(request) == 9 && context_of(connection) == 7,
352 "a context set on the request replaces the inherited one for that request only");
353 check(set_context(session, 11) && context_of(connection) == 7 && context_of(request) == 9,
354 "a context set on the session later does not change handles that exist");
355 const HINTERNET late = connect(session, L"127.0.0.1", 1, 0);
356 check(context_of(late) == 11, "a connection made after that starts with the new one");
357
358 const HINTERNET sent = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER,
359 WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
360 check(context_of(sent) == 7, "a request starts with its connection's context, not the session's");
361 send(sent, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0x51);
362 check(context_of(sent) == 0x51, "the context WinHttpSendRequest is given replaces the inherited one");
363
364 close(sent);
365 close(request);
366 close(late);
367 close(connection);
368 close(session);
369 check(context_at(sent, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 0x51 &&
370 context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 9 &&
371 context_at(late, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 11 &&
372 context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 7,
373 "HANDLE_CLOSING carries each handle's own context");
374 }
375
303 // WinHttpCrackUrl is parsing only and stays the host's. 376 // WinHttpCrackUrl is parsing only and stays the host's.
304 { 377 {
305 wchar_t host[64] = {}, path[64] = {}; 378 wchar_t host[64] = {}, path[64] = {};
diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp
index 6ea54280a..bcea1e2a7 100644
--- a/runtime/test/xbox_present_test.cpp
+++ b/runtime/test/xbox_present_test.cpp
@@ -1263,21 +1263,63 @@ int main() {
1263 constexpr int frames = 30; 1263 constexpr int frames = 30;
1264 const auto start = std::chrono::steady_clock::now(); 1264 const auto start = std::chrono::steady_clock::now();
1265 std::uint64_t last = 0; 1265 std::uint64_t last = 0;
1266 for (int i = 0; i < frames; ++i) { 1266 // One real-time frame: wait for the origin, present colour `c`. True with `shown` false when the present was
1267 // skipped because the window is minimised (PresentX still S_OK, nothing on screen, nothing to read back).
1268 const auto real_frame = [&](int c, bool& shown) -> bool {
1267 pump(); 1269 pump();
1268 std::uint64_t t = 0; 1270 std::uint64_t t = 0;
1269 EXPECT(real.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 1000, 0, &t) == S_OK); 1271 if (real.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 1000, 0, &t) != S_OK || t != last + 1) {
1270 EXPECT(t == last + 1); 1272 std::fprintf(stderr, "real time: token %llu after %llu\n", static_cast<unsigned long long>(t),
1273 static_cast<unsigned long long>(last));
1274 return false;
1275 }
1271 last = t; 1276 last = t;
1272 auto p = plane_of(colours[i % 3], t); 1277 auto p = plane_of(colours[c], t);
1273 EXPECT(real.PresentX(1, &p, nullptr) == S_OK); 1278 if (real.PresentX(1, &p, nullptr) != S_OK) return false;
1274 EXPECT(real.presenter().read_back(frame.bytes, &frame.extent, &frame.format)); 1279 shown = real.presenter().read_back(frame.bytes, &frame.extent, &frame.format);
1275 EXPECT(close_to(frame.at(width / 2, height / 2), expect_rgb[i % 3], 0)); 1280 if (!shown) return IsIconic(window) != FALSE; // skipped only while minimised
1281 const Px got = frame.at(width / 2, height / 2);
1282 if (close_to(got, expect_rgb[c], 0)) return true;
1283 std::fprintf(stderr, "real time: centre %d,%d,%d, presented %d,%d,%d\n", got.r, got.g, got.b, expect_rgb[c].r,
1284 expect_rgb[c].g, expect_rgb[c].b);
1285 return false;
1286 };
1287 // Someone at the desktop can minimise the window during the loop (Win+D in the middle of a CTest run): those
1288 // presents are skipped, and the window is restored so the rest of the loop is seen again.
1289 int unseen = 0;
1290 for (int i = 0; i < frames; ++i) {
1291 bool shown = false;
1292 EXPECT(real_frame(i % 3, shown));
1293 if (!shown) {
1294 ++unseen;
1295 ShowWindow(window, SW_RESTORE);
1296 }
1276 } 1297 }
1277 const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count(); 1298 const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
1278 std::printf("real time: %d frames at 60 Hz in %lld ms (ideal %d)\n", frames, static_cast<long long>(ms), 1299 std::printf("real time: %d frames at 60 Hz in %lld ms (ideal %d), %d skipped while minimised\n", frames,
1279 frames * int(period) / 1000); 1300 static_cast<long long>(ms), frames * int(period) / 1000, unseen);
1280 EXPECT(ms >= (frames - 1) * int(period) / 1000 * 9 / 10 && ms < 5000); 1301 EXPECT(ms >= (frames - 1) * int(period) / 1000 * 9 / 10 && ms < 5000);
1302 EXPECT(unseen < frames);
1303
1304 // Minimised on purpose: the surface is 0x0 (VK_KHR_win32_surface), so PresentX succeeds without showing the
1305 // frame, and read_back must say so rather than hand out the frame before it (TEST-378: the real-time loop
1306 // above once compared that older frame). Each colour differs from the one shown last, so a stale frame fails.
1307 // Restored, the next frame is shown and read back again.
1308 {
1309 ShowWindow(window, SW_MINIMIZE);
1310 int skipped_presents = 0;
1311 for (int i = 0; i < 3; ++i) { // the first present can still reach the old swapchain (then out of date)
1312 bool shown = true;
1313 EXPECT(real_frame(i, shown));
1314 if (!shown) ++skipped_presents;
1315 }
1316 EXPECT(skipped_presents > 0);
1317 ShowWindow(window, SW_RESTORE);
1318 bool shown = false;
1319 for (int i = 0; i < 3 && !shown; ++i) EXPECT(real_frame((i + 1) % 3, shown)); // stale, then recreated
1320 EXPECT(shown);
1321 std::printf("minimised: %d of 3 presents skipped and not read back; restored: shown again\n", skipped_presents);
1322 }
1281 EXPECT(real.PresentX(0, nullptr, nullptr) == S_OK); // the shutdown blank 1323 EXPECT(real.PresentX(0, nullptr, nullptr) == S_OK); // the shutdown blank
1282 } 1324 }
1283 DestroyWindow(window); 1325 DestroyWindow(window);
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index 6464b4907..5102c54ab 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -231,7 +231,8 @@ void check_run_time_load() {
231 auto query = reinterpret_cast<Query>(get_proc(rt_mod, "QueryApiImpl")); 231 auto query = reinterpret_cast<Query>(get_proc(rt_mod, "QueryApiImpl"));
232 auto uninit_api = reinterpret_cast<Uninit>(get_proc(rt_mod, "UninitializeApiImpl")); 232 auto uninit_api = reinterpret_cast<Uninit>(get_proc(rt_mod, "UninitializeApiImpl"));
233 check(init_ex2(0x2410, 0x0, 0x02, &options) == S_OK, "InitializeApiImplEx2 succeeds offline"); 233 check(init_ex2(0x2410, 0x0, 0x02, &options) == S_OK, "InitializeApiImplEx2 succeeds offline");
234 const GUID some_class = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; 234 // XGameSaveImpl (xgameruntime include/xgamesave.idl), not served yet.
235 const GUID some_class = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}};
235 void* out = reinterpret_cast<void*>(1); 236 void* out = reinterpret_cast<void*>(1);
236 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr, 237 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr,
237 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer"); 238 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer");
@@ -489,13 +490,13 @@ void check_run_time_load() {
489 {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}}, 490 {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}},
490 {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}}, 491 {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}},
491 system5}; 492 system5};
492 bool all = true; 493 bool all_inherited = true;
493 for (const GUID& iid : chain) { 494 for (const GUID& iid : chain) {
494 void* same = nullptr; 495 void* same = nullptr;
495 all = all && query(&system_cls, iid, &same) == S_OK && same == sy; 496 all_inherited = all_inherited && query(&system_cls, iid, &same) == S_OK && same == sy;
496 if (same) release(same); 497 if (same) release(same);
497 } 498 }
498 check(all, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)"); 499 check(all_inherited, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)");
499 check(reinterpret_cast<IdQuery>(slot(sy, 5))(sy, sizeof(buf), buf, &used) == S_OK && used == 45 && 500 check(reinterpret_cast<IdQuery>(slot(sy, 5))(sy, sizeof(buf), buf, &used) == S_OK && used == 45 &&
500 reinterpret_cast<IdQuery>(slot(sy, 5))(sy, 44, buf, &used) == 501 reinterpret_cast<IdQuery>(slot(sy, 5))(sy, 44, buf, &used) ==
501 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && 502 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) &&
@@ -512,6 +513,186 @@ void check_run_time_load() {
512 "slots 6-8 (handle tracking, handle check, download bandwidth) answer offline"); 513 "slots 6-8 (handle tracking, handle check, download bandwidth) answer offline");
513 release(sy); 514 release(sy);
514 } 515 }
516
517 // XPackageImpl, asked for as libHttpClient.GDK.dll does: the class id with IXPackageImpl3's interface id. The
518 // slots with an offline answer agree with the named exports; the others are E_NOTIMPL.
519 const GUID package_cls = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}};
520 const GUID package3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}};
521 void* pk = nullptr;
522 check(query(&package_cls, package3, &pk) == S_OK && pk, "QueryApiImpl hands out XPackageImpl for IXPackageImpl3");
523 if (pk) {
524 using Ident = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*);
525 using IdentExport = HRESULT(__stdcall*)(size_t, char*);
526 char a[64] = {}, b[64] = {};
527 const auto ident_export = reinterpret_cast<IdentExport>(
528 rt::shims::find("xgameruntime.dll", "XPackageGetCurrentProcessPackageIdentifier"));
529 check(reinterpret_cast<Ident>(slot(pk, 3))(pk, sizeof(a), a) == S_OK && ident_export &&
530 ident_export(sizeof(b), b) == S_OK && std::strcmp(a, b) == 0,
531 "slot 3 is XPackageGetCurrentProcessPackageIdentifier, the same answer as the export");
532 using IsPackaged = bool(STDMETHODCALLTYPE*)(void*);
533 using IsPackagedExport = bool(__stdcall*)();
534 const auto packaged_export =
535 reinterpret_cast<IsPackagedExport>(rt::shims::find("xgameruntime.dll", "XPackageIsPackagedProcess"));
536 check(packaged_export && reinterpret_cast<IsPackaged>(slot(pk, 4))(pk) == packaged_export(),
537 "slot 4 is XPackageIsPackagedProcess");
538 // Slot 11, XPackageGetUserLocale: one of the package's declared locales, never the host's; nothing written
539 // (but S_OK) when the package declares none.
540 using Locale = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*);
541 char tmp[MAX_PATH] = {};
542 GetTempPathA(sizeof(tmp), tmp);
543 const std::string game = std::string(tmp) + "leonida_xpackage_locale_test";
544 CreateDirectoryA(game.c_str(), nullptr);
545 SetEnvironmentVariableA("LEONIDA_GAME_DIR", game.c_str());
546 char locale[128];
547 std::memset(locale, 'z', sizeof(locale));
548 check(reinterpret_cast<Locale>(slot(pk, 11))(pk, sizeof(locale), locale) == S_OK && locale[0] == 'z',
549 "slot 11 without declared locales: S_OK and nothing written");
550 if (FILE* f = std::fopen((game + "\\MicrosoftGame.Config").c_str(), "wb")) {
551 std::fputs("<Game><Resources><Resource Language=\"zz-ZZ\"/><Resource Language='xx-YY'/></Resources></Game>",
552 f);
553 std::fclose(f);
554 }
555 check(reinterpret_cast<Locale>(slot(pk, 11))(pk, sizeof(locale), locale) == S_OK &&
556 (std::strcmp(locale, "zz-ZZ") == 0 || std::strcmp(locale, "xx-YY") == 0) &&
557 reinterpret_cast<Locale>(slot(pk, 11))(pk, 3, locale) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
558 "slot 11 gives one of the package's declared locales, not the host's; a short buffer is refused");
559 DeleteFileA((game + "\\MicrosoftGame.Config").c_str());
560 RemoveDirectoryA(game.c_str());
561 SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr);
562 {
563 // A game folder outside every ANSI code page (U+16A0, a runic letter) reaches MicrosoftGame.Config intact.
564 wchar_t wtmp[MAX_PATH] = {};
565 GetTempPathW(MAX_PATH, wtmp);
566 const std::wstring wide = std::wstring(wtmp) + L"leonida_xpackage_\u16a0ocale";
567 CreateDirectoryW(wide.c_str(), nullptr);
568 SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", wide.c_str());
569 const std::wstring wconfig = wide + L"\\MicrosoftGame.Config";
570 if (FILE* f = _wfopen(wconfig.c_str(), L"wb")) {
571 std::fputs("<Game><Resources><Resource Language=\"qq-QQ\"/></Resources></Game>", f);
572 std::fclose(f);
573 }
574 char wlocale[32] = {};
575 check(reinterpret_cast<Locale>(slot(pk, 11))(pk, sizeof(wlocale), wlocale) == S_OK &&
576 std::strcmp(wlocale, "qq-QQ") == 0,
577 "slot 11 reads MicrosoftGame.Config from a game folder named outside the ANSI code page");
578 DeleteFileW(wconfig.c_str());
579 RemoveDirectoryW(wide.c_str());
580 SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", nullptr);
581 }
582 // Slots 23-26 are the named exports' content-package mounts: XPackageMount, the path size and path of the
583 // handle, and closing it. XPackageMountHandle is one u64, passed by value.
584 using Mount = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint64_t*);
585 using PathSize = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, size_t*);
586 using Path = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, size_t, char*);
587 using CloseMount = void(STDMETHODCALLTYPE*)(void*, uint64_t);
588 SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", "SLOTDLC_12345678901234567890123=C:\\LeonidaSlotDLC");
589 uint64_t handle = 0;
590 size_t need = 0;
591 char path[MAX_PATH] = {};
592 check(reinterpret_cast<Mount>(slot(pk, 23))(pk, "SLOTDLC_12345678901234567890123", &handle) == S_OK &&
593 handle != 0,
594 "slot 23 (XPackageMount) mounts a content package and hands out a handle");
595 check(reinterpret_cast<PathSize>(slot(pk, 24))(pk, handle, &need) == S_OK &&
596 need == std::strlen("C:\\LeonidaSlotDLC") + 1 &&
597 reinterpret_cast<Path>(slot(pk, 25))(pk, handle, need, path) == S_OK &&
598 std::strcmp(path, "C:\\LeonidaSlotDLC") == 0 &&
599 reinterpret_cast<Path>(slot(pk, 25))(pk, handle, need - 1, path) ==
600 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
601 "slots 24/25: the mount's path, and exactly the size XPackageGetMountPath needs");
602 reinterpret_cast<CloseMount>(slot(pk, 26))(pk, handle);
603 check(reinterpret_cast<PathSize>(slot(pk, 24))(pk, handle, &need) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
604 "slot 26 (XPackageCloseMountHandle) closes the handle");
605 SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", nullptr);
606 using Stub = HRESULT(STDMETHODCALLTYPE*)(void*);
607 check(reinterpret_cast<Stub>(slot(pk, 5))(pk) == E_NOTIMPL && reinterpret_cast<Stub>(slot(pk, 40))(pk) == E_NOTIMPL,
608 "the slots without an offline answer (5, 40) are E_NOTIMPL");
609 struct Progress {
610 uint64_t total, installed, launch;
611 bool launchable, completed;
612 } progress{~0ull, 7, 7, false, false};
613 using GetProgress = void(STDMETHODCALLTYPE*)(void*, void*, Progress*);
614 reinterpret_cast<GetProgress>(slot(pk, 7))(pk, nullptr, &progress);
615 check(progress.launchable && progress.completed && progress.installed == progress.total,
616 "slot 7 (void XPackageGetInstallationProgress) writes an installed, launchable, completed package");
617 using Update = bool(STDMETHODCALLTYPE*)(void*, void*);
618 using UnregProgress = bool(STDMETHODCALLTYPE*)(void*, void*, XTaskQueueRegistrationToken, bool);
619 using UnregInstalled = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool);
620 using Uninstall = bool(STDMETHODCALLTYPE*)(void*, const char*);
621 check(!reinterpret_cast<Update>(slot(pk, 8))(pk, nullptr) &&
622 reinterpret_cast<UnregProgress>(slot(pk, 10))(pk, nullptr, XTaskQueueRegistrationToken{1}, true) &&
623 reinterpret_cast<UnregInstalled>(slot(pk, 22))(pk, XTaskQueueRegistrationToken{1}, false) &&
624 !reinterpret_cast<Uninstall>(slot(pk, 34))(pk, "pkg"),
625 "the bool slots 8, 10, 22 and 34 return their documented offline answers");
626 const GUID chain[] = {
627 package_cls,
628 {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}},
629 {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}},
630 package3};
631 bool all = true;
632 for (const GUID& iid : chain) {
633 void* same = nullptr;
634 all = all && query(&package_cls, iid, &same) == S_OK && same == pk;
635 if (same) release(same);
636 }
637 check(all, "IXPackageImpl3 answers for IXPackageImpl and IXPackageImpl2 too");
638 release(pk);
639 }
640 {
641 // XGameImpl (IXGameImpl3 : IXGameImpl2 : IXGameImpl, xgameruntime include/xgame.idl); IXGameImpl's id is the
642 // class id. Slots: 3 XGameGetXboxTitleId, 4 XLaunchNewGame (void), 5 XLaunchRestartOnCrash.
643 const GUID game_cls = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}};
644 const GUID game2 = {0x50849859, 0x0ad8, 0x4f81, {0x80, 0xe4, 0x5b, 0xc7, 0x86, 0x26, 0xf8, 0x52}};
645 const GUID game3 = {0x2549f142, 0x6419, 0x4a06, {0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34}};
646 void* g = get(game_cls);
647 check(g != nullptr, "QueryApiImpl hands out XGameImpl for its class id");
648 bool every = g != nullptr;
649 for (const GUID& iid : {game2, game3}) {
650 void* same = nullptr;
651 every = every && query(&game_cls, iid, &same) == S_OK && same == g;
652 if (same) release(same);
653 }
654 check(every, "XGameImpl answers for IXGameImpl2's and IXGameImpl3's ids, the same object");
655 if (g) {
656 using TitleId = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t*);
657 using LaunchNew = void(STDMETHODCALLTYPE*)(void*, const char*, const char*, void*);
658 using Restart = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t);
659 char tmp[MAX_PATH] = {};
660 GetTempPathA(sizeof(tmp), tmp);
661 const std::string game = std::string(tmp) + "leonida_xgame_title_test";
662 CreateDirectoryA(game.c_str(), nullptr);
663 SetEnvironmentVariableA("LEONIDA_GAME_DIR", game.c_str());
664 const std::string config = game + "\\MicrosoftGame.Config";
665 auto write_config = [&](const char* text) {
666 if (FILE* f = std::fopen(config.c_str(), "wb")) {
667 std::fputs(text, f);
668 std::fclose(f);
669 }
670 };
671 uint32_t id = 0x5a5a5a5a;
672 DeleteFileA(config.c_str());
673 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == E_FAIL && id == 0x5a5a5a5a,
674 "slot 3 (XGameGetXboxTitleId) without a config: E_FAIL, nothing written");
675 write_config("<Game configVersion=\"1\">\n <TitleId> 1a2B3c4D </TitleId>\n</Game>\n");
676 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == S_OK && id == 0x1A2B3C4Du,
677 "slot 3 gives the config's <TitleId> (hex, either case, whitespace allowed)");
678 check(reinterpret_cast<TitleId>(slot(g, 3))(g, nullptr) == E_INVALIDARG,
679 "slot 3 with a null pointer is E_INVALIDARG");
680 write_config("<Game><TitleId>not-hex</TitleId></Game>");
681 id = 0x5a5a5a5a;
682 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == E_FAIL && id == 0x5a5a5a5a,
683 "slot 3 refuses a <TitleId> that is not hex");
684 write_config("<Game><TitleId>123456789</TitleId></Game>");
685 check(reinterpret_cast<TitleId>(slot(g, 3))(g, &id) == E_FAIL, "slot 3 refuses more than 8 hex digits");
686 DeleteFileA(config.c_str());
687 RemoveDirectoryA(game.c_str());
688 SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr);
689 reinterpret_cast<LaunchNew>(slot(g, 4))(g, "other.exe", "", nullptr);
690 check(true, "slot 4 (void XLaunchNewGame) returns offline");
691 check(reinterpret_cast<Restart>(slot(g, 5))(g, "--restarted", 0) == S_OK,
692 "slot 5 (XLaunchRestartOnCrash) succeeds offline");
693 release(g);
694 }
695 }
515 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds"); 696 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds");
516 697
517 HMODULE k32 = load_w(L"kernel32.dll"); 698 HMODULE k32 = load_w(L"kernel32.dll");
diff --git a/runtime/test/xgameruntime_user_test.cpp b/runtime/test/xgameruntime_user_test.cpp
new file mode 100644
index 000000000..3a9b4c8e0
--- /dev/null
+++ b/runtime/test/xgameruntime_user_test.cpp
@@ -0,0 +1,227 @@
1// XUserImpl through QueryApiImpl, called the way xgameruntime.lib's XUser* thunks call it: QueryApiImpl with the
2// class id (or a later interface id), one vtable slot with `this` first. Slots follow xgameruntime-docs' layout;
3// arguments and expected values follow the public GDK reference. No game data; nothing online.
4//
5// xgameruntime_user_test the offline user, its handles, gamertag "Player"
6// xgameruntime_user_test --expect-gamertag TAG the same, run with LEONIDA_GAMERTAG=TAG
7#include <windows.h>
8
9#include <cstdint>
10#include <cstdio>
11#include <cstring>
12
13#include <XAsync.h>
14#include <XAsyncProvider.h>
15#include <XTaskQueue.h>
16
17#include "shims.h"
18
19namespace rt::shims {
20long xgameruntime_user_open_handles();
21}
22
23namespace {
24
25int g_checks = 0;
26int g_failures = 0;
27
28void check(bool condition, const char* what) {
29 ++g_checks;
30 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
31 if (!condition) ++g_failures;
32}
33
34using XUserHandle = void*;
35struct XUserLocalId {
36 uint64_t value;
37};
38
39constexpr HRESULT E_GAMEUSER_USER_NOT_FOUND = static_cast<HRESULT>(0x89245104);
40constexpr HRESULT E_GAMEUSER_DEFERRAL_NOT_AVAILABLE = static_cast<HRESULT>(0x89245103);
41constexpr HRESULT E_GAMEUSER_FAILED_TO_GET_TOKEN = static_cast<HRESULT>(0x89245111);
42
43constexpr GUID kUserClass = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}};
44constexpr GUID kUserImpl3 = {0x1bf2f8c5, 0xd507, 0x4e52, {0xbb, 0x05, 0xf7, 0x26, 0xd0, 0xe7, 0x11, 0x61}};
45constexpr GUID kUserImpl6 = {0x5131d685, 0x4394, 0x4ee6, {0x8c, 0x18, 0xbf, 0xb5, 0xd4, 0xae, 0xf1, 0xff}};
46constexpr GUID kGamertag = {0xcef4fac0, 0x7676, 0x4a94, {0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74}};
47constexpr GUID kOther = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; // XGameImpl
48
49using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**);
50using Fn = void*;
51Fn slot(void* obj, int index) { return (*static_cast<Fn* const*>(obj))[index]; }
52template <class F> F at(void* obj, int index) { return reinterpret_cast<F>(slot(obj, index)); }
53
54// Waits for an XAsyncBlock on the process queue, as a title polling XAsyncGetStatus(wait = true) does.
55bool finished(XAsyncBlock* async) { return XAsyncGetStatus(async, true) != E_PENDING; }
56
57} // namespace
58
59int main(int argc, char** argv) {
60 const char* expect_tag = "Player";
61 if (argc == 3 && std::strcmp(argv[1], "--expect-gamertag") == 0) expect_tag = argv[2];
62 std::printf("xgameruntime_user_test: XUserImpl through QueryApiImpl (gamertag \"%s\")\n", expect_tag);
63
64 auto query = reinterpret_cast<Query>(rt::shims::find("xgameruntime.dll", "QueryApiImpl"));
65 check(query != nullptr, "QueryApiImpl is registered");
66 if (!query) return 1;
67
68 // ---- the object and its interfaces ----
69 void* user = nullptr;
70 check(query(&kUserClass, kUserClass, &user) == S_OK && user, "QueryApiImpl hands out XUserImpl for its class id");
71 if (!user) return 1;
72 void* user6 = nullptr;
73 void* user3 = nullptr;
74 check(query(&kUserClass, kUserImpl6, &user6) == S_OK && user6 == user &&
75 query(&kUserClass, kUserImpl3, &user3) == S_OK && user3 == user,
76 "IXUserImpl3 and IXUserImpl6 (later versions of the same vtable) answer with the same object");
77 void* tag_face = nullptr;
78 check(query(&kUserClass, kGamertag, &tag_face) == S_OK && tag_face && tag_face != user,
79 "IXUserGamertagImpl is a second interface of the object");
80 void* none = reinterpret_cast<void*>(1);
81 check(query(&kUserClass, kOther, &none) == E_NOINTERFACE && none == nullptr,
82 "an interface the class doesn't have is E_NOINTERFACE with a cleared out pointer");
83
84 // ---- XUserAddAsync / XUserAddResult (slots 7, 8) ----
85 using AddAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, XAsyncBlock*);
86 using AddResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, XUserHandle*);
87 XAsyncBlock add{};
88 check(at<AddAsync>(user, 7)(user, 0x01, &add) == S_OK, "XUserAddAsync(AddDefaultUserSilently) starts");
89 check(finished(&add) && XAsyncGetStatus(&add, false) == S_OK, "it completes with S_OK");
90 XUserHandle h = nullptr;
91 check(at<AddResult>(user, 8)(user, &add, &h) == S_OK && h != nullptr, "XUserAddResult hands out a user handle");
92 XAsyncBlock bad{};
93 check(at<AddAsync>(user, 7)(user, 0x01 | 0x02, &bad) == E_INVALIDARG,
94 "AllowGuests with AddDefaultUserSilently is refused (a guest can't be the default user)");
95 XAsyncBlock picker{};
96 XUserHandle h_picker = nullptr;
97 check(at<AddAsync>(user, 7)(user, 0x00, &picker) == S_OK && finished(&picker) &&
98 at<AddResult>(user, 8)(user, &picker, &h_picker) == S_OK && h_picker,
99 "XUserAddAsync without a silent option also adds the offline user (no account picker offline)");
100
101 // ---- identity (slots 5, 6, 9-14, 19, 20) ----
102 using Compare = int32_t(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserHandle);
103 using MaxUsers = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t*);
104 using GetLocalId = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserLocalId*);
105 using FindLocal = HRESULT(STDMETHODCALLTYPE*)(void*, XUserLocalId, XUserHandle*);
106 using GetId = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint64_t*);
107 using FindId = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XUserHandle*);
108 using GetBool = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, bool*);
109 using GetU32 = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t*);
110 using CheckPrivilege = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, uint32_t, bool*, uint32_t*);
111 uint32_t max_users = 0;
112 check(at<MaxUsers>(user, 6)(user, &max_users) == S_OK && max_users == 1, "XUserGetMaxUsers: one local user");
113 check(at<Compare>(user, 5)(user, h, h_picker) == 0, "XUserCompare: both handles name the same user");
114 XUserLocalId local{};
115 check(at<GetLocalId>(user, 9)(user, h, &local) == S_OK && local.value != 0, "XUserGetLocalId: a non-zero local id");
116 uint64_t xuid = 0;
117 check(at<GetId>(user, 11)(user, h, &xuid) == S_OK && xuid != 0, "XUserGetId: a non-zero user id");
118 XUserHandle by_local = nullptr, by_id = nullptr, missing = reinterpret_cast<XUserHandle>(1);
119 check(at<FindLocal>(user, 10)(user, local, &by_local) == S_OK && by_local &&
120 at<Compare>(user, 5)(user, by_local, h) == 0,
121 "XUserFindUserByLocalId finds it");
122 check(at<FindLocal>(user, 10)(user, XUserLocalId{local.value + 1}, &missing) == E_GAMEUSER_USER_NOT_FOUND &&
123 missing == nullptr,
124 "another local id is E_GAMEUSER_USER_NOT_FOUND");
125 check(at<FindId>(user, 12)(user, xuid, &by_id) == S_OK && by_id, "XUserFindUserById finds it");
126 missing = reinterpret_cast<XUserHandle>(1);
127 check(at<FindId>(user, 12)(user, xuid + 1, &missing) == E_GAMEUSER_USER_NOT_FOUND && missing == nullptr,
128 "another user id is E_GAMEUSER_USER_NOT_FOUND");
129 bool guest = true;
130 check(at<GetBool>(user, 13)(user, h, &guest) == S_OK && !guest, "XUserGetIsGuest: not a guest");
131 uint32_t state = 99, age = 99;
132 check(at<GetU32>(user, 14)(user, h, &state) == S_OK && state == 0, "XUserGetState: SignedIn (0)");
133 check(at<GetU32>(user, 19)(user, h, &age) == S_OK && age == 3, "XUserGetAgeGroup: Adult (3)");
134 bool has = false;
135 uint32_t reason = 99;
136 check(at<CheckPrivilege>(user, 20)(user, h, 0, 254, &has, &reason) == S_OK && has && reason == 0,
137 "XUserCheckPrivilege: granted, deny reason None (0)");
138 check(at<GetBool>(user, 13)(user, nullptr, &guest) == E_INVALIDARG, "a null handle is E_INVALIDARG");
139
140 // ---- XUserResolvePrivilegeWithUiAsync / Result (21, 22) ----
141 using ResolveAsync = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, uint32_t, XAsyncBlock*);
142 using ResolveResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*);
143 XAsyncBlock resolve{};
144 check(at<ResolveAsync>(user, 21)(user, h, 0, 254, &resolve) == S_OK && finished(&resolve) &&
145 at<ResolveResult>(user, 22)(user, &resolve) == S_OK,
146 "XUserResolvePrivilegeWithUiAsync completes with S_OK (nothing to resolve)");
147
148 // ---- tokens: not available offline (23) ----
149 using TokenAsync = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, const char*, const char*, size_t,
150 const void*, size_t, const void*, XAsyncBlock*);
151 XAsyncBlock token{};
152 check(at<TokenAsync>(user, 23)(user, h, 0, "GET", "https://example.invalid/", 0, nullptr, 0, nullptr, &token) ==
153 E_GAMEUSER_FAILED_TO_GET_TOKEN,
154 "XUserGetTokenAndSignatureAsync fails before starting: E_GAMEUSER_FAILED_TO_GET_TOKEN");
155
156 // ---- change events, sign-out deferral (33-36) ----
157 using Register = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, void(CALLBACK*)(void*, XUserLocalId, uint32_t),
158 XTaskQueueRegistrationToken*);
159 using Unregister = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool);
160 using Deferral = HRESULT(STDMETHODCALLTYPE*)(void*, void**);
161 auto on_change = [](void*, XUserLocalId, uint32_t) {};
162 XTaskQueueRegistrationToken reg{};
163 check(at<Register>(user, 33)(user, nullptr, nullptr, on_change, &reg) == S_OK && reg.token != 0,
164 "XUserRegisterForChangeEvent hands out a token");
165 check(at<Unregister>(user, 34)(user, reg, false) && at<Unregister>(user, 34)(user, reg, false) &&
166 at<Unregister>(user, 34)(user, XTaskQueueRegistrationToken{999}, false),
167 "XUserUnregisterForChangeEvent: true, also with wait = false for a token already gone or never issued "
168 "(false would mean still pending, which never happens offline)");
169 void* deferral = reinterpret_cast<void*>(1);
170 check(at<Deferral>(user, 35)(user, &deferral) == E_GAMEUSER_DEFERRAL_NOT_AVAILABLE && deferral == nullptr,
171 "XUserGetSignOutDeferral: E_GAMEUSER_DEFERRAL_NOT_AVAILABLE (nothing signs out offline)");
172
173 // ---- IXUserImpl2: XUserAddByIdWithUiAsync / Result (37, 38) ----
174 using AddByIdAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XAsyncBlock*);
175 XAsyncBlock by_id_add{}, by_other{};
176 XUserHandle h_by_id = nullptr, h_other = reinterpret_cast<XUserHandle>(1);
177 check(at<AddByIdAsync>(user, 37)(user, xuid, &by_id_add) == S_OK && finished(&by_id_add) &&
178 at<AddResult>(user, 38)(user, &by_id_add, &h_by_id) == S_OK && h_by_id,
179 "XUserAddByIdWithUiAsync with the local user's id adds it");
180 check(at<AddByIdAsync>(user, 37)(user, xuid + 1, &by_other) == S_OK && finished(&by_other) &&
181 at<AddResult>(user, 38)(user, &by_other, &h_other) == E_GAMEUSER_USER_NOT_FOUND && h_other == nullptr,
182 "with another id it completes with E_GAMEUSER_USER_NOT_FOUND");
183
184 // ---- IXUserImpl4: XUserIsStoreUser (42) ----
185 using IsStore = bool(STDMETHODCALLTYPE*)(void*, XUserHandle);
186 check(at<IsStore>(user, 42)(user, h) && at<IsStore>(user, 42)(user, nullptr),
187 "XUserIsStoreUser: true, also for a null handle (_In_opt_; always true on console)");
188 using Unknown = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, size_t, char*, size_t*);
189 char probe[16] = "untouched";
190 size_t probe_used = 42;
191 check(at<Unknown>(user, 15)(user, h, sizeof(probe), probe, &probe_used) == E_NOTIMPL,
192 "slot 15 (no public signature) answers E_NOTIMPL rather than S_OK with nothing written");
193
194 // ---- IXUserGamertagImpl: XUserGetGamertag (3) ----
195 using GetTag = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, size_t, char*, size_t*);
196 auto tag = at<GetTag>(tag_face, 3);
197 char buf[101] = {};
198 size_t used = 0;
199 const size_t want = std::strlen(expect_tag) + 1;
200 check(tag(tag_face, h, 0, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0 && used == want,
201 "XUserGetGamertag(Classic): the gamertag, gamertagUsed counting the terminator");
202 check(tag(tag_face, h, 3, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0,
203 "UniqueModern of a classic gamertag: the same text, no '#' and no suffix");
204 check(tag(tag_face, h, 1, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0,
205 "Modern: the classic gamertag when none is set");
206 check(tag(tag_face, h, 2, sizeof(buf), buf, &used) == S_OK && buf[0] == 0 && used == 1,
207 "ModernSuffix: empty (just the terminator)");
208 check(tag(tag_face, h, 0, want - 1, buf, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
209 "a buffer one byte short is E_INSUFFICIENT_BUFFER");
210 check(tag(tag_face, h, 7, sizeof(buf), buf, &used) == E_INVALIDARG, "an unknown component is E_INVALIDARG");
211
212 // ---- handles: duplicate, close, all accounted for (3, 4) ----
213 using Dup = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserHandle*);
214 using Close = void(STDMETHODCALLTYPE*)(void*, XUserHandle);
215 XUserHandle dup = nullptr;
216 check(at<Dup>(user, 3)(user, h, &dup) == S_OK && dup && dup != h && at<Compare>(user, 5)(user, dup, h) == 0,
217 "XUserDuplicateHandle: a new handle for the same user");
218 check(rt::shims::xgameruntime_user_open_handles() == 6, "six handles are open: two adds, two finds, an add by id and a duplicate");
219 for (XUserHandle x : {h, h_picker, by_local, by_id, h_by_id, dup}) at<Close>(user, 4)(user, x);
220 check(rt::shims::xgameruntime_user_open_handles() == 0, "XUserCloseHandle closes each of them");
221 at<Close>(user, 4)(user, h); // a double close: the handle is looked up, not read, so this is a no-op
222 check(rt::shims::xgameruntime_user_open_handles() == 0 && at<GetBool>(user, 13)(user, h, &guest) == E_INVALIDARG,
223 "a closed handle is refused and closing it again does nothing");
224
225 std::printf("xgameruntime_user_test: %d of %d checks failed\n", g_failures, g_checks);
226 return g_failures ? 1 : 0;
227}
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index 1ad4080f7..bd38cab39 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -10,8 +10,12 @@
10#include <cstdint> 10#include <cstdint>
11#include <cstdio> 11#include <cstdio>
12#include <cstring> 12#include <cstring>
13#include <fstream>
14#include <sstream>
15#include <string>
13 16
14#include "shims.h" 17#include "shims.h"
18#include "startup_trace.h"
15 19
16namespace { 20namespace {
17 21
@@ -79,10 +83,26 @@ void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) {
79 const BOOL ok = get_stats(kMeasuredKind, stats); 83 const BOOL ok = get_stats(kMeasuredKind, stats);
80 check(ok != FALSE, "XMemGetWorkingSetStatistics(kind, 64-byte out) returns TRUE"); 84 check(ok != FALSE, "XMemGetWorkingSetStatistics(kind, 64-byte out) returns TRUE");
81 85
86 uint64_t total_memory = 0;
87 std::memcpy(&total_memory, stats + 0, sizeof(total_memory));
88 check(ok != FALSE && total_memory != 0, "XMemGetWorkingSetStatistics writes a non-zero total memory at +0");
89
90 MEMORYSTATUSEX ms{sizeof(ms)};
91 if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) {
92 check(ok != FALSE && total_memory == ms.ullTotalPhys,
93 "XMemGetWorkingSetStatistics total memory (+0) matches GlobalMemoryStatusEx ullTotalPhys");
94 } else {
95 check(ok != FALSE && total_memory == 12ULL * 1024 * 1024 * 1024,
96 "XMemGetWorkingSetStatistics total memory (+0) falls back to 12 GiB title limit");
97 }
98
82 uint64_t working_set = 0; 99 uint64_t working_set = 0;
83 std::memcpy(&working_set, stats + 8, sizeof(working_set)); 100 std::memcpy(&working_set, stats + 8, sizeof(working_set));
84 check(ok != FALSE && working_set != 0, "XMemGetWorkingSetStatistics writes a non-zero size at +8"); 101 check(ok != FALSE && working_set != 0, "XMemGetWorkingSetStatistics writes a non-zero size at +8");
85 102
103 check(ok != FALSE && total_memory >= working_set,
104 "XMemGetWorkingSetStatistics total memory (+0) >= working set (+8)");
105
86 bool tail_untouched = true; 106 bool tail_untouched = true;
87 for (size_t i = 16; i < sizeof(stats); ++i) { 107 for (size_t i = 16; i < sizeof(stats); ++i) {
88 if (stats[i] != 0xa5) { 108 if (stats[i] != 0xa5) {
@@ -204,6 +224,48 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
204 "nonzero XMem allocation attributes are rejected before host allocation"); 224 "nonzero XMem allocation attributes are rejected before host allocation");
205} 225}
206 226
227// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off.
228void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) {
229 wchar_t temp[MAX_PATH];
230 GetTempPathW(MAX_PATH, temp);
231 const std::wstring path =
232 std::wstring(temp) + L"xmem_trace_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl";
233 DeleteFileW(path.c_str());
234
235 void* untraced = alloc(64, 0x1111); // trace not open yet: nothing to write, nothing to crash
236 check(untraced != nullptr, "XMemAlloc with the trace off still allocates");
237 free_mem(untraced, 0x1111);
238
239 check(rt::startup_trace::open(path.c_str()), "open the startup trace file");
240 void* a = alloc(4096, 0x5e50000);
241 void* b = alloc(8192, 0x5e50000); // same word again: no second event
242 void* c = alloc(16, 0x99);
243 free_mem(a, 0x5e50000);
244 free_mem(b, 0x5e50000); // same word again: no second event
245 free_mem(c, 0x99);
246 free_mem(nullptr, 0x77); // a free-only word is recorded too
247 rt::startup_trace::close();
248
249 std::ifstream in(path);
250 std::stringstream text;
251 text << in.rdbuf();
252 const std::string log = text.str();
253 auto count = [&](const std::string& needle) {
254 int n = 0;
255 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n;
256 return n;
257 };
258 check(count("\"kind\":\"xmem_attributes\"") == 5, "five events: two XMemAlloc words and three XMemFree words");
259 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x5e50000\",\"size\":4096") == 1,
260 "XMemAlloc 0x5e50000 is recorded once, with the size of the first call");
261 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x99\",\"size\":16") == 1, "XMemAlloc 0x99 is recorded once");
262 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x5e50000\"") == 1, "XMemFree 0x5e50000 is recorded once");
263 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x77\"") == 1, "XMemFree 0x77 is recorded");
264 check(count("\"attributes\":\"0x1111\"") == 0, "nothing was recorded while the trace was off");
265 check(count("\"caller\":\"") == 5, "every event names its caller");
266 DeleteFileW(path.c_str());
267}
268
207using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); 269using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD);
208 270
209// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host 271// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host
@@ -277,6 +339,7 @@ int main() {
277 if (virtual_alloc && get_write_watch && reset_write_watch) { 339 if (virtual_alloc && get_write_watch && reset_write_watch) {
278 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch); 340 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch);
279 } 341 }
342 test_attribute_trace(alloc, free_mem);
280 343
281 test_title_virtual_alloc(); 344 test_title_virtual_alloc();
282 345