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:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
commitdf91c6624b69ee4e6c6eeca20ed68d331ed0e728 (patch)
tree323c88b9df89bf8abaa2b98d10808474ab675dc2 /runtime/test
parentb40d8039a98f57b26bd05860febbabbe59b97873 (diff)
parent6a6704df1592e1dc4a3215ddf1423a78adb52045 (diff)
Merge main into test/valu-int-misc (#1492)
Conflicted files: runtime/test/shaders/check.py, scripts/run_gpu_tests.py AI-assisted.
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/allocator_proxy_test.cpp382
-rw-r--r--runtime/test/bindless_sizing_test.cpp31
-rw-r--r--runtime/test/check_d3d12_trace.py5
-rw-r--r--runtime/test/check_vk_pipeline_cli.cmake33
-rw-r--r--runtime/test/d3d12_clear_test.cpp3
-rw-r--r--runtime/test/d3d12_compute_test.cpp182
-rw-r--r--runtime/test/d3d12_copy_compare.h25
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp163
-rw-r--r--runtime/test/d3d12_draw_test.cpp136
-rw-r--r--runtime/test/d3d12_gcl8_test.cpp9
-rw-r--r--runtime/test/d3d12_m2_textured_test.cpp24
-rw-r--r--runtime/test/d3d12_present_test.cpp32
-rw-r--r--runtime/test/d3d12_queue_wait_test.cpp38
-rw-r--r--runtime/test/d3d12_set0_compute_test.cpp337
-rw-r--r--runtime/test/d3d12_subgroup_test.cpp672
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp751
-rw-r--r--runtime/test/d3d12_xdxr_rt_test.cpp90
-rw-r--r--runtime/test/depth24_convert_test.cpp91
-rw-r--r--runtime/test/device_proxy_test.cpp41
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp205
-rw-r--r--runtime/test/file_system_test.cpp11
-rw-r--r--runtime/test/fsr_dispatch_test.cpp4
-rw-r--r--runtime/test/gameinput_probe.cpp5
-rw-r--r--runtime/test/gameinput_test.cpp136
-rw-r--r--runtime/test/glsl/cs_set0_sample.comp77
-rw-r--r--runtime/test/glsl/cs_sg_probe.comp29
-rw-r--r--runtime/test/glsl/cs_user_data.comp14
-rw-r--r--runtime/test/glsl/ps_sg_probe.frag11
-rw-r--r--runtime/test/glsl/vs_sg_fullscreen.vert6
-rw-r--r--runtime/test/process_cmdline_test.cpp70
-rw-r--r--runtime/test/queue_proxy_test.cpp74
-rw-r--r--runtime/test/resource_tiling_test.cpp15
-rw-r--r--runtime/test/root_signature_oracle_test.cpp42
-rw-r--r--runtime/test/shader_library_corpus_test.cpp159
-rw-r--r--runtime/test/shader_library_test.cpp14
-rw-r--r--runtime/test/shaders/build.py4
-rw-r--r--runtime/test/shaders/check.py69
-rw-r--r--runtime/test/shaders/cs_fmt_sint32.asm90
-rw-r--r--runtime/test/shaders/cs_w32_sincos.asm60
-rw-r--r--runtime/test/shaders/ps_f16_pack_mods.asm19
-rw-r--r--runtime/test/shaders/ps_imgatomic.asm44
-rw-r--r--runtime/test/shaders/ps_m2_uoff.asm5
-rw-r--r--runtime/test/shaders/ps_scc_logic32.asm44
-rw-r--r--runtime/test/shaders/ps_scc_logic64.asm49
-rw-r--r--runtime/test/shaders/ps_w64x_readlane.asm27
-rw-r--r--runtime/test/subgroup_size_test.cpp256
-rw-r--r--runtime/test/vk_bc_zero_init_test.cpp388
-rw-r--r--runtime/test/vk_bindless_test.cpp179
-rw-r--r--runtime/test/vk_pipeline_check.cpp44
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp42
-rw-r--r--runtime/test/vk_queue_query_sync_test.cpp351
-rw-r--r--runtime/test/vk_sync_validation_selftest.cpp93
-rw-r--r--runtime/test/vk_test_device.h15
-rw-r--r--runtime/test/vk_xdxr_build_test.cpp121
-rw-r--r--runtime/test/xgameruntime_test.cpp34
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp93
56 files changed, 5774 insertions, 170 deletions
diff --git a/runtime/test/allocator_proxy_test.cpp b/runtime/test/allocator_proxy_test.cpp
new file mode 100644
index 000000000..733e37cac
--- /dev/null
+++ b/runtime/test/allocator_proxy_test.cpp
@@ -0,0 +1,382 @@
1// Xbox-ABI command allocator proxies (d3d12_xs_device.h, device slot 9) behind the device proxy, on the Vulkan-backed
2// device and on the host PC runtime (WARP, and the first hardware adapter when there is one):
3// - Vulkan device: slot 9 wraps the allocator; the public chain (9 slots) is forwarded with the real allocator's
4// answers, every slot past it up to the end of the table is refused (E_NOTIMPL), and a read past the table faults
5// in the guard region and is counted;
6// - QueryInterface identity, GetDevice -> the device proxy, references and release orders;
7// - a command list created on the proxy and Reset on it (the Vulkan layer resolves the proxy), recording a buffer
8// copy that runs through the queue and fence proxies and is read back, twice, with the allocator Reset between;
9// and D3D12's allocator rules through the proxy (Reset while a list records: E_FAIL; a second list on a busy
10// allocator: E_INVALIDARG);
11// - MakeResident/Evict with an allocator proxy give the real allocator's HRESULT;
12// - host runtime: slot 9 hands out the PC allocator unwrapped (its lists could not resolve a proxy), and the same
13// copy works.
14// LEONIDA_VK_VALIDATION=1 runs the Vulkan device under VK_LAYER_KHRONOS_validation with synchronization validation;
15// any validation error fails the test. Exits 77 when neither a host D3D12 device nor a Vulkan device can be made.
16// 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_4.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
50struct Backend {
51 const char* label;
52 ID3D12Device* device; // the device proxy
53 ID3D12Device* real; // the device behind it (PC runtime or Vulkan layer)
54 bool vulkan;
55};
56
57using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
58 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
59 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t);
60
61// A call through slot `slot` with all words zero, the way a title calls a console method the PC interface lacks.
62HRESULT call_slot(void* object, unsigned slot) {
63 void** vtable = *reinterpret_cast<void***>(object);
64 return static_cast<HRESULT>(static_cast<std::uint32_t>(
65 reinterpret_cast<SlotFn>(vtable[slot])(object, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)));
66}
67
68ULONG_PTR g_fault_address = 0;
69
70int record_fault(EXCEPTION_POINTERS* info) {
71 g_fault_address = info->ExceptionRecord->NumberParameters >= 2 ? info->ExceptionRecord->ExceptionInformation[1] : 0;
72 return EXCEPTION_EXECUTE_HANDLER;
73}
74
75// The read in a function of its own: clang-cl's __try only catches a fault raised inside a call.
76__declspec(noinline) void* read_entry(void* const* vtable, unsigned slot) {
77 return *static_cast<void* const volatile*>(&vtable[slot]);
78}
79
80// Reads vtable[slot] the way a call through it does. The exception code, or 0 when the read worked.
81DWORD read_slot_guarded(void* const* vtable, unsigned slot) {
82 g_fault_address = 0;
83 __try {
84 void* volatile entry = read_entry(vtable, slot);
85 (void)entry;
86 return 0;
87 } __except (record_fault(GetExceptionInformation())) {
88 return GetExceptionCode();
89 }
90}
91
92int wait_for(const char* label, ID3D12Fence* fence, UINT64 value) {
93 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
94 EXPECT(event != nullptr);
95 const bool set = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && WaitForSingleObject(event, 5000) == 0;
96 CloseHandle(event);
97 EXPECT(set && fence->GetCompletedValue() >= value);
98 return 0;
99}
100
101int make_buffer(const char* label, ID3D12Device* device, D3D12_HEAP_TYPE heap_type, D3D12_RESOURCE_STATES state,
102 Ref<ID3D12Resource>& out) {
103 D3D12_HEAP_PROPERTIES heap{};
104 heap.Type = heap_type;
105 D3D12_RESOURCE_DESC desc{};
106 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
107 desc.Width = 256;
108 desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
109 desc.SampleDesc.Count = 1;
110 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
111 EXPECT(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
112 IID_PPV_ARGS(&out.p))));
113 return 0;
114}
115
116// One recording on `list` (open, recording into the allocator): 256 bytes of `byte` copied from an upload buffer to a
117// readback buffer, executed through the queue proxy, finished through the fence proxy at `value`, then compared.
118int copy_round(const char* label, ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fence* fence,
119 ID3D12GraphicsCommandList* list, std::uint8_t byte, UINT64 value) {
120 Ref<ID3D12Resource> upload, readback;
121 if (make_buffer(label, device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, upload)) return 1;
122 if (make_buffer(label, device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return 1;
123 void* mapped = nullptr;
124 EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped)) && mapped);
125 std::memset(mapped, byte, 256);
126 upload->Unmap(0, nullptr);
127 list->CopyBufferRegion(readback.p, 0, upload.p, 0, 256);
128 EXPECT(SUCCEEDED(list->Close()));
129 ID3D12CommandList* lists[] = {list};
130 queue->ExecuteCommandLists(1, lists);
131 EXPECT(SUCCEEDED(queue->Signal(fence, value)));
132 if (wait_for(label, fence, value)) return 1;
133 const D3D12_RANGE read{0, 256};
134 EXPECT(SUCCEEDED(readback->Map(0, &read, &mapped)) && mapped);
135 const auto* bytes = static_cast<const std::uint8_t*>(mapped);
136 int wrong = 0;
137 for (int i = 0; i < 256; ++i) wrong += bytes[i] != byte;
138 const D3D12_RANGE none{0, 0};
139 readback->Unmap(0, &none);
140 EXPECT(wrong == 0);
141 return 0;
142}
143
144// ---- 1. The proxy itself: slots, identity, guard (Vulkan device) ----
145
146int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) {
147 const char* label = b.label;
148 ID3D12CommandAllocator* real = xs::allocator_proxy_real_allocator(allocator);
149 EXPECT(real && static_cast<void*>(real) != static_cast<void*>(allocator));
150 EXPECT(xs::allocator_proxy_slot_count(allocator) == 9);
151 EXPECT(xs::command_object_proxy_ref_count(allocator) == 1);
152
153 // QueryInterface: the base chain and the allocator itself answer with the proxy; anything else is refused.
154 const IID modelled[] = {__uuidof(IUnknown), __uuidof(ID3D12Object), __uuidof(ID3D12DeviceChild),
155 __uuidof(ID3D12Pageable), __uuidof(ID3D12CommandAllocator)};
156 for (const IID& iid : modelled) {
157 void* same = nullptr;
158 EXPECT(SUCCEEDED(allocator->QueryInterface(iid, &same)) && same == allocator);
159 static_cast<IUnknown*>(same)->Release();
160 }
161 void* other = reinterpret_cast<void*>(1);
162 EXPECT(allocator->QueryInterface(__uuidof(ID3D12Fence), &other) == E_NOINTERFACE && !other);
163 other = reinterpret_cast<void*>(1); // the Vulkan layer's private tag: not modelled, the real object stays hidden
164 EXPECT(allocator->QueryInterface(xs::kLeonidaCommandAllocatorTag, &other) == E_NOINTERFACE && !other);
165 EXPECT(xs::command_object_proxy_ref_count(allocator) == 1);
166
167 ID3D12Device* owner = nullptr;
168 EXPECT(SUCCEEDED(allocator->GetDevice(IID_PPV_ARGS(&owner))) && owner == b.device);
169 owner->Release();
170 // Private data and SetName go to the real allocator; the proxy pointer round-trips as an interface.
171 EXPECT(SUCCEEDED(allocator->SetName(L"leonida allocator proxy")));
172 constexpr GUID key{0x2a6b8c41, 0x77d2, 0x4e19, {0x9c, 0x3a, 0x51, 0xe0, 0x8f, 0x24, 0x6d, 0x0b}};
173 EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, allocator)));
174 IUnknown* back = nullptr;
175 UINT size = sizeof(back);
176 EXPECT(SUCCEEDED(allocator->GetPrivateData(key, &size, &back)) && back == allocator);
177 back->Release();
178 EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, nullptr)));
179
180 // The refused tail: every slot past the public chain, up to the table end, is E_NOTIMPL and counted.
181 const unsigned table = xs::allocator_proxy_table_size();
182 EXPECT(table == 64);
183 for (unsigned slot = 9; slot < table; ++slot) {
184 const std::uint64_t before = xs::allocator_slot_hits(slot);
185 EXPECT(call_slot(allocator, slot) == E_NOTIMPL);
186 EXPECT(xs::allocator_slot_hits(slot) == before + 1 && xs::allocator_slot_first_call_seen(slot));
187 }
188
189 // Past the table: the vtable read itself faults in the guard region, at the slot's address, and is counted.
190 EXPECT(xs::command_object_tables_guarded());
191 void* const* vtable = *reinterpret_cast<void* const* const*>(allocator);
192 EXPECT(read_slot_guarded(vtable, table - 1) == 0);
193 for (unsigned slot : {table, table + 512, table + 7000}) {
194 const std::uint64_t before = xs::allocator_table_overruns();
195 EXPECT(read_slot_guarded(vtable, slot) == EXCEPTION_ACCESS_VIOLATION);
196 EXPECT(g_fault_address == reinterpret_cast<ULONG_PTR>(&vtable[slot]));
197 EXPECT(xs::allocator_table_overruns() == before + 1);
198 }
199 std::printf("%s: allocator proxy: 9 public slots forwarded, slots 9-%u refused, the guard region names a read "
200 "past the table; QueryInterface/GetDevice/private data keep the proxy identity\n", label, table - 1);
201 return 0;
202}
203
204// ---- 2. Lists on the allocator, GPU work, D3D12's allocator rules, residency ----
205
206int check_backend(const Backend& b) {
207 const char* label = b.label;
208 const unsigned long device_refs = xs::device_proxy_ref_count(b.device);
209 {
210 Ref<ID3D12CommandAllocator> allocator;
211 EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
212 IID_PPV_ARGS(&allocator.p))));
213 // Vulkan layer: wrapped. Host runtime: its lists could not resolve a proxy, so the PC allocator comes back.
214 EXPECT(xs::is_allocator_proxy(allocator.p) == b.vulkan);
215 if (b.vulkan && check_proxy(b, allocator.p)) return 1;
216 // As IUnknown, and without an output (the device's own answer), as slot 8 does for queues.
217 Ref<IUnknown> as_unknown;
218 EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(IUnknown),
219 reinterpret_cast<void**>(&as_unknown.p))));
220 EXPECT(xs::is_allocator_proxy(as_unknown.p) == b.vulkan);
221#pragma warning(suppress : 6387) // the null output on purpose
222 EXPECT(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
223 nullptr) ==
224 b.real->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
225 nullptr));
226 Ref<ID3D12Fence> not_an_allocator; // asked for an interface the allocator does not have
227 not_an_allocator.p = reinterpret_cast<ID3D12Fence*>(1);
228 const HRESULT wrong_iid = b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
229 IID_PPV_ARGS(&not_an_allocator.p));
230 const bool cleared = !not_an_allocator.p;
231 not_an_allocator.p = nullptr;
232 EXPECT(FAILED(wrong_iid) && cleared);
233
234 D3D12_COMMAND_QUEUE_DESC queue_desc{};
235 Ref<ID3D12CommandQueue> queue;
236 Ref<ID3D12Fence> fence;
237 EXPECT(SUCCEEDED(b.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
238 EXPECT(SUCCEEDED(b.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
239 EXPECT(xs::is_queue_proxy(queue.p) && xs::is_fence_proxy(fence.p));
240
241 // A list on the allocator: the Vulkan layer resolves the proxy in CreateCommandList.
242 Ref<ID3D12GraphicsCommandList> list;
243 EXPECT(SUCCEEDED(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
244 IID_PPV_ARGS(&list.p))));
245 // D3D12's rules, through the proxy: a recording list holds the allocator.
246 const std::uint64_t resets_before = xs::allocator_slot_hits(8);
247 EXPECT(allocator->Reset() == E_FAIL);
248 Ref<ID3D12GraphicsCommandList> second;
249 EXPECT(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
250 IID_PPV_ARGS(&second.p)) == E_INVALIDARG && !second.p);
251 if (copy_round(label, b.device, queue.p, fence.p, list.p, 0x5a, 1)) return 1;
252
253 // Done on the GPU: the allocator resets through the proxy, and the list resets onto it (Reset resolves it).
254 EXPECT(SUCCEEDED(allocator->Reset()));
255 EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
256 if (copy_round(label, b.device, queue.p, fence.p, list.p, 0xa5, 2)) return 1;
257 // The two allocator Reset calls above went through slot 8 (list->Reset is the list's method, not this one).
258 if (b.vulkan) EXPECT(xs::allocator_slot_hits(8) == resets_before + 2);
259
260 // Residency: the real runtime gets the real allocator (an allocator is a pageable).
261 ID3D12Pageable* pageable = allocator.p;
262 ID3D12CommandAllocator* real_allocator =
263 b.vulkan ? xs::allocator_proxy_real_allocator(allocator.p) : allocator.p;
264 ID3D12Pageable* real_pageable = real_allocator;
265 EXPECT(b.device->MakeResident(1, &pageable) == b.real->MakeResident(1, &real_pageable));
266 EXPECT(b.device->Evict(1, &pageable) == b.real->Evict(1, &real_pageable));
267
268 // Release orders: the allocator first while its (closed) list still exists, then the list.
269 if (b.vulkan) EXPECT(xs::command_object_proxy_ref_count(allocator.p) == 1);
270 allocator.reset();
271 list.reset();
272 }
273 EXPECT(xs::device_proxy_ref_count(b.device) == device_refs); // nothing the proxies made kept the device
274 std::printf("%s: CreateCommandAllocator %s; a list created and Reset on it, two GPU copies through the queue and "
275 "fence proxies read back exactly; allocator rules and residency as on the real allocator\n", label,
276 b.vulkan ? "returns an allocator proxy" : "returns the PC allocator unwrapped");
277 return 0;
278}
279
280int run_host(IDXGIAdapter1* adapter, const char* label) {
281 ID3D12Device* real = nullptr;
282 if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&real)))) {
283 std::printf("%s: no D3D12 device, skipped\n", label);
284 return 77;
285 }
286 real->AddRef(); // the backend's own reference; the proxy takes the other
287 Ref<ID3D12Device> device;
288 if (FAILED(xs::create_device_proxy(real, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device.p)))) {
289 real->Release();
290 real->Release();
291 std::fprintf(stderr, "%s: device proxy creation failed\n", label);
292 return 1;
293 }
294 const int result = check_backend(Backend{label, device.p, real, false});
295 device.reset();
296 if (result) return 1;
297 if (real->Release() != 0) {
298 std::fprintf(stderr, "%s: the PC device outlives its proxies\n", label);
299 return 1;
300 }
301 return 0;
302}
303
304} // namespace
305
306// A failure ends the process with a message on stderr, never in a dialog a test run would wait on.
307static void no_dialogs() {
308 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
309 SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
310}
311
312int main() {
313 no_dialogs();
314 std::setvbuf(stdout, nullptr, _IONBF, 0);
315 const char* label = "allocator_proxy_test";
316 int ran = 0;
317
318 // Host PC runtime: WARP, then the first hardware adapter. Under Wine the host d3d12.dll is Wine's own, not the
319 // PC runtime the proxy is written against, so only Vulkan runs there.
320 const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr;
321 Ref<IDXGIFactory4> factory;
322 if (wine) std::printf("host D3D12: under Wine, skipped\n");
323 if (!wine && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) {
324 Ref<IDXGIAdapter1> warp;
325 if (SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) {
326 const int r = run_host(warp.p, "host WARP");
327 if (r == 1) return 1;
328 ran += r == 0;
329 }
330 for (UINT i = 0;; ++i) {
331 Ref<IDXGIAdapter1> adapter;
332 if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break;
333 DXGI_ADAPTER_DESC1 desc{};
334 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
335 char name[128] = {};
336 WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, name, sizeof(name) - 1, nullptr, nullptr);
337 char host_label[160];
338 std::snprintf(host_label, sizeof(host_label), "host %s", name);
339 const int r = run_host(adapter.p, host_label);
340 if (r == 1) return 1;
341 ran += r == 0;
342 break;
343 }
344 }
345
346 // The Vulkan-backed device, the way D3D12XboxCreateDevice hands it out with LEONIDA_D3D12=vulkan.
347 vktest::Device d;
348 if (d.create()) {
349 label = "Vulkan";
350 rt::d3d12::VulkanDeviceInfo info{};
351 info.get_instance_proc = d.instance_proc;
352 info.instance = d.instance;
353 info.physical = d.physical;
354 info.device = d.device;
355 info.queue = d.queue;
356 info.queue_family = d.family;
357 ID3D12Device* inner = nullptr;
358 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
359 inner->AddRef(); // the backend's own reference; the proxy takes the other
360 ID3D12Device* device = nullptr;
361 EXPECT(SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device))));
362 rt::d3d12::set_device_outer(inner, device);
363 const int result = check_backend(Backend{label, device, inner, true});
364 device->Release();
365 if (result) return 1;
366 EXPECT(inner->Release() == 0); // nothing the proxies made kept the layer's device alive
367 ++ran;
368 if (d.validation_errors()) {
369 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
370 return 1;
371 }
372 } else {
373 std::printf("Vulkan: no device, skipped\n");
374 }
375
376 if (!ran) {
377 std::printf("SKIP allocator_proxy_test: neither a host D3D12 device nor a Vulkan device\n");
378 return 77;
379 }
380 std::printf("allocator_proxy_test: %d backend(s) passed\n", ran);
381 return 0;
382}
diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp
index 469274d56..07715f01e 100644
--- a/runtime/test/bindless_sizing_test.cpp
+++ b/runtime/test/bindless_sizing_test.cpp
@@ -172,6 +172,37 @@ int main() {
172 EXPECT(totals(f).all <= 30000 && count(f, D::dim_2d) > 4096); 172 EXPECT(totals(f).all <= 30000 && count(f, D::dim_2d) > 4096);
173 } 173 }
174 174
175 // D3D-219: past maxPerSetDescriptors, growth follows layout_supported (vkGetDescriptorSetLayoutSupport), which
176 // is asked only above that limit. Intel's Xe-LP reports 6159 and supports the full sizes.
177 {
178 Device d = uniform(1048576, 1048576);
179 d.v11.maxPerSetDescriptors = 6159;
180 d.limits.maxSamplerAllocationCount = 4000;
181 unsigned asked = 0, asked_within = 0;
182 const auto all_supported = [&](const BindlessFeatures& candidate) {
183 ++asked;
184 asked_within += totals(candidate).all <= 6159;
185 return true;
186 };
187 BindlessFeatures f = with_ms(true);
188 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported));
189 EXPECT(asked > 0 && asked_within == 0);
190 EXPECT(count(f, D::dim_2d) == bindless::max_2d_images &&
191 f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers);
192 EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f));
193
194 // A driver that supports less: growth stops where it says no.
195 const auto up_to_20000 = [&](const BindlessFeatures& candidate) { return totals(candidate).all <= 20000; };
196 f = with_ms(true);
197 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, up_to_20000));
198 EXPECT(totals(f).all <= 20000 && totals(f).all > 6159 && count(f, D::dim_2d) > 4096);
199
200 // Without the callback, maxPerSetDescriptors still caps growth as before.
201 f = with_ms(true);
202 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12));
203 EXPECT(totals(f).all <= 6159 || (count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024));
204 }
205
175 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get. 206 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get.
176 EXPECT(BindlessFeatures{}.counts == defaults); 207 EXPECT(BindlessFeatures{}.counts == defaults);
177 std::printf("bindless sizing: synthetic limits gave the expected counts\n"); 208 std::printf("bindless sizing: synthetic limits gave the expected counts\n");
diff --git a/runtime/test/check_d3d12_trace.py b/runtime/test/check_d3d12_trace.py
index a95f01b35..d24e02058 100644
--- a/runtime/test/check_d3d12_trace.py
+++ b/runtime/test/check_d3d12_trace.py
@@ -50,12 +50,17 @@ def main():
50 ] 50 ]
51 else: 51 else:
52 expected = [ 52 expected = [
53 "ID3D12GraphicsCommandList::SetPipelineState called",
54 "ID3D12GraphicsCommandList::SetGraphicsRootSignature called",
53 "ID3D12GraphicsCommandList::SetMarker called", 55 "ID3D12GraphicsCommandList::SetMarker called",
54 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", 56 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported",
55 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", 57 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported",
56 "ID3D12GraphicsCommandList::Close ok", 58 "ID3D12GraphicsCommandList::Close ok",
57 "ID3D12GraphicsCommandList::Close failed", 59 "ID3D12GraphicsCommandList::Close failed",
58 "ID3D12GraphicsCommandList::Reset ok", 60 "ID3D12GraphicsCommandList::Reset ok",
61 "ID3D12GraphicsCommandList::DrawInstanced called",
62 "ID3D12GraphicsCommandList::DrawIndexedInstanced called",
63 "ID3D12GraphicsCommandList::Close failed",
59 ] 64 ]
60 65
61 observed = iter(entries) 66 observed = iter(entries)
diff --git a/runtime/test/check_vk_pipeline_cli.cmake b/runtime/test/check_vk_pipeline_cli.cmake
new file mode 100644
index 000000000..4800d2605
--- /dev/null
+++ b/runtime/test/check_vk_pipeline_cli.cmake
@@ -0,0 +1,33 @@
1file(MAKE_DIRECTORY "${TEST_DIR}")
2file(WRITE "${TEST_DIR}/index.json" "not JSON\n")
3
4# ${RUNNER} is CMAKE_CROSSCOMPILING_EMULATOR: CTest does not apply it to a script
5# test (the command is the host CMake), so the script runs the tool through it itself.
6function(check_invalid option)
7 execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" "${option}" ${ARGN}
8 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
9 if(NOT code STREQUAL "2" OR NOT log MATCHES "${option} requires a valid value")
10 message(FATAL_ERROR "${option} ${ARGN}: expected usage error, got ${code}\n${log}")
11 endif()
12endfunction()
13
14check_invalid(--count)
15check_invalid(--count --compute-only)
16check_invalid(--count 18446744073709551616)
17check_invalid(--jobs 4294967296)
18check_invalid(--start -1)
19check_invalid(--max-bytes 1MiB)
20check_invalid(--large-module-bytes -1)
21check_invalid(--slow nonsense)
22check_invalid(--slow nan)
23check_invalid(--slow -0.5)
24check_invalid(--stage --graphics-only)
25check_invalid(--stats)
26
27execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}"
28 --jobs 2 --start 3 --count 0 --max-bytes 0 --large-module-bytes 0
29 --slow 0.5 --stage cs --stats report.csv
30 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
31if(NOT code STREQUAL "2" OR NOT log MATCHES "malformed JSON")
32 message(FATAL_ERROR "Expected valid arguments to reach the malformed index, got ${code}\n${log}")
33endif()
diff --git a/runtime/test/d3d12_clear_test.cpp b/runtime/test/d3d12_clear_test.cpp
index 53103a31f..3d2cd3944 100644
--- a/runtime/test/d3d12_clear_test.cpp
+++ b/runtime/test/d3d12_clear_test.cpp
@@ -350,6 +350,9 @@ int main(int argc, char** argv) {
350 const ColorFormat color_formats[] = { 350 const ColorFormat color_formats[] = {
351 {DXGI_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM", 4, float_values, nf}, 351 {DXGI_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM", 4, float_values, nf},
352 {DXGI_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM", 4, float_values, nf}, 352 {DXGI_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM", 4, float_values, nf},
353 // B8G8R8X8 is stored in a BGRA8 image; B8G8R8A8 next to it shows what the X byte changes.
354 {DXGI_FORMAT_B8G8R8A8_UNORM, "B8G8R8A8_UNORM", 4, float_values, nf},
355 {DXGI_FORMAT_B8G8R8X8_UNORM, "B8G8R8X8_UNORM", 4, float_values, nf},
353 {DXGI_FORMAT_R32G32B32A32_FLOAT, "R32G32B32A32_FLOAT", 16, float_values, nf}, 356 {DXGI_FORMAT_R32G32B32A32_FLOAT, "R32G32B32A32_FLOAT", 16, float_values, nf},
354 {DXGI_FORMAT_R8G8_UINT, "R8G8_UINT", 2, int_values, ni}, 357 {DXGI_FORMAT_R8G8_UINT, "R8G8_UINT", 2, int_values, ni},
355 {DXGI_FORMAT_R8G8B8A8_UINT, "R8G8B8A8_UINT", 4, int_values, ni}, 358 {DXGI_FORMAT_R8G8B8A8_UINT, "R8G8B8A8_UINT", 4, int_values, ni},
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index 2ac216bcb..e53f9ab4b 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -10,6 +10,7 @@
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 "vk_test_device.h" 11#include "vk_test_device.h"
12#include "../shims/d3d12_com.h" 12#include "../shims/d3d12_com.h"
13#include "../src/gfx10_descriptors.h"
13#include "../src/shader_library.h" 14#include "../src/shader_library.h"
14#include "../shims/d3d12_xs_device.h" 15#include "../shims/d3d12_xs_device.h"
15 16
@@ -33,6 +34,8 @@ using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10
33// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235). 34// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235).
34using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, 35using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t,
35 std::uint64_t, const IID*, void**); 36 std::uint64_t, const IID*, void**);
37// Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out).
38using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**);
36using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); 39using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
37 40
38template<class T> 41template<class T>
@@ -169,6 +172,7 @@ int main() {
169 constexpr UINT elements = 64, bytes = elements * 4; 172 constexpr UINT elements = 64, bytes = elements * 4;
170 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; 173 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000};
171 std::vector<std::uint32_t> first(elements), second(elements); 174 std::vector<std::uint32_t> first(elements), second(elements);
175 std::vector<std::uint32_t> cbv_a_out(elements), cbv_oob_out(elements), cbv_b_out(elements), cbv_null_out(elements);
172 { 176 {
173 rt::d3d12::VulkanDeviceInfo info{}; 177 rt::d3d12::VulkanDeviceInfo info{};
174 info.get_instance_proc = d.instance_proc; 178 info.get_instance_proc = d.instance_proc;
@@ -178,6 +182,7 @@ int main() {
178 info.queue = d.queue; 182 info.queue = d.queue;
179 info.queue_family = d.family; 183 info.queue_family = d.family;
180 info.buffer_device_address = true; 184 info.buffer_device_address = true;
185 info.subgroup = d.subgroup;
181 info.shader_dir = library.string(); 186 info.shader_dir = library.string();
182 ID3D12Device* inner = nullptr; 187 ID3D12Device* inner = nullptr;
183 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); 188 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
@@ -220,6 +225,40 @@ int main() {
220 EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); 225 EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p);
221 pso_desc.CS = {container.data(), container.size()}; 226 pso_desc.CS = {container.data(), container.size()};
222 227
228 // The PSO through slot 67, compute pipeline from native code; maps to CreateComputePipelineState.
229 struct XboxNativeComputeDesc {
230 ID3D12RootSignature* root_signature;
231 const void* kind0;
232 std::uint64_t kind0_size;
233 const void* kind1;
234 std::uint64_t kind1_size;
235 const void* kind6;
236 std::uint64_t kind6_size;
237 const void* kind7;
238 std::uint64_t kind7_size;
239 } native_desc{};
240 native_desc.root_signature = root.p;
241 native_desc.kind6 = fssm.data();
242 native_desc.kind6_size = fssm.size();
243 Ref<ID3D12PipelineState> pso67, unknown67;
244 EXPECT(SUCCEEDED(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
245 device.p, &native_desc, &pso_iid, reinterpret_cast<void**>(&pso67.p))));
246 EXPECT(pso67.p != nullptr);
247 native_desc.kind6 = other.data();
248 native_desc.kind6_size = other.size();
249 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
250 device.p, &native_desc, &pso_iid, reinterpret_cast<void**>(&unknown67.p)) == E_INVALIDARG && !unknown67.p);
251 void* out_null = reinterpret_cast<void*>(0x1111);
252 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
253 device.p, nullptr, &pso_iid, &out_null) == E_INVALIDARG && !out_null);
254 out_null = reinterpret_cast<void*>(0x1111);
255 native_desc.kind6 = fssm.data();
256 native_desc.kind6_size = fssm.size();
257 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
258 device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null);
259 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
260 device.p, &native_desc, &pso_iid, nullptr) == E_POINTER);
261
223 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so 262 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so
224 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag). 263 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag).
225 { 264 {
@@ -343,6 +382,128 @@ int main() {
343 std::memcpy(first.data(), results, bytes); 382 std::memcpy(first.data(), results, bytes);
344 std::memcpy(second.data(), static_cast<const std::uint8_t*>(results) + bytes, bytes); 383 std::memcpy(second.data(), static_cast<const std::uint8_t*>(results) + bytes, bytes);
345 384
385 // CreateConstantBufferView: populate shader-visible descriptor heap slots with GFX10 V# descriptors for a
386 // 512-byte arena constant buffer (two 256-byte CBVs: A at +0, B at +256) and null CBVs.
387 {
388 const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
389 EXPECT(inc == 32);
390 const auto cb_desc = buffer_desc(512, D3D12_RESOURCE_FLAG_NONE);
391 Ref<ID3D12Resource> cb_upload, cb_default, cb_readback;
392 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &cb_desc,
393 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
394 IID_PPV_ARGS(&cb_upload.p))));
395 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &cb_desc,
396 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
397 IID_PPV_ARGS(&cb_default.p))));
398 const auto cb_rb_desc = buffer_desc(4 * bytes, D3D12_RESOURCE_FLAG_NONE);
399 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &cb_rb_desc,
400 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
401 IID_PPV_ARGS(&cb_readback.p))));
402 void* cb_mapped = nullptr;
403 EXPECT(SUCCEEDED(cb_upload->Map(0, nullptr, &cb_mapped)));
404 auto* cb_words = static_cast<std::uint32_t*>(cb_mapped);
405 for (UINT i = 0; i < elements; ++i) {
406 cb_words[i] = 0x10000u + i;
407 cb_words[elements + i] = 0x20000u + i;
408 }
409 const D3D12_GPU_VIRTUAL_ADDRESS cb_va = cb_default->GetGPUVirtualAddress();
410 EXPECT(cb_va >= 0x10000 && cb_va < (1ull << 32));
411
412 const auto slot_cpu = [&](UINT idx) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + idx * inc)}; };
413 const auto slot_gpu = [&](UINT idx) { return D3D12_GPU_DESCRIPTOR_HANDLE{gpu + idx * inc}; };
414
415 // Pre-fill slot 3 with non-zero bytes to prove null CBV zeroes the entire 32-byte slot.
416 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0xA5, inc);
417 device->CreateConstantBufferView(nullptr, slot_cpu(3));
418 std::uint8_t zeros[32] = {};
419 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
420
421 // Zero BufferLocation or zero SizeInBytes also produces a zeroed null V#.
422 const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_loc{0, 256};
423 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0x5A, inc);
424 device->CreateConstantBufferView(&zero_loc, slot_cpu(3));
425 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
426 const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_size{cb_va, 0};
427 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0x5A, inc);
428 device->CreateConstantBufferView(&zero_size, slot_cpu(3));
429 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
430
431 const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_a{cb_va, 256};
432 const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_b{cb_va + 256, 256};
433 device->CreateConstantBufferView(&cbv_a, slot_cpu(1));
434 device->CreateConstantBufferView(&cbv_b, slot_cpu(2));
435
436 // Decode the written V# in slots 1 and 2 and verify every field + zeroed trailing 16 bytes.
437 for (const auto& [slot_idx, expected_va] :
438 {std::pair{1u, std::uint64_t(cb_va)}, std::pair{2u, std::uint64_t(cb_va + 256)}}) {
439 leonida::gfx10::BufferWords raw{};
440 std::memcpy(raw.data(), reinterpret_cast<const void*>(slot_cpu(slot_idx).ptr), sizeof(raw));
441 leonida::gfx10::Buffer decoded{};
442 EXPECT(leonida::gfx10::decode(raw, decoded));
443 EXPECT(decoded.address == expected_va);
444 EXPECT(decoded.stride == 0);
445 EXPECT(decoded.num_records == 256);
446 EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT));
447 EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle);
448 EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw);
449 EXPECT(std::memcmp(reinterpret_cast<const std::uint8_t*>(slot_cpu(slot_idx).ptr) + 16, zeros, 16) == 0);
450 }
451
452 // Copy CBV data into the arena buffer, then run 4 dispatches:
453 // 1) CBV A at byte offset 0 (all 64 dwords in-bounds)
454 // 2) CBV A at byte offset 128 (dwords 0..31 in-bounds, dwords 32..63 OOB -> 0)
455 // 3) CBV B at byte offset 0 (negative control: all 64 dwords flip to 0x20000 + i)
456 // 4) Null CBV at byte offset 0 (negative control: all 64 dwords become 0)
457 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p)));
458 list->CopyBufferRegion(cb_default.p, 0, cb_upload.p, 0, 512);
459 const D3D12_RESOURCE_BARRIER cb_ready[] = {
460 transition(cb_default.p, D3D12_RESOURCE_STATE_COPY_DEST,
461 D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER),
462 transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
463 };
464 list->ResourceBarrier(2, cb_ready);
465 list->SetDescriptorHeaps(1, heaps);
466 list->SetComputeRootSignature(root.p);
467 list->SetComputeRootUnorderedAccessView(1, va_a);
468
469 const struct CbvDispatch {
470 UINT byte_offset;
471 UINT slot_idx;
472 UINT readback_offset;
473 } cbv_dispatches[] = {
474 {0, 1, 0 * bytes},
475 {128, 1, 1 * bytes},
476 {0, 2, 2 * bytes},
477 {0, 3, 3 * bytes},
478 };
479 for (const auto& d_cfg : cbv_dispatches) {
480 const std::uint32_t rc[2] = {d_cfg.byte_offset, 0}; // s1 == 0 selects CBV V# mode
481 list->SetComputeRoot32BitConstants(0, 2, rc, 0);
482 list->SetComputeRootDescriptorTable(2, slot_gpu(d_cfg.slot_idx));
483 list->Dispatch(1, 1, 1);
484 const auto to_src =
485 transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
486 list->ResourceBarrier(1, &to_src);
487 list->CopyBufferRegion(cb_readback.p, d_cfg.readback_offset, out_a.p, 0, bytes);
488 const auto to_uav =
489 transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
490 list->ResourceBarrier(1, &to_uav);
491 }
492 EXPECT(list->Close() == S_OK);
493 queue->ExecuteCommandLists(1, lists);
494 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
495 EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)));
496 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(2, nullptr)));
497
498 void* cb_res = nullptr;
499 EXPECT(SUCCEEDED(cb_readback->Map(0, nullptr, &cb_res)));
500 const auto* src_bytes = static_cast<const std::uint8_t*>(cb_res);
501 std::memcpy(cbv_a_out.data(), src_bytes + 0 * bytes, bytes);
502 std::memcpy(cbv_oob_out.data(), src_bytes + 1 * bytes, bytes);
503 std::memcpy(cbv_b_out.data(), src_bytes + 2 * bytes, bytes);
504 std::memcpy(cbv_null_out.data(), src_bytes + 3 * bytes, bytes);
505 }
506
346 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset(); 507 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset();
347 pso.reset(); 508 pso.reset();
348 root.reset(); 509 root.reset();
@@ -363,6 +524,27 @@ int main() {
363 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b); 524 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b);
364 } 525 }
365 EXPECT(!mismatches); 526 EXPECT(!mismatches);
527 UINT cbv_b_diff = 0, cbv_null_diff = 0;
528 for (std::uint32_t i = 0; i < elements; ++i) {
529 const std::uint32_t want_a = 0x10000u + i;
530 const std::uint32_t want_oob = i < 32 ? (0x10000u + 32u + i) : 0u;
531 const std::uint32_t want_b = 0x20000u + i;
532 if (cbv_a_out[i] != want_a && mismatches++ < 4)
533 std::fprintf(stderr, "CBV A[%u]: got 0x%x want 0x%x\n", i, cbv_a_out[i], want_a);
534 if (cbv_oob_out[i] != want_oob && mismatches++ < 4)
535 std::fprintf(stderr, "CBV OOB[%u]: got 0x%x want 0x%x\n", i, cbv_oob_out[i], want_oob);
536 if (cbv_b_out[i] != want_b && mismatches++ < 4)
537 std::fprintf(stderr, "CBV B[%u]: got 0x%x want 0x%x\n", i, cbv_b_out[i], want_b);
538 if (cbv_null_out[i] != 0u && mismatches++ < 4)
539 std::fprintf(stderr, "CBV null[%u]: got 0x%x want 0\n", i, cbv_null_out[i]);
540 if (cbv_b_out[i] != cbv_a_out[i]) ++cbv_b_diff;
541 if (cbv_null_out[i] != cbv_a_out[i]) ++cbv_null_diff;
542 }
543 EXPECT(!mismatches);
544 EXPECT(cbv_b_diff == elements && cbv_null_diff == elements);
545 std::printf("CreateConstantBufferView: 64/64 dwords matched for CBV A, 32 in-bounds + 32 OOB-zero matched at "
546 "+128, negative controls flipped %u/%u (CBV B) and %u/%u (null CBV)\n",
547 cbv_b_diff, elements, cbv_null_diff, elements);
366 if (d.validation_errors()) { 548 if (d.validation_errors()) {
367 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 549 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
368 return 1; 550 return 1;
diff --git a/runtime/test/d3d12_copy_compare.h b/runtime/test/d3d12_copy_compare.h
index 3679ab754..3d4281a17 100644
--- a/runtime/test/d3d12_copy_compare.h
+++ b/runtime/test/d3d12_copy_compare.h
@@ -5,7 +5,8 @@
5// into a readback buffer prefilled with 0xcd, and the bytes are compared. Only the texels a footprint row holds are 5// into a readback buffer prefilled with 0xcd, and the bytes are compared. Only the texels a footprint row holds are
6// compared (row padding is the driver's); everything else, including the 0xcd around a partial copy, must match. 6// compared (row padding is the driver's); everything else, including the 0xcd around a partial copy, must match.
7// Layouts come from the host's GetCopyableFootprints for both sides (those are compared separately). 7// Layouts come from the host's GetCopyableFootprints for both sides (those are compared separately).
8// LEONIDA_HOST_ADAPTER picks the host side: "warp", or part of an adapter name; unset is the default adapter. 8// LEONIDA_HOST_ADAPTER picks the host side: "warp", or part of an adapter name; unset is the layer's own adapter when
9// the test has set layer_adapter(), else the default adapter.
9#pragma once 10#pragma once
10#include <windows.h> 11#include <windows.h>
11#include <d3d12.h> 12#include <d3d12.h>
@@ -18,6 +19,7 @@
18#include <cstdio> 19#include <cstdio>
19#include <cstring> 20#include <cstring>
20#include <functional> 21#include <functional>
22#include <optional>
21#include <string> 23#include <string>
22#include <vector> 24#include <vector>
23 25
@@ -110,12 +112,25 @@ inline bool try_create_host(Ptr<ID3D12Device>& host, std::string& name, const LU
110 return true; 112 return true;
111} 113}
112 114
113// A host device, or false when there is none (the comparisons are then skipped). When LEONIDA_HOST_ADAPTER names an 115// The adapter behind the layer's Vulkan device (VkPhysicalDeviceIDProperties::deviceLUID), for a test that knows it.
114// adapter that cannot be had, the run fails: a typo must not turn the comparisons into a silent pass. 116// On a PC with two GPUs D3D12's default adapter can be the other one, whose driver accepts other formats (an AMD
117// layer device accepts an R9G9B9E5 render target that the NVIDIA host refuses), so the comparison would be between
118// two GPUs instead of between the layer and the host runtime.
119inline std::optional<LUID>& layer_adapter() {
120 static std::optional<LUID> luid;
121 return luid;
122}
123
124// A host device, or false when there is none (the comparisons are then skipped). Without LEONIDA_HOST_ADAPTER it is
125// on the layer's own adapter when that is set and has a D3D12 device, else on the default adapter. When
126// LEONIDA_HOST_ADAPTER names an adapter that cannot be had, the run fails: a typo must not turn the comparisons into a
127// silent pass.
115inline bool create_host(Ptr<ID3D12Device>& host, std::string& name) { 128inline bool create_host(Ptr<ID3D12Device>& host, std::string& name) {
116 if (try_create_host(host, name)) return true;
117 char want[128] = {}; 129 char want[128] = {};
118 if (GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && want[0]) { 130 const bool named = GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && want[0];
131 if (!named && layer_adapter() && try_create_host(host, name, &*layer_adapter())) return true;
132 if (try_create_host(host, name)) return true;
133 if (named) {
119 std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter, or no D3D12 device on it\n", want); 134 std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter, or no D3D12 device on it\n", want);
120 std::exit(1); 135 std::exit(1);
121 } 136 }
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index 4f587166b..2f6d059c3 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -13,6 +13,9 @@
13// CreateSampler2 samplers that clamp to a UINT (0,0,0,0) and (1,1,1,1) border, and a float white border on 13// CreateSampler2 samplers that clamp to a UINT (0,0,0,0) and (1,1,1,1) border, and a float white border on
14// the UNORM texture. Every texel is the border: 0, 1 and 255 in each channel. Both white borders are built in 14// the UNORM texture. Every texel is the border: 0, 1 and 255 in each channel. Both white borders are built in
15// at the same S# type, so this also checks that they are two samplers, not one. 15// at the same S# type, so this also checks that they are two samplers, not one.
16// - B8G8R8X8 (D3D-87): a B8G8R8X8_UNORM and a B8G8R8A8_UNORM texture uploaded with the same bytes, the fourth
17// never 255. Their default views read the same red, green and blue; B8G8R8X8 reads alpha 1, B8G8R8A8 the
18// stored byte. Views between the two typeless families give a null descriptor.
16// Multisample SRVs: four masked triangles seed different values per sample and array layer. A compute shader reads 19// Multisample SRVs: four masked triangles seed different values per sample and array layer. A compute shader reads
17// them back using the T#s for the 2D, full-array and sliced-array views. The test builds its pipelines in Vulkan 20// them back using the T#s for the 2D, full-array and sliced-array views. The test builds its pipelines in Vulkan
18// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped. 21// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped.
@@ -81,6 +84,13 @@ std::array<std::uint8_t, 4> texel(UINT x, UINT y) {
81 return {std::uint8_t(x * 32), std::uint8_t(y * 32), std::uint8_t(128 + x + 8 * y), 255}; 84 return {std::uint8_t(x * 32), std::uint8_t(y * 32), std::uint8_t(128 + x + 8 * y), 255};
82} 85}
83 86
87// The same texel in B, G, R memory order, with a fourth byte that is never 255: what a B8G8R8X8 texture and a
88// B8G8R8A8 one with the same bytes are uploaded with. Through a view the first reads alpha 1, the second this byte.
89std::array<std::uint8_t, 4> bgrx_texel(UINT x, UINT y) {
90 const auto t = texel(x, y);
91 return {t[2], t[1], t[0], std::uint8_t(3 * (y * 8 + x))};
92}
93
84#ifdef LEONIDA_TEST_CS_SAMPLE_SPV 94#ifdef LEONIDA_TEST_CS_SAMPLE_SPV
85// What cs_sample.comp is pushed: a T#, an S#, and where in the output buffer its 64 texels go. 95// What cs_sample.comp is pushed: a T#, an S#, and where in the output buffer its 64 texels go.
86struct SampleKeys { 96struct SampleKeys {
@@ -292,7 +302,7 @@ int main() {
292 if (device_status != vktest::DeviceStatus::ready) return 1; 302 if (device_status != vktest::DeviceStatus::ready) return 1;
293 303
294 constexpr UINT size = 8, texels = size * size, bytes = texels * 4; 304 constexpr UINT size = 8, texels = size * size, bytes = texels * 4;
295 std::vector<std::uint8_t> results(4 * bytes), after_destruction(bytes), borders(3 * bytes); 305 std::vector<std::uint8_t> results(4 * bytes), after_destruction(bytes), borders(3 * bytes), bgr_results(2 * bytes);
296 bool sampled_through_set = false; 306 bool sampled_through_set = false;
297 UINT lod_mismatches = 0; 307 UINT lod_mismatches = 0;
298 { 308 {
@@ -532,6 +542,32 @@ int main() {
532 for (UINT x = 0; x < fp.Width; ++x) std::memcpy(row + 4 * x, color.data(), 4); 542 for (UINT x = 0; x < fp.Width; ++x) std::memcpy(row + 4 * x, color.data(), 4);
533 } 543 }
534 } 544 }
545 // A B8G8R8X8_UNORM texture and a B8G8R8A8_UNORM one, uploaded with the same bgrx_texel bytes past the cube
546 // array's footprints.
547 constexpr DXGI_FORMAT bgr_formats[2] = {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM};
548 Ref<ID3D12Resource> bgr_textures[2];
549 D3D12_PLACED_SUBRESOURCE_FOOTPRINT bgr_placed[2]{};
550 const auto& last_array = array_levels[std::size(array_levels) - 1];
551 constexpr UINT64 placement = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
552 const UINT64 bgr_start =
553 (last_array.Offset + UINT64(last_array.Footprint.RowPitch) * last_array.Footprint.Height + placement - 1) &
554 ~(placement - 1);
555 for (UINT f = 0; f < 2; ++f) {
556 D3D12_RESOURCE_DESC desc = texture_desc;
557 desc.Format = bgr_formats[f];
558 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
559 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
560 IID_PPV_ARGS(&bgr_textures[f].p))));
561 device->GetCopyableFootprints(&desc, 0, 1, bgr_start + 8192 * f, &bgr_placed[f], nullptr, nullptr, nullptr);
562 EXPECT(bgr_placed[f].Footprint.Format == bgr_formats[f]);
563 EXPECT(bgr_placed[f].Offset + UINT64(bgr_placed[f].Footprint.RowPitch) * size <= upload_desc.Width);
564 for (UINT y = 0; y < size; ++y)
565 for (UINT x = 0; x < size; ++x)
566 std::memcpy(static_cast<std::uint8_t*>(mapped) + bgr_placed[f].Offset +
567 y * bgr_placed[f].Footprint.RowPitch + x * 4,
568 bgrx_texel(x, y).data(), 4);
569 }
570 EXPECT(bgr_placed[0].Footprint.RowPitch == bgr_placed[1].Footprint.RowPitch);
535 571
536 // Shader-visible heaps, start handles in the Xbox shape. 572 // Shader-visible heaps, start handles in the Xbox shape.
537 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); 573 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
@@ -562,7 +598,7 @@ int main() {
562 volume_lod_slot = cube_lod_slot + cube_lod_count, 598 volume_lod_slot = cube_lod_slot + cube_lod_count,
563 ms_slot = volume_lod_slot + volume_lod_count, ms_array_slot, ms_slice_slot, ms_first_layer_slot, 599 ms_slot = volume_lod_slot + volume_lod_count, ms_array_slot, ms_slice_slot, ms_first_layer_slot,
564 ms_uint_slot, ms_uint_array_slot, ms_sint_slot, ms_sint_array_slot, 600 ms_uint_slot, ms_uint_array_slot, ms_sint_slot, ms_sint_array_slot,
565 line_default, line_mip, line_clamped, view_slot_count 601 line_default, line_mip, line_clamped, bgrx_slot, bgra_slot, typed_bgrx_slot, view_slot_count
566 }; 602 };
567 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, view_slot_count, 603 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, view_slot_count,
568 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 604 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
@@ -1099,6 +1135,51 @@ int main() {
1099 std::memset(view_bytes(null_slot), 0x77, step); 1135 std::memset(view_bytes(null_slot), 0x77, step);
1100 device->CreateShaderResourceView(texture.p, &colour_plane, view_slot(null_slot)); 1136 device->CreateShaderResourceView(texture.p, &colour_plane, view_slot(null_slot));
1101 EXPECT(null_at(null_slot)); 1137 EXPECT(null_at(null_slot));
1138
1139 // B8G8R8X8 is a BGRA8 image whose views read alpha as 1, so its T# selects one where B8G8R8A8's selects W.
1140 // B8G8R8X8 and B8G8R8A8 are different typeless families: a view never crosses from one to the other.
1141 device->CreateShaderResourceView(bgr_textures[0].p, nullptr, view_slot(bgrx_slot));
1142 device->CreateShaderResourceView(bgr_textures[1].p, nullptr, view_slot(bgra_slot));
1143 g::Image bgrx_image{}, bgra_image{};
1144 EXPECT(image_at(bgrx_slot, bgrx_image) && image_at(bgra_slot, bgra_image));
1145 EXPECT(bgrx_image.format == g::format_from_vulkan(VK_FORMAT_B8G8R8A8_UNORM) &&
1146 bgra_image.format == bgrx_image.format);
1147 EXPECT((bgrx_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_one}));
1148 EXPECT((bgra_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_w}));
1149 Ref<ID3D12Resource> bgrx_typeless;
1150 D3D12_RESOURCE_DESC bgrx_typeless_desc = texture_desc;
1151 bgrx_typeless_desc.Format = DXGI_FORMAT_B8G8R8X8_TYPELESS;
1152 bgrx_typeless_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // allowed, but no format gives a UAV
1153 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &bgrx_typeless_desc,
1154 D3D12_RESOURCE_STATE_COMMON, nullptr,
1155 IID_PPV_ARGS(&bgrx_typeless.p))));
1156 D3D12_SHADER_RESOURCE_VIEW_DESC bgr_view = flat_view;
1157 bgr_view.Format = DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
1158 device->CreateShaderResourceView(bgrx_typeless.p, &bgr_view, view_slot(typed_bgrx_slot));
1159 g::Image typed_bgrx_image{};
1160 EXPECT(image_at(typed_bgrx_slot, typed_bgrx_image));
1161 EXPECT(typed_bgrx_image.format == g::format_from_vulkan(VK_FORMAT_B8G8R8A8_SRGB));
1162 EXPECT(typed_bgrx_image.swizzle == bgrx_image.swizzle && typed_bgrx_image.address != bgrx_image.address);
1163 bgr_view.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
1164 for (ID3D12Resource* x8 : {bgr_textures[0].p, bgrx_typeless.p}) {
1165 std::memset(view_bytes(null_slot), 0x77, step);
1166 device->CreateShaderResourceView(x8, &bgr_view, view_slot(null_slot));
1167 EXPECT(null_at(null_slot));
1168 }
1169 bgr_view.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
1170 std::memset(view_bytes(null_slot), 0x77, step);
1171 device->CreateShaderResourceView(bgr_textures[1].p, &bgr_view, view_slot(null_slot));
1172 EXPECT(null_at(null_slot));
1173 D3D12_UNORDERED_ACCESS_VIEW_DESC bgrx_write{};
1174 bgrx_write.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
1175 bgrx_write.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
1176 const D3D12_UNORDERED_ACCESS_VIEW_DESC* const bgrx_uavs[2] = {nullptr, &bgrx_write};
1177 for (const D3D12_UNORDERED_ACCESS_VIEW_DESC* uav : bgrx_uavs) {
1178 std::memset(view_bytes(null_slot), 0x77, step);
1179 device->CreateUnorderedAccessView(bgrx_typeless.p, nullptr, uav, view_slot(null_slot));
1180 EXPECT(null_at(null_slot));
1181 }
1182 bgrx_typeless.reset();
1102 cube.reset(); 1183 cube.reset();
1103 writable.reset(); 1184 writable.reset();
1104 1185
@@ -1205,6 +1286,11 @@ int main() {
1205 transition(bc.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); 1286 transition(bc.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
1206 list->ResourceBarrier(1, &barrier); 1287 list->ResourceBarrier(1, &barrier);
1207 } 1288 }
1289 for (UINT f = 0; f < 2; ++f) {
1290 to_texture.pResource = bgr_textures[f].p;
1291 from_upload.PlacedFootprint = bgr_placed[f];
1292 list->CopyTextureRegion(&to_texture, 0, 0, 0, &from_upload, nullptr);
1293 }
1208 to_texture.pResource = volume.p; 1294 to_texture.pResource = volume.p;
1209 for (UINT mip = 0; mip < 2; ++mip) { 1295 for (UINT mip = 0; mip < 2; ++mip) {
1210 to_texture.SubresourceIndex = mip; 1296 to_texture.SubresourceIndex = mip;
@@ -1221,7 +1307,11 @@ int main() {
1221 transition(line.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), 1307 transition(line.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1222 transition(packed.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), 1308 transition(packed.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1223 transition(uint_texture.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), 1309 transition(uint_texture.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1224 transition(volume.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)}; 1310 transition(volume.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1311 transition(bgr_textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST,
1312 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1313 transition(bgr_textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST,
1314 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)};
1225 list->ResourceBarrier(UINT(std::size(sampled)), sampled); 1315 list->ResourceBarrier(UINT(std::size(sampled)), sampled);
1226 to_texture.pResource = array_texture.p; 1316 to_texture.pResource = array_texture.p;
1227 for (UINT sub = 0; sub < std::size(array_levels); ++sub) { 1317 for (UINT sub = 0; sub < std::size(array_levels); ++sub) {
@@ -1854,6 +1944,15 @@ int main() {
1854 } 1944 }
1855 EXPECT(rgb96_differ == 0); 1945 EXPECT(rgb96_differ == 0);
1856 } 1946 }
1947 // The B8G8R8X8 and B8G8R8A8 textures through their default views.
1948 SampleKeys bgr_keys[2] = {};
1949 const UINT bgr_slots[2] = {bgrx_slot, bgra_slot};
1950 for (UINT k = 0; k < 2; ++k) {
1951 std::memcpy(bgr_keys[k].tsharp, view_bytes(bgr_slots[k]), sizeof(bgr_keys[k].tsharp));
1952 std::memcpy(bgr_keys[k].ssharp, sampler_bytes, sizeof(bgr_keys[k].ssharp));
1953 bgr_keys[k].first = k * texels;
1954 }
1955 EXPECT(sample_through_set(d, set0, set0_layout, bgr_keys, bgr_results.data()));
1857#endif 1956#endif
1858 1957
1859 // A destroyed texture takes its views out of the set: the next ExecuteCommandLists writes that, and nothing 1958 // A destroyed texture takes its views out of the set: the next ExecuteCommandLists writes that, and nothing
@@ -2067,6 +2166,47 @@ int main() {
2067#endif 2166#endif
2068 } 2167 }
2069 2168
2169 // Cross-family castable SRV: write_image_descriptor must pass resource.has_view_format_list() into a single
2170 // bind_image call so a listed R8G8B8A8_UINT -> R32_UINT view registers cleanly without a spurious first-pass
2171 // failure (and without double-binding every view).
2172 if (d.bindless) {
2173 Ref<ID3D12Device10> inner10;
2174 EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&inner10.p))));
2175 D3D12_RESOURCE_DESC1 cast_desc{};
2176 cast_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
2177 cast_desc.Width = 4;
2178 cast_desc.Height = 4;
2179 cast_desc.DepthOrArraySize = 1;
2180 cast_desc.MipLevels = 1;
2181 cast_desc.Format = DXGI_FORMAT_R8G8B8A8_UINT;
2182 cast_desc.SampleDesc = {1, 0};
2183 cast_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
2184 const DXGI_FORMAT cast_formats[] = {DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R32_UINT};
2185 Ref<ID3D12Resource> cast_tex;
2186 EXPECT(SUCCEEDED(inner10->CreateCommittedResource3(
2187 &default_heap, D3D12_HEAP_FLAG_NONE, &cast_desc, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr,
2188 2, cast_formats, IID_PPV_ARGS(&cast_tex.p))));
2189 const D3D12_DESCRIPTOR_HEAP_DESC cast_hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1,
2190 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
2191 Ref<ID3D12DescriptorHeap> cast_heap;
2192 EXPECT(SUCCEEDED(inner10->CreateDescriptorHeap(&cast_hd, IID_PPV_ARGS(&cast_heap.p))));
2193 const D3D12_CPU_DESCRIPTOR_HANDLE cast_slot = cast_heap->GetCPUDescriptorHandleForHeapStart();
2194 D3D12_SHADER_RESOURCE_VIEW_DESC cast_srv{};
2195 cast_srv.Format = DXGI_FORMAT_R32_UINT;
2196 cast_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2197 cast_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2198 cast_srv.Texture2D.MipLevels = 1;
2199 inner10->CreateShaderResourceView(cast_tex.p, &cast_srv, cast_slot);
2200 g::ImageWords cast_words{};
2201 std::memcpy(cast_words.data(), reinterpret_cast<const void*>(cast_slot.ptr), sizeof(cast_words));
2202 g::Image decoded{};
2203 EXPECT(g::decode(cast_words, decoded) && decoded.type == g::ImageType::image_2d);
2204 EXPECT(decoded.format == g::format_from_vulkan(VK_FORMAT_R32_UINT));
2205 std::uint32_t cast_key[8]{};
2206 std::memcpy(cast_key, cast_words.data(), sizeof(cast_key));
2207 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, cast_key) != 0);
2208 }
2209
2070 upload.reset(); 2210 upload.reset();
2071 array_texture.reset(); 2211 array_texture.reset();
2072 line.reset(); 2212 line.reset();
@@ -2078,6 +2218,7 @@ int main() {
2078 byte_heap.reset(); 2218 byte_heap.reset();
2079 ms_texture.reset(); 2219 ms_texture.reset();
2080 ms_array.reset(); 2220 ms_array.reset();
2221 for (auto& resource : bgr_textures) resource.reset();
2081 view_heap.reset(); 2222 view_heap.reset();
2082 sampler_heap.reset(); 2223 sampler_heap.reset();
2083 list.reset(); 2224 list.reset();
@@ -2141,6 +2282,19 @@ int main() {
2141 } 2282 }
2142 EXPECT(!mismatches); 2283 EXPECT(!mismatches);
2143 EXPECT(lod_mismatches == 0); 2284 EXPECT(lod_mismatches == 0);
2285 // Both read red, green and blue from the same bytes; B8G8R8X8 reads alpha 1, B8G8R8A8 the stored byte.
2286 const char* bgr_names[2] = {"B8G8R8X8_UNORM", "B8G8R8A8_UNORM"};
2287 for (UINT k = 0; k < 2; ++k)
2288 for (UINT i = 0; i < texels; ++i) {
2289 auto want = texel(i % size, i / size);
2290 if (k == 1) want[3] = bgrx_texel(i % size, i / size)[3];
2291 const std::uint8_t* got = bgr_results.data() + k * bytes + i * 4;
2292 if (std::memcmp(got, want.data(), 4) != 0 && mismatches++ < 4)
2293 std::fprintf(stderr, "%s texel %u: got %u,%u,%u,%u, want %u,%u,%u,%u\n", bgr_names[k], i,
2294 unsigned(got[0]), unsigned(got[1]), unsigned(got[2]), unsigned(got[3]),
2295 unsigned(want[0]), unsigned(want[1]), unsigned(want[2]), unsigned(want[3]));
2296 }
2297 EXPECT(!mismatches);
2144 if (d.validation_errors()) { 2298 if (d.validation_errors()) {
2145 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 2299 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
2146 return 1; 2300 return 1;
@@ -2148,6 +2302,7 @@ int main() {
2148 std::printf("descriptors: copies matched; a T# and an S# from CreateShaderResourceView and CreateSampler were " 2302 std::printf("descriptors: copies matched; a T# and an S# from CreateShaderResourceView and CreateSampler were "
2149 "found in the device's bindless set by a shader, %u RGBA8 and RGB9E5 texels matched, and an unknown descriptor " 2303 "found in the device's bindless set by a shader, %u RGBA8 and RGB9E5 texels matched, and an unknown descriptor "
2150 "and a destroyed texture's gave the fallback; UINT black, UINT white and float white borders read " 2304 "and a destroyed texture's gave the fallback; UINT black, UINT white and float white borders read "
2151 "0, 1 and 255\n", texels); 2305 "0, 1 and 255; B8G8R8X8 read alpha 1 where B8G8R8A8 read the same bytes' alpha (%u texels each)\n",
2306 texels, texels);
2152 return 0; 2307 return 0;
2153} 2308}
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 574872b8a..12a1c71cf 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -84,6 +84,8 @@ int main() {
84 constexpr UINT size = 64; 84 constexpr UINT size = 64;
85 std::vector<std::uint8_t> pixels(size * 256), second_pixels(size * 256); 85 std::vector<std::uint8_t> pixels(size * 256), second_pixels(size * 256);
86 std::vector<std::uint8_t> strip16_pixels(size * 256), strip32_pixels(size * 256), strip_nocut_pixels(size * 256); 86 std::vector<std::uint8_t> strip16_pixels(size * 256), strip32_pixels(size * 256), strip_nocut_pixels(size * 256);
87 std::vector<std::uint8_t> msaa_full_pixels(size * 256), msaa_half_pixels(size * 256);
88 bool ran_msaa = false;
87 const bool logic_op = d.enabled.logicOp == VK_TRUE; 89 const bool logic_op = d.enabled.logicOp == VK_TRUE;
88 { 90 {
89 rt::d3d12::VulkanDeviceInfo info{}; 91 rt::d3d12::VulkanDeviceInfo info{};
@@ -94,6 +96,7 @@ int main() {
94 info.queue = d.queue; 96 info.queue = d.queue;
95 info.queue_family = d.family; 97 info.queue_family = d.family;
96 info.buffer_device_address = true; 98 info.buffer_device_address = true;
99 info.subgroup = d.subgroup;
97 info.shader_dir = library.string(); 100 info.shader_dir = library.string();
98 // Of the PSO features only logicOp is passed on, so the other feature refusals below still apply. 101 // Of the PSO features only logicOp is passed on, so the other feature refusals below still apply.
99 info.features.logicOp = d.enabled.logicOp; 102 info.features.logicOp = d.enabled.logicOp;
@@ -466,6 +469,102 @@ int main() {
466 } 469 }
467 } 470 }
468 471
472 // Multisampled graphics pipeline (4x MSAA): draw the top-left red quad into a 4x MSAA target and resolve.
473 // Full SampleMask (0xFFFFFFFF) writes all 4 samples red; half SampleMask (0x5) writes 2 of 4 samples so the
474 // resolved top-left quadrant shifts from (255, 0, 0, 255) to ~50/50 purple (128, 0, 128, 255).
475 {
476 // SampleDesc.Count == 0, non-power-of-two/out-of-range counts, and non-zero quality must all be rejected.
477 auto bad_desc = pso_desc;
478 Ref<ID3D12PipelineState> bad_pso;
479 for (const DXGI_SAMPLE_DESC sd : {DXGI_SAMPLE_DESC{0, 0}, DXGI_SAMPLE_DESC{3, 0}, DXGI_SAMPLE_DESC{64, 0},
480 DXGI_SAMPLE_DESC{4, 1}, DXGI_SAMPLE_DESC{1, 1}}) {
481 bad_desc.SampleDesc = sd;
482 EXPECT(device->CreateGraphicsPipelineState(&bad_desc, IID_PPV_ARGS(&bad_pso.p)) == E_INVALIDARG &&
483 !bad_pso.p);
484 }
485 // Any power-of-two sample count not supported by the attachment format must also be rejected.
486 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS ms32{DXGI_FORMAT_R8G8B8A8_UNORM, 32,
487 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 0};
488 if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &ms32, sizeof(ms32))) &&
489 ms32.NumQualityLevels == 0) {
490 bad_desc.SampleDesc = {32, 0};
491 EXPECT(device->CreateGraphicsPipelineState(&bad_desc, IID_PPV_ARGS(&bad_pso.p)) == E_INVALIDARG &&
492 !bad_pso.p);
493 }
494
495 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS ms_levels{DXGI_FORMAT_R8G8B8A8_UNORM, 4,
496 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 0};
497 if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &ms_levels,
498 sizeof(ms_levels))) &&
499 ms_levels.NumQualityLevels > 0) {
500 auto ms_rt_desc = rt_desc;
501 ms_rt_desc.SampleDesc.Count = 4;
502 Ref<ID3D12Resource> ms_target;
503 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ms_rt_desc,
504 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
505 IID_PPV_ARGS(&ms_target.p))));
506 D3D12_DESCRIPTOR_HEAP_DESC ms_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1,
507 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
508 Ref<ID3D12DescriptorHeap> ms_rtv_heap;
509 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&ms_heap_desc, IID_PPV_ARGS(&ms_rtv_heap.p))));
510 const D3D12_CPU_DESCRIPTOR_HANDLE ms_rtv{
511 SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(ms_rtv_heap.p, 9))(ms_rtv_heap.p))};
512 device->CreateRenderTargetView(ms_target.p, nullptr, ms_rtv);
513
514 auto ms_pso_desc = pso_desc;
515 ms_pso_desc.SampleDesc.Count = 4;
516 Ref<ID3D12PipelineState> ms_full_pso, ms_half_pso;
517 ms_pso_desc.SampleMask = 0xFFFFFFFFu;
518 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&ms_pso_desc, IID_PPV_ARGS(&ms_full_pso.p))));
519 ms_pso_desc.SampleMask = 0x5u;
520 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&ms_pso_desc, IID_PPV_ARGS(&ms_half_pso.p))));
521
522 struct MsaaPass {
523 ID3D12PipelineState* pso;
524 std::vector<std::uint8_t>* out;
525 };
526 const MsaaPass ms_passes[] = {{ms_full_pso.p, &msaa_full_pixels}, {ms_half_pso.p, &msaa_half_pixels}};
527 UINT64 ms_fence = 20;
528 for (UINT pass = 0; pass < std::size(ms_passes); ++pass) {
529 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, ms_passes[pass].pso)));
530 if (pass > 0) {
531 const auto ms_to_rt = transition(ms_target.p, D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
532 D3D12_RESOURCE_STATE_RENDER_TARGET);
533 list->ResourceBarrier(1, &ms_to_rt);
534 }
535 list->ClearRenderTargetView(ms_rtv, blue, 0, nullptr);
536 list->SetGraphicsRootSignature(root.p);
537 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
538 list->IASetVertexBuffers(0, 1, &vbv);
539 list->IASetIndexBuffer(&ibv);
540 list->RSSetViewports(1, &viewport);
541 list->RSSetScissorRects(1, &scissor);
542 list->OMSetRenderTargets(1, &ms_rtv, FALSE, nullptr);
543 list->SetGraphicsRoot32BitConstants(0, 2, origin, 0);
544 list->SetGraphicsRootConstantBufferView(1, upload_va + 512);
545 list->DrawIndexedInstanced(6, 1, 0, 0, 0);
546 const D3D12_RESOURCE_BARRIER pre_resolve[] = {
547 transition(ms_target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
548 transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RESOLVE_DEST),
549 };
550 list->ResourceBarrier(2, pre_resolve);
551 list->ResolveSubresource(target.p, 0, ms_target.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
552 const auto post_resolve =
553 transition(target.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
554 list->ResourceBarrier(1, &post_resolve);
555 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
556 EXPECT(list->Close() == S_OK);
557 queue->ExecuteCommandLists(1, lists);
558 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
559 ++ms_fence;
560 EXPECT(SUCCEEDED(queue->Signal(fence.p, ms_fence)) &&
561 SUCCEEDED(fence->SetEventOnCompletion(ms_fence, nullptr)));
562 std::memcpy(ms_passes[pass].out->data(), mapped, ms_passes[pass].out->size());
563 }
564 ran_msaa = true;
565 }
566 }
567
469 // A draw with no viewport (never set, or unbound with a count of 0) rasterizes nothing in D3D12. It is not 568 // A draw with no viewport (never set, or unbound with a count of 0) rasterizes nothing in D3D12. It is not
470 // recorded, so the list closes and executes cleanly (Vulkan forbids a 0x0 viewport). 569 // recorded, so the list closes and executes cleanly (Vulkan forbids a 0x0 viewport).
471 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p))); 570 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p)));
@@ -478,7 +577,7 @@ int main() {
478 EXPECT(list->Close() == S_OK); 577 EXPECT(list->Close() == S_OK);
479 queue->ExecuteCommandLists(1, lists); 578 queue->ExecuteCommandLists(1, lists);
480 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 579 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
481 EXPECT(SUCCEEDED(queue->Signal(fence.p, 20)) && SUCCEEDED(fence->SetEventOnCompletion(20, nullptr))); 580 EXPECT(SUCCEEDED(queue->Signal(fence.p, 30)) && SUCCEEDED(fence->SetEventOnCompletion(30, nullptr)));
482 581
483 // Each parent draw starts with a 0.25 blend factor, then executes one of four bundles. 582 // Each parent draw starts with a 0.25 blend factor, then executes one of four bundles.
484 // Empty and reset bundles preserve it. Explicit zero and nullptr replace it with zero and one. 583 // Empty and reset bundles preserve it. Explicit zero and nullptr replace it with zero and one.
@@ -531,7 +630,8 @@ int main() {
531 EXPECT(list->Close() == S_OK); 630 EXPECT(list->Close() == S_OK);
532 queue->ExecuteCommandLists(1, lists); 631 queue->ExecuteCommandLists(1, lists);
533 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 632 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
534 EXPECT(SUCCEEDED(queue->Signal(fence.p, 4)) && SUCCEEDED(fence->SetEventOnCompletion(4, nullptr))); 633 // Above the strip passes' 20: a lower value is already reached, so the wait would return at once.
634 EXPECT(SUCCEEDED(queue->Signal(fence.p, 21)) && SUCCEEDED(fence->SetEventOnCompletion(21, nullptr)));
535 const auto* result = static_cast<const std::uint8_t*>(mapped); 635 const auto* result = static_cast<const std::uint8_t*>(mapped);
536 for (UINT row = 0; row < size; ++row) { 636 for (UINT row = 0; row < size; ++row) {
537 for (UINT col = 0; col < size; ++col) { 637 for (UINT col = 0; col < size; ++col) {
@@ -629,6 +729,38 @@ int main() {
629 std::printf("strip cut (0xFFFF & 0xFFFFFFFF): 4096/4096 pixels matched each (no-cut negative control painted %u " 729 std::printf("strip cut (0xFFFF & 0xFFFFFFFF): 4096/4096 pixels matched each (no-cut negative control painted %u "
630 "bridge pixels in bottom-left)\n", 730 "bridge pixels in bottom-left)\n",
631 nocut_bl_red); 731 nocut_bl_red);
732 if (ran_msaa) {
733 UINT half_changed = 0;
734 for (UINT row = 0; row < size; ++row) {
735 for (UINT col = 0; col < size; ++col) {
736 const bool top_left = row < size / 2 && col < size / 2;
737 const std::uint8_t* got_full = msaa_full_pixels.data() + row * 256 + col * 4;
738 const std::uint8_t* got_half = msaa_half_pixels.data() + row * 256 + col * 4;
739 const std::uint8_t want_full[4] = {std::uint8_t(top_left ? 255 : 0), 0,
740 std::uint8_t(top_left ? 0 : 255), 255};
741 if (std::memcmp(got_full, want_full, 4) != 0 && mismatches++ < 6)
742 std::fprintf(stderr, "4x MSAA full mask (%u,%u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row,
743 got_full[0], got_full[1], got_full[2], got_full[3], want_full[0], want_full[1],
744 want_full[2], want_full[3]);
745 if (top_left) {
746 const bool ok = std::abs(int(got_half[0]) - 128) <= 1 && got_half[1] == 0 &&
747 std::abs(int(got_half[2]) - 128) <= 1 && got_half[3] == 255;
748 if (!ok && mismatches++ < 6)
749 std::fprintf(stderr, "4x MSAA half mask (%u,%u): got %u,%u,%u,%u want ~128,0,128,255\n", col,
750 row, got_half[0], got_half[1], got_half[2], got_half[3]);
751 if (std::memcmp(got_half, got_full, 4) != 0) ++half_changed;
752 } else if (std::memcmp(got_half, want_full, 4) != 0 && mismatches++ < 6) {
753 std::fprintf(stderr, "4x MSAA half mask bg (%u,%u): got %u,%u,%u,%u want 0,0,255,255\n", col, row,
754 got_half[0], got_half[1], got_half[2], got_half[3]);
755 }
756 }
757 }
758 EXPECT(!mismatches);
759 EXPECT(half_changed == (size / 2) * (size / 2));
760 std::printf("4x MSAA graphics pipeline: 4096/4096 resolved pixels matched (SampleMask 0x5 changed %u/%u "
761 "top-left pixels to purple)\n",
762 half_changed, (size / 2) * (size / 2));
763 }
632 if (d.validation_errors()) { 764 if (d.validation_errors()) {
633 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 765 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
634 return 1; 766 return 1;
diff --git a/runtime/test/d3d12_gcl8_test.cpp b/runtime/test/d3d12_gcl8_test.cpp
index 7e3020583..8b0426e6c 100644
--- a/runtime/test/d3d12_gcl8_test.cpp
+++ b/runtime/test/d3d12_gcl8_test.cpp
@@ -36,6 +36,10 @@ int main(int argc, char** argv) {
36 EXPECT(SUCCEEDED(create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); 36 EXPECT(SUCCEEDED(create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
37 EXPECT(SUCCEEDED(create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, IID_PPV_ARGS(&list7.p)))); 37 EXPECT(SUCCEEDED(create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, IID_PPV_ARGS(&list7.p))));
38 38
39 // Null bindings exercise the public entry points without creating a pipeline or loading Vulkan.
40 list7.p->SetPipelineState(nullptr);
41 list7.p->SetGraphicsRootSignature(nullptr);
42
39 // AddRef through the GCL7 pointer gives the count this test expects while the QueryInterface reference is held. 43 // AddRef through the GCL7 pointer gives the count this test expects while the QueryInterface reference is held.
40 const ULONG held = list7.p->AddRef(); 44 const ULONG held = list7.p->AddRef();
41 list7.p->Release(); 45 list7.p->Release();
@@ -82,6 +86,11 @@ int main(int argc, char** argv) {
82 EXPECT(list7.p->AddRef() == held); // QueryInterface released its reference 86 EXPECT(list7.p->AddRef() == held); // QueryInterface released its reference
83 list7.p->Release(); 87 list7.p->Release();
84 88
89 // Calls made before pipeline setup still belong in the trace. They invalidate this list without needing a GPU.
90 list7.p->DrawInstanced(3, 1, 0, 0);
91 list7.p->DrawIndexedInstanced(3, 1, 0, 0, 0);
92 EXPECT(list7.p->Close() == E_INVALIDARG);
93
85 UINT ignored_front = 0, ignored_back = 0; 94 UINT ignored_front = 0, ignored_back = 0;
86 EXPECT(!front_back_stencil_ref(nullptr, ignored_front, ignored_back)); 95 EXPECT(!front_back_stencil_ref(nullptr, ignored_front, ignored_back));
87 96
diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp
index db8e9fd3f..8d13bf214 100644
--- a/runtime/test/d3d12_m2_textured_test.cpp
+++ b/runtime/test/d3d12_m2_textured_test.cpp
@@ -20,6 +20,7 @@
20// [1] POINT/WRAP. The left half takes the WRAP sampler (U + 1 wraps back: the gradient again), the right half the 20// [1] POINT/WRAP. The left half takes the WRAP sampler (U + 1 wraps back: the gradient again), the right half the
21// CLAMP one (U + 1 clamps to the last column: each row is that row's right-edge texel of the reflected texture). The 21// CLAMP one (U + 1 clamps to the last column: each row is that row's right-edge texel of the reflected texture). The
22// pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection. 22// pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection.
23// The control also keeps one unbounded SRV table bound and selects its two entries by a root constant.
23// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). 24// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
24#include "vk_test_device.h" 25#include "vk_test_device.h"
25#include "d3d12_test_shaders.h" 26#include "d3d12_test_shaders.h"
@@ -148,6 +149,22 @@ int main() {
148 pso_desc.SampleDesc.Count = 1; 149 pso_desc.SampleDesc.Count = 1;
149 Ref<ID3D12PipelineState> pso, uoff_pso; 150 Ref<ID3D12PipelineState> pso, uoff_pso;
150 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); 151 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
152 D3D12_DESCRIPTOR_RANGE indexed_range = srv_range;
153 indexed_range.NumDescriptors = UINT32_MAX;
154 D3D12_ROOT_PARAMETER indexed_params[3] = {params[0], params[1], {}};
155 indexed_params[0].DescriptorTable = {1, &indexed_range};
156 indexed_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
157 indexed_params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
158 indexed_params[2].Constants = {0, 0, 2}; // s4 = SRV index, s5 = SRV stride in bytes
159 D3D12_VERSIONED_ROOT_SIGNATURE_DESC indexed_desc = root_desc;
160 indexed_desc.Desc_1_0.NumParameters = 3;
161 indexed_desc.Desc_1_0.pParameters = indexed_params;
162 const auto indexed_blob = serialize_root_signature(indexed_desc);
163 EXPECT(!indexed_blob.empty());
164 Ref<ID3D12RootSignature> indexed_root;
165 EXPECT(SUCCEEDED(device->CreateRootSignature(0, indexed_blob.data(), indexed_blob.size(),
166 IID_PPV_ARGS(&indexed_root.p))));
167 pso_desc.pRootSignature = indexed_root.p;
151 pso_desc.PS = {uoff_container.data(), uoff_container.size()}; 168 pso_desc.PS = {uoff_container.data(), uoff_container.size()};
152 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p)))); 169 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p))));
153 170
@@ -350,8 +367,9 @@ int main() {
350 D3D12_RESOURCE_STATE_RENDER_TARGET); 367 D3D12_RESOURCE_STATE_RENDER_TARGET);
351 list2->ResourceBarrier(1, &back); 368 list2->ResourceBarrier(1, &back);
352 list2->ClearRenderTargetView(rtv, clear, 0, nullptr); 369 list2->ClearRenderTargetView(rtv, clear, 0, nullptr);
353 list2->SetGraphicsRootSignature(root.p); 370 list2->SetGraphicsRootSignature(indexed_root.p);
354 list2->SetDescriptorHeaps(2, heaps); 371 list2->SetDescriptorHeaps(2, heaps);
372 list2->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu});
355 list2->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); 373 list2->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
356 list2->IASetIndexBuffer(&ibv); 374 list2->IASetIndexBuffer(&ibv);
357 list2->RSSetViewports(1, &viewport); 375 list2->RSSetViewports(1, &viewport);
@@ -359,7 +377,8 @@ int main() {
359 for (UINT half = 0; half < 2; ++half) { 377 for (UINT half = 0; half < 2; ++half) {
360 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)}; 378 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)};
361 list2->RSSetScissorRects(1, &scissor); 379 list2->RSSetScissorRects(1, &scissor);
362 list2->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step}); 380 const UINT srv_args[] = {half, step};
381 list2->SetGraphicsRoot32BitConstants(2, 2, srv_args, 0);
363 list2->SetGraphicsRootDescriptorTable( 382 list2->SetGraphicsRootDescriptorTable(
364 1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(half == 0 ? sampler_step : 0)}); 383 1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(half == 0 ? sampler_step : 0)});
365 list2->DrawIndexedInstanced(6, 1, 0, 0, 0); 384 list2->DrawIndexedInstanced(6, 1, 0, 0, 0);
@@ -387,6 +406,7 @@ int main() {
387 uoff_pso.reset(); 406 uoff_pso.reset();
388 list2.reset(); 407 list2.reset();
389 allocator2.reset(); 408 allocator2.reset();
409 indexed_root.reset();
390 root.reset(); 410 root.reset();
391 srv_heap.reset(); 411 srv_heap.reset();
392 sampler_heap.reset(); 412 sampler_heap.reset();
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index 764b3e0f5..8b28eb67a 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -108,11 +108,13 @@ PFN_vkCreateSemaphore real_create_semaphore = nullptr;
108PFN_vkDestroySemaphore real_destroy_semaphore = nullptr; 108PFN_vkDestroySemaphore real_destroy_semaphore = nullptr;
109PFN_vkGetPhysicalDeviceSurfaceFormatsKHR real_surface_formats = nullptr; 109PFN_vkGetPhysicalDeviceSurfaceFormatsKHR real_surface_formats = nullptr;
110PFN_vkCreateSwapchainKHR real_create_swapchain = nullptr; 110PFN_vkCreateSwapchainKHR real_create_swapchain = nullptr;
111PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR real_get_caps = nullptr;
111VkResult fail_next_submit = VK_SUCCESS; // armed: the next vkQueueSubmit returns this and submits nothing 112VkResult fail_next_submit = VK_SUCCESS; // armed: the next vkQueueSubmit returns this and submits nothing
112VkResult next_present = VK_SUCCESS; // armed: the next present that succeeds reports this instead 113VkResult next_present = VK_SUCCESS; // armed: the next present that succeeds reports this instead
113int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore from now fails 114int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore from now fails
114bool fail_surface_formats = false; // armed: the next surface-format query fails before creation 115bool fail_surface_formats = false; // armed: the next surface-format query fails before creation
115bool observe_next_swapchain = false; 116bool observe_next_swapchain = false;
117bool report_undefined_extent = false; // armed: surface capabilities reports undefined extent (0xFFFFFFFF)
116VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE; 118VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE;
117VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE; 119VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE;
118unsigned out_of_date = 0; // presents the real driver reported out of date 120unsigned out_of_date = 0; // presents the real driver reported out of date
@@ -177,6 +179,16 @@ VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice device, const VkSwapcha
177 return result; 179 return result;
178} 180}
179 181
182VKAPI_ATTR VkResult VKAPI_CALL get_surface_capabilities(VkPhysicalDevice physical, VkSurfaceKHR surface,
183 VkSurfaceCapabilitiesKHR* caps) {
184 const VkResult result = real_get_caps(physical, surface, caps);
185 if (result == VK_SUCCESS && report_undefined_extent && caps) {
186 caps->currentExtent.width = 0xFFFFFFFF;
187 caps->currentExtent.height = 0xFFFFFFFF;
188 }
189 return result;
190}
191
180VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { 192VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
181 const std::string_view n = name; 193 const std::string_view n = name;
182 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 194 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
@@ -188,9 +200,12 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char*
188} 200}
189 201
190VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const char* name) { 202VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const char* name) {
191 if (std::string_view(name) == "vkGetDeviceProcAddr") return reinterpret_cast<PFN_vkVoidFunction>(get_device); 203 const std::string_view n = name;
192 if (std::string_view(name) == "vkGetPhysicalDeviceSurfaceFormatsKHR") 204 if (n == "vkGetDeviceProcAddr") return reinterpret_cast<PFN_vkVoidFunction>(get_device);
205 if (n == "vkGetPhysicalDeviceSurfaceFormatsKHR")
193 return reinterpret_cast<PFN_vkVoidFunction>(surface_formats); 206 return reinterpret_cast<PFN_vkVoidFunction>(surface_formats);
207 if (n == "vkGetPhysicalDeviceSurfaceCapabilitiesKHR")
208 return reinterpret_cast<PFN_vkVoidFunction>(get_surface_capabilities);
194 return real_get_instance(instance, name); 209 return real_get_instance(instance, name);
195} 210}
196 211
@@ -204,6 +219,8 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
204 real_surface_formats = reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>( 219 real_surface_formats = reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>(
205 instance_proc(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR")); 220 instance_proc(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"));
206 real_create_swapchain = reinterpret_cast<PFN_vkCreateSwapchainKHR>(real_get_device(device, "vkCreateSwapchainKHR")); 221 real_create_swapchain = reinterpret_cast<PFN_vkCreateSwapchainKHR>(real_get_device(device, "vkCreateSwapchainKHR"));
222 real_get_caps = reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR>(
223 instance_proc(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"));
207} 224}
208} // namespace driver 225} // namespace driver
209 226
@@ -390,8 +407,17 @@ int main() {
390 for (int i = 0; i < 4; ++i) EXPECT(frame(1)); // both frames in flight come round again 407 for (int i = 0; i < 4; ++i) EXPECT(frame(1)); // both frames in flight come round again
391 EXPECT(presenter->presented() == before + 4 - (driver::out_of_date - out_of_date_before)); 408 EXPECT(presenter->presented() == before + 4 - (driver::out_of_date - out_of_date_before));
392 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); 409 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr)));
410
411 // 4. Undefined surface extent (0xFFFFFFFF, reported by Intel UHD graphics / Win32 WSI; D3D-165):
412 // the presenter queries the window client extent and clamps to surface bounds.
413 driver::report_undefined_extent = true;
414 EXPECT(frame(1));
415 EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300);
416 driver::report_undefined_extent = false;
417
393 std::printf("injected: out-of-date and suboptimal presents counted apart, a failed swapchain recreation " 418 std::printf("injected: out-of-date and suboptimal presents counted apart, a failed swapchain recreation "
394 "released and retried, a failed blit submission recovered (%u real out-of-date presents)\n", 419 "released and retried, a failed blit submission recovered, undefined surface extent resolved "
420 "(%u real out-of-date presents)\n",
395 real_out_of_date); 421 real_out_of_date);
396 422
397 // What reached the screen: the centre of the client area, if the window is in front. 423 // What reached the screen: the centre of the client area, if the window is in front.
diff --git a/runtime/test/d3d12_queue_wait_test.cpp b/runtime/test/d3d12_queue_wait_test.cpp
index d1a868a25..3dfb1bad3 100644
--- a/runtime/test/d3d12_queue_wait_test.cpp
+++ b/runtime/test/d3d12_queue_wait_test.cpp
@@ -1,7 +1,9 @@
1// D3D-97: cross-queue Wait-before-Signal must make progress. No game files. 1// D3D-97: cross-queue Wait-before-Signal must make progress. No game files.
2#include "../shims/d3d12_com.h" 2#include "../shims/d3d12_com.h"
3 3
4#include <cstdlib>
4#include <cstdio> 5#include <cstdio>
6#include <cstring>
5 7
6namespace { 8namespace {
7template<class T> struct Ref { 9template<class T> struct Ref {
@@ -10,19 +12,35 @@ template<class T> struct Ref {
10 T* operator->() const { return p; } 12 T* operator->() const { return p; }
11}; 13};
12 14
13bool wait_for(ID3D12Fence* fence, UINT64 value) { 15bool wait_for(ID3D12Fence* fence, UINT64 value, DWORD timeout_ms = 3000) {
14 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 16 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
15 if (!event) return false; 17 if (!event) return false;
16 const bool complete = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && 18 if (FAILED(fence->SetEventOnCompletion(value, event))) {
17 WaitForSingleObject(event, 3000) == WAIT_OBJECT_0; 19 CloseHandle(event); // no wait was registered
20 return false;
21 }
22 if (WaitForSingleObject(event, timeout_ms) != WAIT_OBJECT_0) {
23 // The fence dispatcher can still hold this event, and a queued GPU Wait can keep the queue destructor
24 // blocked forever. End the failed test without closing live handles or waiting for blocked queues.
25 std::fputs("cross-queue Wait-before-Signal timed out\n", stderr);
26 std::fflush(stderr);
27 std::_Exit(1);
28 }
18 CloseHandle(event); 29 CloseHandle(event);
19 return complete; 30 return true;
20} 31}
21} // namespace 32} // namespace
22 33
23int main() { 34int main(int argc, char** argv) {
24 Ref<ID3D12Device> device; 35 Ref<ID3D12Device> device;
25 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p)))) return 77; 36 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p)))) return 77;
37 if (argc == 2 && std::strcmp(argv[1], "--timeout-control") == 0) {
38 Ref<ID3D12Fence> never_signaled;
39 if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&never_signaled.p)))) return 1;
40 // Expected to leave the process with code 1 promptly, without destroying the pending event.
41 wait_for(never_signaled.p, 1, 20);
42 return 0; // a completed wait here means the control did not exercise the timeout path
43 }
26 D3D12_COMMAND_QUEUE_DESC desc{}; 44 D3D12_COMMAND_QUEUE_DESC desc{};
27 Ref<ID3D12CommandQueue> copy, compute, direct_a, direct_b; 45 Ref<ID3D12CommandQueue> copy, compute, direct_a, direct_b;
28 desc.Type = D3D12_COMMAND_LIST_TYPE_COPY; 46 desc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
@@ -49,11 +67,11 @@ int main() {
49 const bool copy_complete = submitted && wait_for(done_copy.p, 1); 67 const bool copy_complete = submitted && wait_for(done_copy.p, 1);
50 const bool direct_complete = submitted && wait_for(done_direct.p, 1); 68 const bool direct_complete = submitted && wait_for(done_direct.p, 1);
51 if (!copy_complete || !direct_complete) { 69 if (!copy_complete || !direct_complete) {
52 // Unblock submitted waits before queue destructors call vkQueueWaitIdle. 70 // A failed submit can leave a GPU Wait pending. Gate 1 is not a valid fallback once queue signals
53 gate_copy->Signal(1); 71 // have claimed 2, so do not destroy queues or fences while their work may still be outstanding.
54 gate_direct->Signal(1); 72 std::fputs("cross-queue Wait-before-Signal did not complete\n", stderr);
55 std::fprintf(stderr, "cross-queue Wait-before-Signal did not complete\n"); 73 std::fflush(stderr);
56 return 1; 74 std::_Exit(1);
57 } 75 }
58 std::puts("copy/compute and direct/direct Wait-before-Signal completed"); 76 std::puts("copy/compute and direct/direct Wait-before-Signal completed");
59 return 0; 77 return 0;
diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp
new file mode 100644
index 000000000..69663d764
--- /dev/null
+++ b/runtime/test/d3d12_set0_compute_test.cpp
@@ -0,0 +1,337 @@
1// Set 0 from the compute bind point, through the Xbox-ABI proxy over the Vulkan device. A compute PSO whose shader
2// declares set-0 bindings is created and dispatched through D3D12 alone; nothing in the test touches Vulkan's
3// descriptor sets. The dispatches only give the right words if the layer has the device's bindless set 0 in the
4// pipeline layout and binds it at the dispatch:
5// - two 8x8 textures, a gradient and its point reflection, uploaded with Map and CopyTextureRegion;
6// - a shader-visible CBV/SRV/UAV heap with an SRV for each in slots 0 and 1 and 32 bytes no view was made for in
7// slot 2, and a sampler heap with a POINT sampler that wraps in slot 0 and one that clamps in slot 1;
8// - a root signature of two constants, a root UAV and the two descriptor tables.
9// test/glsl/cs_set0_sample.comp loads the T# and the S# from the tables in the GPU address arena, looks them up in
10// the descriptor hash table (set 0, binding 2) and samples one tile to the right in U. Four dispatches:
11// 1. slot 0 with the wrapping sampler: the gradient, texel for texel;
12// 2. slot 1 with the wrapping sampler: the reflected texture, so the T# decides the image;
13// 3. slot 2 with the wrapping sampler: the fallback image, one colour everywhere;
14// 4. slot 0 with the clamping sampler: the gradient's right edge in every column, so the S# decides the sampler.
15// A device without the bindless set refuses the PSO. No game data: the program is two marker words and the module is
16// GLSL written to the translator's contract.
17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
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/shader_library.h"
23
24#include <array>
25#include <cstdint>
26#include <cstring>
27#include <filesystem>
28#include <fstream>
29#include <vector>
30
31#ifndef LEONIDA_TEST_CS_SET0_SAMPLE_SPV
32#error "LEONIDA_TEST_CS_SET0_SAMPLE_SPV must name the compiled test shader"
33#endif
34
35#define EXPECT(condition) do { \
36 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
37} while (0)
38
39using namespace d3d12test;
40using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
41
42namespace {
43
44using Texel = std::array<std::uint8_t, 4>;
45constexpr UINT texture_size = 8, texels = texture_size * texture_size, run_bytes = texels * 4, runs = 4;
46
47// The synthetic gradient: red rises with x, green with y, blue falls along the diagonal.
48Texel gradient(UINT x, UINT y) {
49 return {std::uint8_t(x * 36), std::uint8_t(y * 36), std::uint8_t(255 - (x + y) * 16), 255};
50}
51// The second texture: the first one point-reflected, so no texel of it is in the same place.
52Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); }
53
54} // namespace
55
56int main() {
57 vktest::Device d;
58 const auto device_status = d.initialize();
59 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
60 if (device_status != vktest::DeviceStatus::ready) return 1;
61 if (!d.bindless) {
62 std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n");
63 return 77;
64 }
65
66 // The program the PSO carries, and a translator index that maps its hash to the test module. The index lists
67 // set-0 bindings for the shader, as the translator does for one that samples.
68 const auto program = fssm_program({0x43530003, 0xbf810000});
69 const auto container = shader_container(program);
70 const auto library = std::filesystem::temp_directory_path() / "leonida_set0_compute_test";
71 std::filesystem::create_directories(library);
72 std::filesystem::copy_file(LEONIDA_TEST_CS_SET0_SAMPLE_SPV, library / "cs_set0_sample.spv",
73 std::filesystem::copy_options::overwrite_existing);
74 {
75 std::ofstream index(library / "index.json", std::ios::binary);
76 index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program)
77 << "\", \"bindings\": [0, 1, 2], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], "
78 "\"uses_code_base\": false, \"wave64\": false}}";
79 }
80
81 std::vector<std::uint8_t> results(runs * run_bytes);
82 {
83 rt::d3d12::VulkanDeviceInfo info{};
84 info.get_instance_proc = d.instance_proc;
85 info.instance = d.instance;
86 info.physical = d.physical;
87 info.device = d.device;
88 info.queue = d.queue;
89 info.queue_family = d.family;
90 info.buffer_device_address = true;
91 info.bindless = d.bindless;
92 info.bindless_partially_bound = d.partially_bound;
93 info.image_view_min_lod = d.image_view_min_lod;
94 info.shader_dir = library.string();
95 ID3D12Device* inner = nullptr;
96 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
97 Ref<ID3D12Device> device;
98 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
99 reinterpret_cast<void**>(&device.p))));
100 rt::d3d12::set_device_outer(inner, device.p);
101 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
102
103 // Root signature: [0] two constants (s0: the view slot's offset in dwords, s1: the first output element),
104 // [1] a root UAV (s2:s3, the output buffer), [2] the table of views (s4:s5), [3] the table of samplers
105 // (s6:s7).
106 D3D12_DESCRIPTOR_RANGE view_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 0, 0, 0};
107 D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0};
108 D3D12_ROOT_PARAMETER params[4] = {};
109 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
110 params[0].Constants = {0, 0, 2};
111 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
112 params[1].Descriptor = {0, 0};
113 params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
114 params[2].DescriptorTable = {1, &view_range};
115 params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
116 params[3].DescriptorTable = {1, &sampler_range};
117 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
118 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
119 root_desc.Desc_1_0 = {4, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
120 const auto root_blob = serialize_root_signature(root_desc);
121 EXPECT(!root_blob.empty());
122 Ref<ID3D12RootSignature> root;
123 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
124
125 // The PSO: its shader has set-0 bindings, so its layout holds the device's set.
126 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
127 pso_desc.pRootSignature = root.p;
128 pso_desc.CS = {container.data(), container.size()};
129 Ref<ID3D12PipelineState> pso;
130 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
131
132 // A device without the bindless set has nothing such a shader could find its images in: the PSO is refused.
133 {
134 rt::d3d12::VulkanDeviceInfo plain_info = info;
135 plain_info.bindless = plain_info.bindless_partially_bound = false;
136 Ref<ID3D12Device> plain;
137 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(plain_info, IID_PPV_ARGS(&plain.p))));
138 EXPECT(rt::d3d12::bindless_set(plain.p) == VK_NULL_HANDLE);
139 Ref<ID3D12RootSignature> plain_root;
140 EXPECT(SUCCEEDED(plain->CreateRootSignature(0, root_blob.data(), root_blob.size(),
141 IID_PPV_ARGS(&plain_root.p))));
142 D3D12_COMPUTE_PIPELINE_STATE_DESC plain_desc = pso_desc;
143 plain_desc.pRootSignature = plain_root.p;
144 Ref<ID3D12PipelineState> refused;
145 EXPECT(plain->CreateComputePipelineState(&plain_desc, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && !refused.p);
146 }
147
148 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
149 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
150 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
151 D3D12_RESOURCE_DESC texture_desc{};
152 texture_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
153 texture_desc.Width = texture_desc.Height = texture_size;
154 texture_desc.DepthOrArraySize = 1;
155 texture_desc.MipLevels = 1;
156 texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
157 texture_desc.SampleDesc.Count = 1;
158 Ref<ID3D12Resource> textures[2], upload, output, readback;
159 for (auto& texture : textures)
160 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc,
161 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
162 IID_PPV_ARGS(&texture.p))));
163 // The upload buffer: texture A at 0, texture B at 2048 (8 rows of the 256-byte pitch).
164 constexpr UINT64 b_offset = 2048;
165 const auto upload_desc = buffer_desc(4096);
166 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc,
167 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
168 IID_PPV_ARGS(&upload.p))));
169 const auto output_desc = buffer_desc(results.size(), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
170 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &output_desc,
171 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
172 IID_PPV_ARGS(&output.p))));
173 const auto readback_desc = buffer_desc(results.size());
174 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
175 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
176 IID_PPV_ARGS(&readback.p))));
177 D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
178 device->GetCopyableFootprints(&texture_desc, 0, 1, 0, &footprint, nullptr, nullptr, nullptr);
179 EXPECT(footprint.Footprint.RowPitch == 256 && footprint.Footprint.RowPitch * texture_size <= b_offset);
180 std::uint8_t* up = nullptr;
181 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&up))));
182 for (UINT y = 0; y < texture_size; ++y)
183 for (UINT x = 0; x < texture_size; ++x) {
184 const Texel a = gradient(x, y), b = reflected(x, y);
185 std::memcpy(up + y * footprint.Footprint.RowPitch + x * 4, a.data(), 4);
186 std::memcpy(up + b_offset + y * footprint.Footprint.RowPitch + x * 4, b.data(), 4);
187 }
188
189 // The two heaps; their start handles come back in RAX (heap slots 9 and 10). Shader-visible heaps live in
190 // the GPU address arena, so the GPU handles are console VAs and the bytes the views and the samplers wrote
191 // are what the shader loads.
192 const D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4,
193 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
194 const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2,
195 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
196 Ref<ID3D12DescriptorHeap> view_heap, sampler_heap;
197 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&view_heap_desc, IID_PPV_ARGS(&view_heap.p))));
198 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p))));
199 const std::uint64_t view_cpu = reinterpret_cast<XboxHeapHandleFn>(slot(view_heap.p, 9))(view_heap.p);
200 const std::uint64_t view_gpu = reinterpret_cast<XboxHeapHandleFn>(slot(view_heap.p, 10))(view_heap.p);
201 const std::uint64_t sampler_cpu = reinterpret_cast<XboxHeapHandleFn>(slot(sampler_heap.p, 9))(sampler_heap.p);
202 const std::uint64_t sampler_gpu = reinterpret_cast<XboxHeapHandleFn>(slot(sampler_heap.p, 10))(sampler_heap.p);
203 const UINT view_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
204 const UINT sampler_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
205 EXPECT(view_cpu && sampler_cpu && view_gpu >= 0x10000 && sampler_gpu >= 0x10000);
206 EXPECT(view_gpu < (1ull << 32) && sampler_gpu < (1ull << 32));
207 EXPECT(view_step >= 32 && view_step % 4 == 0 && sampler_step >= 16);
208
209 for (UINT i = 0; i < 2; ++i) {
210 D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
211 srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
212 srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
213 srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
214 srv.Texture2D = {0, 1, 0, 0.0f};
215 device->CreateShaderResourceView(textures[i].p, &srv,
216 D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(view_cpu + i * view_step)});
217 }
218 // Slot 2: bytes no view was made for. The hash table has no entry for them.
219 std::uint32_t unknown[8];
220 for (std::uint32_t i = 0; i < 8; ++i) unknown[i] = 0x5a5a0000u + i;
221 std::memcpy(reinterpret_cast<void*>(view_cpu + 2 * view_step), unknown, sizeof(unknown));
222 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, unknown) == 0);
223 for (UINT i = 0; i < 2; ++i) {
224 D3D12_SAMPLER_DESC sampler_desc{};
225 sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
226 sampler_desc.AddressU = sampler_desc.AddressV = sampler_desc.AddressW =
227 i ? D3D12_TEXTURE_ADDRESS_MODE_CLAMP : D3D12_TEXTURE_ADDRESS_MODE_WRAP;
228 sampler_desc.MaxAnisotropy = 1;
229 sampler_desc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
230 sampler_desc.MaxLOD = D3D12_FLOAT32_MAX;
231 device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + i * sampler_step)});
232 }
233
234 D3D12_COMMAND_QUEUE_DESC queue_desc{};
235 Ref<ID3D12CommandQueue> queue;
236 Ref<ID3D12CommandAllocator> allocator;
237 Ref<ID3D12GraphicsCommandList> list;
238 Ref<ID3D12Fence> fence;
239 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
240 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
241 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
242 IID_PPV_ARGS(&list.p))));
243 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
244
245 // Upload both textures and make them shader resources for a compute shader.
246 for (UINT i = 0; i < 2; ++i) {
247 D3D12_TEXTURE_COPY_LOCATION dst{};
248 dst.pResource = textures[i].p;
249 dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
250 D3D12_TEXTURE_COPY_LOCATION src{};
251 src.pResource = upload.p;
252 src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
253 src.PlacedFootprint = footprint;
254 src.PlacedFootprint.Offset = i ? b_offset : 0;
255 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
256 }
257 D3D12_RESOURCE_BARRIER sampled[2] = {
258 transition(textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
259 transition(textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)};
260 list->ResourceBarrier(2, sampled);
261
262 // The four dispatches. Each keeps the slot, the output position and the sampler table it was recorded with.
263 const D3D12_GPU_VIRTUAL_ADDRESS output_va = output->GetGPUVirtualAddress();
264 EXPECT(output_va >= 0x10000 && output_va < (1ull << 32));
265 ID3D12DescriptorHeap* heaps[] = {view_heap.p, sampler_heap.p};
266 list->SetDescriptorHeaps(2, heaps);
267 list->SetComputeRootSignature(root.p);
268 list->SetPipelineState(pso.p);
269 list->SetComputeRootUnorderedAccessView(1, output_va);
270 list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{view_gpu});
271 const UINT view_slot[runs] = {0, 1, 2, 0};
272 const UINT sampler_slot[runs] = {0, 0, 0, 1};
273 for (UINT run = 0; run < runs; ++run) {
274 const std::uint32_t offset_and_first[2] = {view_slot[run] * view_step / 4, run * texels};
275 list->SetComputeRoot32BitConstants(0, 2, offset_and_first, 0);
276 list->SetComputeRootDescriptorTable(
277 3, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(sampler_slot[run]) * sampler_step});
278 list->Dispatch(1, 1, 1);
279 }
280 D3D12_RESOURCE_BARRIER to_copy = transition(output.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
281 D3D12_RESOURCE_STATE_COPY_SOURCE);
282 list->ResourceBarrier(1, &to_copy);
283 list->CopyBufferRegion(readback.p, 0, output.p, 0, results.size());
284 EXPECT(list->Close() == S_OK);
285 ID3D12CommandList* lists[] = {list.p};
286 queue->ExecuteCommandLists(1, lists);
287 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
288 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
289 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
290 void* mapped = nullptr;
291 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
292 std::memcpy(results.data(), mapped, results.size());
293
294 for (auto& texture : textures) texture.reset();
295 for (auto* r : {&upload, &output, &readback}) r->reset();
296 pso.reset();
297 root.reset();
298 view_heap.reset();
299 sampler_heap.reset();
300 list.reset();
301 allocator.reset();
302 queue.reset();
303 fence.reset();
304 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
305 }
306 std::filesystem::remove_all(library);
307
308 // Runs 0, 1 and 3 against the textures; run 2 is the fallback image, whose colour the test does not fix: it
309 // must be one colour everywhere, which neither texture gives.
310 const char* const names[runs] = {"slot 0, wrapping", "slot 1, wrapping", "the unknown slot", "slot 0, clamping"};
311 unsigned mismatches = 0;
312 for (UINT run = 0; run < runs; ++run) {
313 const std::uint8_t* got_run = results.data() + run * run_bytes;
314 for (UINT i = 0; i < texels; ++i) {
315 const UINT x = i % texture_size, y = i / texture_size;
316 const std::uint8_t* got = got_run + i * 4;
317 Texel want{};
318 if (run == 0) want = gradient(x, y);
319 else if (run == 1) want = reflected(x, y);
320 else if (run == 3) want = gradient(texture_size - 1, y);
321 else std::memcpy(want.data(), got_run, 4); // the fallback: texel 0 of the run, everywhere
322 if (std::memcmp(got, want.data(), 4) == 0) continue;
323 if (mismatches++ < 8)
324 std::fprintf(stderr, "%s, texel %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", names[run], i, got[0], got[1],
325 got[2], got[3], want[0], want[1], want[2], want[3]);
326 }
327 }
328 EXPECT(!mismatches);
329 if (d.validation_errors()) {
330 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
331 return 1;
332 }
333 std::printf("set 0 from compute: four dispatches sampled through the bindless set the layer bound; %u texels "
334 "matched for each of two SRVs and for a clamping sampler, and bytes no view was made for gave the "
335 "fallback image\n", texels);
336 return 0;
337}
diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp
new file mode 100644
index 000000000..4eae49a5b
--- /dev/null
+++ b/runtime/test/d3d12_subgroup_test.cpp
@@ -0,0 +1,672 @@
1// Subgroup size control in PSOs, end to end through the Xbox-ABI proxy over the Vulkan device (src/subgroup_size.h):
2// three translated compute shaders from runtime/test/shaders, each dispatched through a D3D12 PSO found by the
3// SHA-256 of its FSSM program, writing eight words through the V# in s[0:3] (four root constants), read back:
4// w64 native cs_w64x_readlane translated natively: v_readlane across both halves of a wave64. Exact only in a
5// 64-wide subgroup, so the PSO must ask for 64 (and full subgroups) on a device that can give it.
6// On a device that cannot (NVIDIA: 32 only) the PSO reports it, and the result is not judged.
7// w64 emulated the same shader translated with --wave64-emulate: exact on any size, the PSO asks for nothing.
8// w32 native cs_wqm_w32, a wave32 shader with whole-quad mode on lane masks; the PSO asks for 32 where the
9// device's default or range would otherwise change it.
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
12// VK_LAYER_KHRONOS_validation; validation errors fail the test.
13#include "vk_test_device.h"
14#include "../shims/d3d12_com.h"
15#include "../src/shader_library.h"
16#include "../shims/d3d12_xs_device.h"
17
18#include <array>
19#include <cstdint>
20#include <cstring>
21#include <filesystem>
22#include <string>
23#include <vector>
24
25#ifndef LEONIDA_TEST_SUBGROUP_SHADERS
26#error "LEONIDA_TEST_SUBGROUP_SHADERS must name the folder with the translated test shaders"
27#endif
28
29#define EXPECT(condition) do { \
30 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
31} while (0)
32
33namespace {
34
35using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t,
36 std::uint64_t, const IID*, void**);
37using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
38using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
39
40template<class T>
41struct Ref {
42 T* p = nullptr;
43 ~Ref() { reset(); }
44 void reset() {
45 if (p) p->Release();
46 p = nullptr;
47 }
48 T* operator->() const { return p; }
49};
50
51void* slot(void* object, unsigned index) { return (*reinterpret_cast<void***>(object))[index]; }
52
53void put32(std::vector<std::uint8_t>& out, std::uint32_t v) {
54 for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i)));
55}
56
57std::vector<std::uint8_t> zlib_stored(const std::vector<std::uint8_t>& data) {
58 std::vector<std::uint8_t> out = {0x78, 0x01, 0x01};
59 const auto length = std::uint16_t(data.size());
60 out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length),
61 std::uint8_t(~length >> 8)});
62 out.insert(out.end(), data.begin(), data.end());
63 std::uint32_t a = 1, b = 0;
64 for (const std::uint8_t x : data) {
65 a = (a + x) % 65521;
66 b = (b + a) % 65521;
67 }
68 const std::uint32_t adler = (b << 16) | a;
69 out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8),
70 std::uint8_t(adler)});
71 return out;
72}
73
74// DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } }, the layout tools/fssm_unpack.py reads.
75std::vector<std::uint8_t> shader_container(const std::vector<std::uint8_t>& fssm) {
76 const auto stream = zlib_stored(fssm);
77 std::vector<std::uint8_t> xbch = {'X', 'B', 'C', 'H'};
78 for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v);
79 xbch.insert(xbch.end(), stream.begin(), stream.end());
80 std::vector<std::uint8_t> dxil(16, 0);
81 dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'});
82 put32(dxil, 1);
83 put32(dxil, 12);
84 put32(dxil, 0x0d);
85 put32(dxil, 16 + 12 + 12);
86 put32(dxil, std::uint32_t(xbch.size()));
87 dxil.insert(dxil.end(), xbch.begin(), xbch.end());
88 std::vector<std::uint8_t> out = {'D', 'X', 'B', 'C'};
89 out.resize(28, 0);
90 put32(out, 1);
91 put32(out, 36);
92 out.insert(out.end(), {'D', 'X', 'I', 'L'});
93 put32(out, std::uint32_t(dxil.size()));
94 out.insert(out.end(), dxil.begin(), dxil.end());
95 return out;
96}
97
98// runtime/test/shaders/compute_fixture.py's header for a compute shader without "; group:" or "; rsrc2:" lines:
99// 0x148 bytes, COMPUTE_PGM_RSRC2 0x8088 (four user SGPRs, TGID_X, 512 bytes of LDS) at 0x138 and a 64x1x1 group.
100std::vector<std::uint8_t> fixture_fssm() {
101 std::vector<std::uint8_t> fssm(0x138, 0);
102 for (const std::uint32_t v : {0x8088u, 64u, 1u, 1u}) put32(fssm, v);
103 return fssm;
104}
105
106std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) {
107 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
108 const auto fn = d3d12 ? reinterpret_cast<SerializeFn>(
109 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
110 : nullptr;
111 std::vector<std::uint8_t> out;
112 ID3DBlob* blob = nullptr;
113 if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) {
114 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
115 out.assign(p, p + blob->GetBufferSize());
116 blob->Release();
117 }
118 return out;
119}
120
121D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) {
122 D3D12_RESOURCE_DESC desc{};
123 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
124 desc.Width = bytes;
125 desc.Height = 1;
126 desc.DepthOrArraySize = 1;
127 desc.MipLevels = 1;
128 desc.SampleDesc.Count = 1;
129 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
130 desc.Flags = flags;
131 return desc;
132}
133
134using Words = std::array<std::uint32_t, 8>;
135
136struct Shader {
137 const char* label;
138 const char* folder; // under LEONIDA_TEST_SUBGROUP_SHADERS; its spirv/ holds index.json and the module
139 Words expected;
140};
141
142constexpr Shader w64_native{"w64 native (cs_w64x_readlane)", "w64_native", {121, 121, 16, 97, 16, 100, 100, 121}};
143constexpr Shader w64_emulated{"w64 emulated (cs_w64x_readlane, --wave64-emulate)", "w64_emulated",
144 {121, 121, 16, 97, 16, 100, 100, 121}};
145constexpr Shader w32_native{"w32 native (cs_wqm_w32)", "w32_native", {12, 1, 4, 0, 8, 15728880, 4, 32}};
146
147struct Result {
148 int failure = 0; // a line number, 0 when the case ran
149 Words words{};
150 std::vector<leonida::SubgroupRequest> requests;
151};
152
153// One dispatch of the shader's PSO on a device created with `caps` as what the layer knows of the GPU.
154Result run(vktest::Device& d, const std::filesystem::path& library, const leonida::SubgroupSizeCaps& caps) {
155 Result result;
156 const auto fail = [&](int line) {
157 result.failure = line;
158 return result;
159 };
160#define CASE_EXPECT(condition) do { if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return fail(__LINE__); } } while (0)
161
162 const auto fssm = fixture_fssm();
163 const auto container = shader_container(fssm);
164 CASE_EXPECT(leonida::fssm_program(container) == fssm);
165 {
166 leonida::ShaderLibrary index;
167 CASE_EXPECT(index.load(library.string()));
168 CASE_EXPECT(index.find("cs", leonida::sha256_hex(fssm))); // the translator's header is the fixture's
169 }
170
171 rt::d3d12::VulkanDeviceInfo info{};
172 info.get_instance_proc = d.instance_proc;
173 info.instance = d.instance;
174 info.physical = d.physical;
175 info.device = d.device;
176 info.queue = d.queue;
177 info.queue_family = d.family;
178 info.buffer_device_address = true;
179 info.shader_dir = library.string();
180 info.subgroup = caps;
181 ID3D12Device* inner = nullptr;
182 CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
183 Ref<ID3D12Device> device;
184 CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
185 reinterpret_cast<void**>(&device.p))));
186 rt::d3d12::set_device_outer(inner, device.p);
187
188 // Root signature: [0] four constants (s0..s3), the V# the shaders store through.
189 D3D12_ROOT_PARAMETER param{};
190 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
191 param.Constants = {0, 0, 4};
192 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
193 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
194 root_desc.Desc_1_0 = {1, &param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
195 const auto root_blob = serialize(root_desc);
196 CASE_EXPECT(!root_blob.empty());
197 Ref<ID3D12RootSignature> root;
198 CASE_EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
199
200 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
201 pso_desc.pRootSignature = root.p;
202 pso_desc.CS = {container.data(), container.size()};
203 const IID pso_iid = __uuidof(ID3D12PipelineState);
204 Ref<ID3D12PipelineState> pso;
205 CASE_EXPECT(SUCCEEDED(reinterpret_cast<XboxComputePipelineFn>(slot(device.p, 62))(
206 device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast<void**>(&pso.p))));
207 const auto* requests = rt::d3d12::pipeline_subgroup_requests(pso.p);
208 CASE_EXPECT(requests && requests->size() == 1);
209 result.requests = *requests;
210
211 constexpr UINT bytes = 256;
212 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
213 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
214 Ref<ID3D12Resource> out, readback;
215 const auto uav = buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
216 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav,
217 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
218 IID_PPV_ARGS(&out.p))));
219 const auto readback_desc = buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE);
220 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
221 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
222 IID_PPV_ARGS(&readback.p))));
223 const D3D12_GPU_VIRTUAL_ADDRESS va = out->GetGPUVirtualAddress();
224 CASE_EXPECT(va >= 0x10000 && va < (1ull << 32));
225
226 D3D12_COMMAND_QUEUE_DESC queue_desc{};
227 Ref<ID3D12CommandQueue> queue;
228 Ref<ID3D12CommandAllocator> allocator;
229 Ref<ID3D12GraphicsCommandList> list;
230 Ref<ID3D12Fence> fence;
231 CASE_EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
232 CASE_EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
233 CASE_EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p,
234 IID_PPV_ARGS(&list.p))));
235 CASE_EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
236
237 // The V# the shaders read from s[0:3]: base = the buffer's console VA (the shader adds the heap base), stride 0,
238 // num_records unlimited, OOB_SELECT 3 (raw: a stride of 0 is a bounds check in the other modes).
239 list->SetComputeRootSignature(root.p);
240 const std::uint32_t vsharp[4] = {std::uint32_t(va), std::uint32_t(va >> 32) & 0xffff, 0xffffffffu, 0x31016FACu};
241 list->SetComputeRoot32BitConstants(0, 4, vsharp, 0);
242 list->Dispatch(1, 1, 1);
243 D3D12_RESOURCE_BARRIER barrier{};
244 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
245 barrier.Transition = {out.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
246 D3D12_RESOURCE_STATE_COPY_SOURCE};
247 list->ResourceBarrier(1, &barrier);
248 list->CopyBufferRegion(readback.p, 0, out.p, 0, bytes);
249 CASE_EXPECT(list->Close() == S_OK);
250 ID3D12CommandList* lists[] = {list.p};
251 queue->ExecuteCommandLists(1, lists);
252 CASE_EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
253 CASE_EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
254 CASE_EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
255 void* mapped = nullptr;
256 CASE_EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
257 std::memcpy(result.words.data(), mapped, sizeof(result.words));
258
259 for (auto* r : {&out, &readback}) r->reset();
260 pso.reset();
261 root.reset();
262 list.reset();
263 allocator.reset();
264 queue.reset();
265 fence.reset();
266 CASE_EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
267#undef CASE_EXPECT
268 return result;
269}
270
271std::string words_text(const Words& w) {
272 std::string s;
273 for (const std::uint32_t v : w) s += (s.empty() ? "" : " ") + std::to_string(v);
274 return s;
275}
276
277// What the decision function says about the shader's own index entry on this device.
278leonida::SubgroupRequest expected_request(const Shader& shader, const leonida::SubgroupSizeCaps& caps) {
279 leonida::ShaderLibrary index;
280 const auto dir = std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / shader.folder / "spirv";
281 if (!index.load(dir.string())) return {};
282 const auto* entry = index.find("cs", leonida::sha256_hex(fixture_fssm()));
283 return entry ? leonida::decide_subgroup_size(*entry, caps) : leonida::SubgroupRequest{};
284}
285
286std::filesystem::path shader_dir(const Shader& shader) {
287 return std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / shader.folder / "spirv";
288}
289
290// ---- Probe shaders (GLSL, test/glsl) and the graphics path -----------------------------------------------------------
291// What the translator would write into an index entry for a shader of each kind.
292struct Mode {
293 const char* label;
294 bool wave64;
295 std::uint32_t size; // subgroup_size
296 bool emulated; // --wave64-emulate: subgroup_size null, wave64_exchange "workgroup"
297};
298constexpr Mode mode_w64{"wave64, subgroup_size 64", true, 64, false};
299constexpr Mode mode_w32{"wave32, subgroup_size 32", false, 32, false};
300constexpr Mode mode_emulated{"emulated (wave64_exchange)", true, 0, true};
301
302std::string mode_json(const Mode& m) {
303 std::string s = std::string("\"wave64\": ") + (m.wave64 ? "true" : "false") + ", \"subgroup_size\": " +
304 (m.emulated ? std::string("null") : std::to_string(m.size));
305 if (m.emulated) s += ", \"wave64_exchange\": \"workgroup\"";
306 return s;
307}
308
309struct LibraryEntry {
310 std::string name, stage, tail; // tail: the rest of the index entry's members
311 std::filesystem::path spv;
312};
313
314// 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) {
316 const auto dir = std::filesystem::temp_directory_path() / ("leonida_subgroup_" + tag);
317 std::filesystem::remove_all(dir);
318 std::filesystem::create_directories(dir);
319 std::ofstream index(dir / "index.json", std::ios::binary);
320 index << "{";
321 bool first = true;
322 for (const LibraryEntry& e : entries) {
323 std::filesystem::copy_file(e.spv, dir / (e.name + ".spv"), std::filesystem::copy_options::overwrite_existing);
324 index << (first ? "" : ",\n") << "\"" << e.name << "\": {\"stage\": \"" << e.stage << "\", \"fssm_sha256\": \""
325 << leonida::sha256_hex(fixture_fssm()) << "\", \"bindings\": [], \"push_constant_bytes\": 144, "
326 << e.tail << "}";
327 first = false;
328 }
329 index << "}";
330 return dir;
331}
332
333std::filesystem::path glsl_spv(const char* name) {
334 return std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / "glsl" / (std::string(name) + ".spv");
335}
336
337// The compute probe: a library with cs_sg_probe in the given mode.
338std::filesystem::path compute_probe_library(const Mode& mode) {
339 return make_library("cs_probe", {{"cs_sg_probe", "cs",
340 "\"local_size\": [64, 1, 1], \"uses_code_base\": false, " + mode_json(mode),
341 glsl_spv("cs_sg_probe.comp")}});
342}
343
344constexpr UINT draw_size = 64;
345using Pixel = std::array<std::uint32_t, 4>;
346
347struct DrawResult {
348 int failure = 0;
349 std::vector<Pixel> pixels; // draw_size * draw_size
350 std::vector<leonida::SubgroupRequest> requests; // vertex, pixel
351};
352
353// One draw of a full-viewport triangle through a graphics PSO whose VS is vs_fullscreen and whose PS is `ps` of the
354// library, into a 64x64 R32G32B32A32_FLOAT target that is read back as bit patterns.
355DrawResult draw(vktest::Device& d, const std::filesystem::path& library, const leonida::SubgroupSizeCaps& caps) {
356 DrawResult result;
357 const auto fail = [&](int line) {
358 result.failure = line;
359 return result;
360 };
361#define CASE_EXPECT(condition) do { if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return fail(__LINE__); } } while (0)
362 const auto container = shader_container(fixture_fssm());
363
364 rt::d3d12::VulkanDeviceInfo info{};
365 info.get_instance_proc = d.instance_proc;
366 info.instance = d.instance;
367 info.physical = d.physical;
368 info.device = d.device;
369 info.queue = d.queue;
370 info.queue_family = d.family;
371 info.buffer_device_address = true;
372 info.shader_dir = library.string();
373 info.subgroup = caps;
374 ID3D12Device* inner = nullptr;
375 CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
376 Ref<ID3D12Device> device;
377 CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
378 reinterpret_cast<void**>(&device.p))));
379 rt::d3d12::set_device_outer(inner, device.p);
380
381 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
382 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
383 root_desc.Desc_1_0 = {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
384 const auto root_blob = serialize(root_desc);
385 CASE_EXPECT(!root_blob.empty());
386 Ref<ID3D12RootSignature> root;
387 CASE_EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
388
389 D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{};
390 pso_desc.pRootSignature = root.p;
391 pso_desc.VS = {container.data(), container.size()};
392 pso_desc.PS = {container.data(), container.size()};
393 pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
394 pso_desc.SampleMask = 0xffffffff;
395 pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
396 pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
397 pso_desc.RasterizerState.DepthClipEnable = TRUE;
398 pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
399 pso_desc.NumRenderTargets = 1;
400 pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
401 pso_desc.SampleDesc.Count = 1;
402 Ref<ID3D12PipelineState> pso;
403 CASE_EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
404 const auto* requests = rt::d3d12::pipeline_subgroup_requests(pso.p);
405 CASE_EXPECT(requests && requests->size() == 2);
406 result.requests = *requests;
407
408 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
409 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
410 constexpr UINT pitch = draw_size * 16;
411 Ref<ID3D12Resource> readback, target;
412 const auto readback_desc = buffer_desc(pitch * draw_size, D3D12_RESOURCE_FLAG_NONE);
413 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
414 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
415 IID_PPV_ARGS(&readback.p))));
416 D3D12_RESOURCE_DESC rt_desc{};
417 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
418 rt_desc.Width = rt_desc.Height = draw_size;
419 rt_desc.DepthOrArraySize = 1;
420 rt_desc.MipLevels = 1;
421 rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
422 rt_desc.SampleDesc.Count = 1;
423 rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
424 CASE_EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc,
425 D3D12_RESOURCE_STATE_COMMON, nullptr,
426 IID_PPV_ARGS(&target.p))));
427 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
428 Ref<ID3D12DescriptorHeap> rtv_heap;
429 CASE_EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
430 const D3D12_CPU_DESCRIPTOR_HANDLE rtv{SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(rtv_heap.p, 9))(rtv_heap.p))};
431 device->CreateRenderTargetView(target.p, nullptr, rtv);
432
433 D3D12_COMMAND_QUEUE_DESC queue_desc{};
434 Ref<ID3D12CommandQueue> queue;
435 Ref<ID3D12CommandAllocator> allocator;
436 Ref<ID3D12GraphicsCommandList> list;
437 Ref<ID3D12Fence> fence;
438 CASE_EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
439 CASE_EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
440 CASE_EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p,
441 IID_PPV_ARGS(&list.p))));
442 CASE_EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
443
444 D3D12_RESOURCE_BARRIER to_target{};
445 to_target.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
446 to_target.Transition = {target.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON,
447 D3D12_RESOURCE_STATE_RENDER_TARGET};
448 list->ResourceBarrier(1, &to_target);
449 const FLOAT zero[4] = {0, 0, 0, 0};
450 list->ClearRenderTargetView(rtv, zero, 0, nullptr);
451 list->SetGraphicsRootSignature(root.p);
452 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
453 const D3D12_VIEWPORT viewport{0, 0, float(draw_size), float(draw_size), 0, 1};
454 const D3D12_RECT scissor{0, 0, LONG(draw_size), LONG(draw_size)};
455 list->RSSetViewports(1, &viewport);
456 list->RSSetScissorRects(1, &scissor);
457 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
458 list->DrawInstanced(3, 1, 0, 0);
459 D3D12_RESOURCE_BARRIER to_copy{};
460 to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
461 to_copy.Transition = {target.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_RENDER_TARGET,
462 D3D12_RESOURCE_STATE_COPY_SOURCE};
463 list->ResourceBarrier(1, &to_copy);
464 D3D12_TEXTURE_COPY_LOCATION dst{};
465 dst.pResource = readback.p;
466 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
467 dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, draw_size, draw_size, 1, pitch}};
468 D3D12_TEXTURE_COPY_LOCATION src{};
469 src.pResource = target.p;
470 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
471 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
472 CASE_EXPECT(list->Close() == S_OK);
473 ID3D12CommandList* lists[] = {list.p};
474 queue->ExecuteCommandLists(1, lists);
475 CASE_EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
476 CASE_EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
477 CASE_EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
478 void* mapped = nullptr;
479 CASE_EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
480 result.pixels.resize(draw_size * draw_size);
481 std::memcpy(result.pixels.data(), mapped, result.pixels.size() * sizeof(Pixel));
482
483 for (auto* r : {&readback, &target}) r->reset();
484 pso.reset();
485 root.reset();
486 rtv_heap.reset();
487 list.reset();
488 allocator.reset();
489 queue.reset();
490 fence.reset();
491 CASE_EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
492#undef CASE_EXPECT
493 return result;
494}
495
496// The vertex shader of every draw. It is marked emulated so that it asks for nothing: only the pixel stage is under test.
497LibraryEntry fullscreen_vs() {
498 return {"vs_fullscreen", "vs", "\"input_signature\": [], " + mode_json(mode_emulated), glsl_spv("vs_sg_fullscreen.vert")};
499}
500
501LibraryEntry ps_probe(const Mode& mode) {
502 return {"ps_sg_probe", "ps", "\"outputs\": [0], " + mode_json(mode), glsl_spv("ps_sg_probe.frag")};
503}
504
505// The wave64 pixel shader with readlane across both halves, translated by the build (test/shaders/ps_w64x_readlane.asm).
506LibraryEntry ps_readlane(const Mode& mode) {
507 return {"ps_w64x_readlane", "ps", "\"outputs\": [0], " + mode_json(mode),
508 std::filesystem::path(LEONIDA_TEST_SUBGROUP_SHADERS) / "ps_w64_native" / "spirv" / "ps_w64x_readlane.spv"};
509}
510
511// The subgroup size a probe pixel reports, or 0 when the pixels disagree or do not look like a probe's.
512std::uint32_t probed_size(const std::vector<Pixel>& pixels) {
513 std::uint32_t size = 0;
514 for (const Pixel& p : pixels) {
515 if ((p[0] & 0xffff0000u) != 0x40000000u) return 0;
516 const std::uint32_t s = p[0] & 0xffff;
517 if (size && s != size) return 0;
518 size = s;
519 }
520 return size;
521}
522
523const Pixel readlane_expected = {0x40000079u, 0x40000010u, 0x40000064u, 0x400000beu};
524
525} // namespace
526
527int main() {
528 vktest::Device d;
529 const auto device_status = d.initialize();
530 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
531 if (device_status != vktest::DeviceStatus::ready) return 1;
532 const leonida::SubgroupSizeCaps& caps = d.subgroup;
533 leonida::SubgroupSizeCaps off = caps; // the control: the layer knows nothing of the device's sizes
534 off.min_size = off.max_size = off.default_size = 0;
535 off.subgroup_size_control = off.compute_full_subgroups = false;
536 off.required_stages = 0;
537
538 unsigned judged = 0;
539 for (const Shader* shader : {&w64_native, &w64_emulated, &w32_native}) {
540 const leonida::SubgroupRequest want = expected_request(*shader, caps);
541 const Result result = run(d, shader_dir(*shader), caps);
542 EXPECT(!result.failure);
543 EXPECT(result.requests.size() == 1);
544 const leonida::SubgroupRequest& got = result.requests[0];
545 // The PSO asked for what the decision function says.
546 EXPECT(got.outcome == want.outcome && got.size == want.size && got.flags == want.flags);
547 EXPECT(got.stage == VK_SHADER_STAGE_COMPUTE_BIT);
548
549 const bool exact = result.words == shader->expected;
550 std::printf("%s: outcome %d, required size %u, full subgroups %s; result %s (%s)\n", shader->label,
551 int(got.outcome), got.size, got.flags ? "yes" : "no", exact ? "exact" : "DIFFERS",
552 words_text(result.words).c_str());
553 if (shader == &w64_native && got.outcome == leonida::SubgroupOutcome::unavailable) {
554 // This GPU cannot give a wave64 compute shader 64 lanes. The layer said so (a log line, above); the
555 // build for this GPU should have used --wave64-emulate, which the next case checks.
556 std::printf(" this device has no 64-wide compute subgroup (sizes %u..%u): native wave64 not judged\n",
557 caps.min_size, caps.max_size);
558 } else {
559 if (!exact) std::fprintf(stderr, "%s: wanted %s\n", shader->label, words_text(shader->expected).c_str());
560 EXPECT(exact);
561 ++judged;
562 }
563 if (shader == &w64_native && got.outcome != leonida::SubgroupOutcome::unavailable) {
564 EXPECT(got.outcome != leonida::SubgroupOutcome::unknown_device);
565 EXPECT(got.outcome == leonida::SubgroupOutcome::required || got.outcome == leonida::SubgroupOutcome::device_fixed ||
566 got.outcome == leonida::SubgroupOutcome::device_default);
567 if (got.outcome == leonida::SubgroupOutcome::required) {
568 EXPECT(got.size == 64);
569 EXPECT(!caps.compute_full_subgroups ||
570 got.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
571 }
572 }
573 if (shader == &w64_emulated) EXPECT(got.outcome == leonida::SubgroupOutcome::emulated && !got.size && !got.flags);
574
575 // Control, not judged: the same PSO with no size asked for.
576 if (shader != &w64_emulated) {
577 const Result control = run(d, shader_dir(*shader), off);
578 EXPECT(!control.failure);
579 std::printf(" control, nothing requested: %s (%s)\n", control.words == shader->expected ? "exact" : "differs",
580 words_text(control.words).c_str());
581 }
582 }
583 // --- The driver's choice, observed: probe shaders that store gl_SubgroupSize ------------------------------------
584 const auto exact_outcome = [](leonida::SubgroupOutcome o) {
585 return o == leonida::SubgroupOutcome::required || o == leonida::SubgroupOutcome::device_fixed;
586 };
587 for (const Mode* mode : {&mode_w64, &mode_w32, &mode_emulated}) {
588 const auto library = compute_probe_library(*mode);
589 const Result r = run(d, library, caps);
590 EXPECT(!r.failure && r.requests.size() == 1);
591 const leonida::SubgroupRequest& req = r.requests[0];
592 const std::uint32_t seen = r.words[0];
593 std::printf("compute probe, %s: outcome %d (asked %u), the driver ran it %u-wide\n", mode->label,
594 int(req.outcome), req.size, seen);
595 if (exact_outcome(req.outcome)) EXPECT(seen == req.wanted); // the size the PSO asked for is the size it got
596 const Result control = run(d, library, off);
597 EXPECT(!control.failure);
598 std::printf(" control, nothing requested: %u-wide (device default %u)\n", control.words[0], caps.default_size);
599 // The request matters: a wave32 shader on a device whose default is not 32 runs at the default without it.
600 if (mode == &mode_w32 && req.outcome == leonida::SubgroupOutcome::required && caps.default_size != 32)
601 EXPECT(control.words[0] != 32);
602 std::filesystem::remove_all(library);
603 }
604
605 std::uint32_t fragment_default = 0;
606 {
607 const auto library = make_library("ps_probe", {fullscreen_vs(), ps_probe(mode_w32)});
608 const DrawResult control = draw(d, library, off);
609 EXPECT(!control.failure);
610 fragment_default = probed_size(control.pixels);
611 EXPECT(fragment_default);
612 std::printf("pixel probe, nothing requested: the driver runs pixel shaders %u-wide\n", fragment_default);
613 std::filesystem::remove_all(library);
614 }
615 for (const Mode* mode : {&mode_w64, &mode_w32, &mode_emulated}) {
616 const auto library = make_library("ps_probe", {fullscreen_vs(), ps_probe(*mode)});
617 const DrawResult r = draw(d, library, caps);
618 EXPECT(!r.failure && r.requests.size() == 2);
619 const leonida::SubgroupRequest& vs_req = r.requests[0];
620 const leonida::SubgroupRequest& req = r.requests[1];
621 EXPECT(vs_req.outcome == leonida::SubgroupOutcome::emulated && vs_req.stage == VK_SHADER_STAGE_VERTEX_BIT);
622 EXPECT(req.stage == VK_SHADER_STAGE_FRAGMENT_BIT);
623 const std::uint32_t seen = probed_size(r.pixels);
624 EXPECT(seen);
625 std::printf("pixel probe, %s: outcome %d (asked %u), the driver ran it %u-wide\n", mode->label,
626 int(req.outcome), req.size, seen);
627 if (exact_outcome(req.outcome)) EXPECT(seen == req.wanted);
628 if (req.outcome == leonida::SubgroupOutcome::required && fragment_default != req.wanted)
629 std::printf(" the request changes it: %u-wide without, %u-wide with\n", fragment_default, seen);
630 std::filesystem::remove_all(library);
631 }
632
633 // --- A wave64 pixel shader with a cross-half v_readlane, through a graphics PSO ---------------------------------
634 {
635 const auto library = make_library("ps_readlane", {fullscreen_vs(), ps_readlane(mode_w64)});
636 const auto count_exact = [](const std::vector<Pixel>& pixels) {
637 std::size_t n = 0;
638 for (const Pixel& p : pixels) n += p == readlane_expected;
639 return n;
640 };
641 const DrawResult r = draw(d, library, caps);
642 EXPECT(!r.failure && r.requests.size() == 2);
643 const leonida::SubgroupRequest& req = r.requests[1];
644 const std::size_t exact = count_exact(r.pixels), total = r.pixels.size();
645 std::printf("wave64 pixel shader (ps_w64x_readlane): outcome %d, required size %u; %zu of %zu pixels exact\n",
646 int(req.outcome), req.size, exact, total);
647 if (exact_outcome(req.outcome)) {
648 if (exact != total)
649 std::fprintf(stderr, "first pixel %08x %08x %08x %08x\n", r.pixels[0][0], r.pixels[0][1],
650 r.pixels[0][2], r.pixels[0][3]);
651 EXPECT(exact == total);
652 ++judged;
653 } else {
654 std::printf(" this device cannot require 64 for a wave64 pixel shader: not judged\n");
655 }
656 const DrawResult control = draw(d, library, off);
657 EXPECT(!control.failure);
658 const std::size_t control_exact = count_exact(control.pixels);
659 std::printf(" control, nothing requested (pixel shaders run %u-wide): %zu of %zu pixels exact\n",
660 fragment_default, control_exact, total);
661 // Where the default is not 64, the shader crosses halves that are not there: the request must matter.
662 if (req.outcome == leonida::SubgroupOutcome::required && fragment_default != 64) EXPECT(control_exact < total);
663 std::filesystem::remove_all(library);
664 }
665 if (d.validation_errors()) {
666 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
667 return 1;
668 }
669 std::printf("subgroup size: %u shaders judged exact through the layer's PSOs (sizes %u..%u, default %u)\n",
670 judged, caps.min_size, caps.max_size, caps.default_size);
671 return 0;
672}
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 1eb25adf1..a528202bc 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -324,8 +324,8 @@ int cpu_copies(ID3D12Device* device, bool bc, const char* path) {
324 return 0; 324 return 0;
325} 325}
326 326
327// The host PC runtime's D3D12 device to compare answers with: the default adapter, or the one LEONIDA_HOST_ADAPTER 327// The host PC runtime's D3D12 device to compare answers with: the layer's own adapter (set in main), else the default
328// names ("warp", or part of an adapter's name); false if there is none. 328// one, or the one LEONIDA_HOST_ADAPTER names ("warp", or part of an adapter's name); false if there is none.
329// Under Wine there is none (copycmp::create_host). 329// Under Wine there is none (copycmp::create_host).
330bool create_host_device(Ref<ID3D12Device>& host, std::string* adapter_name = nullptr) { 330bool create_host_device(Ref<ID3D12Device>& host, std::string* adapter_name = nullptr) {
331 copycmp::Ptr<ID3D12Device> device; 331 copycmp::Ptr<ID3D12Device> device;
@@ -506,6 +506,9 @@ int compare_footprints(ID3D12Device* ours) {
506 {texture_desc(13, 7, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8}, 506 {texture_desc(13, 7, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8},
507 {texture_desc(13, 7, DXGI_FORMAT_A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8}, 507 {texture_desc(13, 7, DXGI_FORMAT_A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8},
508 {texture_desc(13, 7, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE, 4), 4}, 508 {texture_desc(13, 7, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE, 4), 4},
509 {texture_desc(13, 7, DXGI_FORMAT_B8G8R8X8_UNORM, D3D12_RESOURCE_FLAG_NONE, 4, 2), 8},
510 {texture_desc(13, 7, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE, 4), 4},
511 {texture_desc(16, 16, DXGI_FORMAT_B8G8R8X8_TYPELESS, D3D12_RESOURCE_FLAG_NONE, 3), 3},
509 {texture_desc(10, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4), 4}, 512 {texture_desc(10, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE, 4), 4},
510 {texture_desc(4, 4, DXGI_FORMAT_BC7_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE, 1, 3), 3}, 513 {texture_desc(4, 4, DXGI_FORMAT_BC7_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE, 1, 3), 3},
511 {texture_desc(16, 16, DXGI_FORMAT_BC5_UNORM, D3D12_RESOURCE_FLAG_NONE, 5), 5}, 514 {texture_desc(16, 16, DXGI_FORMAT_BC5_UNORM, D3D12_RESOURCE_FLAG_NONE, 5), 5},
@@ -694,6 +697,97 @@ int compare_allocation_info(ID3D12Device* ours) {
694 {"16x16 R8G8_TYPELESS", texture_desc(16, 16, DXGI_FORMAT_R8G8_TYPELESS, none, 1), 16 * 16 * 2}, 697 {"16x16 R8G8_TYPELESS", texture_desc(16, 16, DXGI_FORMAT_R8G8_TYPELESS, none, 1), 16 * 16 * 2},
695 {"16x16 R8G8_UINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_UINT, none, 1), 16 * 16 * 2}, 698 {"16x16 R8G8_UINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_UINT, none, 1), 16 * 16 * 2},
696 {"16x16 R8G8_SINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_SINT, none, 1), 16 * 16 * 2}, 699 {"16x16 R8G8_SINT", texture_desc(16, 16, DXGI_FORMAT_R8G8_SINT, none, 1), 16 * 16 * 2},
700 // Tiled (64KB_UNDEFINED_SWIZZLE) textures: 64 KiB alignment and tile-multiple size; 1D, buffers, 4 KiB
701 // alignment, untileable 96-bit and two-plane depth-stencil formats are invalid.
702 {"tiled 2D 256x256", [&] {
703 D3D12_RESOURCE_DESC d = texture_desc(256, 256, rgba8, none, 1);
704 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
705 return d;
706 }(), 256 * 256 * 4},
707 {"tiled 2D D32F 256x256", [&] {
708 D3D12_RESOURCE_DESC d = texture_desc(256, 256, DXGI_FORMAT_D32_FLOAT,
709 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1);
710 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
711 return d;
712 }(), 256 * 256 * 4},
713 {"tiled 3D 64x64x64", [&] {
714 D3D12_RESOURCE_DESC d = small_volume(64, 64, 64, rgba8);
715 d.Alignment = 0;
716 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
717 return d;
718 }(), 64 * 64 * 64 * 4},
719 {"tiled buffer (invalid)", [&] {
720 D3D12_RESOURCE_DESC d = buffer_desc(4096);
721 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
722 return d;
723 }(), 0},
724 {"tiled 1D (invalid)", [&] {
725 D3D12_RESOURCE_DESC d = line_desc(256, 1, 1, rgba8);
726 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
727 return d;
728 }(), 0},
729 {"tiled 2D 4K alignment (invalid)", [&] {
730 D3D12_RESOURCE_DESC d = with(texture_desc(16, 16, rgba8, none, 1), k4);
731 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
732 return d;
733 }(), 0},
734 {"tiled 2D RGB32F (invalid)", [&] {
735 D3D12_RESOURCE_DESC d = texture_desc(64, 64, DXGI_FORMAT_R32G32B32_FLOAT, none, 1);
736 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
737 return d;
738 }(), 0},
739 {"tiled 2D D24S8 (invalid)", [&] {
740 D3D12_RESOURCE_DESC d = texture_desc(64, 64, DXGI_FORMAT_D24_UNORM_S8_UINT,
741 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1);
742 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
743 return d;
744 }(), 0},
745 {"tiled 2D 4x MSAA RGBA8", [&] {
746 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1), 0, 4);
747 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
748 return d;
749 }(), 256 * 256 * 4 * 4},
750 {"tiled 2D 4x MSAA RGBA32F", [&] {
751 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, DXGI_FORMAT_R32G32B32A32_FLOAT, rt, 1), 0, 4);
752 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
753 return d;
754 }(), 256 * 256 * 16 * 4},
755 {"tiled 2D 4x MSAA D32F", [&] {
756 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, DXGI_FORMAT_D32_FLOAT,
757 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1), 0, 4);
758 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
759 return d;
760 }(), 256 * 256 * 4 * 4},
761 {"tiled 2D 2x MSAA (invalid)", [&] {
762 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1), 0, 2);
763 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
764 return d;
765 }(), 0},
766 {"tiled 2D 8x MSAA (invalid)", [&] {
767 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1), 0, 8);
768 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
769 return d;
770 }(), 0},
771 {"tiled 2D 4x MSAA NONE (invalid)", [&] {
772 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, none, 1), 0, 4);
773 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
774 return d;
775 }(), 0},
776 {"tiled 2D 4x MSAA RT+DS (invalid)", [&] {
777 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8,
778 rt | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1), 0, 4);
779 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
780 return d;
781 }(), 0},
782 {"tiled 2D 4x MSAA 4M alignment (invalid)", [&] {
783 D3D12_RESOURCE_DESC d = with(texture_desc(256, 256, rgba8, rt, 1),
784 D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, 4);
785 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
786 return d;
787 }(), 0},
788 {"UNKNOWN 4x MSAA NONE (invalid)", with(texture_desc(256, 256, rgba8, none, 1), 0, 4), 0},
789 {"UNKNOWN 4x MSAA RT+DS (invalid)",
790 with(texture_desc(256, 256, rgba8, rt | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1), 0, 4), 0},
697 }; 791 };
698 int mismatches = 0; 792 int mismatches = 0;
699 const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a, 793 const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a,
@@ -706,6 +800,18 @@ int compare_allocation_info(ID3D12Device* ours) {
706 for (const Case& c : cases) { 800 for (const Case& c : cases) {
707 const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc); 801 const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc);
708 const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc); 802 const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc);
803 if (c.top_mip_bytes && b.SizeInBytes == UINT64_MAX && c.desc.SampleDesc.Count > 1 &&
804 c.desc.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
805 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS ms{
806 c.desc.Format, c.desc.SampleDesc.Count, D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE, 0};
807 if (SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &ms, sizeof(ms))) &&
808 ms.NumQualityLevels == 0) {
809 if (a.SizeInBytes == UINT64_MAX || a.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)
810 mismatch(c.name, a, b);
811 std::printf("allocation info %s: host unsupported (NumQualityLevels=0), skipped\n", c.name);
812 continue;
813 }
814 }
709 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) { 815 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) {
710 if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment)) 816 if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment))
711 mismatch(c.name, a, b); 817 mismatch(c.name, a, b);
@@ -1506,6 +1612,15 @@ int compare_feature_support(ID3D12Device* ours) {
1506 1612
1507// Same-adapter host D3D12 device matched by VkPhysicalDeviceIDProperties (LUID first, then PCI IDs), falling back 1613// Same-adapter host D3D12 device matched by VkPhysicalDeviceIDProperties (LUID first, then PCI IDs), falling back
1508// to the default adapter. False if the host has no D3D12 device. 1614// to the default adapter. False if the host has no D3D12 device.
1615// D3D11.3 spec 3.2.3.8's ideal FLOAT -> SRGB encoding of c in [0, 1], before scaling to the format's maximum.
1616double ideal_srgb(double c) { return c <= 0.0031308 ? c * 12.92 : 1.055 * std::pow(c, 1.0 / 2.4) - 0.055; }
1617
1618// Both bytes within 0.6 ULP (on the integer side) of the ideal value: the tolerance spec 3.2.3.6 (FLOAT -> UNORM)
1619// and 3.2.3.8 (FLOAT -> SRGB) permit, so two drivers may give the codes either side of a near-tie.
1620bool within_06_ulp(std::uint8_t a, std::uint8_t b, double ideal) {
1621 return std::abs(double(a) - ideal) <= 0.6 && std::abs(double(b) - ideal) <= 0.6;
1622}
1623
1509bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical, 1624bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical,
1510 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host, 1625 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host,
1511 std::string& adapter_name) { 1626 std::string& adapter_name) {
@@ -2147,6 +2262,21 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2147 struct Case { 2262 struct Case {
2148 const char* name; 2263 const char* name;
2149 InvalidCase call; 2264 InvalidCase call;
2265 bool (*comparable)(ID3D12Device*) = nullptr;
2266 };
2267 const auto device10 = [](ID3D12Device* d) {
2268 Ref<ID3D12Device10> newer;
2269 return SUCCEEDED(d->QueryInterface(IID_PPV_ARGS(&newer.p)));
2270 };
2271 const auto not_elevated = [](ID3D12Device*) {
2272 HANDLE token = nullptr;
2273 TOKEN_ELEVATION elevation{};
2274 DWORD size = 0;
2275 const bool elevated = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
2276 GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size) &&
2277 elevation.TokenIsElevated;
2278 if (token) CloseHandle(token);
2279 return !elevated;
2150 }; 2280 };
2151 static const Case cases[] = { 2281 static const Case cases[] = {
2152 // CreateCommittedResource: arguments. 2282 // CreateCommittedResource: arguments.
@@ -2224,7 +2354,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2224 }}, 2354 }},
2225 {"committed: upload buffer in COMMON", [](ID3D12Device* d) { 2355 {"committed: upload buffer in COMMON", [](ID3D12Device* d) {
2226 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2356 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2227 }}, 2357 }, +device10},
2228 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) { 2358 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) {
2229 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST); 2359 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST);
2230 }}, 2360 }},
@@ -2350,7 +2480,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2350 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) { 2480 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) {
2351 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2481 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2352 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE)); 2482 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE));
2353 }}, 2483 }, host_supports_unaligned_block_textures},
2354 {"committed: render target and depth stencil", [](ID3D12Device* d) { 2484 {"committed: render target and depth stencil", [](ID3D12Device* d) {
2355 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2485 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2356 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT, 2486 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT,
@@ -2422,7 +2552,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2422 }}, 2552 }},
2423 {"committed: readback buffer in COMMON", [](ID3D12Device* d) { 2553 {"committed: readback buffer in COMMON", [](ID3D12Device* d) {
2424 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2554 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2425 }}, 2555 }, +device10},
2426 {"committed: readback buffer with UAV", [](ID3D12Device* d) { 2556 {"committed: readback buffer with UAV", [](ID3D12Device* d) {
2427 auto desc = buffer_desc(256); 2557 auto desc = buffer_desc(256);
2428 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; 2558 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
@@ -2582,7 +2712,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2582 }}, 2712 }},
2583 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) { 2713 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) {
2584 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED); 2714 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED);
2585 }}, 2715 }, +device10},
2586 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) { 2716 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) {
2587 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH); 2717 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH);
2588 }}, 2718 }},
@@ -2637,7 +2767,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2637 auto desc = buffer_desc(256); 2767 auto desc = buffer_desc(256);
2638 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2768 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2639 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2769 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2640 }}, 2770 }, +device10},
2641 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) { 2771 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) {
2642 auto desc = buffer_desc(256); 2772 auto desc = buffer_desc(256);
2643 desc.Flags = D3D12_RESOURCE_FLAGS(0x200); 2773 desc.Flags = D3D12_RESOURCE_FLAGS(0x200);
@@ -2665,15 +2795,15 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2665 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) { 2795 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) {
2666 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2796 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2667 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2797 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2668 }}, 2798 }, +device10},
2669 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) { 2799 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) {
2670 auto desc = buffer_desc(256); 2800 auto desc = buffer_desc(256);
2671 desc.Flags = D3D12_RESOURCE_FLAGS(0x400); 2801 desc.Flags = D3D12_RESOURCE_FLAGS(0x400);
2672 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2802 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2673 }}, 2803 }, +device10},
2674 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) { 2804 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) {
2675 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400))); 2805 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400)));
2676 }}, 2806 }, +device10},
2677 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first. 2807 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first.
2678 {"committed: heap type 99, null output", [](ID3D12Device* d) { 2808 {"committed: heap type 99, null output", [](ID3D12Device* d) {
2679 const H heap{D3D12_HEAP_TYPE(99)}; 2809 const H heap{D3D12_HEAP_TYPE(99)};
@@ -2726,7 +2856,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2726 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) { 2856 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) {
2727 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049, 2857 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049,
2728 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2858 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
2729 }}, 2859 }, +device10},
2730 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) { 2860 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) {
2731 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048, 2861 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048,
2732 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2862 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
@@ -2771,7 +2901,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2771 }}, 2901 }},
2772 {"command queue: global realtime priority", [](ID3D12Device* d) { 2902 {"command queue: global realtime priority", [](ID3D12Device* d) {
2773 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME}); 2903 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME});
2774 }}, 2904 }, +not_elevated},
2775 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }}, 2905 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }},
2776 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }}, 2906 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }},
2777 {"command queue: high priority", [](ID3D12Device* d) { 2907 {"command queue: high priority", [](ID3D12Device* d) {
@@ -2861,6 +2991,11 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2861 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 2991 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
2862 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 2992 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
2863 if (a == b) continue; 2993 if (a == b) continue;
2994 if (c.comparable && !c.comparable(host.p)) {
2995 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
2996 a, b);
2997 continue;
2998 }
2864 ++mismatches; 2999 ++mismatches;
2865 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); 3000 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
2866 } 3001 }
@@ -2925,6 +3060,18 @@ int main() {
2925 const auto status = d.initialize(); 3060 const auto status = d.initialize();
2926 if (status == vktest::DeviceStatus::unavailable) return 77; 3061 if (status == vktest::DeviceStatus::unavailable) return 77;
2927 if (status == vktest::DeviceStatus::failed) return 1; 3062 if (status == vktest::DeviceStatus::failed) return 1;
3063 {
3064 // The host comparisons (create_host_device, the copies) run on the layer's own adapter, not D3D12's default
3065 // one, which on a PC with two GPUs can be the other GPU (copycmp::layer_adapter).
3066 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
3067 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
3068 d.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(d.physical, &properties);
3069 if (id.deviceLUIDValid) {
3070 LUID luid{};
3071 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
3072 copycmp::layer_adapter() = luid;
3073 }
3074 }
2928 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)); 3075 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT));
2929 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0; 3076 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0;
2930 { 3077 {
@@ -3142,7 +3289,8 @@ int main() {
3142 DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SINT, 3289 DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SINT,
3143 DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT, 3290 DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT,
3144 DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT, 3291 DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT,
3145 DXGI_FORMAT_R8G8_SINT}) { 3292 DXGI_FORMAT_R8G8_SINT, DXGI_FORMAT_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_UNORM,
3293 DXGI_FORMAT_B8G8R8X8_UNORM_SRGB}) {
3146 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{f}; 3294 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{f};
3147 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs)))); 3295 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs))));
3148 EXPECT(fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D); 3296 EXPECT(fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
@@ -3154,6 +3302,42 @@ int main() {
3154 EXPECT(tex.p != nullptr); 3302 EXPECT(tex.p != nullptr);
3155 } 3303 }
3156 } 3304 }
3305 // D3D-87, B8G8R8X8: no typed UAV and no typed texture that allows unordered access (the typeless family may),
3306 // as the host runtime answers; render targets as for B8G8R8A8.
3307 {
3308 Ref<ID3D12Device> host;
3309 if (create_host_device(host)) {
3310 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
3311 for (DXGI_FORMAT f : {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB,
3312 DXGI_FORMAT_B8G8R8X8_TYPELESS}) {
3313 D3D12_FEATURE_DATA_FORMAT_SUPPORT a{f}, b{f};
3314 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &a, sizeof(a))));
3315 EXPECT(SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &b, sizeof(b))));
3316 constexpr UINT typed_uav = D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW;
3317 constexpr UINT typed_uav2 = D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD | D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE;
3318 EXPECT((UINT(a.Support1) & typed_uav) == (UINT(b.Support1) & typed_uav));
3319 EXPECT((UINT(a.Support2) & typed_uav2) == (UINT(b.Support2) & typed_uav2));
3320 for (auto flag : {D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}) {
3321 const D3D12_RESOURCE_DESC desc = texture_desc(16, 16, f, flag, 1);
3322 Ref<ID3D12Resource> ours_resource, host_resource;
3323 const HRESULT ours_hr = device->CreateCommittedResource(
3324 &default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
3325 IID_PPV_ARGS(&ours_resource.p));
3326 const HRESULT host_hr = host->CreateCommittedResource(
3327 &default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
3328 IID_PPV_ARGS(&host_resource.p));
3329 if (SUCCEEDED(ours_hr) != SUCCEEDED(host_hr))
3330 std::fprintf(stderr, "B8G8R8X8 format %d flags %d: ours %08lx, host %08lx\n", int(f),
3331 int(flag), static_cast<unsigned long>(ours_hr),
3332 static_cast<unsigned long>(host_hr));
3333 EXPECT(SUCCEEDED(ours_hr) == SUCCEEDED(host_hr));
3334 }
3335 }
3336 std::printf("B8G8R8X8: typed UAV support and UAV/RTV resource creation match the host runtime\n");
3337 } else {
3338 std::printf("B8G8R8X8: no host D3D12 device to compare with, skipped\n");
3339 }
3340 }
3157 3341
3158 const int options_mismatches = compare_feature_options(device.p, info); 3342 const int options_mismatches = compare_feature_options(device.p, info);
3159 EXPECT(options_mismatches == 0); 3343 EXPECT(options_mismatches == 0);
@@ -4578,16 +4762,16 @@ int main() {
4578 EXPECT(placed_va && placed_va % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT == 0); 4762 EXPECT(placed_va && placed_va % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT == 0);
4579 EXPECT(placed_b->GetGPUVirtualAddress() == placed_va + 65536); 4763 EXPECT(placed_b->GetGPUVirtualAddress() == placed_va + 65536);
4580 EXPECT(placed_image->GetGPUVirtualAddress() == 0); // only buffers are addressable, as in D3D12 4764 EXPECT(placed_image->GetGPUVirtualAddress() == 0); // only buffers are addressable, as in D3D12
4581 // Off the 64 KiB grid, past the heap end, and tiled: refused, not placed somewhere wrong. 4765 // Off the 64 KiB grid, past the heap end, and non-ROW_MAJOR buffers: E_INVALIDARG, not placed somewhere wrong.
4582 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 512, &placed_buffer, D3D12_RESOURCE_STATE_COMMON, 4766 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 512, &placed_buffer, D3D12_RESOURCE_STATE_COMMON,
4583 nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG); 4767 nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG);
4584 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 256 * 1024, &placed_buffer, 4768 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 256 * 1024, &placed_buffer,
4585 D3D12_RESOURCE_STATE_COMMON, nullptr, 4769 D3D12_RESOURCE_STATE_COMMON, nullptr,
4586 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG); 4770 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG);
4587 D3D12_RESOURCE_DESC tiled = buffer_desc(4096); 4771 D3D12_RESOURCE_DESC tiled_buf = buffer_desc(4096);
4588 tiled.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; 4772 tiled_buf.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
4589 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 0, &tiled, D3D12_RESOURCE_STATE_COMMON, nullptr, 4773 EXPECT(standalone->CreatePlacedResource(placed_heap.p, 0, &tiled_buf, D3D12_RESOURCE_STATE_COMMON, nullptr,
4590 IID_PPV_ARGS(&refused.p)) == E_NOTIMPL); 4774 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG);
4591 EXPECT(!refused.p); 4775 EXPECT(!refused.p);
4592 // A placed buffer reads as zeroed through the copy path, at its console VA. 4776 // A placed buffer reads as zeroed through the copy path, at its console VA.
4593 D3D12_HEAP_PROPERTIES readback_props{}; 4777 D3D12_HEAP_PROPERTIES readback_props{};
@@ -4613,6 +4797,44 @@ int main() {
4613 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes))); 4797 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes)));
4614 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64); 4798 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64);
4615 zeroes->Unmap(0, nullptr); 4799 zeroes->Unmap(0, nullptr);
4800
4801 // Placed buffers carry their console VA in VulkanContext (so VA-resolved commands like WriteBufferImmediate
4802 // find them) and placed readback buffers mark host_readable (so the submission flushes GPU writes to host).
4803 {
4804 D3D12_HEAP_DESC rb_heap_desc{};
4805 rb_heap_desc.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4806 rb_heap_desc.SizeInBytes = 65536;
4807 rb_heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
4808 Ref<ID3D12Heap> rb_heap;
4809 Ref<ID3D12Resource> placed_rb;
4810 EXPECT(SUCCEEDED(standalone->CreateHeap(&rb_heap_desc, IID_PPV_ARGS(&rb_heap.p))));
4811 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(rb_heap.p, 0, &placed_buffer,
4812 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
4813 IID_PPV_ARGS(&placed_rb.p))));
4814 Ref<ID3D12GraphicsCommandList2> placed_list2;
4815 EXPECT(SUCCEEDED(placed_list->QueryInterface(IID_PPV_ARGS(&placed_list2.p))));
4816 EXPECT(SUCCEEDED(placed_allocator->Reset()) && SUCCEEDED(placed_list->Reset(placed_allocator.p, nullptr)));
4817 const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER wp{placed_va + 16, 0xCAFEBABEu};
4818 const D3D12_WRITEBUFFERIMMEDIATE_MODE wm = D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT;
4819 placed_list2->WriteBufferImmediate(1, &wp, &wm);
4820 D3D12_RESOURCE_BARRIER b{};
4821 b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
4822 b.Transition = {placed_a.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
4823 D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
4824 placed_list->ResourceBarrier(1, &b);
4825 placed_list->CopyBufferRegion(placed_rb.p, 0, placed_a.p, 0, 64);
4826 EXPECT(SUCCEEDED(placed_list->Close()));
4827 queue->ExecuteCommandLists(1, placed_lists);
4828 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
4829 EXPECT(SUCCEEDED(queue->Signal(fence.p, 7)) && SUCCEEDED(fence->SetEventOnCompletion(7, nullptr)));
4830 void* rb_bytes = nullptr;
4831 EXPECT(SUCCEEDED(placed_rb->Map(0, nullptr, &rb_bytes)));
4832 std::uint32_t word = 0;
4833 std::memcpy(&word, static_cast<const std::uint8_t*>(rb_bytes) + 16, sizeof(word));
4834 EXPECT(word == 0xCAFEBABEu);
4835 placed_rb->Unmap(0, nullptr);
4836 }
4837
4616 // The heap owns the range: releasing it puts the next heap of that size back at the same place. 4838 // The heap owns the range: releasing it puts the next heap of that size back at the same place.
4617 placed_image.reset(); 4839 placed_image.reset();
4618 placed_b.reset(); 4840 placed_b.reset();
@@ -4622,6 +4844,437 @@ int main() {
4622 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(again.p, 0, &placed_buffer, D3D12_RESOURCE_STATE_GENERIC_READ, 4844 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(again.p, 0, &placed_buffer, D3D12_RESOURCE_STATE_GENERIC_READ,
4623 nullptr, IID_PPV_ARGS(&placed_a.p)))); 4845 nullptr, IID_PPV_ARGS(&placed_a.p))));
4624 EXPECT(placed_a->GetGPUVirtualAddress() == placed_va); 4846 EXPECT(placed_a->GetGPUVirtualAddress() == placed_va);
4847
4848 // D3D-191: tiled placed resources (D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE and Xbox 0x101).
4849 D3D12_HEAP_DESC tiled_heap_desc{};
4850 tiled_heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
4851 tiled_heap_desc.SizeInBytes = 2 * 1024 * 1024;
4852 tiled_heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
4853 Ref<ID3D12Heap> tiled_heap, upload_placed_heap;
4854 EXPECT(SUCCEEDED(standalone->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&tiled_heap.p))));
4855 D3D12_HEAP_DESC upload_heap_desc = tiled_heap_desc;
4856 upload_heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4857 EXPECT(SUCCEEDED(standalone->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p))));
4858
4859 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags,
4860 UINT64 align = 0) {
4861 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
4862 d.Alignment = align;
4863 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
4864 return d;
4865 };
4866 const D3D12_RESOURCE_DESC tiled_rt_desc =
4867 tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
4868 const D3D12_RESOURCE_DESC tiled_bc_desc =
4869 tiled_2d(256, 256, DXGI_FORMAT_BC1_UNORM, 0, D3D12_RESOURCE_FLAG_NONE);
4870 const D3D12_RESOURCE_DESC tiled_ds_desc =
4871 tiled_2d(256, 256, DXGI_FORMAT_D32_FLOAT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
4872 D3D12_RESOURCE_DESC tiled_3d_desc =
4873 tiled_2d(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_RESOURCE_FLAG_NONE);
4874 tiled_3d_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
4875 tiled_3d_desc.DepthOrArraySize = 32;
4876 D3D12_RESOURCE_DESC xbox_tiled_desc =
4877 tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 1, D3D12_RESOURCE_FLAG_NONE);
4878 xbox_tiled_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
4879
4880 Ref<ID3D12Resource> tiled_rt, tiled_bc, tiled_ds, tiled_3d, xbox_tiled;
4881 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 0, &tiled_rt_desc, D3D12_RESOURCE_STATE_COMMON,
4882 nullptr, IID_PPV_ARGS(&tiled_rt.p))));
4883 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 512 * 1024, &tiled_bc_desc,
4884 D3D12_RESOURCE_STATE_COMMON, nullptr,
4885 IID_PPV_ARGS(&tiled_bc.p))));
4886 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 640 * 1024, &tiled_ds_desc,
4887 D3D12_RESOURCE_STATE_COMMON, nullptr,
4888 IID_PPV_ARGS(&tiled_ds.p))));
4889 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 1024 * 1024, &tiled_3d_desc,
4890 D3D12_RESOURCE_STATE_COMMON, nullptr,
4891 IID_PPV_ARGS(&tiled_3d.p))));
4892 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 0, &xbox_tiled_desc, D3D12_RESOURCE_STATE_COMMON,
4893 nullptr, IID_PPV_ARGS(&xbox_tiled.p))));
4894
4895 for (ID3D12Resource* r : {tiled_rt.p, tiled_bc.p, tiled_ds.p, tiled_3d.p}) {
4896 const D3D12_RESOURCE_DESC got = r->GetDesc();
4897 EXPECT(r->GetGPUVirtualAddress() == 0);
4898 EXPECT(got.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE);
4899 EXPECT(got.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
4900 EXPECT(got.MipLevels > 0);
4901 D3D12_HEAP_PROPERTIES got_hp{};
4902 D3D12_HEAP_FLAGS got_hf = D3D12_HEAP_FLAG_NONE;
4903 EXPECT(SUCCEEDED(r->GetHeapProperties(&got_hp, &got_hf)));
4904 EXPECT(got_hp.Type == D3D12_HEAP_TYPE_DEFAULT);
4905 const D3D12_RESOURCE_ALLOCATION_INFO ai = standalone->GetResourceAllocationInfo(0, 1, &got);
4906 UINT tiles = 0;
4907 D3D12_TILE_SHAPE shape{};
4908 standalone->GetResourceTiling(r, &tiles, nullptr, &shape, nullptr, 0, nullptr);
4909 EXPECT(tiles > 0 && shape.WidthInTexels > 0 && ai.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
4910 EXPECT(ai.SizeInBytes == UINT64(tiles) * D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES);
4911 }
4912 EXPECT(static_cast<UINT>(xbox_tiled->GetDesc().Layout) == 0x101);
4913 UINT xbox_tiles = 0;
4914 standalone->GetResourceTiling(xbox_tiled.p, &xbox_tiles, nullptr, nullptr, nullptr, 0, nullptr);
4915 EXPECT(xbox_tiles == 4);
4916
4917 // Refusals matching host D3D12: 1D, 4 KiB alignment, 96-bit, two-plane DS, invalid MSAA, upload heap, past-end.
4918 D3D12_RESOURCE_DESC bad_1d = line_desc(256, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM);
4919 bad_1d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
4920 auto tiled_2d_msaa = [&](UINT samples, D3D12_RESOURCE_FLAGS flags, UINT64 align = 0) {
4921 D3D12_RESOURCE_DESC d = tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 1, flags, align);
4922 d.SampleDesc.Count = samples;
4923 return d;
4924 };
4925 const D3D12_RESOURCE_DESC bad_cases[] = {
4926 bad_1d,
4927 tiled_2d(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, 1, D3D12_RESOURCE_FLAG_NONE,
4928 D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT),
4929 tiled_2d(64, 64, DXGI_FORMAT_R32G32B32_FLOAT, 1, D3D12_RESOURCE_FLAG_NONE),
4930 tiled_2d(64, 64, DXGI_FORMAT_D24_UNORM_S8_UINT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
4931 tiled_2d(64, 64, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
4932 tiled_2d_msaa(2, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET),
4933 tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_NONE),
4934 tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT),
4935 };
4936 for (const D3D12_RESOURCE_DESC& bad : bad_cases) {
4937 Ref<ID3D12Resource> fail;
4938 EXPECT(standalone->CreatePlacedResource(tiled_heap.p, 0, &bad, D3D12_RESOURCE_STATE_COMMON, nullptr,
4939 IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
4940 EXPECT(!fail.p);
4941 }
4942 {
4943 Ref<ID3D12Resource> fail;
4944 EXPECT(standalone->CreatePlacedResource(upload_placed_heap.p, 0, &tiled_rt_desc,
4945 D3D12_RESOURCE_STATE_COMMON, nullptr,
4946 IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
4947 const D3D12_RESOURCE_ALLOCATION_INFO rt_alloc = standalone->GetResourceAllocationInfo(0, 1, &tiled_rt_desc);
4948 EXPECT(standalone->CreatePlacedResource(tiled_heap.p,
4949 tiled_heap_desc.SizeInBytes - rt_alloc.SizeInBytes + 65536,
4950 &tiled_rt_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
4951 IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
4952 EXPECT(!fail.p);
4953 }
4954
4955 // Clear and read back a placed tiled RTV to verify GPU execution.
4956 D3D12_DESCRIPTOR_HEAP_DESC tiled_rtv_desc{};
4957 tiled_rtv_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
4958 tiled_rtv_desc.NumDescriptors = 1;
4959 Ref<ID3D12DescriptorHeap> tiled_rtv_heap;
4960 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&tiled_rtv_desc, IID_PPV_ARGS(&tiled_rtv_heap.p))));
4961 standalone->CreateRenderTargetView(tiled_rt.p, nullptr, tiled_rtv_heap->GetCPUDescriptorHandleForHeapStart());
4962 D3D12_HEAP_PROPERTIES rb_props{D3D12_HEAP_TYPE_READBACK};
4963 const D3D12_RESOURCE_DESC rb_desc = buffer_desc(256);
4964 Ref<ID3D12Resource> tiled_rb;
4965 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&rb_props, D3D12_HEAP_FLAG_NONE, &rb_desc,
4966 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
4967 IID_PPV_ARGS(&tiled_rb.p))));
4968 Ref<ID3D12CommandAllocator> tiled_alloc;
4969 Ref<ID3D12GraphicsCommandList> tiled_list;
4970 EXPECT(SUCCEEDED(standalone->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
4971 IID_PPV_ARGS(&tiled_alloc.p))));
4972 EXPECT(SUCCEEDED(standalone->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, tiled_alloc.p, nullptr,
4973 IID_PPV_ARGS(&tiled_list.p))));
4974 const FLOAT tiled_color[4] = {64.0f / 255.0f, 128.0f / 255.0f, 191.0f / 255.0f, 1.0f};
4975 D3D12_RESOURCE_BARRIER b = transition(tiled_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET);
4976 tiled_list->ResourceBarrier(1, &b);
4977 tiled_list->ClearRenderTargetView(tiled_rtv_heap->GetCPUDescriptorHandleForHeapStart(), tiled_color, 0, nullptr);
4978 b = transition(tiled_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
4979 tiled_list->ResourceBarrier(1, &b);
4980 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
4981 fp.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT};
4982 const D3D12_TEXTURE_COPY_LOCATION copy_dst = footprint(tiled_rb.p, fp);
4983 const D3D12_TEXTURE_COPY_LOCATION copy_src = subresource(tiled_rt.p, 0);
4984 D3D12_BOX box{0, 0, 0, 1, 1, 1};
4985 tiled_list->CopyTextureRegion(&copy_dst, 0, 0, 0, &copy_src, &box);
4986 EXPECT(SUCCEEDED(tiled_list->Close()));
4987 ID3D12CommandList* tiled_lists[] = {tiled_list.p};
4988 queue->ExecuteCommandLists(1, tiled_lists);
4989 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
4990 EXPECT(SUCCEEDED(queue->Signal(fence.p, 8)) && SUCCEEDED(fence->SetEventOnCompletion(8, nullptr)));
4991 void* tiled_bytes = nullptr;
4992 EXPECT(SUCCEEDED(tiled_rb->Map(0, nullptr, &tiled_bytes)));
4993 const std::uint8_t want_rgba[4] = {64, 128, 191, 255};
4994 report("tiled placed RTV", 0, static_cast<std::uint8_t*>(tiled_bytes), want_rgba, 4);
4995 EXPECT(std::memcmp(tiled_bytes, want_rgba, 4) == 0);
4996 tiled_rb->Unmap(0, nullptr);
4997
4998 // Compare placed 64KB_UNDEFINED_SWIZZLE acceptance, layout, alignment, heap props and tile shape with host.
4999 Ref<ID3D12Device> host_dev;
5000 if (create_host_device(host_dev)) {
5001 D3D12_FEATURE_DATA_D3D12_OPTIONS host_opts{};
5002 if (SUCCEEDED(host_dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &host_opts, sizeof(host_opts))) &&
5003 host_opts.TiledResourcesTier != D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED) {
5004 Ref<ID3D12Heap> host_heap;
5005 if (SUCCEEDED(host_dev->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&host_heap.p)))) {
5006 const D3D12_RESOURCE_DESC host_cases[] = {
5007 tiled_2d(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 1, D3D12_RESOURCE_FLAG_NONE),
5008 tiled_2d(256, 256, DXGI_FORMAT_D32_FLOAT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
5009 tiled_3d_desc,
5010 };
5011 for (int idx = 0; idx < int(std::size(host_cases)); ++idx) {
5012 const D3D12_RESOURCE_DESC& host_desc = host_cases[idx];
5013 if (host_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D &&
5014 host_opts.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_3)
5015 continue;
5016 Ref<ID3D12Resource> our_r, host_r;
5017 const HRESULT our_hr = standalone->CreatePlacedResource(
5018 tiled_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
5019 const HRESULT host_hr = host_dev->CreatePlacedResource(
5020 host_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
5021 if (FAILED(host_hr)) continue;
5022 EXPECT(SUCCEEDED(our_hr));
5023 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
5024 EXPECT(our_r->GetDesc().Alignment == host_r->GetDesc().Alignment);
5025 D3D12_HEAP_PROPERTIES ohp{}, hhp{};
5026 EXPECT(SUCCEEDED(our_r->GetHeapProperties(&ohp, nullptr)) &&
5027 SUCCEEDED(host_r->GetHeapProperties(&hhp, nullptr)));
5028 EXPECT(ohp.Type == hhp.Type);
5029 D3D12_TILE_SHAPE os{}, hs{};
5030 standalone->GetResourceTiling(our_r.p, nullptr, nullptr, &os, nullptr, 0, nullptr);
5031 host_dev->GetResourceTiling(host_r.p, nullptr, nullptr, &hs, nullptr, 0, nullptr);
5032 EXPECT(os.WidthInTexels == hs.WidthInTexels && os.HeightInTexels == hs.HeightInTexels &&
5033 os.DepthInTexels == hs.DepthInTexels);
5034 }
5035 }
5036 }
5037 }
5038
5039 // D3D-222: multisampled placed textures (UNKNOWN and 4x tiled).
5040 D3D12_HEAP_DESC msaa_heap_desc{};
5041 msaa_heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
5042 msaa_heap_desc.SizeInBytes = 16 * 1024 * 1024;
5043 msaa_heap_desc.Alignment = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT;
5044 Ref<ID3D12Heap> msaa_heap;
5045 EXPECT(SUCCEEDED(standalone->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&msaa_heap.p))));
5046 D3D12_HEAP_DESC deny_rt_desc = tiled_heap_desc;
5047 deny_rt_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
5048 Ref<ID3D12Heap> deny_rt_heap;
5049 EXPECT(SUCCEEDED(standalone->CreateHeap(&deny_rt_desc, IID_PPV_ARGS(&deny_rt_heap.p))));
5050
5051 auto msaa_desc = [&](UINT w, UINT h, UINT samples, UINT64 align, D3D12_TEXTURE_LAYOUT layout,
5052 D3D12_RESOURCE_FLAGS flags, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM,
5053 UINT16 mips = 1) {
5054 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
5055 d.Alignment = align;
5056 d.SampleDesc.Count = samples;
5057 d.Layout = layout;
5058 return d;
5059 };
5060 const D3D12_RESOURCE_DESC msaa_unk_rt_desc =
5061 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5062 const D3D12_RESOURCE_DESC msaa_unk_small_desc = msaa_desc(
5063 256, 256, 4, D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5064 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5065 const D3D12_RESOURCE_DESC msaa_unk_ds_desc =
5066 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
5067 DXGI_FORMAT_D32_FLOAT);
5068 const D3D12_RESOURCE_DESC msaa_tiled_rt_desc = tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5069 D3D12_RESOURCE_DESC msaa_xbox_rt_desc = msaa_tiled_rt_desc;
5070 msaa_xbox_rt_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
5071
5072 Ref<ID3D12Resource> msaa_unk_rt, msaa_unk_small, msaa_unk_ds, msaa_tiled_rt, msaa_xbox_rt, msaa_cast_rt;
5073 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
5074 &msaa_unk_rt_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
5075 IID_PPV_ARGS(&msaa_unk_rt.p))));
5076 EXPECT(msaa_unk_rt->GetGPUVirtualAddress() == 0);
5077 EXPECT(msaa_unk_rt->GetDesc().Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5078 EXPECT(msaa_unk_rt->GetDesc().SampleDesc.Count == 4);
5079 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_unk_small_desc,
5080 D3D12_RESOURCE_STATE_COMMON, nullptr,
5081 IID_PPV_ARGS(&msaa_unk_small.p))));
5082 EXPECT(msaa_unk_small->GetDesc().Alignment == D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5083 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, 8 * 1024 * 1024, &msaa_unk_ds_desc,
5084 D3D12_RESOURCE_STATE_COMMON, nullptr,
5085 IID_PPV_ARGS(&msaa_unk_ds.p))));
5086 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_tiled_rt_desc,
5087 D3D12_RESOURCE_STATE_COMMON, nullptr,
5088 IID_PPV_ARGS(&msaa_tiled_rt.p))));
5089 EXPECT(msaa_tiled_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5090 UINT msaa_tiles = 0;
5091 D3D12_TILE_SHAPE msaa_shape{};
5092 standalone->GetResourceTiling(msaa_tiled_rt.p, &msaa_tiles, nullptr, &msaa_shape, nullptr, 0, nullptr);
5093 EXPECT(msaa_tiles == 16 && msaa_shape.WidthInTexels == 64 && msaa_shape.HeightInTexels == 64);
5094 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_xbox_rt_desc,
5095 D3D12_RESOURCE_STATE_COMMON, nullptr,
5096 IID_PPV_ARGS(&msaa_xbox_rt.p))));
5097 EXPECT(msaa_xbox_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5098 EXPECT(static_cast<UINT>(msaa_xbox_rt->GetDesc().Layout) == 0x101);
5099
5100 {
5101 Ref<ID3D12Device10> standalone10;
5102 EXPECT(SUCCEEDED(standalone->QueryInterface(IID_PPV_ARGS(&standalone10.p))));
5103 D3D12_RESOURCE_DESC1 cast_msaa{};
5104 cast_msaa.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5105 cast_msaa.Width = 64;
5106 cast_msaa.Height = 64;
5107 cast_msaa.DepthOrArraySize = 1;
5108 cast_msaa.MipLevels = 1;
5109 cast_msaa.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS;
5110 cast_msaa.SampleDesc.Count = 4;
5111 cast_msaa.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
5112 const DXGI_FORMAT cast_list[] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
5113 EXPECT(SUCCEEDED(standalone10->CreatePlacedResource2(
5114 msaa_heap.p, 0, &cast_msaa, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 2, cast_list,
5115 IID_PPV_ARGS(&msaa_cast_rt.p))));
5116 }
5117
5118 // Refusals matching host D3D12 for MSAA placed resources.
5119 {
5120 struct BadMsaaCase {
5121 ID3D12Heap* heap;
5122 UINT64 offset;
5123 D3D12_RESOURCE_DESC desc;
5124 };
5125 D3D12_RESOURCE_DESC msaa_3d =
5126 msaa_desc(16, 16, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5127 msaa_3d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
5128 msaa_3d.DepthOrArraySize = 8;
5129 const BadMsaaCase bad_msaa[] = {
5130 // 4 MiB-aligned UNKNOWN MSAA fails on a 64 KiB heap (even at offset 0) and at misaligned offsets.
5131 {tiled_heap.p, 0, msaa_unk_rt_desc},
5132 {msaa_heap.p, 65536, msaa_unk_rt_desc},
5133 {msaa_heap.p, msaa_heap_desc.SizeInBytes - 65536, msaa_unk_small_desc},
5134 {upload_placed_heap.p, 0, msaa_unk_small_desc},
5135 {deny_rt_heap.p, 0, msaa_unk_small_desc},
5136 {msaa_heap.p, 0,
5137 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE)},
5138 {msaa_heap.p, 0,
5139 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5140 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)},
5141 {msaa_heap.p, 0,
5142 msaa_desc(64, 64, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
5143 DXGI_FORMAT_R8G8B8A8_UNORM, 0)},
5144 {msaa_heap.p, 0, msaa_3d},
5145 };
5146 for (const BadMsaaCase& bad : bad_msaa) {
5147 Ref<ID3D12Resource> fail;
5148 EXPECT(standalone->CreatePlacedResource(bad.heap, bad.offset, &bad.desc, D3D12_RESOURCE_STATE_COMMON,
5149 nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
5150 EXPECT(!fail.p);
5151 }
5152 }
5153
5154 // Clear placed 4x MSAA RTVs (UNKNOWN + tiled) and DSV, resolve, and read back to verify GPU execution.
5155 {
5156 const D3D12_RESOURCE_DESC resolved_desc =
5157 texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1);
5158 Ref<ID3D12Resource> msaa_resolved_unk, msaa_resolved_tiled;
5159 D3D12_HEAP_PROPERTIES def_hp{D3D12_HEAP_TYPE_DEFAULT};
5160 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5161 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5162 IID_PPV_ARGS(&msaa_resolved_unk.p))));
5163 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5164 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5165 IID_PPV_ARGS(&msaa_resolved_tiled.p))));
5166
5167 D3D12_DESCRIPTOR_HEAP_DESC msaa_rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5168 D3D12_DESCRIPTOR_HEAP_DESC msaa_dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5169 Ref<ID3D12DescriptorHeap> msaa_rtv_heap, msaa_dsv_heap;
5170 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_rtv_hd, IID_PPV_ARGS(&msaa_rtv_heap.p))));
5171 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_dsv_hd, IID_PPV_ARGS(&msaa_dsv_heap.p))));
5172 const UINT rtv_step = standalone->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
5173 const D3D12_CPU_DESCRIPTOR_HANDLE rtv0 = msaa_rtv_heap->GetCPUDescriptorHandleForHeapStart();
5174 const D3D12_CPU_DESCRIPTOR_HANDLE rtv1{rtv0.ptr + rtv_step};
5175 standalone->CreateRenderTargetView(msaa_unk_rt.p, nullptr, rtv0);
5176 standalone->CreateRenderTargetView(msaa_tiled_rt.p, nullptr, rtv1);
5177 standalone->CreateDepthStencilView(msaa_unk_ds.p, nullptr, msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart());
5178
5179 EXPECT(SUCCEEDED(tiled_alloc->Reset()) && SUCCEEDED(tiled_list->Reset(tiled_alloc.p, nullptr)));
5180 D3D12_RESOURCE_BARRIER barriers[] = {
5181 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5182 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5183 transition(msaa_unk_ds.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE),
5184 };
5185 tiled_list->ResourceBarrier(3, barriers);
5186 tiled_list->ClearRenderTargetView(rtv0, tiled_color, 0, nullptr);
5187 tiled_list->ClearRenderTargetView(rtv1, tiled_color, 0, nullptr);
5188 tiled_list->ClearDepthStencilView(msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart(),
5189 D3D12_CLEAR_FLAG_DEPTH, 0.5f, 0, 0, nullptr);
5190 D3D12_RESOURCE_BARRIER to_resolve[] = {
5191 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5192 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5193 };
5194 tiled_list->ResourceBarrier(2, to_resolve);
5195 tiled_list->ResolveSubresource(msaa_resolved_unk.p, 0, msaa_unk_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5196 tiled_list->ResolveSubresource(msaa_resolved_tiled.p, 0, msaa_tiled_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5197 D3D12_RESOURCE_BARRIER to_copy[] = {
5198 transition(msaa_resolved_unk.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5199 transition(msaa_resolved_tiled.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5200 };
5201 tiled_list->ResourceBarrier(2, to_copy);
5202 Ref<ID3D12Resource> msaa_rb;
5203 const D3D12_RESOURCE_DESC msaa_rb_desc = buffer_desc(1024);
5204 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&rb_props, D3D12_HEAP_FLAG_NONE, &msaa_rb_desc,
5205 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
5206 IID_PPV_ARGS(&msaa_rb.p))));
5207 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp_unk{}, fp_tiled{};
5208 fp_unk.Offset = 0;
5209 fp_unk.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT};
5210 fp_tiled = fp_unk;
5211 fp_tiled.Offset = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
5212 const D3D12_TEXTURE_COPY_LOCATION dst_unk = footprint(msaa_rb.p, fp_unk);
5213 const D3D12_TEXTURE_COPY_LOCATION src_unk = subresource(msaa_resolved_unk.p, 0);
5214 const D3D12_TEXTURE_COPY_LOCATION dst_tiled = footprint(msaa_rb.p, fp_tiled);
5215 const D3D12_TEXTURE_COPY_LOCATION src_tiled = subresource(msaa_resolved_tiled.p, 0);
5216 tiled_list->CopyTextureRegion(&dst_unk, 0, 0, 0, &src_unk, &box);
5217 tiled_list->CopyTextureRegion(&dst_tiled, 0, 0, 0, &src_tiled, &box);
5218 EXPECT(SUCCEEDED(tiled_list->Close()));
5219 queue->ExecuteCommandLists(1, tiled_lists);
5220 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
5221 EXPECT(SUCCEEDED(queue->Signal(fence.p, 9)) && SUCCEEDED(fence->SetEventOnCompletion(9, nullptr)));
5222 void* msaa_bytes = nullptr;
5223 EXPECT(SUCCEEDED(msaa_rb->Map(0, nullptr, &msaa_bytes)));
5224 const auto* out_bytes = static_cast<const std::uint8_t*>(msaa_bytes);
5225 report("placed MSAA UNKNOWN RTV resolve", 0, out_bytes, want_rgba, 4);
5226 report("placed MSAA tiled RTV resolve", 0, out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4);
5227 EXPECT(std::memcmp(out_bytes, want_rgba, 4) == 0);
5228 EXPECT(std::memcmp(out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4) == 0);
5229 msaa_rb->Unmap(0, nullptr);
5230 }
5231
5232 // Host parity for MSAA placed acceptance/refusals, layout, alignment, heap flags and tiled 4x shape.
5233 if (host_dev.p) {
5234 Ref<ID3D12Heap> host_heap64, host_heap4m;
5235 if (SUCCEEDED(host_dev->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&host_heap64.p))) &&
5236 SUCCEEDED(host_dev->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&host_heap4m.p)))) {
5237 struct MsaaParityCase {
5238 ID3D12Heap* our_heap;
5239 ID3D12Heap* host_heap;
5240 UINT64 offset;
5241 D3D12_RESOURCE_DESC desc;
5242 };
5243 const MsaaParityCase parity[] = {
5244 {tiled_heap.p, host_heap64.p, 0, msaa_unk_rt_desc},
5245 {msaa_heap.p, host_heap4m.p, 65536, msaa_unk_rt_desc},
5246 {msaa_heap.p, host_heap4m.p, 0, msaa_unk_rt_desc},
5247 {tiled_heap.p, host_heap64.p, 65536, msaa_unk_small_desc},
5248 {tiled_heap.p, host_heap64.p, 65536, msaa_tiled_rt_desc},
5249 };
5250 for (const MsaaParityCase& mc : parity) {
5251 Ref<ID3D12Resource> our_r, host_r;
5252 const HRESULT our_hr = standalone->CreatePlacedResource(
5253 mc.our_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
5254 const HRESULT host_hr = host_dev->CreatePlacedResource(
5255 mc.host_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
5256 EXPECT(SUCCEEDED(our_hr) == SUCCEEDED(host_hr));
5257 if (FAILED(host_hr)) {
5258 EXPECT(our_hr == host_hr);
5259 continue;
5260 }
5261 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
5262 EXPECT(our_r->GetDesc().Alignment == host_r->GetDesc().Alignment);
5263 EXPECT(our_r->GetDesc().SampleDesc.Count == host_r->GetDesc().SampleDesc.Count);
5264 D3D12_HEAP_PROPERTIES ohp{}, hhp{};
5265 EXPECT(SUCCEEDED(our_r->GetHeapProperties(&ohp, nullptr)) &&
5266 SUCCEEDED(host_r->GetHeapProperties(&hhp, nullptr)));
5267 EXPECT(ohp.Type == hhp.Type);
5268 if (mc.desc.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
5269 D3D12_TILE_SHAPE os{}, hs{};
5270 standalone->GetResourceTiling(our_r.p, nullptr, nullptr, &os, nullptr, 0, nullptr);
5271 host_dev->GetResourceTiling(host_r.p, nullptr, nullptr, &hs, nullptr, 0, nullptr);
5272 EXPECT(os.WidthInTexels == hs.WidthInTexels && os.HeightInTexels == hs.HeightInTexels &&
5273 os.DepthInTexels == hs.DepthInTexels);
5274 }
5275 }
5276 }
5277 }
4625 } 5278 }
4626 5279
4627 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as 5280 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as
@@ -4853,6 +5506,15 @@ int main() {
4853 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0); 5506 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0);
4854 } 5507 }
4855 5508
5509 // The tolerance host_side applies, pinned here so every GPU checks it: its accept side only runs where the
5510 // host rounds differently (Intel's SRGB clear), so a change to it would otherwise stay green elsewhere.
5511 // One code either side of a near-tie is accepted; two codes, or a code past 0.6 ULP, are not.
5512 EXPECT(within_06_ulp(187, 188, ideal_srgb(0.5) * 255.0) && within_06_ulp(127, 128, 127.5));
5513 EXPECT(!within_06_ulp(186, 188, ideal_srgb(0.5) * 255.0) && !within_06_ulp(126, 128, 127.5));
5514 EXPECT(!within_06_ulp(224, 225, ideal_srgb(0.75) * 255.0) &&
5515 !within_06_ulp(136, 137, ideal_srgb(0.25) * 255.0));
5516 EXPECT(!within_06_ulp(254, 255, 255.0));
5517
4856 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise. 5518 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise.
4857 bool compared = false; 5519 bool compared = false;
4858 const char* source = "no host"; 5520 const char* source = "no host";
@@ -4862,33 +5524,44 @@ int main() {
4862 if (!placed_cast_scenario(device10, false, host.data())) return false; 5524 if (!placed_cast_scenario(device10, false, host.data())) return false;
4863 if (!placed_cast_refusals(device10, host_refusals)) return false; 5525 if (!placed_cast_refusals(device10, host_refusals)) return false;
4864 unsigned differences = 0; 5526 unsigned differences = 0;
4865 // D3D12 does not pin float -> UNORM at a tie: the D3D11.3 functional spec (3.2.3.6 FLOAT -> UNORM) 5527 // D3D12 does not pin float -> UNORM or float -> SRGB to one code: the D3D11.3 functional spec
4866 // computes c * (2^n - 1) + 0.5 and drops the fraction, but permits a tolerance of 0.6 ULP on the integer 5528 // (3.2.3.6 FLOAT -> UNORM, 3.2.3.8 FLOAT -> SRGB) permits a tolerance of 0.6 ULP on the integer side, so
4867 // side, so a value exactly halfway between two codes (0.5 * 255 = 127.5) may map to either. WARP and AMD 5529 // a value near halfway between two codes may map to either. The plain clear's 0.5 * 255 = 127.5 is a
4868 // give the upper code; NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080 616.64, RTX 3090 5530 // tie: WARP and AMD give the upper code, NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080
4869 // 610.88 and RTX 5070 Laptop 617.42). On the layer's own adapter (same LUID) the comparison stays exact; 5531 // 616.64, RTX 3090 610.88 and RTX 5070 Laptop 617.42). The SRGB-cast clear's 0.5 encodes to 187.516:
4870 // against another adapter or WARP the plain clear accepts either code on a tie channel. 5532 // WARP and NVIDIA's Vulkan driver give 188, Intel's Vulkan driver 187 (UHD 770 101.7092), both within
5533 // 0.6 ULP. On the layer's own adapter (same LUID) the comparison stays exact; against another adapter
5534 // or WARP a byte may differ when both sides are within 0.6 ULP of the ideal value.
4871 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour 5535 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour
4872 unsigned tie_bytes_other_way = 0; 5536 const auto within_tolerance = [&](std::uint8_t ours_byte, std::uint8_t host_byte, double ideal) {
5537 return !same_adapter && within_06_ulp(ours_byte, host_byte, ideal);
5538 };
5539 unsigned plain_within = 0, srgb_within = 0;
4873 for (UINT row = 0; row < 4; ++row) 5540 for (UINT row = 0; row < 4; ++row)
4874 for (UINT i = 0; i < 16; ++i) { 5541 for (UINT i = 0; i < 16; ++i) {
4875 const UINT a = row * 256 + i, b = 1024 + row * 256 + i; 5542 const UINT a = row * 256 + i, b = 1024 + row * 256 + i;
4876 const double scaled = double(clear_value[i % 4]) * 255.0; 5543 const double c = clear_value[i % 4];
4877 const bool tie = !same_adapter && scaled - std::floor(scaled) == 0.5; 5544 const double plain_ideal = c * 255.0;
4878 if (tie && std::abs(int(ours[b]) - int(host[b])) == 1) { 5545 const double srgb_ideal = (i % 4 == 3 ? c : ideal_srgb(c)) * 255.0; // alpha stays linear
4879 ++tie_bytes_other_way; 5546 if (ours[b] != host[b]) {
4880 } else if (ours[b] != host[b] && differences++ < 8) { 5547 if (within_tolerance(ours[b], host[b], plain_ideal))
4881 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i, 5548 ++plain_within;
4882 ours[b], host[b]); 5549 else if (differences++ < 8)
5550 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i,
5551 ours[b], host[b]);
5552 }
5553 if (ours[a] != host[a]) {
5554 if (within_tolerance(ours[a], host[a], srgb_ideal))
5555 ++srgb_within;
5556 else if (differences++ < 8)
5557 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n",
5558 row, i, ours[a], host[a]);
4883 } 5559 }
4884 if (ours[a] != host[a] && differences++ < 8)
4885 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n", row,
4886 i, ours[a], host[a]);
4887 } 5560 }
4888 if (tie_bytes_other_way) 5561 if (plain_within || srgb_within)
4889 std::printf("placed plain clear: the host rounds the exact .5 tie the other way in %u bytes (within " 5562 std::printf("placed clears: %u plain and %u SRGB-cast bytes differ from the host by one code, both "
4890 "the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6)\n", 5563 "within the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6 and 3.2.3.8\n",
4891 tie_bytes_other_way); 5564 plain_within, srgb_within);
4892 for (UINT i = 0; i < 3; ++i) 5565 for (UINT i = 0; i < 3; ++i)
4893 if (our_refusals[i] != host_refusals[i]) { 5566 if (our_refusals[i] != host_refusals[i]) {
4894 ++differences; 5567 ++differences;
diff --git a/runtime/test/d3d12_xdxr_rt_test.cpp b/runtime/test/d3d12_xdxr_rt_test.cpp
index 9499dbe0d..0b4d3da52 100644
--- a/runtime/test/d3d12_xdxr_rt_test.cpp
+++ b/runtime/test/d3d12_xdxr_rt_test.cpp
@@ -2,7 +2,8 @@
2// 4.8, src/xdxr_build.h), the layout the game's translated traversal shaders read. A BLAS of two geometries (an 2// 4.8, src/xdxr_build.h), the layout the game's translated traversal shaders read. A BLAS of two geometries (an
3// unindexed triangle soup, and an R16-indexed grid with a 16-byte stride and a 3x4 transform) and a TLAS of three 3// unindexed triangle soup, and an R16-indexed grid with a 16-byte stride and a 3x4 transform) and a TLAS of three
4// instances are built through the D3D12 API, sized by GetRaytracingAccelerationStructurePrebuildInfo, copied to 4// instances are built through the D3D12 API, sized by GetRaytracingAccelerationStructurePrebuildInfo, copied to
5// readback buffers and written to <out dir> as <case>.bin + <case>.json at their console GPU virtual addresses. 5// readback buffers and written to <out dir>; the BLAS is then updated in place (PERFORM_UPDATE) after its soup moves,
6// and written again as d3d12_blas_update as <case>.bin + <case>.json at their console GPU virtual addresses.
6// `python -I tools/xdxr_bvh.py check-build <out dir>` validates them and traces rays against brute force (ctest: 7// `python -I tools/xdxr_bvh.py check-build <out dir>` validates them and traces rays against brute force (ctest:
7// d3d12_xdxr_rt + d3d12_xdxr_rt_check). Exit 77 without a Vulkan device, or with LEONIDA_RT_AS=khr. No game files. 8// d3d12_xdxr_rt + d3d12_xdxr_rt_check). Exit 77 without a Vulkan device, or with LEONIDA_RT_AS=khr. No game files.
8#include "../shims/d3d12_com.h" 9#include "../shims/d3d12_com.h"
@@ -153,6 +154,7 @@ int main(int argc, char** argv) {
153 154
154 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; 155 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{};
155 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; 156 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
157 blas_inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE; // updated below
156 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; 158 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
157 blas_inputs.NumDescs = 2; 159 blas_inputs.NumDescs = 2;
158 blas_inputs.pGeometryDescs = geometries; 160 blas_inputs.pGeometryDescs = geometries;
@@ -239,7 +241,7 @@ int main(int argc, char** argv) {
239 ID3D12CommandList* lists[] = {list.p}; 241 ID3D12CommandList* lists[] = {list.p};
240 queue->ExecuteCommandLists(1, lists); 242 queue->ExecuteCommandLists(1, lists);
241 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal"); 243 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal");
242 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 244 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // reused for the update below
243 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) && 245 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) &&
244 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; 246 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
245 if (event) CloseHandle(event); 247 if (event) CloseHandle(event);
@@ -258,31 +260,35 @@ int main(int argc, char** argv) {
258 rb->Unmap(0, nullptr); 260 rb->Unmap(0, nullptr);
259 return ok; 261 return ok;
260 }; 262 };
261 std::string tris = "["; 263 // The BLAS's triangles as the reference sees them, for the soup's current positions.
262 bool first = true; 264 auto triangles_json = [&](const std::vector<float>& soup_now) {
263 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) { 265 std::string tris = "[";
264 tris += first ? "\n [" : ",\n ["; 266 bool first = true;
265 first = false; 267 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) {
266 for (int k = 0; k < 3; ++k) 268 tris += first ? "\n [" : ",\n [";
267 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]"; 269 first = false;
268 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]"; 270 for (int k = 0; k < 3; ++k)
269 }; 271 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]";
270 for (UINT t = 0; t < soup_tris; ++t) { 272 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]";
271 float v[3][3]; 273 };
272 for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup[9 * t + k]; 274 for (UINT t = 0; t < soup_tris; ++t) {
273 add_tri(v, 0, t); 275 float v[3][3];
274 } 276 for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup_now[9 * t + k];
275 for (UINT t = 0; t < indices.size() / 3; ++t) { 277 add_tri(v, 0, t);
276 float v[3][3];
277 for (int k = 0; k < 3; ++k) {
278 const float* p = &grid[4 * indices[3 * t + k]];
279 for (int r = 0; r < 3; ++r)
280 v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] +
281 transform[4 * r + 3];
282 } 278 }
283 add_tri(v, 1, t); 279 for (UINT t = 0; t < indices.size() / 3; ++t) {
284 } 280 float v[3][3];
285 tris += "]"; 281 for (int k = 0; k < 3; ++k) {
282 const float* p = &grid[4 * indices[3 * t + k]];
283 for (int r = 0; r < 3; ++r)
284 v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] +
285 transform[4 * r + 3];
286 }
287 add_tri(v, 1, t);
288 }
289 return tris + "]";
290 };
291 const std::string tris = triangles_json(soup);
286 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas", 292 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas",
287 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + 293 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
288 ", \"triangles\": " + tris + "}\n")) 294 ", \"triangles\": " + tris + "}\n"))
@@ -298,6 +304,38 @@ int main(int argc, char** argv) {
298 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + 304 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) +
299 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n")) 305 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n"))
300 return fail("TLAS readback"); 306 return fail("TLAS readback");
307
308 // ---- PERFORM_UPDATE in place: the soup moves (every vertex), the grid stays; the BLAS is refitted ----
309 std::vector<float> moved = soup;
310 std::uniform_real_distribution<float> nudge(-1.0f, 1.0f);
311 for (std::size_t v = 0; v < moved.size(); v += 3) {
312 moved[v] = moved[v] * 1.3f + nudge(rng);
313 moved[v + 1] = moved[v + 1] * 0.7f + nudge(rng);
314 moved[v + 2] += nudge(rng);
315 }
316 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return fail("Map upload for the update");
317 std::memcpy(mapped + (soup_va - upload->GetGPUVirtualAddress()), moved.data(), std::size_t(soup_bytes));
318 upload->Unmap(0, nullptr);
319 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for the update");
320 build.Inputs = blas_inputs;
321 build.Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
322 build.DestAccelerationStructureData = blas->GetGPUVirtualAddress();
323 build.SourceAccelerationStructureData = blas->GetGPUVirtualAddress();
324 list->BuildRaytracingAccelerationStructure(&build, 0, nullptr);
325 list->ResourceBarrier(1, &barrier);
326 list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes);
327 if (FAILED(hr = list->Close())) return fail("Close (update)", hr);
328 queue->ExecuteCommandLists(1, lists);
329 if (FAILED(queue->Signal(fence.p, 2))) return fail("Signal (update)");
330 event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
331 const bool updated = event && SUCCEEDED(fence->SetEventOnCompletion(2, event)) &&
332 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
333 if (event) CloseHandle(event);
334 if (!updated) return fail("the update did not complete");
335 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas_update",
336 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
337 ", \"triangles\": " + triangles_json(moved) + "}\n"))
338 return fail("BLAS readback after the update");
301 std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n", 339 std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n",
302 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), 340 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
303 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), 341 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
diff --git a/runtime/test/depth24_convert_test.cpp b/runtime/test/depth24_convert_test.cpp
index 365628519..89e98b091 100644
--- a/runtime/test/depth24_convert_test.cpp
+++ b/runtime/test/depth24_convert_test.cpp
@@ -673,6 +673,97 @@ int main() {
673 std::printf("depth24: 96-bit texels repack both ways, split into rows and into slices\n"); 673 std::printf("depth24: 96-bit texels repack both ways, split into rows and into slices\n");
674 } 674 }
675 675
676 // 7. ScratchBuffers::collect() must check VkResult from vkGetSemaphoreCounterValue() (leaving in-flight
677 // chunks retired if the query fails even when *pValue is overwritten with UINT64_MAX) and reclaim
678 // ticket-0 batches without querying the timeline semaphore.
679 {
680 struct MockVk {
681 std::uint64_t next_handle = 1;
682 VkResult sem_result = VK_ERROR_DEVICE_LOST;
683 std::uint64_t sem_value = UINT64_MAX;
684 unsigned sem_queries = 0;
685 unsigned destroyed_buffers = 0;
686
687 static MockVk*& state() {
688 static MockVk* s = nullptr;
689 return s;
690 }
691 static VKAPI_ATTR VkResult VKAPI_CALL create_buf(VkDevice, const VkBufferCreateInfo*,
692 const VkAllocationCallbacks*, VkBuffer* out) {
693 *out = reinterpret_cast<VkBuffer>(state()->next_handle++);
694 return VK_SUCCESS;
695 }
696 static VKAPI_ATTR void VKAPI_CALL destroy_buf(VkDevice, VkBuffer, const VkAllocationCallbacks*) {
697 ++state()->destroyed_buffers;
698 }
699 static VKAPI_ATTR void VKAPI_CALL mem_req(VkDevice, VkBuffer, VkMemoryRequirements* req) {
700 *req = {};
701 req->size = 4096;
702 req->alignment = 256;
703 req->memoryTypeBits = 1;
704 }
705 static VKAPI_ATTR VkResult VKAPI_CALL bind_buf(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) {
706 return VK_SUCCESS;
707 }
708 static VKAPI_ATTR void VKAPI_CALL free_mem(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) {}
709 static VKAPI_ATTR VkResult VKAPI_CALL get_sem(VkDevice, VkSemaphore, std::uint64_t* out) {
710 ++state()->sem_queries;
711 if (out) *out = state()->sem_value;
712 return state()->sem_result;
713 }
714 static VKAPI_ATTR VkResult VKAPI_CALL wait_idle(VkDevice) { return VK_SUCCESS; }
715 static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL gdpa(VkDevice, const char* name) {
716 if (std::strcmp(name, "vkCreateBuffer") == 0) return reinterpret_cast<PFN_vkVoidFunction>(create_buf);
717 if (std::strcmp(name, "vkDestroyBuffer") == 0)
718 return reinterpret_cast<PFN_vkVoidFunction>(destroy_buf);
719 if (std::strcmp(name, "vkGetBufferMemoryRequirements") == 0)
720 return reinterpret_cast<PFN_vkVoidFunction>(mem_req);
721 if (std::strcmp(name, "vkBindBufferMemory") == 0)
722 return reinterpret_cast<PFN_vkVoidFunction>(bind_buf);
723 if (std::strcmp(name, "vkFreeMemory") == 0) return reinterpret_cast<PFN_vkVoidFunction>(free_mem);
724 if (std::strcmp(name, "vkGetSemaphoreCounterValue") == 0)
725 return reinterpret_cast<PFN_vkVoidFunction>(get_sem);
726 if (std::strcmp(name, "vkDeviceWaitIdle") == 0) return reinterpret_cast<PFN_vkVoidFunction>(wait_idle);
727 return nullptr;
728 }
729 };
730 MockVk mock{};
731 MockVk::state() = &mock;
732 const VkSemaphore fake_sem = reinterpret_cast<VkSemaphore>(std::uintptr_t(0x1234));
733 {
734 ScratchBuffers scratch(&MockVk::gdpa, reinterpret_cast<VkDevice>(std::uintptr_t(1)),
735 [&](const VkMemoryRequirements&) {
736 return reinterpret_cast<VkDeviceMemory>(mock.next_handle++);
737 });
738 EXPECT(scratch.loaded());
739 VkBuffer b1 = VK_NULL_HANDLE, b2 = VK_NULL_HANDLE;
740 VkDeviceSize off = 0;
741 EXPECT(scratch.get(1024, b1, off));
742 scratch.retire(fake_sem, 1);
743 // Query fails with VK_ERROR_DEVICE_LOST while writing UINT64_MAX to *pValue: chunk must NOT be recycled!
744 scratch.collect();
745 EXPECT(scratch.get(1024, b2, off));
746 EXPECT(b2 != b1); // b1 is still in flight; must not have been reclaimed into spare_
747 // Unsubmitted batch (ticket == 0): must reclaim without calling vkGetSemaphoreCounterValue.
748 const unsigned queries_before = mock.sem_queries;
749 scratch.retire(fake_sem, 0);
750 mock.sem_result = VK_SUCCESS;
751 mock.sem_value = 0;
752 scratch.collect();
753 EXPECT(mock.sem_queries == queries_before + 1); // only queried for b1 (ticket 1), not b2 (ticket 0)
754 VkBuffer b3 = VK_NULL_HANDLE;
755 EXPECT(scratch.get(1024, b3, off));
756 EXPECT(b3 == b2); // b2 was reclaimed cleanly from ticket 0
757 // Now b1's ticket completes cleanly.
758 mock.sem_value = 1;
759 scratch.collect();
760 scratch.retire(fake_sem, 0);
761 }
762 EXPECT(mock.destroyed_buffers == 2);
763 MockVk::state() = nullptr;
764 std::printf("depth24: ScratchBuffers::collect() checks vkGetSemaphoreCounterValue VkResult and ticket 0 ok\n");
765 }
766
676 EXPECT(gpu.validation_errors() == 0); 767 EXPECT(gpu.validation_errors() == 0);
677 std::printf("depth24_convert_test: ok\n"); 768 std::printf("depth24_convert_test: ok\n");
678 return 0; 769 return 0;
diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp
index e414f155b..70cae9a89 100644
--- a/runtime/test/device_proxy_test.cpp
+++ b/runtime/test/device_proxy_test.cpp
@@ -151,19 +151,19 @@ int main() {
151 unsigned slots = rt::d3d12_xs::device_proxy_slot_count(device.Get()); 151 unsigned slots = rt::d3d12_xs::device_proxy_slot_count(device.Get());
152 std::printf("proxy forwards %u PC vtable slots (ID3D12Device..Device14 max is 83)\n", slots); 152 std::printf("proxy forwards %u PC vtable slots (ID3D12Device..Device14 max is 83)\n", slots);
153 check(slots >= 44, "proxy forwards at least the base ID3D12Device vtable"); 153 check(slots >= 44, "proxy forwards at least the base ID3D12Device vtable");
154 check(!rt::d3d12_xs::device_slot_overridden(9), "device slot 9 is forwarded (PC CreateCommandAllocator)"); 154 check(rt::d3d12_xs::device_slot_overridden(9), "device slot 9 is CreateCommandAllocator (allocator proxies)");
155 check(!rt::d3d12_xs::device_slot_overridden(10), "device slot 10 is forwarded (PC CreateGraphicsPipelineState)"); 155 check(!rt::d3d12_xs::device_slot_overridden(10), "device slot 10 is forwarded (PC CreateGraphicsPipelineState)");
156 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override"); 156 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override");
157 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override"); 157 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override");
158 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override"); 158 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override");
159 check(rt::d3d12_xs::device_slot_overridden(67), 159 check(rt::d3d12_xs::device_slot_overridden(67),
160 "device slot 67 is refused (console DeserializeComputePipelineStateX, " 160 "device slot 67 is the DeserializeComputePipelineStateX override (console native-code compute pipeline, not PC CreateProtectedResourceSession1)");
161 "not PC CreateProtectedResourceSession1)");
162 161
163 void** proxy_vtbl = *reinterpret_cast<void***>(device.Get()); 162 void** proxy_vtbl = *reinterpret_cast<void***>(device.Get());
164 void** real_vtbl = real ? *reinterpret_cast<void***>(real) : nullptr; 163 void** real_vtbl = real ? *reinterpret_cast<void***>(real) : nullptr;
165 check(proxy_vtbl != nullptr && proxy_vtbl[14] != real_vtbl[14], "slot 14 thunk differs from the PC entry"); 164 check(proxy_vtbl != nullptr && proxy_vtbl[14] != real_vtbl[14], "slot 14 thunk differs from the PC entry");
166 if (slots > 62) check(proxy_vtbl[62] != real_vtbl[62], "slot 62 thunk differs from PC CreateStateObject"); 165 if (slots > 62) check(proxy_vtbl[62] != real_vtbl[62], "slot 62 thunk differs from PC CreateStateObject");
166 if (slots > 67) check(proxy_vtbl[67] != real_vtbl[67], "slot 67 thunk differs from PC CreateProtectedResourceSession1");
167 if (slots > 76) check(proxy_vtbl[76] != real_vtbl[76], "slot 76 thunk differs from PC CreateCommittedResource3"); 167 if (slots > 76) check(proxy_vtbl[76] != real_vtbl[76], "slot 76 thunk differs from PC CreateCommittedResource3");
168 168
169 rt::d3d12_xs::reset_device_proxy_stats(); 169 rt::d3d12_xs::reset_device_proxy_stats();
@@ -278,6 +278,8 @@ int main() {
278 ComPtr<ID3D12CommandAllocator> allocator; 278 ComPtr<ID3D12CommandAllocator> allocator;
279 hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.GetAddressOf())); 279 hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.GetAddressOf()));
280 check(SUCCEEDED(hr) && allocator != nullptr, "device slot 9 forwards CreateCommandAllocator"); 280 check(SUCCEEDED(hr) && allocator != nullptr, "device slot 9 forwards CreateCommandAllocator");
281 // A PC runtime allocator is not wrapped: the PC runtime's lists could not resolve an allocator proxy.
282 check(!rt::d3d12_xs::is_allocator_proxy(allocator.Get()), "slot 9 hands out the PC allocator unwrapped");
281 check(rt::d3d12_xs::device_slot_hits(9) == 1, "slot 9 hit counter is 1"); 283 check(rt::d3d12_xs::device_slot_hits(9) == 1, "slot 9 hit counter is 1");
282 284
283 // Slot 76: buffer resource with the measured Xbox layout word 0x101; PC committed resources take ROW_MAJOR. 285 // Slot 76: buffer resource with the measured Xbox layout word 0x101; PC committed resources take ROW_MAJOR.
@@ -342,6 +344,31 @@ int main() {
342 check(SUCCEEDED(hr) && pso != nullptr, "slot 62 creates a compute PSO via CreateComputePipelineState"); 344 check(SUCCEEDED(hr) && pso != nullptr, "slot 62 creates a compute PSO via CreateComputePipelineState");
343 check(rt::d3d12_xs::device_slot_hits(62) == 1, "slot 62 hit counter is 1"); 345 check(rt::d3d12_xs::device_slot_hits(62) == 1, "slot 62 hit counter is 1");
344 check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set"); 346 check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set");
347
348 // Slot 67: Xbox native compute pipeline creation. Maps the console descriptor (+0x00 root signature,
349 // +0x28 kind 6 code blob, +0x30 code size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and calls CreateComputePipelineState.
350 struct XboxNativeComputeDesc {
351 ID3D12RootSignature* root_signature;
352 const void* kind0;
353 std::uint64_t kind0_size;
354 const void* kind1;
355 std::uint64_t kind1_size;
356 const void* kind6;
357 std::uint64_t kind6_size;
358 const void* kind7;
359 std::uint64_t kind7_size;
360 } xbox_desc{};
361 xbox_desc.root_signature = root_signature.Get();
362 xbox_desc.kind6 = bytecode->GetBufferPointer();
363 xbox_desc.kind6_size = bytecode->GetBufferSize();
364
365 using XboxCreateNativeComputePsoFn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**);
366 auto create_native_pso = reinterpret_cast<XboxCreateNativeComputePsoFn>(proxy_vtbl[67]);
367 ComPtr<ID3D12PipelineState> pso67;
368 hr = create_native_pso(device.Get(), &xbox_desc, &iid_pso, reinterpret_cast<void**>(pso67.GetAddressOf()));
369 check(SUCCEEDED(hr) && pso67 != nullptr, "slot 67 creates a compute PSO via CreateComputePipelineState");
370 check(rt::d3d12_xs::device_slot_hits(67) == 1, "slot 67 hit counter is 1");
371 check(rt::d3d12_xs::device_slot_first_call_seen(67), "slot 67 first-call flag is set");
345 } 372 }
346 373
347 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions, 374 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions,
@@ -357,6 +384,14 @@ int main() {
357 D3D12_COMPUTE_PIPELINE_STATE_DESC empty_pso{}; 384 D3D12_COMPUTE_PIPELINE_STATE_DESC empty_pso{};
358 hr = reinterpret_cast<Slot62Fn>(proxy_vtbl[62])(device.Get(), &empty_pso, 0, 0, nullptr, &proxy_out); 385 hr = reinterpret_cast<Slot62Fn>(proxy_vtbl[62])(device.Get(), &empty_pso, 0, 0, nullptr, &proxy_out);
359 check(FAILED(hr) && proxy_out == nullptr, "slot 62 nulls its output for a null IID"); 386 check(FAILED(hr) && proxy_out == nullptr, "slot 62 nulls its output for a null IID");
387 using Slot67Fn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**);
388 proxy_out = reinterpret_cast<void*>(0x1111);
389 const IID iid_pso = __uuidof(ID3D12PipelineState);
390 hr = reinterpret_cast<Slot67Fn>(proxy_vtbl[67])(device.Get(), nullptr, &iid_pso, &proxy_out);
391 check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null description");
392 proxy_out = reinterpret_cast<void*>(0x1111);
393 hr = reinterpret_cast<Slot67Fn>(proxy_vtbl[67])(device.Get(), &root_desc, nullptr, &proxy_out);
394 check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null IID");
360 using Slot76Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, 395 using Slot76Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
361 const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, 396 const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
362 const D3D12_CLEAR_VALUE*, const IID*, void**); 397 const D3D12_CLEAR_VALUE*, const IID*, void**);
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index 86129852e..c42707640 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -77,6 +77,19 @@ HWND create_test_window(int width, int height) {
77 nullptr); 77 nullptr);
78} 78}
79 79
80// Native DXGI on NVIDIA and WARP reports DISJOINT once after creation or ResizeBuffers, including when the
81// first query follows a Present. A null output must not consume that notification (D3D-211).
82bool check_statistics_disjoint(IDXGISwapChain* swapchain) {
83 if (swapchain->GetFrameStatistics(nullptr) != DXGI_ERROR_INVALID_CALL) return false;
84 DXGI_FRAME_STATISTICS stats;
85 std::memset(&stats, 0xcd, sizeof(stats));
86 if (swapchain->GetFrameStatistics(&stats) != DXGI_ERROR_FRAME_STATISTICS_DISJOINT) return false;
87 if (stats.PresentCount || stats.PresentRefreshCount || stats.SyncRefreshCount ||
88 stats.SyncQPCTime.QuadPart || stats.SyncGPUTime.QuadPart)
89 return false;
90 return swapchain->GetFrameStatistics(&stats) == S_OK;
91}
92
80} // namespace 93} // namespace
81 94
82int main() { 95int main() {
@@ -263,6 +276,18 @@ int main() {
263 scd.BufferCount = 2; 276 scd.BufferCount = 2;
264 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; 277 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
265 278
279 for (const UINT count : {0u, 1u, DXGI_MAX_SWAP_CHAIN_BUFFERS + 1u}) {
280 DXGI_SWAP_CHAIN_DESC1 invalid = scd;
281 invalid.BufferCount = count;
282 IDXGISwapChain1* rejected = nullptr;
283 const HRESULT hr = factory->CreateSwapChainForHwnd(queue, hwnd, &invalid, nullptr, nullptr, &rejected);
284 if (rejected) {
285 rejected->Release();
286 return fail("CreateSwapChainForHwnd returned a swapchain for an invalid buffer count");
287 }
288 if (hr != DXGI_ERROR_INVALID_CALL) return fail("CreateSwapChainForHwnd invalid buffer count HRESULT");
289 }
290
266 IDXGISwapChain1* sc1 = nullptr; 291 IDXGISwapChain1* sc1 = nullptr;
267 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1) 292 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1)
268 return fail("CreateSwapChainForHwnd"); 293 return fail("CreateSwapChainForHwnd");
@@ -270,6 +295,8 @@ int main() {
270 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3"); 295 if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3");
271 sc1->Release(); 296 sc1->Release();
272 297
298 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification");
299
273 ID3D12CommandQueue* got_queue = nullptr; 300 ID3D12CommandQueue* got_queue = nullptr;
274 if (FAILED(sc->GetDevice(IID_PPV_ARGS(&got_queue))) || got_queue != queue) { 301 if (FAILED(sc->GetDevice(IID_PPV_ARGS(&got_queue))) || got_queue != queue) {
275 if (got_queue) got_queue->Release(); 302 if (got_queue) got_queue->Release();
@@ -406,6 +433,25 @@ int main() {
406 return 0; 433 return 0;
407 }; 434 };
408 435
436 // Invalid counts must leave the initial back buffers usable for the first frame.
437 {
438 DXGI_SWAP_CHAIN_DESC1 before_resize{};
439 if (FAILED(sc->GetDesc1(&before_resize))) return fail("GetDesc1 before invalid resizes");
440 const std::vector<UINT> node_masks(DXGI_MAX_SWAP_CHAIN_BUFFERS + 1, 1);
441 const std::vector<IUnknown*> present_queues(DXGI_MAX_SWAP_CHAIN_BUFFERS + 1, queue);
442 for (const UINT count : {1u, DXGI_MAX_SWAP_CHAIN_BUFFERS + 1u}) {
443 if (sc->ResizeBuffers(count, 64, 64, DXGI_FORMAT_UNKNOWN, 0) != E_INVALIDARG)
444 return fail("ResizeBuffers invalid buffer count HRESULT");
445 if (sc->ResizeBuffers1(count, 64, 64, DXGI_FORMAT_UNKNOWN, 0, node_masks.data(), present_queues.data()) !=
446 E_INVALIDARG)
447 return fail("ResizeBuffers1 invalid buffer count HRESULT");
448 }
449 DXGI_SWAP_CHAIN_DESC1 after_resize{};
450 if (FAILED(sc->GetDesc1(&after_resize)) || after_resize.BufferCount != before_resize.BufferCount ||
451 after_resize.Width != before_resize.Width || after_resize.Height != before_resize.Height)
452 return fail("Invalid resize changed swapchain buffers");
453 }
454
409 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present. 455 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present.
410 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f}; 456 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f};
411 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1; 457 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1;
@@ -593,13 +639,14 @@ int main() {
593 if (sc->GetLastPresentCount(nullptr) != E_INVALIDARG) 639 if (sc->GetLastPresentCount(nullptr) != E_INVALIDARG)
594 return fail("GetLastPresentCount(nullptr) should return E_INVALIDARG"); 640 return fail("GetLastPresentCount(nullptr) should return E_INVALIDARG");
595 641
642 if (!check_statistics_disjoint(sc)) return fail("post-resize frame-statistics disjoint notification");
596 DXGI_FRAME_STATISTICS stats{}; 643 DXGI_FRAME_STATISTICS stats{};
597 if (FAILED(sc->GetFrameStatistics(&stats)) || stats.PresentCount != count_before || 644 if (FAILED(sc->GetFrameStatistics(&stats)) || stats.PresentCount != count_before ||
598 stats.PresentRefreshCount != count_before || stats.SyncRefreshCount != count_before || 645 stats.PresentRefreshCount != count_before || stats.SyncRefreshCount != count_before ||
599 stats.SyncQPCTime.QuadPart == 0) 646 stats.SyncQPCTime.QuadPart == 0)
600 return fail("GetFrameStatistics values"); 647 return fail("GetFrameStatistics values");
601 if (sc->GetFrameStatistics(nullptr) != E_INVALIDARG) 648 if (sc->GetFrameStatistics(nullptr) != DXGI_ERROR_INVALID_CALL)
602 return fail("GetFrameStatistics(nullptr) should return E_INVALIDARG"); 649 return fail("GetFrameStatistics(nullptr) should return DXGI_ERROR_INVALID_CALL");
603 } 650 }
604 651
605 // SwapChain::GetParent and non-waitable SetMaximumFrameLatency/GetMaximumFrameLatency (host DXGI returns 652 // SwapChain::GetParent and non-waitable SetMaximumFrameLatency/GetMaximumFrameLatency (host DXGI returns
@@ -731,6 +778,8 @@ int main() {
731 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at 778 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at
732 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size. 779 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size.
733 { 780 {
781 DXGI_SWAP_CHAIN_DESC1 before_zero{};
782 if (FAILED(sc->GetDesc1(&before_zero))) return fail("GetDesc1 before zero-count resize");
734 RECT wr{0, 0, 300, 200}; 783 RECT wr{0, 0, 300, 200};
735 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); 784 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
736 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER); 785 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER);
@@ -738,7 +787,8 @@ int main() {
738 GetClientRect(hwnd, &cr); 787 GetClientRect(hwnd, &cr);
739 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)"); 788 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)");
740 DXGI_SWAP_CHAIN_DESC1 d{}; 789 DXGI_SWAP_CHAIN_DESC1 d{};
741 sc->GetDesc1(&d); 790 if (FAILED(sc->GetDesc1(&d)) || d.BufferCount != before_zero.BufferCount)
791 return fail("ResizeBuffers(0, 0, 0) changed the buffer count");
742 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) { 792 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) {
743 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height, 793 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height,
744 cr.right, cr.bottom); 794 cr.right, cr.bottom);
@@ -778,11 +828,31 @@ int main() {
778 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG"); 828 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG");
779 factory5->Release(); 829 factory5->Release();
780 830
831 constexpr UINT tearing_flag = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
832 constexpr UINT waitable_flag = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
833 constexpr UINT both_flags = tearing_flag | waitable_flag;
834 const UINT node_masks[2] = {1, 1};
835 IUnknown* const present_queues[2] = {queue, queue};
836 const auto rejects_flag_change = [&](IDXGISwapChain3* chain, UINT flags) {
837 DXGI_SWAP_CHAIN_DESC1 before{}, after{};
838 if (FAILED(chain->GetDesc1(&before))) return false;
839 const UINT width = before.Width + 1;
840 return chain->ResizeBuffers(0, width, before.Height, DXGI_FORMAT_UNKNOWN, flags) == E_INVALIDARG &&
841 chain->ResizeBuffers1(2, width, before.Height, DXGI_FORMAT_UNKNOWN, flags,
842 node_masks, present_queues) == E_INVALIDARG &&
843 SUCCEEDED(chain->GetDesc1(&after)) && after.Flags == before.Flags &&
844 after.BufferCount == before.BufferCount && after.Width == before.Width &&
845 after.Height == before.Height;
846 };
847
781 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected. 848 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected.
849 for (UINT flags : {waitable_flag, tearing_flag, both_flags})
850 if (!rejects_flag_change(sc, flags)) return fail("Resize accepted adding a creation-only flag");
782 if (sc->GetFrameLatencyWaitableObject() != nullptr) 851 if (sc->GetFrameLatencyWaitableObject() != nullptr)
783 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject"); 852 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject");
784 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL) 853 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL)
785 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL"); 854 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL");
855 if (FAILED(sc->Present(0, 0))) return fail("Present after rejected resize on a plain swapchain");
786 856
787 HWND hwnd3 = create_test_window(128, 96); 857 HWND hwnd3 = create_test_window(128, 96);
788 if (!hwnd3) return fail("CreateWindowExW (third)"); 858 if (!hwnd3) return fail("CreateWindowExW (third)");
@@ -790,7 +860,7 @@ int main() {
790 wdesc.Width = 128; 860 wdesc.Width = 128;
791 wdesc.Height = 96; 861 wdesc.Height = 96;
792 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer 862 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer
793 wdesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; 863 wdesc.Flags = both_flags;
794 IDXGISwapChain1* wsc1 = nullptr; 864 IDXGISwapChain1* wsc1 = nullptr;
795 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1) 865 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1)
796 return fail("CreateSwapChainForHwnd (tearing + waitable)"); 866 return fail("CreateSwapChainForHwnd (tearing + waitable)");
@@ -798,6 +868,8 @@ int main() {
798 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)"); 868 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)");
799 wsc1->Release(); 869 wsc1->Release();
800 870
871 for (UINT flags : {0u, waitable_flag, tearing_flag})
872 if (!rejects_flag_change(wsc, flags)) return fail("Resize accepted removing a creation-only flag");
801 DXGI_SWAP_CHAIN_DESC1 got_desc{}; 873 DXGI_SWAP_CHAIN_DESC1 got_desc{};
802 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags) 874 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags)
803 return fail("Waitable swapchain GetDesc1 did not preserve Flags"); 875 return fail("Waitable swapchain GetDesc1 did not preserve Flags");
@@ -817,13 +889,134 @@ int main() {
817 return fail("Present(1, ALLOW_TEARING) should return DXGI_ERROR_INVALID_CALL"); 889 return fail("Present(1, ALLOW_TEARING) should return DXGI_ERROR_INVALID_CALL");
818 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING))) 890 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)))
819 return fail("Present(0, ALLOW_TEARING) on untouched 10-bit offscreen swapchain failed"); 891 return fail("Present(0, ALLOW_TEARING) on untouched 10-bit offscreen swapchain failed");
892 if (!check_statistics_disjoint(wsc)) return fail("first statistics query after Present should be disjoint");
820 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0) 893 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
821 return fail("Post-Present WaitForSingleObject on waitable swapchain failed"); 894 return fail("Post-Present WaitForSingleObject on waitable swapchain failed");
895 if (FAILED(wsc->ResizeBuffers(0, wdesc.Width + 1, wdesc.Height, DXGI_FORMAT_UNKNOWN, both_flags)) ||
896 FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Width != wdesc.Width + 1 || got_desc.Flags != both_flags)
897 return fail("ResizeBuffers with matching creation flags failed");
898 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)) ||
899 WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
900 return fail("Present or wait after resizing the waitable swapchain failed");
822 CloseHandle(waitable); 901 CloseHandle(waitable);
823 wsc->Release(); 902 wsc->Release();
824 DestroyWindow(hwnd3); 903 DestroyWindow(hwnd3);
825 } 904 }
826 905
906 // CreateSwapChainForCoreWindow & Occlusion status registration
907 {
908 // 1. Parameter validation
909 IDXGISwapChain1* sc_dummy = nullptr;
910 if (factory->CreateSwapChainForCoreWindow(queue, nullptr, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
911 return fail("CreateSwapChainForCoreWindow(null window) should return E_INVALIDARG");
912 if (factory->CreateSwapChainForCoreWindow(nullptr, queue, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
913 return fail("CreateSwapChainForCoreWindow(null device) should return E_INVALIDARG");
914 if (factory->CreateSwapChainForCoreWindow(queue, queue, nullptr, nullptr, &sc_dummy) != E_INVALIDARG)
915 return fail("CreateSwapChainForCoreWindow(null desc) should return E_INVALIDARG");
916 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, nullptr) != E_POINTER)
917 return fail("CreateSwapChainForCoreWindow(null out) should return E_POINTER");
918
919 // Non-CoreWindow IUnknown
920 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL)
921 return fail("CreateSwapChainForCoreWindow with non-CoreWindow should return DXGI_ERROR_INVALID_CALL");
922
923 // 2. Mock ICoreWindow with ICoreWindowInterop
924 static constexpr GUID kIID_ICoreWindowInterop = {
925 0x45D64A29, 0xA63E, 0x4CB6, {0xB4, 0x98, 0x57, 0x81, 0xD2, 0x98, 0xCB, 0x4F}};
926 struct MockCoreWindow final : public IUnknown {
927 HWND window_handle = nullptr;
928 std::atomic<ULONG> refs{1};
929
930 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
931 if (!out) return E_POINTER;
932 if (riid == IID_IUnknown || riid == kIID_ICoreWindowInterop) {
933 *out = this;
934 AddRef();
935 return S_OK;
936 }
937 *out = nullptr;
938 return E_NOINTERFACE;
939 }
940 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
941 ULONG STDMETHODCALLTYPE Release() override {
942 ULONG r = --refs;
943 if (!r) delete this;
944 return r;
945 }
946 virtual HRESULT STDMETHODCALLTYPE get_WindowHandle(HWND* hwnd) {
947 if (!hwnd) return E_POINTER;
948 *hwnd = window_handle;
949 return S_OK;
950 }
951 virtual HRESULT STDMETHODCALLTYPE put_MessageHandled(unsigned char) { return S_OK; }
952 };
953
954 auto* mock_cw = new MockCoreWindow();
955 // Null HWND in interop
956 if (factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL) {
957 mock_cw->Release();
958 return fail("CreateSwapChainForCoreWindow with null HWND should return DXGI_ERROR_INVALID_CALL");
959 }
960
961 // Valid HWND in mock CoreWindow
962 HWND hwnd4 = create_test_window(160, 120);
963 if (!hwnd4) {
964 mock_cw->Release();
965 return fail("CreateWindowExW (fourth)");
966 }
967 mock_cw->window_handle = hwnd4;
968 IDXGISwapChain1* cw_sc1 = nullptr;
969 if (FAILED(factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &cw_sc1)) || !cw_sc1) {
970 mock_cw->Release();
971 DestroyWindow(hwnd4);
972 return fail("CreateSwapChainForCoreWindow with valid MockCoreWindow failed");
973 }
974 IDXGISwapChain3* cw_sc = nullptr;
975 if (FAILED(cw_sc1->QueryInterface(IID_PPV_ARGS(&cw_sc))) || !cw_sc) {
976 cw_sc1->Release();
977 mock_cw->Release();
978 DestroyWindow(hwnd4);
979 return fail("QI IDXGISwapChain3 on CoreWindow swapchain failed");
980 }
981 cw_sc1->Release();
982 DXGI_SWAP_CHAIN_DESC1 cw_desc{};
983 if (FAILED(cw_sc->GetDesc1(&cw_desc)) || cw_desc.Width != scd.Width || cw_desc.Height != scd.Height) {
984 cw_sc->Release();
985 mock_cw->Release();
986 DestroyWindow(hwnd4);
987 return fail("GetDesc1 on CoreWindow swapchain mismatch");
988 }
989 if (FAILED(cw_sc->Present(0, 0))) {
990 cw_sc->Release();
991 mock_cw->Release();
992 DestroyWindow(hwnd4);
993 return fail("Present on CoreWindow swapchain failed");
994 }
995 cw_sc->Release();
996 mock_cw->Release();
997 DestroyWindow(hwnd4);
998
999 // 3. Occlusion status registration
1000 DWORD cookie1 = 0, cookie2 = 0;
1001 if (factory->RegisterOcclusionStatusWindow(nullptr, WM_USER, &cookie1) != DXGI_ERROR_INVALID_CALL)
1002 return fail("RegisterOcclusionStatusWindow(null hwnd) should return DXGI_ERROR_INVALID_CALL");
1003 if (factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, nullptr) != DXGI_ERROR_INVALID_CALL)
1004 return fail("RegisterOcclusionStatusWindow(null cookie) should return DXGI_ERROR_INVALID_CALL");
1005 if (FAILED(factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, &cookie1)) || cookie1 == 0)
1006 return fail("RegisterOcclusionStatusWindow failed");
1007
1008 HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1009 if (factory->RegisterOcclusionStatusEvent(nullptr, &cookie2) != DXGI_ERROR_INVALID_CALL)
1010 return fail("RegisterOcclusionStatusEvent(null event) should return DXGI_ERROR_INVALID_CALL");
1011 if (factory->RegisterOcclusionStatusEvent(ev, nullptr) != DXGI_ERROR_INVALID_CALL)
1012 return fail("RegisterOcclusionStatusEvent(null cookie) should return DXGI_ERROR_INVALID_CALL");
1013 if (FAILED(factory->RegisterOcclusionStatusEvent(ev, &cookie2)) || cookie2 == 0 || cookie2 == cookie1)
1014 return fail("RegisterOcclusionStatusEvent failed or duplicated cookie");
1015 factory->UnregisterOcclusionStatus(cookie1);
1016 factory->UnregisterOcclusionStatus(cookie2);
1017 CloseHandle(ev);
1018 }
1019
827 rtv_heap->Release(); 1020 rtv_heap->Release();
828 sc->Release(); 1021 sc->Release();
829 fence->Release(); 1022 fence->Release();
@@ -843,7 +1036,7 @@ int main() {
843 return 1; 1036 return 1;
844 } 1037 }
845 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off"); 1038 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off");
846 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, GetBuffer+GetDesc, clear+readback, Present, " 1039 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, CreateSwapChainForCoreWindow, occlusion status, "
847 "ResizeBuffers; 0 validation errors)\n"); 1040 "GetBuffer+GetDesc, clear+readback, Present, ResizeBuffers; 0 validation errors)\n");
848 return 0; 1041 return 0;
849} 1042}
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index c33098d2a..1fcaf6710 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -99,7 +99,7 @@ int main() {
99 write_path(package / "data" / "hello.txt", "package"); 99 write_path(package / "data" / "hello.txt", "package");
100 write_path(package / "data" / "dup.txt", "package"); 100 write_path(package / "data" / "dup.txt", "package");
101 write_path(package / "data" / "bye.txt", "package"); 101 write_path(package / "data" / "bye.txt", "package");
102 std::filesystem::create_directories(package / "data" / "sub"); 102 write_path(package / "data" / "sub" / "nested.txt", "nested");
103 103
104 rt::fs::configure(package, overlay); 104 rt::fs::configure(package, overlay);
105 check(rt::fs::game_dir() == package, "configure() sets the game folder"); 105 check(rt::fs::game_dir() == package, "configure() sets the game folder");
@@ -249,6 +249,15 @@ int main() {
249 SetLastError(0); 249 SetLastError(0);
250 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND, 250 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
251 "deleting a file that never existed reports ERROR_FILE_NOT_FOUND"); 251 "deleting a file that never existed reports ERROR_FILE_NOT_FOUND");
252
253 // Deleting a nested package file creates parent directories inside .gta6rt-deleted/; those marker parent
254 // directories must not hide the corresponding ancestor directories in the package.
255 check(delete_w(L"GAME:\\data\\sub\\nested.txt") != FALSE, "DeleteFileW accepts a nested package file");
256 const DWORD sub_attrs = attributes_w(L"GAME:\\data\\sub");
257 check(sub_attrs != INVALID_FILE_ATTRIBUTES && (sub_attrs & FILE_ATTRIBUTE_DIRECTORY) != 0,
258 "deleting a nested package file does not hide its parent folder");
259 check(contains(list(first_w, next_w, find_close, L"GAME:\\data\\*"), L"sub"),
260 "the parent folder stays listed after deleting a nested package file");
252 } 261 }
253 262
254 // Nothing leaves the package and the overlay. 263 // Nothing leaves the package and the overlay.
diff --git a/runtime/test/fsr_dispatch_test.cpp b/runtime/test/fsr_dispatch_test.cpp
index 7affaee7a..9a66071ac 100644
--- a/runtime/test/fsr_dispatch_test.cpp
+++ b/runtime/test/fsr_dispatch_test.cpp
@@ -28,7 +28,7 @@
28// driver refuses one of its textures (DXGI_FORMAT_R9G9B9E5_SHAREDEXP with ALLOW_UNORDERED_ACCESS); on WARP the 28// driver refuses one of its textures (DXGI_FORMAT_R9G9B9E5_SHAREDEXP with ALLOW_UNORDERED_ACCESS); on WARP the
29// context is created as is. The other backend ids are controls: they end in FFX_API_RETURN_ERROR before the device 29// context is created as is. The other backend ids are controls: they end in FFX_API_RETURN_ERROR before the device
30// is touched. In step 7 the dispatch is recorded up to the DLL's compute pipeline, which a PC device cannot create 30// is touched. In step 7 the dispatch is recorded up to the DLL's compute pipeline, which a PC device cannot create
31// (slot 67 is console-only and refused; slot 62's code is not a PC shader). The INFO lines are the measurement; the 31// (slot 67 and 62 codes are not PC shaders). The INFO lines are the measurement; the
32// PASS/FAIL checks only cover what is known to work. 32// PASS/FAIL checks only cover what is known to work.
33#include <windows.h> 33#include <windows.h>
34 34
@@ -958,7 +958,7 @@ int main() {
958 note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " + 958 note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " +
959 std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast<uint32_t>(g_slot62_hr))); 959 std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast<uint32_t>(g_slot62_hr)));
960 if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted)); 960 if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted));
961 // On a PC device both pipeline paths fail (67 is refused, 62's code is not a PC shader); on the 961 // On a PC device both pipeline paths fail (neither slot 67's nor 62's code is a PC shader); on the
962 // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes 962 // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes
963 // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10, 963 // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10,
964 // the same pointer it passes to SetPipelineState): a documented stop, not a test failure. 964 // the same pointer it passes to SetPipelineState): a documented stop, not a test failure.
diff --git a/runtime/test/gameinput_probe.cpp b/runtime/test/gameinput_probe.cpp
index aa077b257..32ddf5d91 100644
--- a/runtime/test/gameinput_probe.cpp
+++ b/runtime/test/gameinput_probe.cpp
@@ -85,12 +85,17 @@ int main(int argc, char** argv) {
85 if (input->GetCurrentReading(GameInputKindGamepad, nullptr, &r) == S_OK) { 85 if (input->GetCurrentReading(GameInputKindGamepad, nullptr, &r) == S_OK) {
86 GameInputGamepadState s{}; 86 GameInputGamepadState s{};
87 GameInputUiNavigationState ui{}; 87 GameInputUiNavigationState ui{};
88 GameInputMotionState m{};
89 const bool motion = r->GetMotionState(&m);
88 r->GetGamepadState(&s); 90 r->GetGamepadState(&s);
89 r->GetUiNavigationState(&ui); 91 r->GetUiNavigationState(&ui);
90 std::printf("\rbuttons=%04x ui=%06x LT=%.2f RT=%.2f L=(%+.2f,%+.2f) R=(%+.2f,%+.2f) seq=%llu ", s.buttons, 92 std::printf("\rbuttons=%04x ui=%06x LT=%.2f RT=%.2f L=(%+.2f,%+.2f) R=(%+.2f,%+.2f) seq=%llu ", s.buttons,
91 ui.buttons, s.leftTrigger, s.rightTrigger, s.leftThumbstickX, s.leftThumbstickY, 93 ui.buttons, s.leftTrigger, s.rightTrigger, s.leftThumbstickX, s.leftThumbstickY,
92 s.rightThumbstickX, s.rightThumbstickY, 94 s.rightThumbstickX, s.rightThumbstickY,
93 static_cast<unsigned long long>(r->GetSequenceNumber(GameInputKindGamepad))); 95 static_cast<unsigned long long>(r->GetSequenceNumber(GameInputKindGamepad)));
96 if (motion) // fractions of motionInfo's maxima: accel includes gravity, so a resting pad shows ~0.5 g
97 std::printf("\n[a]=(%+.2f,%+.2f,%+.2f) [w]=(%+.2f,%+.2f,%+.2f) ", m.accelerationX, m.accelerationY,
98 m.accelerationZ, m.angularVelocityX, m.angularVelocityY, m.angularVelocityZ);
94 std::fflush(stdout); 99 std::fflush(stdout);
95 r->Release(); 100 r->Release();
96 } 101 }
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index a0bcaf444..d1923ceaf 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -80,7 +80,7 @@ bool SDLCALL on_effect(void* u, const void* data, int size) {
80} 80}
81void SDLCALL on_player(void* u, int index) { static_cast<Pad*>(u)->player = index; } 81void SDLCALL on_player(void* u, int index) { static_cast<Pad*>(u)->player = index; }
82 82
83void attach(Pad& pad, const char* name, uint16_t vendor, uint16_t product, bool trigger_motors) { 83void attach(Pad& pad, const char* name, uint16_t vendor, uint16_t product, bool trigger_motors, bool sensors = false) {
84 SDL_VirtualJoystickDesc d; 84 SDL_VirtualJoystickDesc d;
85 SDL_INIT_INTERFACE(&d); 85 SDL_INIT_INTERFACE(&d);
86 d.type = SDL_JOYSTICK_TYPE_GAMEPAD; 86 d.type = SDL_JOYSTICK_TYPE_GAMEPAD;
@@ -97,6 +97,11 @@ void attach(Pad& pad, const char* name, uint16_t vendor, uint16_t product, bool
97 d.SetLED = on_led; 97 d.SetLED = on_led;
98 d.SendEffect = on_effect; 98 d.SendEffect = on_effect;
99 d.SetPlayerIndex = on_player; 99 d.SetPlayerIndex = on_player;
100 static const SDL_VirtualJoystickSensorDesc kSensors[] = {{SDL_SENSOR_GYRO, 250.0f}, {SDL_SENSOR_ACCEL, 250.0f}};
101 if (sensors) {
102 d.nsensors = 2;
103 d.sensors = kSensors;
104 }
100 pad.id = SDL_AttachVirtualJoystick(&d); 105 pad.id = SDL_AttachVirtualJoystick(&d);
101 pad.js = pad.id ? SDL_OpenJoystick(pad.id) : nullptr; 106 pad.js = pad.id ? SDL_OpenJoystick(pad.id) : nullptr;
102 if (pad.js) { // triggers at rest: the full-range virtual axis maps -32768 to 0 107 if (pad.js) { // triggers at rest: the full-range virtual axis maps -32768 to 0
@@ -206,6 +211,134 @@ bool sticks_at_rest(const GameInputGamepadState& st) {
206 st.rightThumbstickY == 0 && st.leftTrigger == 0 && st.rightTrigger == 0; 211 st.rightThumbstickY == 0 && st.leftTrigger == 0 && st.rightTrigger == 0;
207} 212}
208 213
214// ---- motion: SDL sensors through the shim ----
215void send_motion(Pad& pad, float ax, float ay, float az, float gx, float gy, float gz) {
216 const Uint64 ts = SDL_GetTicksNS();
217 const float accel[3] = {ax, ay, az};
218 const float gyro[3] = {gx, gy, gz};
219 SDL_SendJoystickVirtualSensorData(pad.js, SDL_SENSOR_ACCEL, ts, accel, 3);
220 SDL_SendJoystickVirtualSensorData(pad.js, SDL_SENSOR_GYRO, ts, gyro, 3);
221}
222
223GameInputMotionState motion_state(IGameInput* input, IGameInputDevice* dev, bool* ok = nullptr) {
224 GameInputMotionState ms{};
225 IGameInputReading* r = nullptr;
226 const bool got = input->GetCurrentReading(GameInputKindMotion, dev, &r) == S_OK && r && r->GetMotionState(&ms);
227 if (r) r->Release();
228 if (ok) *ok = got;
229 return ms;
230}
231
232void test_motion(IGameInput* input) {
233 const size_t events_before = g_device_events.size(); // other tests' events are still queued in the vector
234 Pad gyro_pad, plain;
235 attach(gyro_pad, "Leonida virtual gyro pad", 0x054C, 0x0CE6, false, true); // Sony ids, sensors on
236 attach(plain, "Leonida virtual plain pad", 0x045E, 0x02FF, false);
237 rt::gameinput::poll();
238 check(rt::gameinput::connected_count() == 2, "motion: both pads connected");
239 // The connect events for these two pads are the first two CONNECTED events after `events_before`, deduplicated
240 // by device: earlier test sections leave their device callbacks registered, so every connect is delivered more
241 // than once, and a disconnect from a previous test may be queued in between.
242 std::vector<IGameInputDevice*> found;
243 for (size_t i = events_before; i < g_device_events.size() && found.size() < 2; ++i) {
244 const DeviceEvent& e = g_device_events[i];
245 if (!(e.current & GameInputDeviceConnected)) continue;
246 if (std::find(found.begin(), found.end(), e.device) != found.end()) continue;
247 found.push_back(e.device);
248 }
249 IGameInputDevice* mdev = found.size() > 0 ? found[0] : nullptr; // attach order: gyro pad first
250 IGameInputDevice* pdev = found.size() > 1 ? found[1] : nullptr;
251 if (mdev) mdev->AddRef();
252 if (pdev) pdev->AddRef();
253 check(mdev && pdev, "motion: both device objects arrived");
254 if (!mdev || !pdev) return;
255
256 const GameInputDeviceInfo* mi = mdev->GetDeviceInfo();
257 const GameInputDeviceInfo* pi = pdev->GetDeviceInfo();
258 check((mi->supportedInput & GameInputKindMotion) != 0, "motion: the gyro pad reports GameInputKindMotion");
259 check((pi->supportedInput & GameInputKindMotion) == 0, "motion: the plain pad does not");
260 const GameInputMotionInfo* mmotion = static_cast<const GameInputMotionInfo*>(mi->motionInfo);
261 check(mmotion != nullptr && mmotion->maxAcceleration == 19.6133f && mmotion->maxAngularVelocity == 34.9066f &&
262 mmotion->maxMagneticFieldStrength == 0.0f,
263 "motion: motionInfo carries the shim's maxima (magnetometer unavailable)");
264 check(pi->motionInfo == nullptr, "motion: the plain pad's motionInfo is null");
265
266 // Before the first sensor sample arrives, SDL answers reads with zeros and the shim reports no motion at all.
267 IGameInputReading* r = nullptr;
268 GameInputMotionState unused{};
269 check(input->GetCurrentReading(GameInputKindGamepad, mdev, &r) == S_OK && r && !r->GetMotionState(&unused),
270 "motion: before the first sample, GetMotionState is false even on a sensor pad");
271 if (r) r->Release();
272
273 // 9.80665 m/s^2 is half of the 2 g maximum; 17.4533 rad/s is half of 2000 deg/s. A reading with the sample needs
274 // either a gamepad change or the ~8 ms motion cadence, so the test waits out the window before polling.
275 send_motion(gyro_pad, 0.0f, 0.0f, 9.80665f, 17.4533f, 0.0f, 0.0f);
276 Sleep(12);
277 rt::gameinput::poll();
278 bool got = false;
279 const GameInputMotionState ms = motion_state(input, mdev, &got);
280 check(got, "motion: GetMotionState true on a motion reading");
281 check(approx(ms.accelerationZ, 0.5f) && approx(ms.angularVelocityX, 0.5f),
282 "motion: accel and gyro normalised against the motionInfo maxima");
283 check(ms.accelerometerAccuracy == GameInputMotionAccuracyHigh && ms.gyroscopeAccuracy == GameInputMotionAccuracyHigh,
284 "motion: live sensors report High accuracy");
285 check(ms.magnetometerAccuracy == GameInputMotionAccuracyUnknown &&
286 ms.orientationAccuracy == GameInputMotionAccuracyUnknown,
287 "motion: sensors the shim does not provide report Unknown");
288
289 r = nullptr;
290 check(input->GetCurrentReading(GameInputKindMotion, pdev, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r,
291 "motion: a motion query on the plain pad is READING_NOT_FOUND");
292 check(input->GetCurrentReading(GameInputKindGamepad, mdev, &r) == S_OK && r && !r->GetMotionState(nullptr) &&
293 (r->GetInputKind() & GameInputKindMotion),
294 "motion: GetMotionState(nullptr) is false; the gyro pad's reading kind includes Motion");
295 if (r) r->Release();
296 unused = {};
297 check(input->GetCurrentReading(GameInputKindGamepad, pdev, &r) == S_OK && r &&
298 !(r->GetInputKind() & GameInputKindMotion) && !r->GetMotionState(&unused),
299 "motion: the plain pad's reading has no motion kind and GetMotionState is false");
300 if (r) r->Release();
301
302 send_motion(gyro_pad, 100.0f, -100.0f, 0.0f, 0.0f, 0.0f, -100.0f);
303 Sleep(12);
304 rt::gameinput::poll();
305 const GameInputMotionState sat = motion_state(input, mdev);
306 check(sat.accelerationX == 1.0f && sat.accelerationY == -1.0f && sat.angularVelocityZ == -1.0f,
307 "motion: out-of-range sensor values clamp to the +-1 fraction range");
308
309 // The cadence: with the buttons idle, a changed gyro yields a new reading only once per ~8 ms window, not one
310 // per poll, so the history still spans the half second it is documented for.
311 send_motion(gyro_pad, 0.0f, 0.0f, 9.80665f, 0.0f, 0.0f, 0.0f);
312 rt::gameinput::poll();
313 IGameInputReading* first = nullptr;
314 check(input->GetCurrentReading(GameInputKindMotion, mdev, &first) == S_OK && first,
315 "motion: a reading exists after a sensor update");
316 send_motion(gyro_pad, 0.0f, 0.0f, 9.80665f, 34.9066f, 0.0f, 0.0f); // gravity stays: zero accel means "no sample"
317 rt::gameinput::poll();
318 IGameInputReading* none = nullptr;
319 check(input->GetNextReading(first, GameInputKindMotion, mdev, &none) == GAMEINPUT_E_READING_NOT_FOUND && !none,
320 "motion: no new reading within the 8 ms cadence window");
321 Sleep(12);
322 rt::gameinput::poll();
323 IGameInputReading* next = nullptr;
324 check(input->GetNextReading(first, GameInputKindMotion, mdev, &next) == S_OK && next,
325 "motion: after the window the latest sensor state is in a new reading");
326 if (next) {
327 GameInputMotionState later{};
328 check(next->GetMotionState(&later) && approx(later.angularVelocityX, 1.0f),
329 "motion: the new reading carries the newest gyro sample");
330 next->Release();
331 }
332 if (first) first->Release();
333
334 detach(gyro_pad);
335 detach(plain);
336 rt::gameinput::poll();
337 if (mdev) mdev->Release();
338 if (pdev) pdev->Release();
339 check(rt::gameinput::connected_count() == 0, "motion: both pads closed again");
340}
341
209// WASD, the mouse and its buttons. Runs in the focused mode with focus and nothing held. 342// WASD, the mouse and its buttons. Runs in the focused mode with focus and nothing held.
210void test_keyboard_pad_sticks(IGameInput* input, IGameInputDevice* kb) { 343void test_keyboard_pad_sticks(IGameInput* input, IGameInputDevice* kb) {
211 rt::gameinput::poll(); 344 rt::gameinput::poll();
@@ -965,6 +1098,7 @@ int main() {
965 1098
966 test_twins(input); 1099 test_twins(input);
967 test_keyboard_pad(input); 1100 test_keyboard_pad(input);
1101 test_motion(input);
968 input->Release(); 1102 input->Release();
969 1103
970 std::printf("%d checks, %d failures\n", g_checks, g_failures); 1104 std::printf("%d checks, %d failures\n", g_checks, g_failures);
diff --git a/runtime/test/glsl/cs_set0_sample.comp b/runtime/test/glsl/cs_set0_sample.comp
new file mode 100644
index 000000000..f007da556
--- /dev/null
+++ b/runtime/test/glsl/cs_set0_sample.comp
@@ -0,0 +1,77 @@
1#version 460
2// A compute shader that samples through set 0 the way translated shaders do, written to the translator's runtime
3// contract (docs/design.md, "User data", "Xbox GPU addresses" and "Images"; the lookup is tools/rdna2spirv.py
4// desc_probe), standing in for a translated one in d3d12_set0_compute_test. Its root arguments:
5// s0 a root constant: where the view slot to sample starts inside the view table, in dwords
6// s1 a root constant: the first element of the output it writes
7// s2:s3 a root UAV: the console VA of the output buffer
8// s4:s5 a descriptor table of views: a T# in the first eight dwords of each slot
9// s6:s7 a descriptor table of samplers: the S# of its first slot, four dwords
10// It loads the T# and the S# from the tables at heap base + VA, looks both up in the hash table at set 0 binding 2
11// (FNV-1a over the eight key dwords, eight probes, a miss is index 0; an S# key is its four dwords and four of
12// 0xFFFFFFFF), samples the 2D image array at binding 0 with the sampler array at binding 1, and writes
13// out[s1 + i] = the texel at ((i % 8) + 0.5, (i / 8) + 0.5) / 8 + (1, 0), as RGBA8 with red in the low byte.
14// The whole tile to the right in U: a sampler that wraps in U gives the texel at the same place in the image, one
15// that clamps gives the image's right edge. So the result depends on the S# as well as on the T#.
16// Set 0 is the device's bindless set. The D3D12 layer has it in the pipeline layout and binds it at the dispatch,
17// because the index lists bindings for this shader; nothing else in the test binds it.
18#extension GL_EXT_nonuniform_qualifier : require
19#extension GL_EXT_buffer_reference : require
20#extension GL_EXT_buffer_reference_uvec2 : require
21
22layout(local_size_x = 64) in;
23
24layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words {
25 uint w[];
26};
27
28layout(push_constant) uniform UserData {
29 uint s[32];
30 uvec2 heap_base;
31 uvec2 code_base;
32} pc;
33
34layout(set = 0, binding = 0) uniform texture2D images[];
35layout(set = 0, binding = 1) uniform sampler samplers[];
36layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap {
37 uint map[]; // mask, then 10 uints per slot: key[8], index, pad
38};
39
40uvec2 add64(uvec2 a, uvec2 b) {
41 uint carry;
42 const uint low = uaddCarry(a.x, b.x, carry);
43 return uvec2(low, a.y + b.y + carry);
44}
45
46Words at(uvec2 va) {
47 return Words(add64(pc.heap_base, va));
48}
49
50uint lookup(uint key[8]) {
51 uint h = 2166136261u;
52 for (int i = 0; i < 8; ++i) h = (h ^ key[i]) * 16777619u;
53 const uint mask = map[0];
54 for (uint k = 0; k < 8; ++k) {
55 const uint slot = 1 + ((h + k) & mask) * 10;
56 bool same = true;
57 for (int i = 0; i < 8; ++i) same = same && map[slot + i] == key[i];
58 if (same) return map[slot + 8];
59 }
60 return 0;
61}
62
63void main() {
64 const uint i = gl_GlobalInvocationID.x;
65 Words views = at(uvec2(pc.s[4], pc.s[5]));
66 Words sampler_table = at(uvec2(pc.s[6], pc.s[7]));
67 uint image_key[8], sampler_key[8];
68 for (int k = 0; k < 8; ++k) {
69 image_key[k] = views.w[pc.s[0] + k];
70 sampler_key[k] = k < 4 ? sampler_table.w[k] : 0xffffffffu;
71 }
72 const uint image = lookup(image_key), smp = lookup(sampler_key);
73 const vec2 uv = (vec2(i % 8, i / 8) + 0.5) / 8.0 + vec2(1.0, 0.0);
74 const vec4 texel = textureLod(sampler2D(images[image], samplers[smp]), uv, 0.0);
75 Words result = at(uvec2(pc.s[2], pc.s[3]));
76 result.w[pc.s[1] + i] = packUnorm4x8(texel);
77}
diff --git a/runtime/test/glsl/cs_sg_probe.comp b/runtime/test/glsl/cs_sg_probe.comp
new file mode 100644
index 000000000..921cf1a49
--- /dev/null
+++ b/runtime/test/glsl/cs_sg_probe.comp
@@ -0,0 +1,29 @@
1#version 460
2// A compute shader written to the translator's runtime contract that stores the subgroup size the driver ran it
3// with (gl_SubgroupSize) in out[0], for d3d12_subgroup_test. s0:s1 is a root UAV: the console VA of the output.
4#extension GL_EXT_buffer_reference : require
5#extension GL_EXT_buffer_reference_uvec2 : require
6#extension GL_KHR_shader_subgroup_basic : require
7
8layout(local_size_x = 64) in;
9
10layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words {
11 uint w[];
12};
13
14layout(push_constant) uniform UserData {
15 uint s[32];
16 uvec2 heap_base;
17 uvec2 code_base;
18} pc;
19
20uvec2 add64(uvec2 a, uvec2 b) {
21 uint carry;
22 const uint low = uaddCarry(a.x, b.x, carry);
23 return uvec2(low, a.y + b.y + carry);
24}
25
26void main() {
27 Words out_words = Words(add64(pc.heap_base, uvec2(pc.s[0], pc.s[1])));
28 if (gl_LocalInvocationIndex == 0u) out_words.w[0] = gl_SubgroupSize;
29}
diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp
index a932cc086..82779ccb1 100644
--- a/runtime/test/glsl/cs_user_data.comp
+++ b/runtime/test/glsl/cs_user_data.comp
@@ -36,8 +36,20 @@ Words at(uvec2 va) {
36void main() { 36void main() {
37 const uint i = gl_GlobalInvocationID.x; 37 const uint i = gl_GlobalInvocationID.x;
38 Words table = at(uvec2(pc.s[4], pc.s[5])); 38 Words table = at(uvec2(pc.s[4], pc.s[5]));
39 Words result = at(uvec2(pc.s[2], pc.s[3]));
40 if (pc.s[1] == 0u) {
41 // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView.
42 const uint num_records = table.w[2];
43 const uint byte_off = pc.s[0] + i * 4u;
44 if (byte_off + 4u <= num_records) {
45 Words cbv = at(uvec2(table.w[0], table.w[1] & 0xFFFFu));
46 result.w[i] = cbv.w[byte_off >> 2u];
47 } else {
48 result.w[i] = 0u;
49 }
50 return;
51 }
39 Words constants = at(uvec2(table.w[0], table.w[1])); 52 Words constants = at(uvec2(table.w[0], table.w[1]));
40 Words code = at(pc.code_base); 53 Words code = at(pc.code_base);
41 Words result = at(uvec2(pc.s[2], pc.s[3]));
42 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1]; 54 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1];
43} 55}
diff --git a/runtime/test/glsl/ps_sg_probe.frag b/runtime/test/glsl/ps_sg_probe.frag
new file mode 100644
index 000000000..7b4f74e1a
--- /dev/null
+++ b/runtime/test/glsl/ps_sg_probe.frag
@@ -0,0 +1,11 @@
1#version 460
2// A pixel shader that outputs the subgroup size the driver ran it with, (0x40000000 | gl_SubgroupSize, 0x40000000 |
3// gl_SubgroupInvocationID, ...) as float bit patterns (the or keeps them normal floats), for d3d12_subgroup_test.
4#extension GL_KHR_shader_subgroup_basic : require
5
6layout(location = 0) out vec4 target;
7
8void main() {
9 target = uintBitsToFloat(uvec4(0x40000000u | gl_SubgroupSize, 0x40000000u | gl_SubgroupInvocationID, 0x40000000u,
10 0x40000000u));
11}
diff --git a/runtime/test/glsl/vs_sg_fullscreen.vert b/runtime/test/glsl/vs_sg_fullscreen.vert
new file mode 100644
index 000000000..80e4b203a
--- /dev/null
+++ b/runtime/test/glsl/vs_sg_fullscreen.vert
@@ -0,0 +1,6 @@
1#version 460
2// One triangle that covers the whole viewport, from gl_VertexIndex alone, for d3d12_subgroup_test.
3void main() {
4 const vec2 p = vec2(float((gl_VertexIndex << 1) & 2), float(gl_VertexIndex & 2));
5 gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
6}
diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp
index 4c78835bb..8f35a8ef7 100644
--- a/runtime/test/process_cmdline_test.cpp
+++ b/runtime/test/process_cmdline_test.cpp
@@ -1,10 +1,14 @@
1// The process shim's command line round-trips: what GetCommandLineW says must parse with CommandLineToArgvW (the 1// The process shim's command line round-trips: what GetCommandLineW says must parse with CommandLineToArgvW (the
2// documented rules the CRT's argv parser shares) back to the __wargv the shim hands out, and __wargv must hold what 2// documented rules the CRT's argv parser shares) back to the __wargv the shim hands out, and __wargv must hold what
3// main.cpp passed, whatever the system code page (RT-84). No game files. 3// main.cpp passed, whatever the system code page (RT-84). The WinMain line (lpCmdLine) is the game's too, and the
4// command line and ExitProcess are served under kernelbase.dll and the API-set names as well as kernel32.dll.
5// No game files.
4#include <windows.h> 6#include <windows.h>
5#include <shellapi.h> 7#include <shellapi.h>
6 8
7#include <cstdio> 9#include <cstdio>
10#include <cstring>
11#include <cwchar>
8#include <string> 12#include <string>
9#include <vector> 13#include <vector>
10 14
@@ -54,6 +58,60 @@ void check_non_ascii(const std::wstring& want, const char* what) {
54 ++failures; 58 ++failures;
55 } 59 }
56} 60}
61
62// An executable can import GetCommandLineA/W and ExitProcess from kernel32.dll, kernelbase.dll or the API set its
63// umbrella library names, and the loader matches the DLL name exactly: every name must hand out the same shim.
64void check_import_names() {
65 for (const char* dll : {"kernelbase.dll", "api-ms-win-core-processenvironment-l1-1-0.dll"})
66 for (const char* name : {"GetCommandLineA", "GetCommandLineW"}) {
67 void* fn = rt::shims::find(dll, name);
68 if (!fn || fn != rt::shims::find("kernel32.dll", name)) {
69 std::fprintf(stderr, "FAIL %s!%s is not the kernel32.dll shim\n", dll, name);
70 ++failures;
71 }
72 }
73 for (const char* dll : {"kernelbase.dll", "api-ms-win-core-processthreads-l1-1-0.dll"}) {
74 void* fn = rt::shims::find(dll, "ExitProcess");
75 if (!fn || fn != rt::shims::find("kernel32.dll", "ExitProcess")) {
76 std::fprintf(stderr, "FAIL %s!ExitProcess is not the kernel32.dll shim\n", dll);
77 ++failures;
78 }
79 }
80 for (const char* dll : {"api-ms-win-crt-runtime-l1-1-0.dll", "ucrtbase.dll", "ucrtbased.dll"})
81 for (const char* name : {"_get_narrow_winmain_command_line", "_get_wide_winmain_command_line"})
82 if (!rt::shims::find(dll, name)) {
83 std::fprintf(stderr, "FAIL %s!%s is not shimmed\n", dll, name);
84 ++failures;
85 }
86}
87
88// lpCmdLine as the CRT's WinMain startup gets it from _get_wide/_get_narrow_winmain_command_line: the game's command
89// line after the program name and the blanks that follow it (the narrow one in the ANSI code page).
90void check_winmain(const std::wstring& program, const std::vector<std::wstring>& args, const wchar_t* want,
91 const char* what) {
92 rt::process::set_command_line(program, args);
93 using Wide = wchar_t*(__cdecl*)();
94 using Narrow = char*(__cdecl*)();
95 for (const char* dll : {"api-ms-win-crt-runtime-l1-1-0.dll", "ucrtbase.dll"}) {
96 const auto wide_fn = reinterpret_cast<Wide>(rt::shims::find(dll, "_get_wide_winmain_command_line"));
97 const auto narrow_fn = reinterpret_cast<Narrow>(rt::shims::find(dll, "_get_narrow_winmain_command_line"));
98 if (!wide_fn || !narrow_fn) continue; // check_import_names has reported the missing shim
99 const wchar_t* wide = wide_fn();
100 const char* line = narrow_fn();
101 char expected[256] = {};
102 WideCharToMultiByte(CP_ACP, 0, want, -1, expected, sizeof(expected), nullptr, nullptr);
103 if (!wide || std::wcscmp(wide, want) != 0) {
104 std::fwprintf(stderr, L"FAIL %hs (%hs): the wide WinMain line is [%ls], want [%ls]\n", what, dll,
105 wide ? wide : L"(null)", want);
106 ++failures;
107 }
108 if (!line || std::strcmp(line, expected) != 0) {
109 std::fprintf(stderr, "FAIL %s (%s): the narrow WinMain line is [%s], want [%s]\n", what, dll,
110 line ? line : "(null)", expected);
111 ++failures;
112 }
113 }
114}
57} // namespace 115} // namespace
58 116
59int main() { 117int main() {
@@ -67,8 +125,16 @@ int main() {
67 // Greek, Cyrillic and CJK together: no single-byte code page holds all of them, so this covers every PC. 125 // Greek, Cyrillic and CJK together: no single-byte code page holds all of them, so this covers every PC.
68 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page"); 126 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page");
69 127
128 check_import_names();
129 check_winmain(L"game.exe", {L"-foo", L"with space"}, L"-foo \"with space\"", "arguments after a plain name");
130 check_winmain(L"C:\\My Games\\game.exe", {L"-x"}, L"-x", "a quoted program name with a space");
131 check_winmain(L"game.exe", {}, L"", "no arguments");
132 // A byte above 0x7f in the narrow program name is part of the name, not the end of it.
133 check_winmain(L"caf\u00e9.exe", {L"-x"}, L"-x", "a non-ASCII program name");
134
70 if (failures) return 1; 135 if (failures) return 1;
71 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u)\n", 136 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u); "
137 "the WinMain line and the kernelbase/API-set names are the game's\n",
72 GetACP()); 138 GetACP());
73 return 0; 139 return 0;
74} 140}
diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp
index 23a550685..69c1c26bd 100644
--- a/runtime/test/queue_proxy_test.cpp
+++ b/runtime/test/queue_proxy_test.cpp
@@ -33,6 +33,7 @@
33#include <cstring> 33#include <cstring>
34#include <cwchar> 34#include <cwchar>
35#include <iterator> 35#include <iterator>
36#include <mutex>
36#include <string> 37#include <string>
37#include <system_error> 38#include <system_error>
38#include <thread> 39#include <thread>
@@ -822,29 +823,37 @@ ChildRun run_process(const wchar_t* exe, const wchar_t* arguments, DWORD limit_m
822 RunnerFault fault = RunnerFault::none) { 823 RunnerFault fault = RunnerFault::none) {
823 ChildRun run; 824 ChildRun run;
824 std::wstring command = L"\"" + std::wstring(exe) + L"\" " + arguments; 825 std::wstring command = L"\"" + std::wstring(exe) + L"\" " + arguments;
825 SECURITY_ATTRIBUTES inherit{sizeof(inherit), nullptr, TRUE}; 826 // Both ends are made uninheritable. The write end becomes inheritable only while the start lock is held, just for
827 // its own child's CreateProcessW: children are started from several threads at once (check_differential), and a
828 // write end inheritable at any other time would also go to a sibling started meanwhile, which would then keep this
829 // pipe open after this child ended.
826 HANDLE read_end = nullptr, write_end = nullptr; 830 HANDLE read_end = nullptr, write_end = nullptr;
827 if (fault == RunnerFault::pipe) SetLastError(ERROR_NOT_ENOUGH_MEMORY); 831 if (fault == RunnerFault::pipe) SetLastError(ERROR_NOT_ENOUGH_MEMORY);
828 if (fault == RunnerFault::pipe || !CreatePipe(&read_end, &write_end, &inherit, 0)) { 832 if (fault == RunnerFault::pipe || !CreatePipe(&read_end, &write_end, nullptr, 0)) {
829 report_runner_error("CreatePipe"); 833 report_runner_error("CreatePipe");
830 return run; 834 return run;
831 } 835 }
832 if (!SetHandleInformation(read_end, HANDLE_FLAG_INHERIT, 0)) {
833 report_runner_error("SetHandleInformation");
834 CloseHandle(read_end);
835 CloseHandle(write_end);
836 return run;
837 }
838 STARTUPINFOW startup{sizeof(startup)}; 836 STARTUPINFOW startup{sizeof(startup)};
839 startup.dwFlags = STARTF_USESTDHANDLES; 837 startup.dwFlags = STARTF_USESTDHANDLES;
840 startup.hStdOutput = write_end; 838 startup.hStdOutput = write_end;
841 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); 839 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
842 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); 840 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
843 PROCESS_INFORMATION process{}; 841 PROCESS_INFORMATION process{};
844 const BOOL started = 842 BOOL started = FALSE;
845 CreateProcessW(exe, command.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &process); 843 DWORD start_error = 0;
846 const DWORD start_error = GetLastError(); 844 {
847 CloseHandle(write_end); // the child holds the only write end now: the reader sees the pipe end when it is gone 845 static std::mutex start_lock;
846 const std::lock_guard<std::mutex> hold(start_lock);
847 if (!SetHandleInformation(write_end, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) {
848 report_runner_error("SetHandleInformation");
849 CloseHandle(read_end);
850 CloseHandle(write_end);
851 return run;
852 }
853 started = CreateProcessW(exe, command.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &process);
854 start_error = GetLastError();
855 CloseHandle(write_end); // the child holds the only write end now: the reader sees the pipe end when it is gone
856 }
848 if (!started) { 857 if (!started) {
849 std::fprintf(stderr, "child runner: CreateProcessW \"%ls\" failed (error %lu)\n", exe, start_error); 858 std::fprintf(stderr, "child runner: CreateProcessW \"%ls\" failed (error %lu)\n", exe, start_error);
850 CloseHandle(read_end); 859 CloseHandle(read_end);
@@ -1044,14 +1053,49 @@ int check_child_runner() {
1044 return 0; 1053 return 0;
1045} 1054}
1046 1055
1056// How many differential children run at once: LEONIDA_QUEUE_PROXY_JOBS when set (1 = one after another, as before),
1057// else half the logical processors, from 1 to 8. Each child pays its own device start-up (about 5 s each on an AMD
1058// RDNA2 iGPU, TEST-242), and that waiting is what running them side by side hides.
1059unsigned differential_jobs() {
1060 char value[16] = {};
1061 const DWORD length = GetEnvironmentVariableA("LEONIDA_QUEUE_PROXY_JOBS", value, sizeof(value));
1062 if (length > 0 && length < sizeof(value)) { // set, and short enough to be a number
1063 const unsigned long jobs = std::strtoul(value, nullptr, 10);
1064 if (jobs >= 1 && jobs <= 64) return static_cast<unsigned>(jobs);
1065 }
1066 const unsigned half = std::thread::hardware_concurrency() / 2;
1067 return half < 1 ? 1 : half > 8 ? 8 : half;
1068}
1069
1047// Each case, in a child process for the real object and in another for the proxy: the same HRESULT, the device 1070// Each case, in a child process for the real object and in another for the proxy: the same HRESULT, the device
1048// removed (or not) alike, and no validation errors. A case the real runtime faults on is reported, not compared. 1071// removed (or not) alike, and no validation errors. A case the real runtime faults on is reported, not compared.
1072// The children run differential_jobs() at a time; the results are judged afterwards in case order, so the report is
1073// the same as one child after another would give (a proxy child whose real one faulted is run but not judged).
1049int check_differential(const Backend& b) { 1074int check_differential(const Backend& b) {
1050 const char* label = b.label; 1075 const char* label = b.label;
1051 int compared = 0, faulting = 0; 1076 int compared = 0, faulting = 0;
1052 for (int i = 0; i < static_cast<int>(std::size(kDiffCases)); ++i) { 1077 constexpr int kCases = static_cast<int>(std::size(kDiffCases));
1078 std::vector<ChildResult> results(2 * kCases); // [2 * case] real, [2 * case + 1] proxy
1079 {
1080 std::atomic<int> next{0};
1081 const auto work = [&] {
1082 for (int job; (job = next.fetch_add(1)) < 2 * kCases;)
1083 results[job] = run_child(b.kind, job / 2, job % 2 == 1);
1084 };
1085 const unsigned jobs = differential_jobs();
1086 std::vector<std::thread> pool;
1087 try {
1088 for (unsigned t = 1; t < jobs; ++t) pool.emplace_back(work);
1089 } catch (const std::system_error& e) { // fewer helpers; this thread still runs every job left
1090 std::fprintf(stderr, "%s: %zu of %u differential runner threads (%s)\n", label, pool.size() + 1, jobs,
1091 e.what());
1092 }
1093 work();
1094 for (std::thread& t : pool) t.join();
1095 }
1096 for (int i = 0; i < kCases; ++i) {
1053 const char* name = kDiffCases[i].name; 1097 const char* name = kDiffCases[i].name;
1054 const ChildResult want = run_child(b.kind, i, false); 1098 const ChildResult& want = results[2 * i];
1055 if (!want.ok) { 1099 if (!want.ok) {
1056 std::fprintf(stderr, "%s: %s: the real-object child did not report\n", label, name); 1100 std::fprintf(stderr, "%s: %s: the real-object child did not report\n", label, name);
1057 return 1; 1101 return 1;
@@ -1061,7 +1105,7 @@ int check_differential(const Backend& b) {
1061 ++faulting; 1105 ++faulting;
1062 continue; 1106 continue;
1063 } 1107 }
1064 const ChildResult got = run_child(b.kind, i, true); 1108 const ChildResult& got = results[2 * i + 1];
1065 if (!got.ok || !got.ran || got.hr != want.hr || got.removed != want.removed || got.validation || 1109 if (!got.ok || !got.ran || got.hr != want.hr || got.removed != want.removed || got.validation ||
1066 want.validation) { 1110 want.validation) {
1067 std::fprintf(stderr, 1111 std::fprintf(stderr,
diff --git a/runtime/test/resource_tiling_test.cpp b/runtime/test/resource_tiling_test.cpp
index 4634f6830..4e0f39d48 100644
--- a/runtime/test/resource_tiling_test.cpp
+++ b/runtime/test/resource_tiling_test.cpp
@@ -6,6 +6,7 @@
6#include "../src/resource_tiling.h" 6#include "../src/resource_tiling.h"
7 7
8#include <cstdio> 8#include <cstdio>
9#include <tuple>
9 10
10#define CHECK(condition) do { \ 11#define CHECK(condition) do { \
11 if (!(condition)) { \ 12 if (!(condition)) { \
@@ -176,6 +177,20 @@ int main() {
176 } 177 }
177 } 178 }
178 179
180 // 2D 4x MSAA: tile shape divides by 4 in texels, 1 mip only, unsupported sample counts fail.
181 for (const auto& ms : {std::tuple{1u, 128u, 128u, 4u}, std::tuple{2u, 128u, 64u, 8u},
182 std::tuple{4u, 64u, 64u, 16u}, std::tuple{8u, 64u, 32u, 32u},
183 std::tuple{16u, 32u, 32u, 64u}}) {
184 const auto [bytes, sw, sh, want_tiles] = ms;
185 CHECK(resource_tiling({TiledKind::texture2d, 256, 256, 1, 1, bytes, 1, 4}, t));
186 CHECK(t.shape.width == sw && t.shape.height == sh && t.shape.depth == 1 && t.total_tiles == want_tiles);
187 }
188 CHECK(resource_tiling({TiledKind::texture2d, 64, 64, 1, 1, 1, 1, 4}, t) && t.total_tiles == 1);
189 CHECK(!resource_tiling({TiledKind::texture2d, 256, 256, 1, 1, 4, 1, 2}, t));
190 CHECK(!resource_tiling({TiledKind::texture2d, 256, 256, 1, 1, 4, 1, 8}, t));
191 CHECK(!resource_tiling({TiledKind::texture2d, 256, 256, 1, 2, 4, 1, 4}, t));
192 CHECK(!resource_tiling({TiledKind::texture3d, 64, 64, 16, 1, 4, 1, 4}, t));
193
179 // Element sizes that have no tile shape, and empty descriptions. 194 // Element sizes that have no tile shape, and empty descriptions.
180 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 1, 12, 1}, t)); 195 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 1, 12, 1}, t));
181 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 0, 4, 1}, t)); 196 CHECK(!resource_tiling({TiledKind::texture2d, 64, 64, 1, 0, 4, 1}, t));
diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp
index d0794ddbd..261004328 100644
--- a/runtime/test/root_signature_oracle_test.cpp
+++ b/runtime/test/root_signature_oracle_test.cpp
@@ -120,6 +120,48 @@ int main() {
120 const PackResult packed = pack(model); 120 const PackResult packed = pack(model);
121 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords"); 121 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords");
122 122
123 // The descriptor count and range offset are independent. The final SRV range is unbounded
124 // and begins immediately after the fixed range, but the whole table still occupies one GPU address.
125 {
126 D3D12_DESCRIPTOR_RANGE1 ranges[] = {
127 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 2, 3, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC, 0},
128 {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, UINT32_MAX, 7, 1,
129 D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND},
130 };
131 D3D12_ROOT_PARAMETER1 table_and_constants[2] = {{}, params[0]};
132 auto& table = table_and_constants[0];
133 table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
134 table.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
135 table.DescriptorTable = {2, ranges};
136 const auto unbounded_desc = make_desc(table_and_constants, 2);
137 Blobs unbounded;
138 const HRESULT result =
139 D3D12SerializeVersionedRootSignature(&unbounded_desc, &unbounded.blob, &unbounded.error);
140 check(result == S_OK, "Microsoft serializer accepts an unbounded SRV range");
141 RootSignature table_model;
142 if (SUCCEEDED(result) && unbounded.blob &&
143 parse_blob(unbounded.blob, table_model) && table_model.params.size() == 2 &&
144 table_model.params[0].ranges.size() == 2) {
145 const auto& fixed = table_model.params[0].ranges[0];
146 const auto& tail = table_model.params[0].ranges[1];
147 check(table_model.params[0].type == ParamType::Table &&
148 table_model.params[0].visibility == Visibility::Pixel &&
149 fixed.num_descriptors == 2 && fixed.offset_in_table == 0 &&
150 tail.range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV &&
151 tail.num_descriptors == UINT32_MAX && tail.base_shader_register == 7 &&
152 tail.register_space == 1 && tail.flags == D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE &&
153 tail.offset_in_table == kRangeOffsetAppend,
154 "fixed and unbounded SRV ranges survive native serialization");
155 const auto table_pack = pack(table_model);
156 check(table_pack.ok && table_pack.d3d12_cost == 5 && table_pack.dword_count == 6 &&
157 table_pack.provenance.size() == 6 &&
158 table_pack.provenance[1].param_index == 0 && table_pack.provenance[2].param_index == 1,
159 "unbounded SRV table occupies two SGPRs before the following constants");
160 } else {
161 check(false, "native unbounded table parses with two ranges and two parameters");
162 }
163 }
164
123 // Static samplers, one signature per version: every field round-trips through the real serializer, and 1.2 165 // Static samplers, one signature per version: every field round-trips through the real serializer, and 1.2
124 // adds D3D12_STATIC_SAMPLER_DESC1::Flags (a 14th dword) to each sampler record. Each also carries a table and a 166 // adds D3D12_STATIC_SAMPLER_DESC1::Flags (a 14th dword) to each sampler record. Each also carries a table and a
125 // root descriptor, so the 1.1/1.2 descriptor and range flags sit between the samplers and the header. 167 // root descriptor, so the 1.1/1.2 descriptor and range flags sit between the samplers and the header.
diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp
new file mode 100644
index 000000000..6e3e6be94
--- /dev/null
+++ b/runtime/test/shader_library_corpus_test.cpp
@@ -0,0 +1,159 @@
1// The runtime's shader lookup (src/shader_library.h) over a translated corpus from the player's own copy.
2//
3// LEONIDA_SHADERS=<work>/shaders/spirv the translator's output (index.json and the .spv modules)
4// LEONIDA_SHADER_DXBC=<work>/shaders/dxbc optional; the carved DXBC containers, default <spirv>/../dxbc
5//
6// For every container the test does what d3d12_vulkan_device.cpp does with a PSO's bytecode: inflate the FSSM program
7// from the DXIL/XDAT/XBCH entry, hash it and look it up under the container's stage. The stage comes from the DXIL
8// part's program header, not from index.json. Every container has to resolve to its own entry (the one named after
9// the file, or one of its `~N` duplicates) with a readable SPIR-V module, and every index entry has to be reached by
10// a container. Containers with more than one 0x0D payload are counted, and their first payload must not stand in for
11// the last: that is the rule fssm_program follows, so a regression to the first payload fails here.
12//
13// Without LEONIDA_SHADERS it prints SKIP and exits 77 (SKIP_RETURN_CODE). It reads the work folder in place, writes
14// nothing, and prints counts; on a failure it names at most a few shaders, which stay on your machine.
15#include "../src/shader_library.h"
16
17#include <cstdio>
18#include <cstdlib>
19#include <filesystem>
20#include <fstream>
21#include <set>
22#include <string>
23#include <vector>
24
25namespace {
26
27namespace fs = std::filesystem;
28
29std::string env(const char* name) {
30 const char* value = std::getenv(name);
31 return value ? value : "";
32}
33
34std::vector<std::uint8_t> read_file(const fs::path& path) {
35 std::ifstream file(path, std::ios::binary);
36 return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
37}
38
39std::uint32_t u32(std::span<const std::uint8_t> data, std::size_t at) {
40 if (at + 4 > data.size()) return 0;
41 std::uint32_t v;
42 std::memcpy(&v, data.data() + at, 4);
43 return v;
44}
45
46// The stage the DXIL program header names (DxilProgramHeader::ProgramVersion, kind in bits 31:16; D3D12's
47// D3D12_SHADER_VERSION_TYPE), in the translator's spelling. Empty for a kind the corpus has no translation for.
48std::string dxil_stage(std::span<const std::uint8_t> container) {
49 const auto dxil = leonida::dxbc_part(container, "DXIL");
50 if (dxil.size() < 4) return {};
51 switch (u32(dxil, 0) >> 16) {
52 case 0: return "ps";
53 case 1: return "vs";
54 case 2: return "gs";
55 case 5: return "cs";
56 case 13: return "ms";
57 default: return {};
58 }
59}
60
61// Every 0x0D (XBCH) payload of the container's XDAT table, in table order, inflated. fssm_program keeps the last.
62std::vector<std::vector<std::uint8_t>> all_programs(std::span<const std::uint8_t> container) {
63 std::vector<std::vector<std::uint8_t>> out;
64 const auto dxil = leonida::dxbc_part(container, "DXIL");
65 std::size_t xdat = 0;
66 while (xdat + 4 <= dxil.size() && std::memcmp(dxil.data() + xdat, "XDAT", 4) != 0) ++xdat;
67 const std::uint32_t count = u32(dxil, xdat + 4);
68 for (std::uint32_t i = 0; i < count; ++i) {
69 const std::size_t entry = xdat + 12 + 12 * std::size_t(i);
70 if (entry + 12 > dxil.size()) break;
71 const std::uint32_t tag = u32(dxil, entry), offset = u32(dxil, entry + 4), size = u32(dxil, entry + 8);
72 if (tag != 0x0d || size < 24 || std::size_t(offset) + size > dxil.size()) continue;
73 const auto blob = dxil.subspan(offset, size);
74 std::vector<std::uint8_t> program;
75 if (std::memcmp(blob.data(), "XBCH", 4) == 0 && leonida::zlib_inflate(blob.subspan(24), program, u32(blob, 16)))
76 out.push_back(std::move(program));
77 }
78 return out;
79}
80
81bool own_entry(const leonida::ShaderEntry& entry, const std::string& stem) {
82 return entry.name == stem || entry.name.rfind(stem + "~", 0) == 0;
83}
84
85} // namespace
86
87int main() {
88 const std::string spirv_dir = env("LEONIDA_SHADERS");
89 if (spirv_dir.empty()) {
90 std::printf("SKIP (no translated corpus: set LEONIDA_SHADERS to <work>/shaders/spirv)\n");
91 return 77;
92 }
93 std::string dxbc_dir = env("LEONIDA_SHADER_DXBC");
94 if (dxbc_dir.empty()) dxbc_dir = (fs::path(spirv_dir) / ".." / "dxbc").lexically_normal().string();
95
96 int failures = 0, named = 0;
97 const auto fail = [&](const std::string& what, const std::string& shader) {
98 ++failures;
99 if (named++ < 8) std::fprintf(stderr, "FAIL %s: %s\n", what.c_str(), shader.c_str());
100 };
101
102 leonida::ShaderLibrary library;
103 std::string error;
104 if (!library.load(spirv_dir, &error)) {
105 std::fprintf(stderr, "FAIL loading %s: %s\n", spirv_dir.c_str(), error.c_str());
106 return 1;
107 }
108 std::error_code ec;
109 if (!fs::is_directory(dxbc_dir, ec)) {
110 std::fprintf(stderr, "FAIL no DXBC folder %s (set LEONIDA_SHADER_DXBC)\n", dxbc_dir.c_str());
111 return 1;
112 }
113
114 std::size_t containers = 0, multi = 0;
115 std::set<std::string> reached;
116 for (const auto& item : fs::directory_iterator(dxbc_dir)) {
117 if (!item.is_regular_file() || item.path().extension() != ".dxbc") continue;
118 ++containers;
119 const std::string stem = item.path().stem().string();
120 const auto bytes = read_file(item.path());
121 const std::string stage = dxil_stage(bytes);
122 if (stage.empty()) {
123 fail("no shader stage in the DXIL program header", stem);
124 continue;
125 }
126 const auto program = leonida::fssm_program(bytes);
127 if (program.size() < 4 || std::memcmp(program.data(), "FSSM", 4) != 0) {
128 fail("no FSSM program", stem);
129 continue;
130 }
131 bool found = false;
132 for (const leonida::ShaderEntry* entry : library.candidates(stage, leonida::sha256_hex(program))) {
133 if (!own_entry(*entry, stem)) continue;
134 found = true;
135 reached.insert(entry->name);
136 if (library.spirv(*entry).empty()) fail("no SPIR-V module for", entry->name);
137 }
138 if (!found) fail("not found under its " + stage + " stage", stem);
139
140 // The 0x0D payloads that differ from the last: none of them may be what the index has for this container.
141 const auto programs = all_programs(bytes);
142 if (programs.empty() || programs.back() != program) fail("fssm_program is not the last 0x0D payload", stem);
143 bool differs = false;
144 for (std::size_t i = 0; i + 1 < programs.size(); ++i) {
145 if (programs[i] == program) continue;
146 differs = true;
147 for (const leonida::ShaderEntry* entry : library.candidates(stage, leonida::sha256_hex(programs[i])))
148 if (own_entry(*entry, stem)) fail("an earlier 0x0D payload is the indexed program", stem);
149 }
150 multi += differs;
151 }
152
153 if (containers == 0) fail("no .dxbc containers in", dxbc_dir);
154 if (reached.size() != library.size())
155 fail(std::to_string(library.size() - reached.size()) + " index entries reached by no container", spirv_dir);
156 std::printf("%zu containers, %zu index entries, %zu reached; %zu containers with more than one program; "
157 "%d failures\n", containers, library.size(), reached.size(), multi, failures);
158 return failures ? 1 : 0;
159}
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index 1fecf1205..49189f69c 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -194,6 +194,7 @@ int main() {
194 const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test"; 194 const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test";
195 std::filesystem::create_directories(dir); 195 std::filesystem::create_directories(dir);
196 const std::string hash = sha256_hex(skewed(600)); 196 const std::string hash = sha256_hex(skewed(600));
197 const std::string hash2 = sha256_hex(bytes("another program"));
197 { 198 {
198 std::ofstream index(dir / "index.json", std::ios::binary); 199 std::ofstream index(dir / "index.json", std::ios::binary);
199 index << "{\"cs_test\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash 200 index << "{\"cs_test\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash
@@ -208,6 +209,10 @@ int main() {
208 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, " 209 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, "
209 "\"component_type\": \"float\"}]},\n" 210 "\"component_type\": \"float\"}]},\n"
210 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"outputs\": [0, 2]},\n" 211 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"outputs\": [0, 2]},\n"
212 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
213 "\"subgroup_size\": 64},\n"
214 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
215 "\"subgroup_size\": null, \"wave64_exchange\": \"workgroup\"},\n"
211 " \"ps_unhashed\": {\"stage\": \"ps\", \"bindings\": []}}"; 216 " \"ps_unhashed\": {\"stage\": \"ps\", \"bindings\": []}}";
212 std::ofstream spv(dir / "cs_test.spv", std::ios::binary); 217 std::ofstream spv(dir / "cs_test.spv", std::ios::binary);
213 const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; 218 const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0};
@@ -215,7 +220,7 @@ int main() {
215 } 220 }
216 ShaderLibrary library; 221 ShaderLibrary library;
217 std::string error; 222 std::string error;
218 CHECK(library.load(dir.string(), &error) && library.size() == 4); 223 CHECK(library.load(dir.string(), &error) && library.size() == 6);
219 const ShaderEntry* vs = library.find("vs", hash); 224 const ShaderEntry* vs = library.find("vs", hash);
220 CHECK(vs && vs->input_signature.size() == 2 && vs->input_signature[0].semantic == "COLOR"); 225 CHECK(vs && vs->input_signature.size() == 2 && vs->input_signature[0].semantic == "COLOR");
221 CHECK(vs->input_signature[1].register_index == 2 && vs->input_signature[1].system_value == 6 && 226 CHECK(vs->input_signature[1].register_index == 2 && vs->input_signature[1].system_value == 6 &&
@@ -232,6 +237,13 @@ int main() {
232 CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144); 237 CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144);
233 CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64); 238 CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64);
234 CHECK(!library.find("ms", hash)); // no mesh shader with this hash 239 CHECK(!library.find("ms", hash)); // no mesh shader with this hash
240 // The subgroup fields of the index (wave64 / subgroup_size / wave64_exchange): absent, native and emulated.
241 CHECK(!entry->subgroup_size && entry->wave64_exchange.empty() && !entry->emulated());
242 const ShaderEntry* native = library.find("ps", hash2);
243 CHECK(native && native->wave64 && native->subgroup_size == 64 && !native->emulated());
244 const ShaderEntry* emulated = library.find("cs", hash2);
245 CHECK(emulated && emulated->wave64 && emulated->subgroup_size == 0 && emulated->wave64_exchange == "workgroup" &&
246 emulated->emulated());
235 CHECK(library.spirv(*entry).size() == 5); 247 CHECK(library.spirv(*entry).size() == 5);
236 CHECK(!library.load((dir / "missing").string(), &error) && !error.empty()); 248 CHECK(!library.load((dir / "missing").string(), &error) && !error.empty());
237 { 249 {
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index f7979ee69..c9796f244 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -135,6 +135,10 @@ def translate_tests(work, names):
135def main(): 135def main():
136 if len(sys.argv) < 2: 136 if len(sys.argv) < 2:
137 sys.exit(__doc__) 137 sys.exit(__doc__)
138 # The CMake test targets name the spirv-as/spirv-val folder here instead of passing a whole PATH, which the Visual
139 # Studio generator's command line can't carry intact (a PATH entry ending in a backslash escapes the next quote).
140 if os.environ.get("LEONIDA_SPIRV_TOOLS"):
141 os.environ["PATH"] = os.environ["LEONIDA_SPIRV_TOOLS"] + os.pathsep + os.environ.get("PATH", "")
138 out = Path(sys.argv[1]) 142 out = Path(sys.argv[1])
139 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys()) 143 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys())
140 names = sys.argv[2:] or available 144 names = sys.argv[2:] or available
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 5b4fa43c8..585d208e6 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -81,7 +81,7 @@ CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed001
81WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", 81WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute",
82 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", 82 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32",
83 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", 83 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext",
84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops") 84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos")
85# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is 85# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
86# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with 86# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with
87# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may 87# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may
@@ -130,6 +130,8 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
130 ("cs_wqm_w64", [20, 4, 12, 8, 1, 0, 15728895, 20]), ("cs_wqm_w32", [12, 1, 4, 0, 8, 15728880, 4, 32]), 130 ("cs_wqm_w64", [20, 4, 12, 8, 1, 0, 15728895, 20]), ("cs_wqm_w32", [12, 1, 4, 0, 8, 15728880, 4, 32]),
131 ("cs_bpermute32", [0, 50, 162, 99, 36, 218, 183, 15]), 131 ("cs_bpermute32", [0, 50, 162, 99, 36, 218, 183, 15]),
132 ("cs_w32_partial_scmp", [0, 1, 1, 0, 1, 1, 1, 1]), # a 20-thread wave32: s_cmp mask, -1 132 ("cs_w32_partial_scmp", [0, 1, 1, 0, 1, 1, 1, 1]), # a 20-thread wave32: s_cmp mask, -1
133 # SHADER-88: v_sin/v_cos reduce the angle in turns (a regression guard, tolerance 1e-3)
134 ("cs_w32_sincos", [1, 1, 1, 1, 1, 1]),
133 ("cs_wqm_w64_half", [11, 14, 0, 1, 6, 8, 12, 2]), 135 ("cs_wqm_w64_half", [11, 14, 0, 1, 6, 8, 12, 2]),
134 # SHADER-91: two s_barrier sites in wave-uniform branches meet like one barrier; wave 0 reads wave 3 136 # SHADER-91: two s_barrier sites in wave-uniform branches meet like one barrier; wave 0 reads wave 3
135 ("cs_barrier_divergent", [127, 126, 125, 124, 123, 122, 121, 120]), 137 ("cs_barrier_divergent", [127, 126, 125, 124, 123, 122, 121, 120]),
@@ -156,6 +158,22 @@ CMPX_CLASS_WORDS = [0xEEEEEEEE] * 3 + [0x22] + [0x11] * 4
156# cs_fmt_1010102.asm: descriptor loads, immediate-format load, raw input words and the two packed stores. 158# cs_fmt_1010102.asm: descriptor loads, immediate-format load, raw input words and the two packed stores.
157FMT_1010102_WORDS = [0, 0x3F800000, 0, 0x3F800000, 0x3F800000, 0, 0x3F800000, 0, 159FMT_1010102_WORDS = [0, 0x3F800000, 0, 0x3F800000, 0x3F800000, 0, 0x3F800000, 0,
158 0, 0x3F800000, 0, 0x3F800000, 0xC00FFC00, 0x003FF003, 0xE00003FF, 0xFFE00003] 160 0, 0x3F800000, 0, 0x3F800000, 0xC00FFC00, 0x003FF003, 0xE00003FF, 0xFFE00003]
161# cs_fmt_sint32.asm: hand-derived full-width and D16 load results, inputs, stores, and untouched words.
162FMT_SINT32_WORDS = [
163 0x80000000, 0x7FFFFFFF, 0x80000000, 1,
164 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0x80000000,
165 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
166 0x80000000, 0x7FFFFFFF, 0, 0,
167 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0,
168 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
169 0x7FFF8000, 0x0011FFFD, 0x7FFF8000, 0x0011FFFD,
170 0xFFFFFFFD, 0xFFFFFFFD, 0xEEEEEEEE, 0xEEEEEEEE,
171 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
172 0x80000000, 0x7FFFFFFF, 0xEEEEEEEE, 0xEEEEEEEE,
173 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0xEEEEEEEE,
174 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17,
175 0xFFFFFFFD, 0xFFFF8000, 0xFFFFFFFD, *[0xEEEEEEEE] * 13,
176]
159# cs_fmt_xy_xyz.asm (TEST-185): 12 xy/xyz loads, then the 9 store regions read back, as a Radeon 680M (gfx1035) gives 177# cs_fmt_xy_xyz.asm (TEST-185): 12 xy/xyz loads, then the 9 store regions read back, as a Radeon 680M (gfx1035) gives
160# them natively, with the updated UINT saturation case checked on gfx1036. Layout and rules in the .asm header. 178# them natively, with the updated UINT saturation case checked on gfx1036. Layout and rules in the .asm header.
161FMT_XY_XYZ_WORDS = [ 179FMT_XY_XYZ_WORDS = [
@@ -197,6 +215,9 @@ W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1"
197# LEONIDA_BARY_FALLBACK=1 (set for build.py too): a pixel shader that reads raw barycentrics was translated with 215# LEONIDA_BARY_FALLBACK=1 (set for build.py too): a pixel shader that reads raw barycentrics was translated with
198# --bary-fallback and is drawn through its pass-through geometry shader, <name>.bary_gs.spv. 216# --bary-fallback and is drawn through its pass-through geometry shader, <name>.bary_gs.spv.
199BARY_FALLBACK = os.environ.get("LEONIDA_BARY_FALLBACK") == "1" 217BARY_FALLBACK = os.environ.get("LEONIDA_BARY_FALLBACK") == "1"
218# LEONIDA_F16_INTERP_FALLBACK=1 (as build.py reads it): *_f16 interps were translated from decoded-half inputs, with no
219# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there.
220F16_HALVES = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1"
200W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), 221W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]),
201 ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), 222 ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]),
202 ("cs_w64x_writelane", [4660, 77, 99, 2748, 0, 0, 4660, 99]), 223 ("cs_w64x_writelane", [4660, 77, 99, 2748, 0, 0, 4660, 99]),
@@ -236,6 +257,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
236 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000), 257 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000),
237 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000), 258 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000),
238 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), 259 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203),
260 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
261 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
239 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000), 262 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000),
240 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000), 263 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000),
241 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers) 264 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers)
@@ -248,6 +271,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
248 "ps_f16_const": (0xaaaa3d00, 0x38005555, 0xaaaa3800, 0x3f000000), 271 "ps_f16_const": (0xaaaa3d00, 0x38005555, 0xaaaa3800, 0x3f000000),
249 "ps_f16_const2": (0x42003d00, 0x3d004200, 0xaaaabc00, 3), 272 "ps_f16_const2": (0x42003d00, 0x3d004200, 0xaaaabc00, 3),
250 "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200), 273 "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200),
274 # v_pack_b32_f16 neg/abs on the selected half: a sign flip / clear before packing (SHADER-260)
275 "ps_f16_pack_mods": (0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400),
251 "ps_sff_imm": (2, 1, 20, 16), 276 "ps_sff_imm": (2, 1, 20, 16),
252 "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000), 277 "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000),
253 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), 278 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000),
@@ -267,7 +292,13 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
267 "ps_vint_bits": (0xfffffffe, 0x40000000, 0x1e6a2c48, 0x000001d5), 292 "ps_vint_bits": (0xfffffffe, 0x40000000, 0x1e6a2c48, 0x000001d5),
268 "ps_vint_mul24": (0x13345678, 0xfffffffd, 0x00007fff, 0x0000ffff), 293 "ps_vint_mul24": (0x13345678, 0xfffffffd, 0x00007fff, 0x0000ffff),
269 "ps_vint_minmax": (0x7ffffffe, 0x80000001, 0x80000001, 0x7ffffffe), 294 "ps_vint_minmax": (0x7ffffffe, 0x80000001, 0x80000001, 0x7ffffffe),
270 "ps_vint_minmax3": (0xf0f0f0f0, 0xab800000, 0xf0f0f0f0, 0xab800000)} 295 "ps_vint_minmax3": (0xf0f0f0f0, 0xab800000, 0xf0f0f0f0, 0xab800000),
296 # v_readlane_b32 across both halves of a wave64 (the .asm header derives the words)
297 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000be)}
298# Pixel shaders that are exact only when the pixel stage really ran 64 lanes wide. vk_harness says so when it chained
299# a required subgroup size onto the fragment stage ("fragment subgroup size: N required"). A device that cannot
300# require 64 there (NVIDIA: 32 only; llvmpipe: 8) has no frame to judge: the test is skipped, not failed.
301WIDE_PIXEL_TESTS = {"ps_w64x_readlane": 64}
271# h0..h7 of the ps_vint_* fixtures: 24-bit fields with bit 23 set and garbage above, 33 (a shift of 32+), a 302# h0..h7 of the ps_vint_* fixtures: 24-bit fields with bit 23 set and garbage above, 33 (a shift of 32+), a
272# negative i32 that is a large u32, and plain bit patterns. 303# negative i32 that is a large u32, and plain bit patterns.
273VINT_ENV = {"VKH_SGPRS": "0x1000,0,32,0", 304VINT_ENV = {"VKH_SGPRS": "0x1000,0,32,0",
@@ -444,6 +475,10 @@ def fmt_1010102_test(tools, spirv, env=None):
444 return dump_test(tools, spirv, "cs_fmt_1010102", FMT_1010102_WORDS + [0xEEEEEEEE] * 48, 64, env) 475 return dump_test(tools, spirv, "cs_fmt_1010102", FMT_1010102_WORDS + [0xEEEEEEEE] * 48, 64, env)
445 476
446 477
478def fmt_sint32_test(tools, spirv, env=None):
479 return dump_test(tools, spirv, "cs_fmt_sint32", FMT_SINT32_WORDS, len(FMT_SINT32_WORDS), env)
480
481
447def fmt_xy_xyz_test(tools, spirv, env=None): 482def fmt_xy_xyz_test(tools, spirv, env=None):
448 """TEST-185: the 84 result words and the untouched words after them, up to the inputs at 0x200. The heap needs 483 """TEST-185: the 84 result words and the untouched words after them, up to the inputs at 0x200. The heap needs
449 0x2d0 bytes, so it is 192 words.""" 484 0x2d0 bytes, so it is 192 words."""
@@ -692,9 +727,10 @@ def subgroup_size(spirv, name):
692 return None 727 return None
693 728
694 729
695def bindless_test(tools, spirv): 730def bindless_test(tools, spirv, pixel="ps_tex"):
696 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).""" 731 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).
697 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_tex")] 732 ps_imgatomic: image atomics in a pixel shader through the set's r32ui storage arrays, checked per texel."""
733 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", pixel)]
698 for path in shaders: 734 for path in shaders:
699 if not os.path.isfile(path): 735 if not os.path.isfile(path):
700 return f"missing {os.path.basename(path)}" 736 return f"missing {os.path.basename(path)}"
@@ -702,6 +738,9 @@ def bindless_test(tools, spirv):
702 if code == UNSUPPORTED: 738 if code == UNSUPPORTED:
703 m = re.search(r"unsupported: .*", out) 739 m = re.search(r"unsupported: .*", out)
704 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") 740 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})")
741 if pixel == "ps_imgatomic":
742 m = re.search(r"ps_imgatomic: (\d+) of \d+ texels wrong.*; (\d+) of \d+ render-target pixels wrong", out)
743 return "" if code == 0 and m and m.group(1) == "0" and m.group(2) == "0" else failure(code, out, 3)
705 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out) 744 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out)
706 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3) 745 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3)
707 746
@@ -1072,13 +1111,27 @@ def interp_f16_high_problem(px):
1072 return "" if err < 2e-3 else f"f16 halves off by {err:.3g}" 1111 return "" if err < 2e-3 else f"f16 halves off by {err:.3g}"
1073 1112
1074 1113
1114def wide_pixel_skip(name, out):
1115 """A Skip when `name` needs a 64-wide pixel stage (WIDE_PIXEL_TESTS) and vk_harness's output does not say that size
1116 was required of the fragment stage, else None."""
1117 want = WIDE_PIXEL_TESTS.get(name)
1118 if not want or re.search(rf"^fragment subgroup size: {want} required$", out, re.MULTILINE):
1119 return None
1120 m = re.search(r"subgroup (\d+)\.\.(\d+)", out)
1121 seen = f": subgroup {m.group(1)}..{m.group(2)}" if m else ""
1122 return Skip(f"SKIP (this device cannot require a {want}-wide fragment subgroup{seen})")
1123
1124
1075def pixel_test(tools, spirv, name): 1125def pixel_test(tools, spirv, name):
1076 path = os.path.join(spirv, name + ".spv") 1126 path = os.path.join(spirv, name + ".spv")
1127 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES):
1128 # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair (no .spv).
1129 return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)")
1077 if not os.path.isfile(path): 1130 if not os.path.isfile(path):
1078 return f"missing {name}.spv" 1131 return f"missing {name}.spv"
1079 if name in ("ps_texoff", "ps_texoff_implicit"): 1132 if name in ("ps_texoff", "ps_texoff_implicit"):
1080 return texoff_test(tools, spirv, name) 1133 return texoff_test(tools, spirv, name)
1081 if name in ("ps_interp_f16_high", "ps_ij_computed") and BARY_FALLBACK: 1134 if name == "ps_interp_f16_high" and BARY_FALLBACK:
1082 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)") 1135 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)")
1083 fmt = "<4f" if name == "ps_bary" else "<2I2f" if name in ("ps_flat", "ps_uniform_branch", "ps_scc_mask32") else "<4I" 1136 fmt = "<4f" if name == "ps_bary" else "<2I2f" if name in ("ps_flat", "ps_uniform_branch", "ps_scc_mask32") else "<4I"
1084 px, out = pixels(tools, spirv, name, fmt, PIXEL_VERTEX.get(name, "vs_ids")) 1137 px, out = pixels(tools, spirv, name, fmt, PIXEL_VERTEX.get(name, "vs_ids"))
@@ -1093,6 +1146,8 @@ def pixel_test(tools, spirv, name):
1093 return Skip("SKIP (vk_harness reported no subgroup width)") 1146 return Skip("SKIP (vk_harness reported no subgroup width)")
1094 if int(m.group(1)) < 32: 1147 if int(m.group(1)) < 32:
1095 return Skip(f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)") 1148 return Skip(f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)")
1149 if skip := wide_pixel_skip(name, out):
1150 return skip
1096 if name == "ps_vcmpx_forms": 1151 if name == "ps_vcmpx_forms":
1097 if skip := vcmpx_forms_narrow_skip(out): 1152 if skip := vcmpx_forms_narrow_skip(out):
1098 return skip 1153 return skip
@@ -1184,6 +1239,7 @@ def main():
1184 results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump", 1239 results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump",
1185 expected_words=CMPX_CLASS_WORDS))) 1240 expected_words=CMPX_CLASS_WORDS)))
1186 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv))) 1241 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv)))
1242 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv)))
1187 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv))) 1243 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv)))
1188 for name, groups, want in GLOBAL_OFFSET: 1244 for name, groups, want in GLOBAL_OFFSET:
1189 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want))) 1245 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want)))
@@ -1222,6 +1278,7 @@ def main():
1222 results.append((name, texture_constant_test(tools, spirv, name))) 1278 results.append((name, texture_constant_test(tools, spirv, name)))
1223 results.append(("ps_tex", bindless_test(tools, spirv))) 1279 results.append(("ps_tex", bindless_test(tools, spirv)))
1224 results.append(("ps_ssharp", sampler_test(tools, spirv))) 1280 results.append(("ps_ssharp", sampler_test(tools, spirv)))
1281 results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic")))
1225 for name in MIP_TEST_PASSES: 1282 for name in MIP_TEST_PASSES:
1226 results.append((name, texture_mip_test(tools, spirv, name))) 1283 results.append((name, texture_mip_test(tools, spirv, name)))
1227 for name in GRADIENT_TESTS: 1284 for name in GRADIENT_TESTS:
diff --git a/runtime/test/shaders/cs_fmt_sint32.asm b/runtime/test/shaders/cs_fmt_sint32.asm
new file mode 100644
index 000000000..a444421ce
--- /dev/null
+++ b/runtime/test/shaders/cs_fmt_sint32.asm
@@ -0,0 +1,90 @@
1; SHADER-257: GFX10 32-bit signed typed buffers. Lane 0 writes [-2147483648, 2147483647, -3, 17] at 0x80.
2; MUBUF loads at out[0..11] test integer DST_SEL=1 for format 63 (X,Y,X,1) and raw words for 73/76.
3; MTBUF loads at out[12..23] use a bound 32_FLOAT descriptor and take width and identity selectors from the
4; instruction (XY00, XYZ0, XYZW). D16 loads at out[24..27] check signed saturation, including -3, for both forms.
5; Single-channel SINT MUBUF/MTBUF loads place -3 in out[28..29].
6; MUBUF stores at 0x90/0xa0/0xb0 write the low 2/3/4 original words. The D16 store at 0xc0 sign-extends
7; 0xfffd and 0x8000 to dwords. The single-channel store at 0xc8 writes -3. Unwritten words retain 0xeeeeeeee.
8v_cmpx_eq_u32_e32 0, v0
9v_mov_b32_e32 v1, 0x80000000
10v_mov_b32_e32 v2, 0x7fffffff
11v_mov_b32_e32 v3, -3
12v_mov_b32_e32 v4, 17
13v_mov_b32_e32 v5, 0x80
14buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
15s_mov_b32 s4, s0
16s_mov_b32 s5, s1
17s_mov_b32 s6, s2
18
19; MUBUF load via format 63.
20s_mov_b32 s7, 0x3103f32c
21buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
22v_mov_b32_e32 v6, 0x0
23buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
24
25; MUBUF load via format 73.
26s_mov_b32 s7, 0x31049fac
27buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
28v_mov_b32_e32 v6, 0x10
29buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
30
31; MUBUF load via format 76.
32s_mov_b32 s7, 0x3104cfac
33buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
34v_mov_b32_e32 v6, 0x20
35buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
36
37; A bound FLOAT descriptor with a different size and selectors from each instruction.
38s_mov_b32 s7, 0x31016000
39tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_SINT] offen
40v_mov_b32_e32 v6, 0x30
41buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
42tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_SINT] offen
43v_mov_b32_e32 v6, 0x40
44buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
45tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen
46v_mov_b32_e32 v6, 0x50
47buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
48
49; Packs (0x8000, 0x7fff) and (0xfffd, 0x0011).
50s_mov_b32 s7, 0x3104cfac
51buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen
52v_mov_b32_e32 v6, 0x60
53buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
54s_mov_b32 s7, 0x31016000
55tbuffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen
56v_mov_b32_e32 v6, 0x68
57buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
58
59; Single-component 32_SINT at 0x88, with a bound FLOAT descriptor for the MTBUF case.
60s_mov_b32 s7, 0x31015004
61buffer_load_format_x v8, v5, s[4:7], 0 offen offset:8
62s_mov_b32 s7, 0x31016000
63tbuffer_load_format_x v9, v5, s[4:7], 0 format:[BUF_FMT_32_SINT] offen offset:8
64v_mov_b32_e32 v6, 0x70
65buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
66
67; MUBUF store via format 63.
68s_mov_b32 s7, 0x3103ffac
69v_mov_b32_e32 v6, 0x90
70buffer_store_format_xy v[1:2], v6, s[4:7], 0 offen
71
72; MUBUF store via format 73.
73s_mov_b32 s7, 0x31049fac
74v_mov_b32_e32 v6, 0xa0
75buffer_store_format_xyz v[1:3], v6, s[4:7], 0 offen
76
77; MUBUF store via format 76.
78s_mov_b32 s7, 0x3104cfac
79v_mov_b32_e32 v6, 0xb0
80buffer_store_format_xyzw v[1:4], v6, s[4:7], 0 offen
81
82; A signed packed store must extend both halves.
83s_mov_b32 s7, 0x3103ffac
84v_mov_b32_e32 v6, 0xc0
85v_mov_b32_e32 v7, 0x8000fffd
86buffer_store_format_d16_xy v7, v6, s[4:7], 0 offen
87s_mov_b32 s7, 0x31015004
88v_mov_b32_e32 v6, 0xc8
89buffer_store_format_x v3, v6, s[4:7], 0 offen
90s_endpgm
diff --git a/runtime/test/shaders/cs_w32_sincos.asm b/runtime/test/shaders/cs_w32_sincos.asm
new file mode 100644
index 000000000..6777867da
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_sincos.asm
@@ -0,0 +1,60 @@
1; SHADER-88: v_sin_f32 / v_cos_f32 take the angle in turns and must reduce it in turns before scaling by 2*pi.
2; Six large-angle cases (254.25, 254.5, -200.75, 100.3, 254.51, -254.51 turns); each stores 1 when
3; |result - reference| < 1e-3 (the reference is sin/cos(2*pi*x) in double; a Vulkan Sin/Cos is only guaranteed to
4; 2^-11 = 4.9e-4 in [-pi, pi], so the shader compares with a tolerance and stores a flag, not the float).
5; Lane 0 stores out[0..5] = 1 1 1 1 1 1. (Expected references, f32 bits: 1.0, -1.0, 1.0, 0xbe9e39de,
6; 0xbd808642, 0xbf7f7ed2.)
7; group: 32,1,1
8; Run: vk_compute_test cs_w32_sincos.spv 1 dump -> out[0..5] = 1 1 1 1 1 1
9; mattr: +wavefrontsize32,-wavefrontsize64
10v_mov_b32_e32 v9, 0x3a83126f
11v_cmpx_eq_u32_e32 0, v0
12v_mov_b32_e32 v1, 0x437e4000
13v_sin_f32_e32 v2, v1
14v_sub_f32_e32 v2, 0x3f800000, v2
15v_and_b32_e32 v2, 0x7fffffff, v2
16v_cmp_gt_f32_e32 vcc_lo, v9, v2
17v_cndmask_b32_e64 v20, 0, 1, vcc_lo
18v_mov_b32_e32 v21, 0
19buffer_store_dword v20, v21, s[0:3], 0 offen
20v_mov_b32_e32 v1, 0x437e8000
21v_cos_f32_e32 v2, v1
22v_sub_f32_e32 v2, 0xbf800000, v2
23v_and_b32_e32 v2, 0x7fffffff, v2
24v_cmp_gt_f32_e32 vcc_lo, v9, v2
25v_cndmask_b32_e64 v20, 0, 1, vcc_lo
26v_mov_b32_e32 v21, 4
27buffer_store_dword v20, v21, s[0:3], 0 offen
28v_mov_b32_e32 v1, 0xc348c000
29v_sin_f32_e32 v2, v1
30v_sub_f32_e32 v2, 0x3f800000, v2
31v_and_b32_e32 v2, 0x7fffffff, v2
32v_cmp_gt_f32_e32 vcc_lo, v9, v2
33v_cndmask_b32_e64 v20, 0, 1, vcc_lo
34v_mov_b32_e32 v21, 8
35buffer_store_dword v20, v21, s[0:3], 0 offen
36v_mov_b32_e32 v1, 0x42c8999a
37v_cos_f32_e32 v2, v1
38v_sub_f32_e32 v2, 0xbe9e39de, v2
39v_and_b32_e32 v2, 0x7fffffff, v2
40v_cmp_gt_f32_e32 vcc_lo, v9, v2
41v_cndmask_b32_e64 v20, 0, 1, vcc_lo
42v_mov_b32_e32 v21, 12
43buffer_store_dword v20, v21, s[0:3], 0 offen
44v_mov_b32_e32 v1, 0x437e828f
45v_sin_f32_e32 v2, v1
46v_sub_f32_e32 v2, 0xbd808642, v2
47v_and_b32_e32 v2, 0x7fffffff, v2
48v_cmp_gt_f32_e32 vcc_lo, v9, v2
49v_cndmask_b32_e64 v20, 0, 1, vcc_lo
50v_mov_b32_e32 v21, 16
51buffer_store_dword v20, v21, s[0:3], 0 offen
52v_mov_b32_e32 v1, 0xc37e828f
53v_cos_f32_e32 v2, v1
54v_sub_f32_e32 v2, 0xbf7f7ed2, v2
55v_and_b32_e32 v2, 0x7fffffff, v2
56v_cmp_gt_f32_e32 vcc_lo, v9, v2
57v_cndmask_b32_e64 v20, 0, 1, vcc_lo
58v_mov_b32_e32 v21, 20
59buffer_store_dword v20, v21, s[0:3], 0 offen
60s_endpgm
diff --git a/runtime/test/shaders/ps_f16_pack_mods.asm b/runtime/test/shaders/ps_f16_pack_mods.asm
new file mode 100644
index 000000000..1ef415ee9
--- /dev/null
+++ b/runtime/test/shaders/ps_f16_pack_mods.asm
@@ -0,0 +1,19 @@
1; v_pack_b32_f16 with NEG and ABS on a source: each acts on the selected 16-bit half as a plain bit move
2; (ABS clears bit 15, NEG flips it, ABS first), before the half is packed. The rule and its words were measured
3; on a Radeon 680M (gfx1036, RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with raw kernels: -v0 turned 0x7c01
4; into 0xfe01 under IEEE mode 1 and 0xfc01 under mode 0, in either half and with op_sel (#1548 SHADER-260).
5; Quieting an sNaN half under IEEE mode 1 is not modelled (SHADER-190); the values below are not NaNs.
6; v0 = 0.25 | 3.0 << 16, v1 = 4.0 | 0.25 << 16 (low | high half).
7; -v0, |v1|: -0x3400 | 0x4400 << 16
8; v0, -v1: 0x3400 | -0x4400 << 16
9; -|v0|, v1 op_sel:[1,0,0]: -(0x4200) | 0x4400 << 16
10; -v0, -|v1| op_sel:[0,1,0]: -0x3400 | -(0x3400) << 16
11; Expected mrt0 bits: 0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400
12v_mov_b32 v0, 0x42003400
13v_mov_b32 v1, 0x34004400
14v_pack_b32_f16 v2, -v0, |v1|
15v_pack_b32_f16 v3, v0, -v1
16v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0]
17v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0]
18exp mrt0 v2, v3, v4, v5 done vm
19s_endpgm
diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm
new file mode 100644
index 000000000..b8f888c13
--- /dev/null
+++ b/runtime/test/shaders/ps_imgatomic.asm
@@ -0,0 +1,44 @@
1; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders:
2; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0
3; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s:
4; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords:
5; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target),
6; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8
7; images:
8; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31),
9; umax3d[px & 3][ty >> 1][tx >> 1] = max(id) (a 4x4x4 image)
10; After its atomics, every odd px is discarded (v_cmpx). The atomics of a pixel that is discarded afterwards still
11; count, as on hardware: the expected values above are over all 4096 pixels. Even pixels export 1.0.
12; Run: vk_bindless_test vs_ids.spv ps_imgatomic.spv (images cleared to 0, umin to 0xffffffff; checked per texel)
13s_load_dwordx8 s[8:15], s[2:3], 0x0
14s_load_dwordx8 s[16:23], s[2:3], 0x20
15s_load_dwordx8 s[24:31], s[2:3], 0x40
16s_load_dwordx8 s[32:39], s[2:3], 0x60
17s_waitcnt lgkmcnt(0)
18v_interp_p1_f32_e32 v2, v0, attr0.x
19v_interp_p2_f32_e32 v2, v1, attr0.x
20v_interp_p1_f32_e32 v3, v0, attr0.y
21v_interp_p2_f32_e32 v3, v1, attr0.y
22v_mul_f32_e32 v2, 0x42800000, v2
23v_mul_f32_e32 v3, 0x42800000, v3
24v_cvt_u32_f32_e32 v4, v2
25v_cvt_u32_f32_e32 v5, v3
26v_lshlrev_b32_e32 v6, 6, v5
27v_add_nc_u32_e32 v6, v6, v4
28v_lshrrev_b32_e32 v7, 3, v4
29v_lshrrev_b32_e32 v8, 3, v5
30image_atomic_umax v6, v[7:8], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
31image_atomic_umin v6, v[7:8], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
32v_and_b32_e32 v9, 31, v6
33v_lshlrev_b32_e64 v9, v9, 1
34image_atomic_or v9, v[7:8], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
35v_lshrrev_b32_e32 v10, 1, v7
36v_lshrrev_b32_e32 v11, 1, v8
37v_and_b32_e32 v12, 3, v4
38image_atomic_umax v6, v[10:12], s[32:39] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
39s_waitcnt vmcnt(0)
40v_and_b32_e32 v13, 1, v4
41v_cmpx_eq_u32_e32 0, v13
42v_mov_b32_e32 v14, 1.0
43exp mrt0 v14, v14, v14, v14 done vm
44s_endpgm
diff --git a/runtime/test/shaders/ps_m2_uoff.asm b/runtime/test/shaders/ps_m2_uoff.asm
index 7f1167944..1c96f50d5 100644
--- a/runtime/test/shaders/ps_m2_uoff.asm
+++ b/runtime/test/shaders/ps_m2_uoff.asm
@@ -2,9 +2,12 @@
2; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one 2; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one
3; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by 3; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by
4; @Vonsek (#1489). Run: d3d12_m2_textured_test. 4; @Vonsek (#1489). Run: d3d12_m2_textured_test.
5; The same unbounded SRV table stays bound across both draws. Root constants s4 and s5 hold
6; the descriptor index and byte stride, respectively.
5; fssm-at: 0x10 7; fssm-at: 0x10
6; fssm-data: 0x324d5350 0x4f465520 8; fssm-data: 0x324d5350 0x4f465520
7s_load_dwordx8 s[8:15], s[0:1], 0x0 9s_mul_i32 s20, s4, s5
10s_load_dwordx8 s[8:15], s[0:1], s20
8s_load_dwordx4 s[16:19], s[2:3], 0x0 11s_load_dwordx4 s[16:19], s[2:3], 0x0
9s_waitcnt lgkmcnt(0) 12s_waitcnt lgkmcnt(0)
10v_interp_p1_f32_e32 v2, v0, attr0.x 13v_interp_p1_f32_e32 v2, v0, attr0.x
diff --git a/runtime/test/shaders/ps_scc_logic32.asm b/runtime/test/shaders/ps_scc_logic32.asm
new file mode 100644
index 000000000..3b36f1362
--- /dev/null
+++ b/runtime/test/shaders/ps_scc_logic32.asm
@@ -0,0 +1,44 @@
1; s_nand_b32, s_nor_b32, s_xnor_b32: D = ~(S0 op S1), SCC = (D != 0). Values by hand from the RDNA2 ISA SOP2 text.
2; s2 = 0xf0f0f0f0, s3 = 0xff00ff00: and = 0xf000f000, or = 0xfff0fff0, xor = 0x0ff00ff0.
3; Expected mrt0 bits: nand 0x0fff0fff, nor 0x000f000f, xnor 0xf00ff00f, and an SCC word, bit n = SCC after case n:
4; 0 nand(-1, -1) = 0 -> 0 1 nor(0, 0) = -1 -> 1 2 xnor(x, x) = -1 -> 1
5; 3 xnor(x, ~x) = 0 -> 0 4 nor(0xfffffff0, 0) = 0xf -> 1 5 nand(0x80000000, -1) = 0x7fffffff -> 1
6; so the SCC word is 0x36.
7s_mov_b32 s2, 0xf0f0f0f0
8s_mov_b32 s3, 0xff00ff00
9s_nand_b32 s4, s2, s3
10s_nor_b32 s5, s2, s3
11s_xnor_b32 s6, s2, s3
12s_mov_b32 s8, -1
13s_mov_b32 s9, 0
14s_mov_b32 s10, 0x0f0f0f0f
15s_mov_b32 s11, 0xfffffff0
16s_mov_b32 s12, 0x80000000
17s_nand_b32 s13, s8, s8
18s_cselect_b32 s20, 1, 0
19s_nor_b32 s13, s9, s9
20s_cselect_b32 s21, 1, 0
21s_xnor_b32 s13, s2, s2
22s_cselect_b32 s22, 1, 0
23s_xnor_b32 s13, s2, s10
24s_cselect_b32 s23, 1, 0
25s_nor_b32 s13, s11, s9
26s_cselect_b32 s24, 1, 0
27s_nand_b32 s13, s12, s8
28s_cselect_b32 s25, 1, 0
29s_lshl_b32 s21, s21, 1
30s_lshl_b32 s22, s22, 2
31s_lshl_b32 s23, s23, 3
32s_lshl_b32 s24, s24, 4
33s_lshl_b32 s25, s25, 5
34s_or_b32 s20, s20, s21
35s_or_b32 s20, s20, s22
36s_or_b32 s20, s20, s23
37s_or_b32 s20, s20, s24
38s_or_b32 s20, s20, s25
39v_mov_b32_e32 v0, s4
40v_mov_b32_e32 v1, s5
41v_mov_b32_e32 v2, s6
42v_mov_b32_e32 v3, s20
43exp mrt0 v0, v1, v2, v3 done vm
44s_endpgm
diff --git a/runtime/test/shaders/ps_scc_logic64.asm b/runtime/test/shaders/ps_scc_logic64.asm
new file mode 100644
index 000000000..3ffb677ae
--- /dev/null
+++ b/runtime/test/shaders/ps_scc_logic64.asm
@@ -0,0 +1,49 @@
1; s_nand_b64, s_nor_b64, s_xnor_b64 on plain SGPR pairs: D = ~(S0 op S1), SCC = ((D.lo | D.hi) != 0). By hand from the RDNA2 ISA.
2; A = s[2:3] = (lo 0xf0f0f0f0, hi 0x0000ffff), B = s[4:5] = (lo 0xff00ff00, hi 0x00ff00ff).
3; Expected mrt0 bits: nand.lo 0x0fff0fff, nor.hi 0xff000000 (A.hi | B.hi = 0x00ffffff), xnor.hi 0xff0000ff (A.hi ^ B.hi = 0x00ffff00),
4; and an SCC word, bit n = SCC after case n (X = (-1, 0), Y = (0, -1)):
5; 0 nand(ones, ones) = 0 -> 0 1 nor(X, 0) = (0, -1), only the high dword set -> 1
6; 2 xnor(X, X) = all ones -> 1 3 xnor(X, Y) = 0 -> 0
7; 4 nor(Y, (0xfffffff0, 0)) = (0xf, 0), only the low dword set -> 1
8; so the SCC word is 0x16.
9s_mov_b32 s2, 0xf0f0f0f0
10s_mov_b32 s3, 0x0000ffff
11s_mov_b32 s4, 0xff00ff00
12s_mov_b32 s5, 0x00ff00ff
13s_nand_b64 s[6:7], s[2:3], s[4:5]
14s_nor_b64 s[8:9], s[2:3], s[4:5]
15s_xnor_b64 s[10:11], s[2:3], s[4:5]
16s_mov_b32 s12, -1
17s_mov_b32 s13, -1
18s_mov_b32 s14, -1
19s_mov_b32 s15, 0
20s_mov_b32 s16, 0
21s_mov_b32 s17, -1
22s_mov_b32 s18, 0
23s_mov_b32 s19, 0
24s_mov_b32 s24, 0xfffffff0
25s_mov_b32 s25, 0
26s_nand_b64 s[30:31], s[12:13], s[12:13]
27s_cselect_b32 s40, 1, 0
28s_nor_b64 s[30:31], s[14:15], s[18:19]
29s_cselect_b32 s41, 1, 0
30s_xnor_b64 s[30:31], s[14:15], s[14:15]
31s_cselect_b32 s42, 1, 0
32s_xnor_b64 s[30:31], s[14:15], s[16:17]
33s_cselect_b32 s43, 1, 0
34s_nor_b64 s[30:31], s[16:17], s[24:25]
35s_cselect_b32 s44, 1, 0
36s_lshl_b32 s41, s41, 1
37s_lshl_b32 s42, s42, 2
38s_lshl_b32 s43, s43, 3
39s_lshl_b32 s44, s44, 4
40s_or_b32 s40, s40, s41
41s_or_b32 s40, s40, s42
42s_or_b32 s40, s40, s43
43s_or_b32 s40, s40, s44
44v_mov_b32_e32 v0, s6
45v_mov_b32_e32 v1, s9
46v_mov_b32_e32 v2, s11
47v_mov_b32_e32 v3, s40
48exp mrt0 v0, v1, v2, v3 done vm
49s_endpgm
diff --git a/runtime/test/shaders/ps_w64x_readlane.asm b/runtime/test/shaders/ps_w64x_readlane.asm
new file mode 100644
index 000000000..895254471
--- /dev/null
+++ b/runtime/test/shaders/ps_w64x_readlane.asm
@@ -0,0 +1,27 @@
1; Wave64 pixel shader with v_readlane_b32 across both halves of the wave (RDNA2 ISA: lane = S1 % 64, EXEC ignored).
2; The translator's pixel path takes the lane from SubgroupLocalInvocationId, which is the hardware lane only in a
3; 64-wide subgroup; in a 32-wide one the lane select wraps (lane 40 reads lane 8), so the words below differ.
4; v2 = 3 * lane + 1. Every lane of a full wave reads the same scalars:
5; s6 = v2[40] = 121, s7 = v2[5] = 16, s8 = v2[33] = 100, s9 = v2[63] = 190
6; Each is or'ed with 0x40000000 so the export is a normal float (a float render target keeps bit patterns, but a
7; denormal could be flushed). Export mrt0 = (0x40000079, 0x40000010, 0x40000064, 0x400000be) for every covered
8; pixel of a full wave; draw a triangle that covers the whole target so every wave is full.
9; Run: d3d12_subgroup_test (the PS through a D3D12 graphics PSO, R32G32B32A32_FLOAT target).
10; mattr: +wavefrontsize64,-wavefrontsize32
11v_mbcnt_lo_u32_b32 v1, -1, 0
12v_mbcnt_hi_u32_b32 v1, -1, v1
13v_mad_u32_u24 v2, v1, 3, 1
14v_readlane_b32 s6, v2, 40
15v_readlane_b32 s7, v2, 5
16v_readlane_b32 s8, v2, 33
17v_readlane_b32 s9, v2, 63
18s_or_b32 s6, s6, 0x40000000
19s_or_b32 s7, s7, 0x40000000
20s_or_b32 s8, s8, 0x40000000
21s_or_b32 s9, s9, 0x40000000
22v_mov_b32 v3, s6
23v_mov_b32 v4, s7
24v_mov_b32 v5, s8
25v_mov_b32 v6, s9
26exp mrt0 v3, v4, v5, v6 done vm
27s_endpgm
diff --git a/runtime/test/subgroup_size_test.cpp b/runtime/test/subgroup_size_test.cpp
new file mode 100644
index 000000000..e61387e07
--- /dev/null
+++ b/runtime/test/subgroup_size_test.cpp
@@ -0,0 +1,256 @@
1// The subgroup-size decision of pipeline creation (src/subgroup_size.h) without a GPU: synthetic shader index
2// entries against synthetic device properties, and the VkPipelineShaderStageCreateInfo chain that results.
3// The devices are the three shapes known so far:
4// - AMD, Windows driver (measured on a Radeon 880M, 26.11.2) and current Mesa RADV on GFX10+: sizes 32..64, the
5// stages FRAGMENT | COMPUTE | TASK | MESH can be required;
6// - NVIDIA: every stage can be required, but the only size is 32;
7// - an old RADV: sizes 32..64, COMPUTE only.
8// No game data.
9#include "../src/subgroup_size.h"
10
11#include <cstdio>
12#include <string>
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 namespace leonida;
22
23namespace {
24
25constexpr VkShaderStageFlags amd_stages = VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT |
26 VK_SHADER_STAGE_TASK_BIT_EXT | VK_SHADER_STAGE_MESH_BIT_EXT;
27constexpr VkShaderStageFlags all_stages = VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT |
28 VK_SHADER_STAGE_TASK_BIT_EXT | VK_SHADER_STAGE_MESH_BIT_EXT;
29
30SubgroupSizeCaps amd() {
31 SubgroupSizeCaps c;
32 c.subgroup_size_control = c.compute_full_subgroups = true;
33 c.min_size = 32;
34 c.max_size = 64;
35 c.default_size = 64;
36 c.max_compute_workgroup_subgroups = 16;
37 c.required_stages = amd_stages;
38 return c;
39}
40
41SubgroupSizeCaps nvidia() {
42 SubgroupSizeCaps c;
43 c.subgroup_size_control = c.compute_full_subgroups = true;
44 c.min_size = c.max_size = c.default_size = 32;
45 c.max_compute_workgroup_subgroups = 32;
46 c.required_stages = all_stages;
47 return c;
48}
49
50SubgroupSizeCaps old_radv() {
51 SubgroupSizeCaps c = amd();
52 c.required_stages = VK_SHADER_STAGE_COMPUTE_BIT;
53 return c;
54}
55
56// An index entry as the translator writes it: `wave64` shaders carry subgroup_size 64, the rest 32, and a shader
57// translated with --wave64-emulate has no size and a wave64_exchange.
58ShaderEntry entry(const char* stage, bool wave64, std::array<std::uint32_t, 3> local = {64, 1, 1},
59 bool emulated = false) {
60 ShaderEntry e;
61 e.name = std::string(stage) + (wave64 ? "_w64" : "_w32") + (emulated ? "_emu" : "");
62 e.stage = stage;
63 e.wave64 = wave64;
64 e.subgroup_size = emulated ? 0 : (wave64 ? 64 : 32);
65 if (emulated) e.wave64_exchange = "workgroup";
66 e.local_size = local;
67 return e;
68}
69
70} // namespace
71
72int main() {
73 // --- AMD-like -------------------------------------------------------------------------------------------
74 {
75 const SubgroupSizeCaps caps = amd();
76 // Native wave64 compute: 64, plus full subgroups when X is a multiple of 64.
77 auto r = decide_subgroup_size(entry("cs", true), caps);
78 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.wanted == 64);
79 CHECK(r.stage == VK_SHADER_STAGE_COMPUTE_BIT);
80 CHECK(r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
81 r = decide_subgroup_size(entry("cs", true, {128, 2, 1}), caps);
82 CHECK(r.size == 64 && (r.flags & VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT));
83 // X not a multiple of 64 (32x2): 64 is still required, full subgroups are not (-pNext-02757).
84 r = decide_subgroup_size(entry("cs", true, {32, 2, 1}), caps);
85 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0);
86 r = decide_subgroup_size(entry("cs", true, {96, 1, 1}), caps);
87 CHECK(r.size == 64 && r.flags == 0);
88 // A wave32 compute shader on a 32..64 device: 32 (the default is 64 here), full subgroups when X % 32 == 0.
89 r = decide_subgroup_size(entry("cs", false, {96, 1, 1}), caps);
90 CHECK(r.outcome == SubgroupOutcome::required && r.size == 32 &&
91 r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
92 r = decide_subgroup_size(entry("cs", false, {48, 1, 1}), caps);
93 CHECK(r.size == 32 && r.flags == 0);
94 // Pixel shaders can be required on AMD: wave64 gets 64, wave32 gets 32, never a full-subgroups flag.
95 r = decide_subgroup_size(entry("ps", true), caps);
96 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0 &&
97 r.stage == VK_SHADER_STAGE_FRAGMENT_BIT);
98 r = decide_subgroup_size(entry("ps", false), caps);
99 CHECK(r.outcome == SubgroupOutcome::required && r.size == 32 && r.flags == 0);
100 // Mesh: wave64 by construction, 64 and no flag (the flag is only asked of compute).
101 r = decide_subgroup_size(entry("ms", true, {128, 1, 1}), caps);
102 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0 &&
103 r.stage == VK_SHADER_STAGE_MESH_BIT_EXT);
104 // Vertex and geometry stages are not in the list: a wave64 VS cannot be given 64, but the default is 64, so it
105 // works as it is (device_default); there is no emulation for it.
106 r = decide_subgroup_size(entry("vs", true), caps);
107 CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0 && r.wanted == 64);
108 r = decide_subgroup_size(entry("gs", true), caps);
109 CHECK(r.outcome == SubgroupOutcome::device_default);
110 // A wave32 VS on a 64-wide default is wrong too.
111 r = decide_subgroup_size(entry("vs", false), caps);
112 CHECK(r.outcome == SubgroupOutcome::unavailable && r.wanted == 32);
113 // Emulated shaders ask for nothing, whatever the stage.
114 r = decide_subgroup_size(entry("cs", true, {64, 1, 1}, true), caps);
115 CHECK(r.outcome == SubgroupOutcome::emulated && r.size == 0 && r.flags == 0);
116 r = decide_subgroup_size(entry("ms", true, {128, 1, 1}, true), caps);
117 CHECK(r.outcome == SubgroupOutcome::emulated && r.size == 0 && r.flags == 0);
118 }
119
120 // --- NVIDIA-like: 32 only ----------------------------------------------------------------------------------
121 {
122 const SubgroupSizeCaps caps = nvidia();
123 // Wave32 is what the device does: nothing to chain, in any stage.
124 for (const char* stage : {"cs", "ps", "vs", "gs", "ms"}) {
125 const auto r = decide_subgroup_size(entry(stage, false), caps);
126 CHECK(r.outcome == SubgroupOutcome::device_fixed && r.size == 0 && r.flags == 0);
127 }
128 // Wave64 cannot be had (64 > max): native wave64 is reported in every stage, emulated is fine.
129 for (const char* stage : {"cs", "ps", "vs", "gs", "ms"}) {
130 const auto r = decide_subgroup_size(entry(stage, true), caps);
131 CHECK(r.outcome == SubgroupOutcome::unavailable && r.size == 0 && r.flags == 0 && r.wanted == 64);
132 }
133 const auto emulated = decide_subgroup_size(entry("cs", true, {64, 1, 1}, true), caps);
134 CHECK(emulated.outcome == SubgroupOutcome::emulated && emulated.size == 0);
135 }
136
137 // --- An old RADV: COMPUTE only ----------------------------------------------------------------------------------
138 {
139 const SubgroupSizeCaps caps = old_radv();
140 auto r = decide_subgroup_size(entry("cs", true), caps);
141 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 &&
142 r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
143 // Pixel shaders cannot be required, and the default is 64: a wave32 PS is wrong, a wave64 PS works as it is
144 // (device_default: nothing guarantees the default, min != max).
145 r = decide_subgroup_size(entry("ps", false), caps);
146 CHECK(r.outcome == SubgroupOutcome::unavailable && r.size == 0);
147 r = decide_subgroup_size(entry("ps", true), caps);
148 CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0);
149 r = decide_subgroup_size(entry("ms", true, {128, 1, 1}), caps);
150 CHECK(r.outcome == SubgroupOutcome::device_default);
151 }
152
153 // --- Feature, limit and index edge cases -------------------------------------------------------------------------
154 {
155 SubgroupSizeCaps caps = amd();
156 // computeFullSubgroups off: the size is still required, the flag is not set.
157 caps.compute_full_subgroups = false;
158 auto r = decide_subgroup_size(entry("cs", true), caps);
159 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0);
160 // subgroupSizeControl not enabled: the chain would break VUID -pNext-02755, so it is not asked for.
161 caps = amd();
162 caps.subgroup_size_control = false;
163 r = decide_subgroup_size(entry("cs", true), caps);
164 CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0 && r.flags == 0);
165 // The workgroup must fit size * maxComputeWorkgroupSubgroups (-pNext-02756): 1024 > 64 * 8.
166 caps = amd();
167 caps.max_compute_workgroup_subgroups = 8;
168 r = decide_subgroup_size(entry("cs", true, {1024, 1, 1}), caps);
169 CHECK(r.outcome == SubgroupOutcome::device_default);
170 r = decide_subgroup_size(entry("cs", true, {512, 1, 1}), caps);
171 CHECK(r.outcome == SubgroupOutcome::required && r.size == 64);
172 r = decide_subgroup_size(entry("cs", true, {16, 8, 8}), caps); // 1024 invocations too
173 CHECK(r.outcome == SubgroupOutcome::device_default);
174 // The limit is for compute and mesh; a pixel shader is not subject to it.
175 r = decide_subgroup_size(entry("ps", true), caps);
176 CHECK(r.outcome == SubgroupOutcome::required);
177 // A size that is not a power of two, or outside [min, max], is not chained.
178 caps = amd();
179 ShaderEntry odd = entry("cs", true);
180 odd.subgroup_size = 48;
181 CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable);
182 odd.subgroup_size = 128;
183 CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable);
184 odd.subgroup_size = 16;
185 CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable);
186 // An entry without subgroup_size (an index from an older translator) follows `wave64`.
187 ShaderEntry bare = entry("cs", true);
188 bare.subgroup_size = 0;
189 CHECK(decide_subgroup_size(bare, amd()).size == 64);
190 bare.wave64 = false;
191 CHECK(decide_subgroup_size(bare, amd()).size == 32);
192 // Device sizes that were never queried: nothing is asked for and nothing is reported.
193 CHECK(decide_subgroup_size(entry("cs", true), SubgroupSizeCaps{}).outcome == SubgroupOutcome::unknown_device);
194 // A stage this layer has no pipeline for.
195 CHECK(decide_subgroup_size(entry("rt", true), amd()).outcome == SubgroupOutcome::unknown_stage);
196 // A device that only has 64 runs a wave64 shader as it is.
197 caps = amd();
198 caps.min_size = caps.max_size = caps.default_size = 64;
199 CHECK(decide_subgroup_size(entry("ps", true), caps).outcome == SubgroupOutcome::device_fixed);
200 CHECK(decide_subgroup_size(entry("ps", false), caps).outcome == SubgroupOutcome::unavailable);
201 }
202
203 // --- The create-info chain -------------------------------------------------------------------------------------
204 {
205 const SubgroupSizeCaps caps = amd();
206 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo storage{};
207 VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
208 stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
209 apply_subgroup_request(decide_subgroup_size(entry("cs", true), caps), storage, stage);
210 CHECK(stage.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT);
211 CHECK(stage.pNext == &storage);
212 CHECK(storage.sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO);
213 CHECK(storage.requiredSubgroupSize == 64 && storage.pNext == nullptr);
214
215 // It goes in front of what the stage already chains.
216 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo other{};
217 VkPipelineShaderStageCreateInfo chained{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
218 chained.pNext = &other;
219 apply_subgroup_request(decide_subgroup_size(entry("ps", false), caps), storage, chained);
220 CHECK(chained.pNext == &storage && storage.pNext == &other && storage.requiredSubgroupSize == 32);
221 CHECK(chained.flags == 0);
222
223 // A request for nothing leaves the stage alone, whatever the reason.
224 for (const auto& e : {entry("cs", true, {64, 1, 1}, true), entry("vs", true)}) {
225 VkPipelineShaderStageCreateInfo untouched{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
226 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo unused{};
227 apply_subgroup_request(decide_subgroup_size(e, caps), unused, untouched);
228 CHECK(untouched.pNext == nullptr && untouched.flags == 0 && unused.sType == 0);
229 }
230 }
231
232 // --- Querying the device ----------------------------------------------------------------------------------------
233 {
234 VkPhysicalDevice device = reinterpret_cast<VkPhysicalDevice>(std::uintptr_t(0x1000));
235 VkPhysicalDevice seen = VK_NULL_HANDLE;
236 const auto fake = [&](VkPhysicalDevice physical, VkPhysicalDeviceProperties2* properties) {
237 seen = physical;
238 auto* subgroup = static_cast<VkPhysicalDeviceSubgroupProperties*>(properties->pNext);
239 auto* control = static_cast<VkPhysicalDeviceSubgroupSizeControlProperties*>(subgroup->pNext);
240 subgroup->subgroupSize = 64;
241 control->minSubgroupSize = 32;
242 control->maxSubgroupSize = 64;
243 control->maxComputeWorkgroupSubgroups = 16;
244 control->requiredSubgroupSizeStages = amd_stages;
245 };
246 SubgroupSizeCaps caps;
247 CHECK(query_subgroup_size_caps(fake, device, true, false, caps));
248 CHECK(seen == device);
249 CHECK(caps.default_size == 64 && caps.min_size == 32 && caps.max_size == 64 &&
250 caps.max_compute_workgroup_subgroups == 16 && caps.required_stages == amd_stages);
251 CHECK(caps.subgroup_size_control && !caps.compute_full_subgroups);
252 }
253
254 std::printf("subgroup size decision: AMD-like, NVIDIA-like, old RADV, limits, create-info chain and query OK\n");
255 return 0;
256}
diff --git a/runtime/test/vk_bc_zero_init_test.cpp b/runtime/test/vk_bc_zero_init_test.cpp
new file mode 100644
index 000000000..6edc36fcb
--- /dev/null
+++ b/runtime/test/vk_bc_zero_init_test.cpp
@@ -0,0 +1,388 @@
1// Committed block-compressed (BC*) texture zero-initialization regression (D3D-220, #1725):
2// D3D12 committed textures start zeroed unless D3D12_HEAP_FLAG_CREATE_NOT_ZEROED is set. Vulkan forbids
3// vkCmdClearColorImage on BC formats, so detail::initialize() must zero-fill them via vkCmdCopyBufferToImage
4// from either the device zero page (vk.zero_buffer) or a zeroed transfer-scratch chunk (vk.copy_scratch).
5//
6// Cases (all on explicitly poisoned 0x5A backing memory when host-visible, plus default device memory):
7// 1. Path A (vk.zero_buffer): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4) — untouched blocks are 0x00.
8// 2. Path A (vk.zero_buffer): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips — mip 1 untouched block (bytes 56..63) is 0x00.
9// 3. Path A (tiny 32-byte vk.zero_buffer): 32x32 BC7 image tiled in multiple row/column chunks — all 1024 bytes are 0x00.
10// 4. Path B (enable_copy_scratch, no zero_buffer — matches d3d12_copy_xfmt): both D3D-220 cases match bit for bit.
11// 5. not_zeroed = true (CREATE_NOT_ZEROED): zero-fill is skipped.
12// Skips with exit code 77 when no Vulkan 1.3 device with textureCompressionBC is available. No game data.
13#include "vk_test_device.h"
14#include "../src/vulkan_backend.h"
15
16#include <algorithm>
17#include <cstdint>
18#include <cstdio>
19#include <cstring>
20#include <vector>
21
22#define EXPECT(condition) do { \
23 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
24} while (0)
25
26namespace {
27
28struct OwnedImage {
29 VkDevice device = VK_NULL_HANDLE;
30 PFN_vkDestroyImage destroy_image = nullptr;
31 PFN_vkFreeMemory free_memory = nullptr;
32 VkImage image = VK_NULL_HANDLE;
33 VkDeviceMemory memory = VK_NULL_HANDLE;
34 bool poisoned = false;
35
36 ~OwnedImage() {
37 if (image && destroy_image) destroy_image(device, image, nullptr);
38 if (memory && free_memory) free_memory(device, memory, nullptr);
39 }
40 OwnedImage(const OwnedImage&) = delete;
41 OwnedImage& operator=(const OwnedImage&) = delete;
42 OwnedImage() = default;
43};
44
45bool create_image(const vktest::Device& d, VkFormat format, std::uint32_t width, std::uint32_t height,
46 std::uint32_t mips, VkBuffer poison_buf, OwnedImage& out) {
47 out.device = d.device;
48 out.destroy_image = d.fn<PFN_vkDestroyImage>("vkDestroyImage");
49 out.free_memory = d.fn<PFN_vkFreeMemory>("vkFreeMemory");
50
51 VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
52 info.imageType = VK_IMAGE_TYPE_2D;
53 info.format = format;
54 info.extent = {width, height, 1};
55 info.mipLevels = mips;
56 info.arrayLayers = 1;
57 info.samples = VK_SAMPLE_COUNT_1_BIT;
58 info.tiling = VK_IMAGE_TILING_OPTIMAL;
59 info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
60 if (d.fn<PFN_vkCreateImage>("vkCreateImage")(d.device, &info, nullptr, &out.image) != VK_SUCCESS) return false;
61
62 VkMemoryRequirements req{};
63 d.fn<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(d.device, out.image, &req);
64 VkPhysicalDeviceMemoryProperties mp{};
65 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp);
66
67 std::uint32_t type = UINT32_MAX;
68 for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) {
69 if (!(req.memoryTypeBits & (1u << i))) continue;
70 if (type == UINT32_MAX) type = i;
71 if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
72 type = i;
73 break;
74 }
75 }
76 if (type == UINT32_MAX) return false;
77
78 VkMemoryAllocateInfo alloc{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
79 alloc.allocationSize = req.size;
80 alloc.memoryTypeIndex = type;
81 if (d.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(d.device, &alloc, nullptr, &out.memory) != VK_SUCCESS)
82 return false;
83 if (d.fn<PFN_vkBindImageMemory>("vkBindImageMemory")(d.device, out.image, out.memory, 0) != VK_SUCCESS)
84 return false;
85
86 // Pre-fill every mip on the GPU with 0x5A so stale recycled VRAM is modeled deterministically on every GPU
87 // (discrete and integrated alike), before registering the image in LayoutTracker as UNDEFINED.
88 if (poison_buf) {
89 const bool ok = const_cast<vktest::Device&>(d).run([&](VkCommandBuffer cb) {
90 VkImageMemoryBarrier to_dst{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
91 to_dst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
92 to_dst.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
93 to_dst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
94 to_dst.srcQueueFamilyIndex = to_dst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
95 to_dst.image = out.image;
96 to_dst.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1};
97 d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
98 VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
99 nullptr, 1, &to_dst);
100 std::vector<VkBufferImageCopy> regions;
101 for (std::uint32_t m = 0; m < mips; ++m) {
102 VkBufferImageCopy r{};
103 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, m, 0, 1};
104 r.imageExtent = {std::max(1u, width >> m), std::max(1u, height >> m), 1};
105 regions.push_back(r);
106 }
107 d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage")(
108 cb, poison_buf, out.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, std::uint32_t(regions.size()),
109 regions.data());
110 return true;
111 });
112 if (!ok) return false;
113 out.poisoned = true;
114 }
115 return true;
116}
117
118VkDeviceMemory allocate_device_local(const vktest::Device& d, const VkMemoryRequirements& req) {
119 VkPhysicalDeviceMemoryProperties mp{};
120 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp);
121 std::uint32_t chosen = UINT32_MAX;
122 for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) {
123 if (!(req.memoryTypeBits & (1u << i))) continue;
124 if (chosen == UINT32_MAX) chosen = i;
125 if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
126 chosen = i;
127 break;
128 }
129 }
130 if (chosen == UINT32_MAX) return VK_NULL_HANDLE;
131 VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
132 info.allocationSize = req.size;
133 info.memoryTypeIndex = chosen;
134 VkDeviceMemory mem = VK_NULL_HANDLE;
135 if (d.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(d.device, &info, nullptr, &mem) != VK_SUCCESS)
136 return VK_NULL_HANDLE;
137 return mem;
138}
139
140// Runs the two D3D-220 partial uncompressed -> BC1 copies on a given context/queue:
141// (a) CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)
142// (b) CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips
143int run_d3d220_cases(const vktest::Device& d, leonida::VulkanContext& ctx, leonida::VulkanQueue& q,
144 VkBuffer poison_buf, VkBuffer up_buf, void* up_ptr, VkBuffer rb_buf, void* rb_ptr,
145 const char* label) {
146 using namespace leonida;
147
148 auto* up = static_cast<std::uint8_t*>(up_ptr);
149 auto* rb = static_cast<std::uint8_t*>(rb_ptr);
150 for (std::size_t i = 0; i < 4096; ++i) up[i] = static_cast<std::uint8_t>(i * 7 + 3);
151
152 // Case (a): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4).
153 // Destination has 4x4 BC1 blocks (8 bytes/block). Only blocks (2,1), (3,1), (2,2), (3,2) are written;
154 // the other 12 blocks (including block (0,0) at byte 0) must be 0x00.
155 {
156 OwnedImage src_img, dst_img;
157 EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 2, 2, 1, VK_NULL_HANDLE, src_img));
158 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, dst_img));
159
160 ResourceBinding src_rb{};
161 src_rb.image = src_img.image;
162 src_rb.format = VK_FORMAT_R32G32_UINT;
163 src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
164 src_rb.width = 2; src_rb.height = 2; src_rb.mip_levels = 1; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1;
165
166 ResourceBinding dst_rb{};
167 dst_rb.image = dst_img.image;
168 dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
169 dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
170 dst_rb.width = 16; dst_rb.height = 16; dst_rb.mip_levels = 1; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1;
171
172 ctx.add_resource(10, src_rb, VK_IMAGE_LAYOUT_UNDEFINED);
173 ctx.add_resource(11, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED);
174 std::memset(rb, 0xCD, 4096);
175
176 CommandList list;
177 CopyLocation up_loc{1, true, 0, 0, 2, 2, 1, 256};
178 CopyLocation src_loc{10, false, 0, 0, 0, 0, 0, 0};
179 CopyLocation dst_loc{11, false, 0, 0, 0, 0, 0, 0};
180 CopyLocation rb_loc{2, true, 0, 0, 16, 16, 1, 256};
181 EXPECT(list.copy_texture({src_loc, 0, 0, 0, up_loc, false, {}}));
182 EXPECT(list.transition({10, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
183 EXPECT(list.copy_texture({dst_loc, 8, 4, 0, src_loc, false, {}}));
184 EXPECT(list.transition({11, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
185 EXPECT(list.copy_texture({rb_loc, 0, 0, 0, dst_loc, false, {}}));
186 EXPECT(list.close());
187
188 const CommandList* ptr = &list;
189 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
190 EXPECT(q.idle());
191
192 // Check every 8-byte block across the 4x4 block grid (row pitch 256).
193 for (std::uint32_t by = 0; by < 4; ++by) {
194 for (std::uint32_t bx = 0; bx < 4; ++bx) {
195 const std::uint8_t* got = rb + std::size_t(by) * 256 + std::size_t(bx) * 8;
196 if (bx >= 2 && bx < 4 && by >= 1 && by < 3) {
197 const std::uint8_t* want = up + std::size_t(by - 1) * 256 + std::size_t(bx - 2) * 8;
198 EXPECT(std::memcmp(got, want, 8) == 0);
199 } else {
200 for (int k = 0; k < 8; ++k) EXPECT(got[k] == 0x00);
201 }
202 }
203 }
204 ctx.remove_resource(10);
205 ctx.remove_resource(11);
206 }
207
208 // Case (b): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips.
209 // Mip 0: 3x2 -> 12x8 (3x2 = 6 blocks written).
210 // Mip 1: 1x1 -> 6x4 (2x1 = 2 blocks; block 0 is written, block 1 at bytes 8..15 of mip 1 is untouched -> 0x00).
211 {
212 OwnedImage src_img, dst_img;
213 EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 3, 2, 2, VK_NULL_HANDLE, src_img));
214 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 12, 8, 2, poison_buf, dst_img));
215
216 ResourceBinding src_rb{};
217 src_rb.image = src_img.image;
218 src_rb.format = VK_FORMAT_R32G32_UINT;
219 src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
220 src_rb.width = 3; src_rb.height = 2; src_rb.mip_levels = 2; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1;
221
222 ResourceBinding dst_rb{};
223 dst_rb.image = dst_img.image;
224 dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
225 dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
226 dst_rb.width = 12; dst_rb.height = 8; dst_rb.mip_levels = 2; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1;
227
228 ctx.add_resource(12, src_rb, VK_IMAGE_LAYOUT_UNDEFINED);
229 ctx.add_resource(13, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED);
230 std::memset(rb, 0xCD, 4096);
231
232 // Upload mip 0 at offset 0 (2 rows * 256 = 512 bytes) and mip 1 at offset 512 (1 row * 256).
233 CommandList list;
234 CopyLocation up0{1, true, 0, 0, 3, 2, 1, 256};
235 CopyLocation up1{1, true, 0, 512, 1, 1, 1, 256};
236 CopyLocation src0{12, false, 0, 0, 0, 0, 0, 0};
237 CopyLocation src1{12, false, 1, 0, 0, 0, 0, 0};
238 CopyLocation dst0{13, false, 0, 0, 0, 0, 0, 0};
239 CopyLocation dst1{13, false, 1, 0, 0, 0, 0, 0};
240 CopyLocation rb0{2, true, 0, 0, 12, 8, 1, 256};
241 CopyLocation rb1{2, true, 0, 512, 6, 4, 1, 256};
242 EXPECT(list.copy_texture({src0, 0, 0, 0, up0, false, {}}));
243 EXPECT(list.copy_texture({src1, 0, 0, 0, up1, false, {}}));
244 EXPECT(list.transition({12, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
245 EXPECT(list.copy_resource({13, 12}));
246 EXPECT(list.transition({13, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
247 EXPECT(list.copy_texture({rb0, 0, 0, 0, dst0, false, {}}));
248 EXPECT(list.copy_texture({rb1, 0, 0, 0, dst1, false, {}}));
249 EXPECT(list.close());
250
251 const CommandList* ptr = &list;
252 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
253 EXPECT(q.idle());
254
255 // Mip 0: 2 rows of 3 blocks (24 bytes per row).
256 EXPECT(std::memcmp(rb + 0, up + 0, 24) == 0);
257 EXPECT(std::memcmp(rb + 256, up + 256, 24) == 0);
258 // Mip 1: block 0 (bytes 0..7) matches up + 512; untouched block 1 (bytes 8..15) must be 0x00.
259 EXPECT(std::memcmp(rb + 512, up + 512, 8) == 0);
260 for (int k = 8; k < 16; ++k) EXPECT(rb[512 + k] == 0x00);
261
262 ctx.remove_resource(12);
263 ctx.remove_resource(13);
264 }
265
266 (void)up_buf;
267 (void)rb_buf;
268 std::printf("bc zero-init (%s): partial CopyTextureRegion and 2-mip CopyResource ok\n", label);
269 return 0;
270}
271
272} // namespace
273
274int main() {
275 using namespace leonida;
276
277 vktest::Device d;
278 if (!d.create(false) || !d.bc) {
279 std::fprintf(stderr, "vk_bc_zero_init_test: no Vulkan 1.3 device with BC support, skipped\n");
280 return 77;
281 }
282
283 void* up_ptr = nullptr;
284 void* rb_ptr = nullptr;
285 void* zero_ptr = nullptr;
286 void* poison_ptr = nullptr;
287 const VkBuffer up_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up_ptr);
288 const VkBuffer rb_buf = d.buffer(8192, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb_ptr);
289 const VkBuffer zero_buf = d.buffer(65536, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &zero_ptr);
290 const VkBuffer poison_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &poison_ptr);
291 EXPECT(up_buf && rb_buf && zero_buf && poison_buf);
292 std::memset(zero_ptr, 0, 65536);
293 std::memset(poison_ptr, 0x5A, 4096);
294
295 ResourceBinding up_rb{};
296 up_rb.buffer = up_buf;
297 up_rb.size = 4096;
298 ResourceBinding rb_rb{};
299 rb_rb.buffer = rb_buf;
300 rb_rb.size = 8192;
301 rb_rb.host_readable = true;
302
303 // Path A: device arena zero page (vk.zero_buffer).
304 {
305 VulkanContext ctx(d.device_proc, d.device, true);
306 EXPECT(ctx.loaded());
307 ctx.set_zero_page(zero_buf, 0, 65536);
308 ctx.add_resource(1, up_rb);
309 ctx.add_resource(2, rb_rb);
310 VulkanQueue q(ctx, d.queue, d.family);
311 EXPECT(q.ok());
312 EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "zero_buffer") == 0);
313
314 // Multi-tile chunking: shrink zero_page to 32 bytes (2 BC7 blocks) and zero-init a 32x32 BC7 image (64 blocks).
315 ctx.set_zero_page(zero_buf, 16, 32);
316 OwnedImage bc7_img;
317 EXPECT(create_image(d, VK_FORMAT_BC7_UNORM_BLOCK, 32, 32, 1, poison_buf, bc7_img));
318 ResourceBinding bc7_rb{};
319 bc7_rb.image = bc7_img.image;
320 bc7_rb.format = VK_FORMAT_BC7_UNORM_BLOCK;
321 bc7_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
322 bc7_rb.width = 32; bc7_rb.height = 32; bc7_rb.mip_levels = 1; bc7_rb.array_layers = 1; bc7_rb.depth = 1; bc7_rb.samples = 1;
323 ctx.add_resource(20, bc7_rb, VK_IMAGE_LAYOUT_UNDEFINED);
324 std::memset(rb_ptr, 0xCD, 8192);
325
326 CommandList list;
327 EXPECT(list.transition({20, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
328 CopyLocation bc7_loc{20, false, 0, 0, 0, 0, 0, 0};
329 CopyLocation rb_loc{2, true, 0, 0, 32, 32, 1, 256};
330 EXPECT(list.copy_texture({rb_loc, 0, 0, 0, bc7_loc, false, {}}));
331 EXPECT(list.close());
332 const CommandList* ptr = &list;
333 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
334 EXPECT(q.idle());
335
336 auto* rb = static_cast<std::uint8_t*>(rb_ptr);
337 for (std::uint32_t row = 0; row < 8; ++row)
338 for (std::uint32_t x = 0; x < 8 * 16; ++x)
339 EXPECT(rb[row * 256 + x] == 0x00);
340 ctx.remove_resource(20);
341 std::printf("bc zero-init (tiny 32-byte zero_buffer chunking on 32x32 BC7): ok\n");
342
343 // CREATE_NOT_ZEROED (not_zeroed = true) must skip zero-fill.
344 ctx.set_zero_page(zero_buf, 0, 65536);
345 OwnedImage nz_img;
346 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, nz_img));
347 EXPECT(nz_img.poisoned);
348 ResourceBinding nz_rb{};
349 nz_rb.image = nz_img.image;
350 nz_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
351 nz_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
352 nz_rb.width = 16; nz_rb.height = 16; nz_rb.mip_levels = 1; nz_rb.array_layers = 1; nz_rb.depth = 1; nz_rb.samples = 1;
353 nz_rb.not_zeroed = true;
354 ctx.add_resource(21, nz_rb, VK_IMAGE_LAYOUT_UNDEFINED);
355 std::memset(rb_ptr, 0xCD, 8192);
356
357 CommandList nz_list;
358 EXPECT(nz_list.transition({21, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
359 CopyLocation nz_loc{21, false, 0, 0, 0, 0, 0, 0};
360 CopyLocation nz_rb_loc{2, true, 0, 0, 16, 16, 1, 256};
361 EXPECT(nz_list.copy_texture({nz_rb_loc, 0, 0, 0, nz_loc, false, {}}));
362 EXPECT(nz_list.close());
363 const CommandList* nz_ptr = &nz_list;
364 EXPECT(q.execute({&nz_ptr, 1}) == ReplayResult::success);
365 EXPECT(q.idle());
366 EXPECT(rb[0] == 0x5A);
367 ctx.remove_resource(21);
368 std::printf("bc zero-init (not_zeroed = true skips zero-fill): ok\n");
369 }
370
371 // Path B: copy_scratch + vkCmdFillBuffer fallback (no zero_buffer, matching d3d12_copy_xfmt without BDA).
372 {
373 VulkanContext ctx(d.device_proc, d.device, true);
374 EXPECT(ctx.loaded());
375 ctx.enable_copy_scratch(d.device_proc, [&](const VkMemoryRequirements& req) {
376 return allocate_device_local(d, req);
377 });
378 ctx.add_resource(1, up_rb);
379 ctx.add_resource(2, rb_rb);
380 VulkanQueue q(ctx, d.queue, d.family);
381 EXPECT(q.ok());
382 EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "copy_scratch") == 0);
383 }
384
385 EXPECT(d.validation_errors() == 0);
386 std::printf("vk_bc_zero_init_test: ok\n");
387 return 0;
388}
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 73ac39013..419a1dda4 100644
--- a/runtime/test/vk_bindless_test.cpp
+++ b/runtime/test/vk_bindless_test.cpp
@@ -24,6 +24,7 @@
24#include "vk_shader_fma.h" 24#include "vk_shader_fma.h"
25#include "../src/vulkan_bindless.h" 25#include "../src/vulkan_bindless.h"
26 26
27#include <algorithm>
27#include <array> 28#include <array>
28#include <cmath> 29#include <cmath>
29#include <cstdio> 30#include <cstdio>
@@ -105,7 +106,7 @@ std::uint32_t probe_depth(std::span<const std::uint32_t> table, const Descriptor
105 106
106int main(int argc, char** argv) { 107int main(int argc, char** argv) {
107 if (argc < 3) { 108 if (argc < 3) {
108 std::fprintf(stderr, "usage: vk_bindless_test <vs_ids.spv> <ps_tex.spv>\n"); 109 std::fprintf(stderr, "usage: vk_bindless_test <vs_ids.spv> <ps_tex.spv | ps_imgatomic.spv>\n");
109 return 2; 110 return 2;
110 } 111 }
111 // A bad readback in a single channel must still fail when all three others match. 112 // A bad readback in a single channel must still fail when all three others match.
@@ -225,6 +226,15 @@ int main(int argc, char** argv) {
225 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; 226 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12};
226 enable.features.shaderInt64 = VK_TRUE; 227 enable.features.shaderInt64 = VK_TRUE;
227 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; 228 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
229 // ps_imgatomic: image atomics in a pixel shader need fragment stores and atomics.
230 const bool atomic_mode = std::strstr(argv[2], "imgatomic") != nullptr;
231 if (atomic_mode) {
232 if (!have.features.fragmentStoresAndAtomics) {
233 std::printf("unsupported: fragmentStoresAndAtomics (image atomics in a pixel shader)\n");
234 return unsupported;
235 }
236 enable.features.fragmentStoresAndAtomics = VK_TRUE;
237 }
228 238
229 std::uint32_t qn = 0; 239 std::uint32_t qn = 0;
230 vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); 240 vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr);
@@ -260,7 +270,7 @@ int main(int argc, char** argv) {
260 LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout); 270 LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout);
261 LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); 271 LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass);
262 LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); 272 LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer);
263 LD(vkFreeMemory); LD(vkDestroyDevice); 273 LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage);
264 VkQueue queue = VK_NULL_HANDLE; 274 VkQueue queue = VK_NULL_HANDLE;
265 vkGetDeviceQueue(dev, qi, 0, &queue); 275 vkGetDeviceQueue(dev, qi, 0, &queue);
266 VkPhysicalDeviceMemoryProperties mp; 276 VkPhysicalDeviceMemoryProperties mp;
@@ -663,6 +673,171 @@ int main(int argc, char** argv) {
663 const std::uint32_t sampler_index = set.add_sampler(nearest); 673 const std::uint32_t sampler_index = set.add_sampler(nearest);
664 EXPECT(decoy_sampler == 1 && sampler_index == 2); 674 EXPECT(decoy_sampler == 1 && sampler_index == 2);
665 675
676 if (atomic_mode) {
677 // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from
678 // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd
679 // pixels are discarded after their atomics, which still count.
680 constexpr std::uint32_t atomic_va = 1024, AW = 8, A3 = 4;
681 const std::array<DescriptorKey, 4> keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8},
682 {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8},
683 {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8},
684 {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}};
685 for (std::uint32_t k = 0; k < 4; ++k)
686 std::memcpy(static_cast<char*>(heap_map) + atomic_va + 32 * k, keys[k].data(), 32);
687 const VkImageUsageFlags atomic_usage =
688 VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
689 VK_IMAGE_USAGE_TRANSFER_DST_BIT;
690 VkImage images[4];
691 VkImageView views[4];
692 for (int k = 0; k < 3; ++k) CHECK(make_image(VK_FORMAT_R32_UINT, AW, AW, atomic_usage, &images[k], &views[k]));
693 { // the 3D image
694 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
695 ii.imageType = VK_IMAGE_TYPE_3D;
696 ii.format = VK_FORMAT_R32_UINT;
697 ii.extent = {A3, A3, A3};
698 ii.mipLevels = 1;
699 ii.arrayLayers = 1;
700 ii.samples = VK_SAMPLE_COUNT_1_BIT;
701 ii.usage = atomic_usage;
702 CHECK(vkCreateImage(dev, &ii, nullptr, &images[3]));
703 VkMemoryRequirements mr;
704 vkGetImageMemoryRequirements(dev, images[3], &mr);
705 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
706 ai.allocationSize = mr.size;
707 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
708 VkDeviceMemory m;
709 CHECK(vkAllocateMemory(dev, &ai, nullptr, &m));
710 allocations.push_back(m);
711 CHECK(vkBindImageMemory(dev, images[3], m, 0));
712 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
713 vi.image = images[3];
714 vi.viewType = VK_IMAGE_VIEW_TYPE_3D;
715 vi.format = VK_FORMAT_R32_UINT;
716 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
717 CHECK(vkCreateImageView(dev, &vi, nullptr, &views[3]));
718 }
719 std::uint32_t indices[4];
720 for (int k = 0; k < 4; ++k) {
721 StorageViews storage;
722 storage.as_uint = views[k];
723 storage.r32ui = views[k];
724 indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k],
725 VK_IMAGE_LAYOUT_GENERAL, storage);
726 EXPECT(indices[k] != 0);
727 EXPECT(set.insert_key(keys[k], indices[k]));
728 }
729 EXPECT(flush());
730
731 // Clear: umax and or start at 0, umin at all ones; then GENERAL for the shader's atomics.
732 CHECK(vkResetCommandBuffer(cmd, 0));
733 CHECK(vkBeginCommandBuffer(cmd, &begin));
734 if (!set.fallbacks_ready()) set.record_fallback_init(cmd);
735 for (int k = 0; k < 4; ++k) {
736 VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
737 b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
738 b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
739 b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
740 b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
741 b.image = images[k];
742 b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
743 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0,
744 nullptr, 0, nullptr, 1, &b);
745 VkClearColorValue value{};
746 for (auto& c : value.uint32) c = k == 1 ? 0xFFFFFFFFu : 0u;
747 vkCmdClearColorImage(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, &value, 1, &b.subresourceRange);
748 b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
749 b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
750 b.oldLayout = b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
751 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0,
752 nullptr, 0, nullptr, 1, &b);
753 }
754 CHECK(submit());
755
756 // The draw, then the images and the render target read back.
757 const VkDeviceSize image_bytes = 3 * AW * AW * 4 + A3 * A3 * A3 * 4;
758 VkBuffer atomic_readback;
759 void* atomic_map;
760 CHECK(make_buffer(image_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &atomic_readback, &atomic_map));
761 CHECK(vkResetCommandBuffer(cmd, 0));
762 CHECK(vkBeginCommandBuffer(cmd, &begin));
763 VkClearValue clear{};
764 for (float& channel : clear.color.float32) channel = 0.25f;
765 VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
766 rbi.renderPass = pass;
767 rbi.framebuffer = framebuffer;
768 rbi.renderArea = scissor;
769 rbi.clearValueCount = 1;
770 rbi.pClearValues = &clear;
771 vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE);
772 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
773 const VkDescriptorSet bound = set.set();
774 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr);
775 std::uint32_t block[36] = {};
776 block[2] = atomic_va;
777 block[32] = std::uint32_t(heap_base);
778 block[33] = std::uint32_t(heap_base >> 32);
779 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,
780 sizeof(block), block);
781 vkCmdDraw(cmd, 3, 1, 0, 0);
782 vkCmdEndRenderPass(cmd);
783 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
784 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
785 after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
786 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after,
787 0, nullptr, 0, nullptr);
788 VkDeviceSize offset = 0;
789 for (int k = 0; k < 4; ++k) {
790 VkBufferImageCopy rc{};
791 rc.bufferOffset = offset;
792 rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
793 rc.imageExtent = k == 3 ? VkExtent3D{A3, A3, A3} : VkExtent3D{AW, AW, 1};
794 vkCmdCopyImageToBuffer(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, atomic_readback, 1, &rc);
795 offset += k == 3 ? A3 * A3 * A3 * 4 : AW * AW * 4;
796 }
797 VkBufferImageCopy tc{};
798 tc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
799 tc.imageExtent = {W, H, 1};
800 vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &tc);
801 CHECK(submit());
802
803 // The model: every pixel's atomics, discarded or not.
804 std::vector<std::uint32_t> want(3 * AW * AW + A3 * A3 * A3, 0);
805 for (std::uint32_t t = 0; t < AW * AW; ++t) want[AW * AW + t] = 0xFFFFFFFFu;
806 for (std::uint32_t py = 0; py < H; ++py)
807 for (std::uint32_t px = 0; px < W; ++px) {
808 const std::uint32_t id = px + 64 * py, t = (py >> 3) * AW + (px >> 3);
809 want[t] = std::max(want[t], id);
810 want[AW * AW + t] = std::min(want[AW * AW + t], id);
811 want[2 * AW * AW + t] |= 1u << (id & 31);
812 const std::uint32_t v = ((px & 3) * A3 + (py >> 4)) * A3 + (px >> 4);
813 want[3 * AW * AW + v] = std::max(want[3 * AW * AW + v], id);
814 }
815 const auto* got = static_cast<const std::uint32_t*>(atomic_map);
816 const char* names[] = {"2D umax", "2D umin", "2D or", "3D umax"};
817 unsigned wrong = 0;
818 for (std::size_t i = 0; i < want.size(); ++i) {
819 if (got[i] == want[i]) continue;
820 const int k = i < 3 * AW * AW ? int(i / (AW * AW)) : 3;
821 if (wrong++ < 8)
822 std::printf(" %s texel %zu: got 0x%08x, want 0x%08x\n", names[k],
823 k == 3 ? i - 3 * AW * AW : i % (AW * AW), got[i], want[i]);
824 }
825 const float* rt = static_cast<const float*>(readback_map);
826 unsigned bad_rt = 0;
827 for (std::uint32_t py = 0; py < H; ++py)
828 for (std::uint32_t px = 0; px < W; ++px)
829 bad_rt += rt[(py * W + px) * 4] != ((px & 1) ? 0.25f : 1.0f);
830 std::printf("ps_imgatomic: %u of %zu texels wrong (2D umax/umin/or 8x8 each, 3D umax 4x4x4); "
831 "%u of %u render-target pixels wrong (odd columns discarded)\n",
832 wrong, want.size(), bad_rt, W * H);
833 vkDeviceWaitIdle(dev);
834 if (g_validation_errors) {
835 std::printf("ps_imgatomic: %u validation errors\n", g_validation_errors);
836 return 1;
837 }
838 return wrong || bad_rt ? 1 : 0;
839 }
840
666 // A view that comes and goes before the set is flushed is never written: a texture created and destroyed 841 // A view that comes and goes before the set is flushed is never written: a texture created and destroyed
667 // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view 842 // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view
668 // would be a validation error. 843 // would be a validation error.
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index bdefac894..a8fe0eaeb 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -32,6 +32,7 @@
32#include <cctype> 32#include <cctype>
33#include <charconv> 33#include <charconv>
34#include <chrono> 34#include <chrono>
35#include <cmath>
35#include <condition_variable> 36#include <condition_variable>
36#include <cstdio> 37#include <cstdio>
37#include <cstring> 38#include <cstring>
@@ -395,27 +396,36 @@ int main(int argc, char** argv) {
395 bool cache_feedback = false; 396 bool cache_feedback = false;
396 for (int i = 2; i < argc; i++) { 397 for (int i = 2; i < argc; i++) {
397 std::string a = argv[i]; 398 std::string a = argv[i];
398 auto val = [&] { return i + 1 < argc ? std::string(argv[++i]) : std::string("0"); }; 399 auto value = [&]() -> std::string_view {
399 if (a == "--jobs") jobs = std::max(1u, uint32_t(std::stoul(val()))); 400 if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {};
400 else if (a == "--start") start = std::stoull(val()); 401 return argv[++i];
401 else if (a == "--count") count = std::stoull(val()); 402 };
402 else if (a == "--slow") slow = std::stod(val()); 403 auto number = [&](auto& dest) {
403 else if (a == "--stage") stage_filter = val(); 404 const auto text = value();
405 if (text.empty()) return false;
406 const auto end = text.data() + text.size();
407 const auto [ptr, ec] = std::from_chars(text.data(), end, dest);
408 return ec == std::errc{} && ptr == end;
409 };
410 bool valid = true;
411 if (a == "--jobs") {
412 valid = number(jobs);
413 jobs = std::max(1u, jobs);
414 } else if (a == "--start") valid = number(start);
415 else if (a == "--count") valid = number(count);
416 else if (a == "--slow") valid = number(slow) && std::isfinite(slow) && slow >= 0.0;
417 else if (a == "--stage") valid = !(stage_filter = value()).empty();
404 else if (a == "--compute-only") stage_filter = "cs"; 418 else if (a == "--compute-only") stage_filter = "cs";
405 else if (a == "--graphics-only") stage_filter = "graphics"; 419 else if (a == "--graphics-only") stage_filter = "graphics";
406 else if (a == "--max-bytes") max_bytes = std::stoull(val()); 420 else if (a == "--max-bytes") valid = number(max_bytes);
407 else if (a == "--large-module-bytes") { 421 else if (a == "--large-module-bytes") valid = number(large_module_bytes);
408 const std::string_view value = i + 1 < argc ? argv[++i] : ""; 422 else if (a == "--stats") valid = !(stats_path = value()).empty();
409 const auto end = value.data() + value.size();
410 const auto [ptr, ec] = std::from_chars(value.data(), end, large_module_bytes);
411 if (ec != std::errc{} || ptr != end) {
412 std::fprintf(stderr, "--large-module-bytes requires a non-negative byte count\n");
413 return 2;
414 }
415 }
416 else if (a == "--stats") stats_path = val();
417 else if (a == "--cache-feedback") cache_feedback = true; 423 else if (a == "--cache-feedback") cache_feedback = true;
418 else cache_path = a; 424 else cache_path = a;
425 if (!valid) {
426 std::fprintf(stderr, "%s requires a valid value\n", a.c_str());
427 return 2;
428 }
419 } 429 }
420 if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") { 430 if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") {
421 std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str()); 431 std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str());
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index 3748aeec7..46a2531ef 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -19,10 +19,12 @@
19#include "../src/vulkan_present.h" 19#include "../src/vulkan_present.h"
20 20
21#include <atomic> 21#include <atomic>
22#include <chrono>
22#include <cmath> 23#include <cmath>
23#include <cstdint> 24#include <cstdint>
24#include <cstdio> 25#include <cstdio>
25#include <cstdlib> 26#include <cstdlib>
27#include <functional>
26#include <string_view> 28#include <string_view>
27#include <thread> 29#include <thread>
28#include <vector> 30#include <vector>
@@ -49,10 +51,12 @@ namespace driver {
49PFN_vkGetInstanceProcAddr real_get_instance = nullptr; 51PFN_vkGetInstanceProcAddr real_get_instance = nullptr;
50PFN_vkGetDeviceProcAddr real_get_device = nullptr; 52PFN_vkGetDeviceProcAddr real_get_device = nullptr;
51PFN_vkQueueSubmit real_submit = nullptr; 53PFN_vkQueueSubmit real_submit = nullptr;
54PFN_vkQueuePresentKHR real_present = nullptr;
52PFN_vkCmdPipelineBarrier real_barrier = nullptr; 55PFN_vkCmdPipelineBarrier real_barrier = nullptr;
53PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; 56PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
54 57
55std::atomic<VkResult> fail_next_submit{VK_SUCCESS}; 58std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
59std::function<void()> on_next_present;
56std::atomic<bool> observe_capture{false}; 60std::atomic<bool> observe_capture{false};
57std::atomic<bool> saw_capture_waw{false}; 61std::atomic<bool> saw_capture_waw{false};
58std::atomic<std::uint32_t> capture_copies{0}; 62std::atomic<std::uint32_t> capture_copies{0};
@@ -65,6 +69,15 @@ VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count,
65 return real_submit(queue, count, submits, fence); 69 return real_submit(queue, count, submits, fence);
66} 70}
67 71
72VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoKHR* info) {
73 if (on_next_present) {
74 auto cb = std::move(on_next_present);
75 on_next_present = {};
76 cb();
77 }
78 return real_present(queue, info);
79}
80
68VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage, 81VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage,
69 VkPipelineStageFlags dst_stage, VkDependencyFlags flags, 82 VkPipelineStageFlags dst_stage, VkDependencyFlags flags,
70 std::uint32_t mem_count, const VkMemoryBarrier* mem, 83 std::uint32_t mem_count, const VkMemoryBarrier* mem,
@@ -100,6 +113,7 @@ VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage
100VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { 113VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
101 const std::string_view n = name; 114 const std::string_view n = name;
102 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 115 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
116 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
103 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier); 117 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier);
104 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer); 118 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer);
105 return real_get_device(device, name); 119 return real_get_device(device, name);
@@ -114,6 +128,7 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
114 real_get_instance = instance_proc; 128 real_get_instance = instance_proc;
115 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr")); 129 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
116 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit")); 130 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
131 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
117 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier")); 132 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier"));
118 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer")); 133 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer"));
119} 134}
@@ -193,15 +208,36 @@ int main() {
193 EXPECT(presenter.ok()); 208 EXPECT(presenter.ok());
194 EXPECT(presenter.enable_capture()); 209 EXPECT(presenter.enable_capture());
195 210
196 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker. 211 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker (O(1) rollback
212 // even with many live tracked textures), and tracker_mutex_ must be released before vkQueuePresentKHR.
213 for (ResourceId extra = 1000; extra < 1512; ++extra)
214 context.add_resource(extra, side_rb, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
197 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 215 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
198 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); 216 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
199 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY); 217 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY);
200 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 218 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
201 219 EXPECT(context.layout(1000, 0) == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
202 // Next present succeeds, runs the deferred zero-fill, and commits GENERAL. 220
221 // Next present succeeds, runs the deferred zero-fill, commits GENERAL, and unlocks tracker_mutex_ before
222 // vkQueuePresentKHR so other threads' emit() / layout() calls are not blocked by presentation.
223 std::atomic<bool> read_done{false};
224 VkImageLayout seen_during_present = VK_IMAGE_LAYOUT_UNDEFINED;
225 bool unblocked_during_present = false;
226 std::thread reader;
227 driver::on_next_present = [&] {
228 reader = std::thread([&] {
229 seen_during_present = context.layout(1, 0);
230 read_done.store(true, std::memory_order_release);
231 });
232 std::this_thread::sleep_for(std::chrono::milliseconds(30));
233 unblocked_during_present = read_done.load(std::memory_order_acquire);
234 };
203 EXPECT(presenter.present(1, true) == VK_SUCCESS); 235 EXPECT(presenter.present(1, true) == VK_SUCCESS);
236 if (reader.joinable()) reader.join();
237 EXPECT(unblocked_during_present);
238 EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL);
204 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL); 239 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL);
240 for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra);
205 std::vector<std::uint8_t> pixels; 241 std::vector<std::uint8_t> pixels;
206 VkExtent2D ext{}; 242 VkExtent2D ext{};
207 VkFormat fmt = VK_FORMAT_UNDEFINED; 243 VkFormat fmt = VK_FORMAT_UNDEFINED;
diff --git a/runtime/test/vk_queue_query_sync_test.cpp b/runtime/test/vk_queue_query_sync_test.cpp
new file mode 100644
index 000000000..a9daf6477
--- /dev/null
+++ b/runtime/test/vk_queue_query_sync_test.cpp
@@ -0,0 +1,351 @@
1// VulkanQueue / VulkanContext query-state synchronization and failed-submit wait preservation regressions
2// (runtime/src/vulkan_backend.h):
3// 1. VulkanContext::remove_query_pool() must serialize with tracker_mutex_ so an in-flight VulkanQueue::execute()
4// that already unlocked resource_mutex_ cannot suffer a use-after-free in QueryReplay::commit().
5// 2. VulkanQueue::execute() must acquire tracker_mutex_ before QueryReplay::plan() so concurrent queues see
6// submission-order query state (no data race on QueryPool::ended / QueryPool::occlusion and no stale zero-fill).
7// 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() timeline semaphores for the retry.
8// 4. Concurrent multi-queue query End/Resolve + add/remove_query_pool stress with zero Vulkan validation errors.
9// Skips with exit code 77 when no Vulkan 1.3 device is available. No game data.
10#include "vk_test_device.h"
11#include "../src/vulkan_backend.h"
12
13#include <atomic>
14#include <chrono>
15#include <cstdint>
16#include <cstdio>
17#include <cstring>
18#include <functional>
19#include <string_view>
20#include <thread>
21#include <vector>
22
23#define EXPECT(condition) do { \
24 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
25} while (0)
26
27namespace {
28
29namespace driver {
30PFN_vkGetDeviceProcAddr real_get_device = nullptr;
31PFN_vkQueueSubmit real_submit = nullptr;
32PFN_vkCmdCopyQueryPoolResults real_copy_queries = nullptr;
33PFN_vkCmdFillBuffer real_fill_buffer = nullptr;
34
35std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
36std::atomic<bool> capture_next_waits{false};
37std::atomic<std::uint32_t> captured_wait_count{0};
38std::atomic<std::uintptr_t> captured_wait_sem{0};
39std::atomic<std::uint64_t> captured_wait_val{0};
40
41std::atomic<bool> count_resolves{false};
42std::atomic<std::uint32_t> copy_query_calls{0};
43std::atomic<std::uint32_t> fill_buffer_calls{0};
44
45// Optional one-shot callback invoked inside vkQueueSubmit right before calling the real driver.
46// Returning non-VK_SUCCESS short-circuits the submit with that status.
47std::function<VkResult()> on_next_submit;
48
49VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits,
50 VkFence fence) {
51 if (on_next_submit) {
52 auto cb = std::move(on_next_submit);
53 on_next_submit = {};
54 const VkResult override_res = cb();
55 if (override_res != VK_SUCCESS) return override_res;
56 }
57 const VkResult armed = fail_next_submit.exchange(VK_SUCCESS);
58 if (armed != VK_SUCCESS) return armed;
59 if (capture_next_waits.exchange(false) && count > 0 && submits) {
60 captured_wait_count.store(submits[0].waitSemaphoreCount);
61 if (submits[0].waitSemaphoreCount > 0 && submits[0].pWaitSemaphores) {
62 captured_wait_sem.store(reinterpret_cast<std::uintptr_t>(submits[0].pWaitSemaphores[0]));
63 const auto* timeline = reinterpret_cast<const VkTimelineSemaphoreSubmitInfo*>(submits[0].pNext);
64 if (timeline && timeline->sType == VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO &&
65 timeline->waitSemaphoreValueCount > 0 && timeline->pWaitSemaphoreValues) {
66 captured_wait_val.store(timeline->pWaitSemaphoreValues[0]);
67 }
68 }
69 }
70 return real_submit(queue, count, submits, fence);
71}
72
73VKAPI_ATTR void VKAPI_CALL cmd_copy_query_pool_results(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
74 std::uint32_t count, VkBuffer dst, VkDeviceSize offset,
75 VkDeviceSize stride, VkQueryResultFlags flags) {
76 if (count_resolves.load(std::memory_order_relaxed)) copy_query_calls.fetch_add(1, std::memory_order_relaxed);
77 real_copy_queries(cb, pool, first, count, dst, offset, stride, flags);
78}
79
80VKAPI_ATTR void VKAPI_CALL cmd_fill_buffer(VkCommandBuffer cb, VkBuffer dst, VkDeviceSize offset, VkDeviceSize size,
81 std::uint32_t data) {
82 if (count_resolves.load(std::memory_order_relaxed)) fill_buffer_calls.fetch_add(1, std::memory_order_relaxed);
83 real_fill_buffer(cb, dst, offset, size, data);
84}
85
86VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
87 const std::string_view n = name;
88 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
89 if (n == "vkCmdCopyQueryPoolResults") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_query_pool_results);
90 if (n == "vkCmdFillBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_fill_buffer);
91 return real_get_device(device, name);
92}
93
94void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) {
95 real_get_device = device_proc;
96 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(device_proc(device, "vkQueueSubmit"));
97 real_copy_queries =
98 reinterpret_cast<PFN_vkCmdCopyQueryPoolResults>(device_proc(device, "vkCmdCopyQueryPoolResults"));
99 real_fill_buffer = reinterpret_cast<PFN_vkCmdFillBuffer>(device_proc(device, "vkCmdFillBuffer"));
100}
101} // namespace driver
102
103} // namespace
104
105int main() {
106 using namespace leonida;
107
108 vktest::Device d;
109 if (!d.create(false)) {
110 std::fprintf(stderr, "vk_queue_query_sync_test: no Vulkan 1.3 device, skipped\n");
111 return 77;
112 }
113 driver::install(d.device_proc, d.device);
114
115 const auto create_query_pool = d.fn<PFN_vkCreateQueryPool>("vkCreateQueryPool");
116 const auto destroy_query_pool = d.fn<PFN_vkDestroyQueryPool>("vkDestroyQueryPool");
117 EXPECT(create_query_pool && destroy_query_pool);
118
119 auto make_occlusion_pool = [&](std::uint32_t count) -> VkQueryPool {
120 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
121 info.queryType = VK_QUERY_TYPE_OCCLUSION;
122 info.queryCount = count;
123 VkQueryPool pool = VK_NULL_HANDLE;
124 if (create_query_pool(d.device, &info, nullptr, &pool) != VK_SUCCESS) return VK_NULL_HANDLE;
125 return pool;
126 };
127
128 const VkQueryPool pool_uaf = make_occlusion_pool(2);
129 const VkQueryPool pool_race = make_occlusion_pool(2);
130 const VkQueryPool pool_stress = make_occlusion_pool(32);
131 EXPECT(pool_uaf && pool_race && pool_stress);
132
133 {
134 VulkanContext context(driver::get_device, d.device, true);
135 EXPECT(context.loaded());
136 VulkanQueue queue_a(context, d.queue, d.family);
137 VulkanQueue queue_b(context, d.queue, d.family);
138 EXPECT(queue_a.ok() && queue_b.ok());
139
140 void* src_ptr = nullptr;
141 void* dst_ptr = nullptr;
142 void* res_ptr = nullptr;
143 const VkBuffer src_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src_ptr);
144 const VkBuffer dst_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &dst_ptr);
145 const VkBuffer res_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &res_ptr);
146 EXPECT(src_buf && dst_buf && res_buf);
147
148 ResourceBinding src_rb{};
149 src_rb.buffer = src_buf;
150 src_rb.size = 64;
151 ResourceBinding dst_rb{};
152 dst_rb.buffer = dst_buf;
153 dst_rb.size = 64;
154 dst_rb.host_readable = true;
155 ResourceBinding res_rb{};
156 res_rb.buffer = res_buf;
157 res_rb.size = 64;
158 res_rb.host_readable = true;
159 context.add_resource(1, src_rb);
160 context.add_resource(2, dst_rb);
161 context.add_resource(3, res_rb);
162
163 // 1. remove_query_pool() must block on tracker_mutex_ while execute() is between resource_lock.unlock() and
164 // QueryReplay::commit(), preventing a use-after-free on the QueryPool* stored in QueryReplay::pending_.
165 {
166 constexpr QueryHeapId heap_id = 77;
167 QueryPool qp{};
168 qp.pool = pool_uaf;
169 qp.heap_type = d3d12_query_heap::occlusion;
170 qp.count = 2;
171 qp.ended.assign(2, false);
172 context.add_query_pool(heap_id, qp);
173
174 CommandList list;
175 EXPECT(list.begin_query({heap_id, d3d12_query::occlusion, 0}));
176 EXPECT(list.end_query({heap_id, d3d12_query::occlusion, 0}));
177 EXPECT(list.close());
178 const CommandList* ptr = &list;
179
180 std::atomic<bool> removed{false};
181 bool removed_during_submit = false;
182 std::thread remover;
183 driver::on_next_submit = [&]() -> VkResult {
184 remover = std::thread([&] {
185 context.remove_query_pool(heap_id);
186 removed.store(true, std::memory_order_release);
187 });
188 std::this_thread::sleep_for(std::chrono::milliseconds(30));
189 removed_during_submit = removed.load(std::memory_order_acquire);
190 // If remove_query_pool already erased the node, abort the submit so queries.commit() does not
191 // corrupt the heap before the EXPECT below reports the failure cleanly.
192 return removed_during_submit ? VK_ERROR_OUT_OF_HOST_MEMORY : VK_SUCCESS;
193 };
194 const ReplayResult exec_res = queue_a.execute({&ptr, 1});
195 if (remover.joinable()) remover.join();
196 EXPECT(!removed_during_submit);
197 EXPECT(exec_res == ReplayResult::success);
198 EXPECT(removed.load(std::memory_order_acquire));
199 EXPECT(context.query_heap_type(heap_id) == ~0u);
200 EXPECT(queue_a.idle());
201 std::printf("queue/query sync: remove_query_pool serialized with QueryReplay::commit ok\n");
202 }
203
204 // 2. Concurrent queue_b.execute(ResolveQueries) must not run QueryReplay::plan() before queue_a commits
205 // EndQuery; otherwise queue_b sees ended[0] == false and emits vkCmdFillBuffer(0) instead of copying.
206 {
207 constexpr QueryHeapId heap_id = 88;
208 QueryPool qp{};
209 qp.pool = pool_race;
210 qp.heap_type = d3d12_query_heap::occlusion;
211 qp.count = 2;
212 qp.ended.assign(2, false);
213 context.add_query_pool(heap_id, qp);
214
215 CommandList end_list;
216 EXPECT(end_list.begin_query({heap_id, d3d12_query::occlusion, 0}));
217 EXPECT(end_list.end_query({heap_id, d3d12_query::occlusion, 0}));
218 EXPECT(end_list.close());
219 const CommandList* end_ptr = &end_list;
220
221 CommandList resolve_list;
222 EXPECT(resolve_list.resolve_queries({heap_id, d3d12_query::occlusion, 0, 1, 3, 0}));
223 EXPECT(resolve_list.close());
224 const CommandList* resolve_ptr = &resolve_list;
225
226 std::memset(res_ptr, 0xAB, 64);
227 driver::copy_query_calls.store(0);
228 driver::fill_buffer_calls.store(0);
229 driver::count_resolves.store(true);
230
231 std::thread resolver;
232 ReplayResult resolve_res = ReplayResult::unsupported;
233 driver::on_next_submit = [&]() -> VkResult {
234 resolver = std::thread([&] { resolve_res = queue_b.execute({&resolve_ptr, 1}); });
235 // Give queue_b ample time to run prepare() and reach QueryReplay::plan() while queue_a holds
236 // tracker_mutex_ (and has already unlocked resource_mutex_).
237 std::this_thread::sleep_for(std::chrono::milliseconds(40));
238 return VK_SUCCESS;
239 };
240
241 const ReplayResult end_res = queue_a.execute({&end_ptr, 1});
242 if (resolver.joinable()) resolver.join();
243 driver::count_resolves.store(false);
244 EXPECT(end_res == ReplayResult::success);
245 EXPECT(resolve_res == ReplayResult::success);
246 EXPECT(queue_a.idle() && queue_b.idle());
247 EXPECT(driver::copy_query_calls.load() == 1);
248 EXPECT(driver::fill_buffer_calls.load() == 0);
249 std::uint64_t resolved = 0xDEADBEEFULL;
250 std::memcpy(&resolved, res_ptr, sizeof(resolved));
251 EXPECT(resolved == 0); // empty occlusion query resolves 0 via vkCmdCopyQueryPoolResults
252 context.remove_query_pool(heap_id);
253 std::printf("queue/query sync: cross-queue QueryReplay::plan serialized with commit ok\n");
254 }
255
256 // 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() semaphores for the retry.
257 {
258 VulkanFence fence(context, 0);
259 EXPECT(fence.semaphore() != VK_NULL_HANDLE);
260
261 const std::uint64_t pattern = 0x1122334455667788ULL;
262 std::memcpy(src_ptr, &pattern, sizeof(pattern));
263 std::memset(dst_ptr, 0, sizeof(pattern));
264
265 CommandList copy_list;
266 EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)}));
267 EXPECT(copy_list.close());
268 const CommandList* ptr = &copy_list;
269
270 queue_a.wait(fence.semaphore(), 1);
271 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
272 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::unsupported);
273
274 // Retry: the pending wait on (fence, 1) must still be attached to the next vkQueueSubmit.
275 EXPECT(fence.signal(1));
276 driver::captured_wait_count.store(0);
277 driver::captured_wait_sem.store(0);
278 driver::captured_wait_val.store(0);
279 driver::capture_next_waits.store(true);
280 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success);
281 EXPECT(queue_a.idle());
282 EXPECT(driver::captured_wait_count.load() == 1);
283 EXPECT(driver::captured_wait_sem.load() == reinterpret_cast<std::uintptr_t>(fence.semaphore()));
284 EXPECT(driver::captured_wait_val.load() == 1);
285
286 std::uint64_t got = 0;
287 std::memcpy(&got, dst_ptr, sizeof(got));
288 EXPECT(got == pattern);
289 std::printf("queue/query sync: pending Wait() preserved across failed vkQueueSubmit ok\n");
290 }
291
292 // 4. Concurrent multi-queue EndQuery + ResolveQueries + temporary query pool add/remove stress.
293 // Each iteration uses a distinct query slot so no slot is reset while another submission resolves it.
294 {
295 constexpr QueryHeapId main_heap = 99;
296 QueryPool qp{};
297 qp.pool = pool_stress;
298 qp.heap_type = d3d12_query_heap::occlusion;
299 qp.count = 32;
300 qp.ended.assign(32, false);
301 context.add_query_pool(main_heap, qp);
302
303 CommandList res_list;
304 EXPECT(res_list.resolve_queries({main_heap, d3d12_query::occlusion, 0, 1, 3, 0}));
305 EXPECT(res_list.close());
306 const CommandList* res_ptr_cmd = &res_list;
307
308 std::atomic<bool> stop{false};
309 std::atomic<bool> worker_err{false};
310 std::thread worker([&] {
311 for (std::uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) {
312 if (queue_b.execute({&res_ptr_cmd, 1}) != ReplayResult::success || !queue_b.idle()) {
313 worker_err.store(true);
314 break;
315 }
316 const QueryHeapId temp_id = 1000 + (round % 16);
317 context.add_query_pool(temp_id, qp);
318 context.remove_query_pool(temp_id);
319 }
320 });
321
322 ReplayResult main_err = ReplayResult::success;
323 for (std::uint32_t i = 0; i < 32; ++i) {
324 CommandList end_list;
325 if (!end_list.begin_query({main_heap, d3d12_query::occlusion, i}) ||
326 !end_list.end_query({main_heap, d3d12_query::occlusion, i}) || !end_list.close()) {
327 main_err = ReplayResult::invalid_query;
328 break;
329 }
330 const CommandList* end_ptr = &end_list;
331 main_err = queue_a.execute({&end_ptr, 1});
332 if (main_err != ReplayResult::success) break;
333 }
334 stop.store(true, std::memory_order_relaxed);
335 worker.join();
336 EXPECT(main_err == ReplayResult::success);
337 EXPECT(!worker_err.load());
338 EXPECT(queue_a.idle() && queue_b.idle());
339 context.remove_query_pool(main_heap);
340 std::printf("queue/query sync: concurrent multi-queue query stress ok\n");
341 }
342 }
343
344 destroy_query_pool(d.device, pool_uaf, nullptr);
345 destroy_query_pool(d.device, pool_race, nullptr);
346 destroy_query_pool(d.device, pool_stress, nullptr);
347
348 EXPECT(d.validation_errors() == 0);
349 std::printf("vk_queue_query_sync_test: ok\n");
350 return 0;
351}
diff --git a/runtime/test/vk_sync_validation_selftest.cpp b/runtime/test/vk_sync_validation_selftest.cpp
new file mode 100644
index 000000000..6b6cf380f
--- /dev/null
+++ b/runtime/test/vk_sync_validation_selftest.cpp
@@ -0,0 +1,93 @@
1// Proves that Vulkan synchronization validation reports hazards on this machine when LEONIDA_VK_VALIDATION=1, so a
2// "0 validation errors" from the GPU tests means the layer looked, not that it was absent or silent.
3//
4// vk_test_device.h asks for VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT whenever validation is on.
5// This test records two vkCmdCopyBuffer into the same bytes:
6// - without a barrier between them, synchronization validation must report the write-after-write hazard;
7// - with a transfer -> transfer memory barrier, it must report nothing.
8// The second half keeps the first honest: a layer that reported every copy would fail it.
9//
10// Exit codes: 0 pass; 1 the hazard was not reported, the barrier case was, or the device failed;
11// 77 (ctest skip) when validation is not requested or there is no Vulkan device. No game files, no runtime code.
12#include "vk_test_device.h"
13
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17
18namespace {
19
20// Validation errors reported while recording and submitting the two copies, or ~0u when the copies could not run.
21unsigned copy_twice(vktest::Device& d, bool barrier) {
22 void* mapped = nullptr;
23 const VkBuffer src = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &mapped);
24 const VkBuffer dst = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped);
25 if (!src || !dst) return ~0u;
26 const auto copy = d.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
27 const auto pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
28 const unsigned before = d.validation_errors();
29 const bool ran = d.run([&](VkCommandBuffer cb) {
30 const VkBufferCopy region{0, 0, 4096};
31 copy(cb, src, dst, 1, &region);
32 if (barrier) {
33 VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
34 memory.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
35 memory.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
36 pipeline_barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &memory, 0,
37 nullptr, 0, nullptr);
38 }
39 copy(cb, src, dst, 1, &region);
40 return true;
41 });
42 return ran ? d.validation_errors() - before : ~0u;
43}
44
45bool validation_requested() {
46#ifdef _MSC_VER
47#pragma warning(push)
48#pragma warning(disable : 4996) // getenv: read once, as vk_test_device.h does
49#endif
50 const char* env = std::getenv("LEONIDA_VK_VALIDATION");
51#ifdef _MSC_VER
52#pragma warning(pop)
53#endif
54 return env && std::strcmp(env, "0") != 0;
55}
56
57} // namespace
58
59int main() {
60 if (!validation_requested()) {
61 std::printf("SKIP vk_sync_validation_selftest: LEONIDA_VK_VALIDATION is not set, nothing to prove\n");
62 return 77;
63 }
64 vktest::Device d;
65 const auto status = d.initialize(); // fails, with a message, when the Khronos layer is not installed
66 if (status == vktest::DeviceStatus::unavailable) {
67 std::printf("SKIP vk_sync_validation_selftest: no Vulkan device\n");
68 return 77;
69 }
70 if (status != vktest::DeviceStatus::ready || !d.validation) {
71 std::fprintf(stderr, "vk_sync_validation_selftest: no validated Vulkan device\n");
72 return 1;
73 }
74 const unsigned hazard = copy_twice(d, false);
75 const unsigned clean = copy_twice(d, true);
76 if (hazard == ~0u || clean == ~0u) {
77 std::fprintf(stderr, "vk_sync_validation_selftest: the copies could not be recorded or submitted\n");
78 return 1;
79 }
80 std::printf("two copies into the same bytes: %u validation error(s) without a barrier, %u with one\n", hazard,
81 clean);
82 if (hazard == 0) {
83 std::fprintf(stderr, "vk_sync_validation_selftest: FAIL, the write-after-write hazard was not reported: "
84 "synchronization validation is not active, so 0 errors elsewhere proves nothing\n");
85 return 1;
86 }
87 if (clean != 0) {
88 std::fprintf(stderr, "vk_sync_validation_selftest: FAIL, the synchronized copies were reported too\n");
89 return 1;
90 }
91 std::printf("vk_sync_validation_selftest: PASS, synchronization validation is active\n");
92 return 0;
93}
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 0fb490d18..635a3107b 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -6,6 +6,7 @@
6#include "vulkan_loader.h" 6#include "vulkan_loader.h"
7#include "../src/vulkan_device_filter.h" 7#include "../src/vulkan_device_filter.h"
8#include "vk_device_pick.h" 8#include "vk_device_pick.h"
9#include "../src/subgroup_size.h"
9 10
10#include <algorithm> 11#include <algorithm>
11#include <cstdint> 12#include <cstdint>
@@ -101,6 +102,8 @@ public:
101 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported 102 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported
102 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) 103 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address())
103 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance 104 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance
105 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them.
106 leonida::SubgroupSizeCaps subgroup;
104 107
105 Device() = default; 108 Device() = default;
106 Device(const Device&) = delete; 109 Device(const Device&) = delete;
@@ -328,6 +331,15 @@ public:
328 conditional_rendering ? &enable_conditional : nullptr}; 331 conditional_rendering ? &enable_conditional : nullptr};
329 enable13.dynamicRendering = VK_TRUE; 332 enable13.dynamicRendering = VK_TRUE;
330 enable13.synchronization2 = VK_TRUE; 333 enable13.synchronization2 = VK_TRUE;
334 enable13.subgroupSizeControl = features13.subgroupSizeControl;
335 enable13.computeFullSubgroups = features13.computeFullSubgroups;
336 leonida::query_subgroup_size_caps(instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2"),
337 physical, features13.subgroupSizeControl, features13.computeFullSubgroups,
338 subgroup);
339 std::printf("subgroup sizes: %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, "
340 "computeFullSubgroups %s\n",
341 subgroup.min_size, subgroup.max_size, subgroup.default_size, unsigned(subgroup.required_stages),
342 subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off");
331 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436 343 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436
332 // (zero-based VS ids) is in; harmless before. 344 // (zero-based VS ids) is in; harmless before.
333 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13}; 345 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13};
@@ -364,6 +376,7 @@ public:
364 queue_info.pQueuePriorities = &priority; 376 queue_info.pQueuePriorities = &priority;
365 VkPhysicalDeviceFeatures enable{}; 377 VkPhysicalDeviceFeatures enable{};
366 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available 378 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available
379 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features)
367 bc = features.features.textureCompressionBC == VK_TRUE; 380 bc = features.features.textureCompressionBC == VK_TRUE;
368 enable.shaderSampledImageArrayDynamicIndexing = bindless; 381 enable.shaderSampledImageArrayDynamicIndexing = bindless;
369 enable.shaderStorageImageArrayDynamicIndexing = bindless; 382 enable.shaderStorageImageArrayDynamicIndexing = bindless;
@@ -434,6 +447,7 @@ public:
434 if (host_image_copy) device_extensions.push_back(host_image_copy_name); 447 if (host_image_copy) device_extensions.push_back(host_image_copy_name);
435 const char* swapchain = "VK_KHR_swapchain"; 448 const char* swapchain = "VK_KHR_swapchain";
436 if (presentation) device_extensions.push_back(swapchain); 449 if (presentation) device_extensions.push_back(swapchain);
450#if defined(VK_KHR_swapchain_maintenance1)
437 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{ 451 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{
438 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR}; 452 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR};
439 if (presentation) { 453 if (presentation) {
@@ -455,6 +469,7 @@ public:
455 } 469 }
456 } 470 }
457 } 471 }
472#endif
458#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME 473#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
459 if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); 474 if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME);
460#endif 475#endif
diff --git a/runtime/test/vk_xdxr_build_test.cpp b/runtime/test/vk_xdxr_build_test.cpp
index 136f49f68..6f354b2b2 100644
--- a/runtime/test/vk_xdxr_build_test.cpp
+++ b/runtime/test/vk_xdxr_build_test.cpp
@@ -6,10 +6,11 @@
6// 6//
7// Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride; 7// Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride;
8// R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no 8// R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no
9// triangles; 5000 triangles (three radix-sort tiles); and a TLAS of four instances (rotated and scaled, one with mask 0, one with no BLAS). 9// triangles; 5000 triangles (many radix-sort tiles); updates (refits) in place and into another buffer; a TLAS of four instances (rotated and scaled, one with mask 0, one with no BLAS).
10// Exit 77 when there is no Vulkan device with bufferDeviceAddress. 10// Exit 77 when there is no Vulkan device with bufferDeviceAddress.
11// `vk_xdxr_build_test <out dir> <triangles>` instead times BLAS builds of that many random triangles (wall clock of 11// `vk_xdxr_build_test <out dir> <triangles>` instead times BLAS builds of that many random triangles (wall clock of
12// one submission each, after one warm-up; result and scratch in device-local memory) and writes nothing. 12// one submission each, after one warm-up; result and scratch in device-local memory), then in-place updates
13// (refits) of the same structure, and writes nothing.
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "../src/xdxr_build.h" 15#include "../src/xdxr_build.h"
15 16
@@ -117,9 +118,12 @@ struct Built {
117 std::vector<Tri> tris; 118 std::vector<Tri> tris;
118}; 119};
119 120
121// With `moved` (the same geometries with new vertex positions) the BLAS is then updated: refitted in place, or with
122// `into_other` into a second buffer, in which case the untouched source is written too, as <name>_source.
120int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name, 123int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name,
121 const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0) { 124 const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0,
122 std::vector<Buffer> keep; 125 const std::vector<Geometry>* moved = nullptr, bool into_other = false) {
126 std::vector<Buffer> keep, vertex_buffers;
123 std::vector<XdxrTriangles> descs; 127 std::vector<XdxrTriangles> descs;
124 std::uint32_t total = 0; 128 std::uint32_t total = 0;
125 for (std::size_t g = 0; g < geometries.size(); ++g) { 129 for (std::size_t g = 0; g < geometries.size(); ++g) {
@@ -134,6 +138,7 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
134 d.triangle_count = geo.triangle_count; 138 d.triangle_count = geo.triangle_count;
135 d.flags = 1; 139 d.flags = 1;
136 keep.push_back(v); 140 keep.push_back(v);
141 vertex_buffers.push_back(v);
137 if (!geo.indices.empty()) { 142 if (!geo.indices.empty()) {
138 Buffer ib = make(gpu, geo.indices.size() * 4); 143 Buffer ib = make(gpu, geo.indices.size() * 4);
139 EXPECT(ib.buffer); 144 EXPECT(ib.buffer);
@@ -170,13 +175,41 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
170 return recorded; 175 return recorded;
171 })); 176 }));
172 built.address = base; 177 built.address = base;
173 const auto* bytes = static_cast<const char*>(dst.map) + (base - dst.address); 178 auto dump = [&](const std::string& case_name, const Buffer& buffer, std::uint64_t at, const std::vector<Tri>& tris) {
174 EXPECT(write_file(dir + "/" + name + ".bin", bytes, layout.size)); 179 const auto* bytes = static_cast<const char*>(buffer.map) + (at - buffer.address);
175 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(base) + 180 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) +
176 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) + 181 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) +
177 ", \"triangles\": " + tris_json(built.tris) + "}\n"; 182 ", \"triangles\": " + tris_json(tris) + "}\n";
178 EXPECT(write_file(dir + "/" + name + ".json", json.data(), json.size())); 183 return write_file(dir + "/" + case_name + ".bin", bytes, layout.size) &&
179 std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes); 184 write_file(dir + "/" + case_name + ".json", json.data(), json.size());
185 };
186 if (!moved) {
187 EXPECT(dump(name, dst, base, built.tris));
188 std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes);
189 return 0;
190 }
191 // the update: new positions in the same vertex buffers, then a refit of the structure just built
192 EXPECT(moved->size() == geometries.size());
193 std::vector<Tri> moved_tris;
194 for (std::size_t g = 0; g < moved->size(); ++g) {
195 EXPECT((*moved)[g].vertex_data.size() == geometries[g].vertex_data.size());
196 std::memcpy(vertex_buffers[g].map, (*moved)[g].vertex_data.data(), (*moved)[g].vertex_data.size() * 4);
197 expand((*moved)[g], std::uint32_t(g), moved_tris);
198 }
199 Buffer other = into_other ? make(gpu, layout.size + 256) : Buffer{};
200 const std::uint64_t target = into_other ? (other.address + 255) & ~std::uint64_t(255) : base;
201 EXPECT(!into_other || other.buffer);
202 EXPECT(gpu.run([&](VkCommandBuffer cb) {
203 recorded = builder.record_blas(cb, layout, descs, target, scratch.address, base);
204 barrier_to_host(gpu, cb);
205 return recorded;
206 }));
207 if (into_other) EXPECT(dump(name + "_source", dst, base, built.tris)); // a refit must not touch its source
208 EXPECT(dump(name, into_other ? other : dst, target, moved_tris));
209 built.tris = moved_tris;
210 built.address = target;
211 std::printf("%s: %u triangles refitted %s, %u bytes\n", name.c_str(), total,
212 into_other ? "into another buffer" : "in place", layout.size);
180 return 0; 213 return 0;
181} 214}
182 215
@@ -234,8 +267,17 @@ int main(int argc, char** argv) {
234 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); 267 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
235 if (rep) best = std::min(best, ms); 268 if (rep) best = std::min(best, ms);
236 } 269 }
237 std::printf("%u triangles: %.2f ms (best of 3), result %u bytes, scratch %llu bytes, sort size %u\n", n, best, 270 double refit = 1e30; // an update of the structure just built, in place
238 layout.size, static_cast<unsigned long long>(layout.scratch), layout.sort_size); 271 for (int rep = 0; rep < 4; ++rep) {
272 const auto t0 = std::chrono::steady_clock::now();
273 EXPECT(gpu.run([&](VkCommandBuffer cb) {
274 return builder.record_blas(cb, layout, {d}, dst.address, scratch.address, dst.address);
275 }));
276 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
277 if (rep) refit = std::min(refit, ms);
278 }
279 std::printf("%u triangles: %.2f ms (best of 3), refit %.2f ms, result %u bytes, scratch %llu bytes, sort size %u\n",
280 n, best, refit, layout.size, static_cast<unsigned long long>(layout.scratch), layout.sort_size);
239 return 0; 281 return 0;
240 } 282 }
241 283
@@ -287,10 +329,33 @@ int main(int argc, char** argv) {
287 b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive 329 b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive
288 if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1; 330 if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1;
289 if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1; 331 if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1;
290 // three radix-sort tiles of 2048, the last one partial (fewer rays: the reference's brute force is slow) 332 // many radix-sort tiles (RADIX_TILE elements each), the last one partial (fewer rays: the brute force is slow)
291 Built tiles; 333 Built tiles;
292 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1; 334 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1;
293 335
336 // Updates. Every triangle moves (its own offset, and a stretch), so each box changes; the tree is kept.
337 auto move = [&](Geometry g, float amount) {
338 std::uniform_real_distribution<float> d(-amount, amount);
339 const std::uint32_t floats = g.stride / 4;
340 for (std::size_t v = 0; v + 2 < g.vertex_data.size(); v += floats) {
341 const float dx = d(rng), dy = d(rng);
342 g.vertex_data[v] = g.vertex_data[v] * 1.25f + dx;
343 g.vertex_data[v + 1] = g.vertex_data[v + 1] * 0.8f + dy;
344 if (!g.xy) g.vertex_data[v + 2] += d(rng);
345 }
346 return g;
347 };
348 {
349 Built refitted;
350 const Geometry big = soup(3000); // the radix-sort path
351 const std::vector<Geometry> after = {move(big, 1.5f)};
352 if (build_blas(gpu, builder, dir, "blas_refit_in_place", {big}, refitted, 300, &after)) return 1;
353 Built copied;
354 const Geometry g = grid(12, 4, false); // R32 indices, stride 16; the small-sort path
355 const std::vector<Geometry> after_grid = {move(g, 0.3f)};
356 if (build_blas(gpu, builder, dir, "blas_refit_into_other", {g}, copied, 0, &after_grid, true)) return 1;
357 }
358
294 // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address 359 // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address
295 // (256-byte units in 32 bits), as on the console; device addresses can be wider (llvmpipe's are host pointers). 360 // (256-byte units in 32 bits), as on the console; device addresses can be wider (llvmpipe's are host pointers).
296 // The instances hold application-style addresses, device address - bias, as the layer's address window does. 361 // The instances hold application-style addresses, device address - bias, as the layer's address window does.
@@ -338,6 +403,34 @@ int main(int argc, char** argv) {
338 } 403 }
339 json += "]}\n"; 404 json += "]}\n";
340 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size())); 405 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size()));
406
407 // The TLAS updated in place: every instance moves and turns; the masked and the BLAS-less ones stay so.
408 Inst moved_insts[sizeof insts / sizeof insts[0]];
409 std::memcpy(moved_insts, insts, sizeof insts);
410 const float c2 = std::cos(1.9f), s2 = std::sin(1.9f);
411 const float turned[12] = {c2, 0, s2, 4, 0, 1, 0, -3, -s2, 0, c2, 2};
412 std::memcpy(moved_insts[0].m, turned, sizeof turned);
413 moved_insts[1].m[3] -= 7;
414 moved_insts[1].m[7] += 5;
415 moved_insts[2].m[11] -= 4;
416 for (std::uint32_t i = 0; i < count; ++i) std::memcpy(static_cast<char*>(descs.map) + 64 * i, moved_insts[i].m, 48);
417 EXPECT(gpu.run([&](VkCommandBuffer cb) {
418 recorded = builder.record_tlas(cb, layout, descs.address, base, scratch.address, bias, base);
419 barrier_to_host(gpu, cb);
420 return recorded;
421 }));
422 EXPECT(write_file(dir + "/tlas_refit.bin", static_cast<const char*>(dst.map) + (base - dst.address), layout.size));
423 std::string json2 = "{\"kind\": \"tlas\", \"address\": " + std::to_string(base) + ", \"bias\": " +
424 std::to_string(bias) + ", \"blas\": [\"blas_random\", \"blas_grid_u16_stride16\"], \"instances\": [";
425 for (std::uint32_t i = 0; i < count; ++i) {
426 json2 += i ? ", {" : "{";
427 json2 += "\"transform\": [";
428 for (int k = 0; k < 12; ++k) json2 += (k ? ", " : "") + num(moved_insts[i].m[k]);
429 json2 += "], \"mask\": " + std::to_string(moved_insts[i].id_mask >> 24) + ", \"blas\": " +
430 std::to_string(moved_insts[i].which) + "}";
431 }
432 json2 += "]}\n";
433 EXPECT(write_file(dir + "/tlas_refit.json", json2.data(), json2.size()));
341 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size); 434 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size);
342 return 0; 435 return 0;
343} 436}
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index 755b64381..ac36f40d9 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -10,6 +10,7 @@
10#include <atomic> 10#include <atomic>
11#include <cstdint> 11#include <cstdint>
12#include <cstdio> 12#include <cstdio>
13#include <cstdlib>
13#include <cstring> 14#include <cstring>
14 15
15#include <XAsync.h> 16#include <XAsync.h>
@@ -98,6 +99,31 @@ HRESULT CALLBACK provider(XAsyncOp op, const XAsyncProviderData* data) {
98 } 99 }
99} 100}
100 101
102HMODULE g_teardown_rt_mod = nullptr;
103FARPROC(WINAPI* g_teardown_get_proc)(HMODULE, LPCSTR) = nullptr;
104BOOL(WINAPI* g_teardown_free_lib)(HMODULE) = nullptr;
105
106// Registered with std::atexit before check_run_time_load() constructs any function-local statics in library_loader.
107// LIFO atexit order means this runs after those statics would have been destroyed, simulating mapped-DLL
108// DLL_PROCESS_DETACH or earlier atexit handlers calling GetProcAddress/FreeLibrary on a pseudo-handle during exit.
109void check_late_teardown() {
110 if (!g_teardown_rt_mod || !g_teardown_get_proc || !g_teardown_free_lib) return;
111 if (g_teardown_get_proc(g_teardown_rt_mod, "UninitializeApiImpl") == nullptr) {
112 std::fprintf(stderr, "FAIL late teardown GetProcAddress on pseudo-handle\n");
113 std::_Exit(1);
114 }
115 SetLastError(0);
116 if (g_teardown_get_proc(g_teardown_rt_mod, "LateTeardownMissingSymbol") != nullptr ||
117 GetLastError() != ERROR_PROC_NOT_FOUND) {
118 std::fprintf(stderr, "FAIL late teardown unserved GetProcAddress on pseudo-handle\n");
119 std::_Exit(1);
120 }
121 if (g_teardown_free_lib(g_teardown_rt_mod) != TRUE) {
122 std::fprintf(stderr, "FAIL late teardown FreeLibrary on pseudo-handle\n");
123 std::_Exit(1);
124 }
125}
126
101// xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five 127// xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five
102// names (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path through the loader shims, 128// names (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path through the loader shims,
103// bound by the api set XCurl.dll imports them from, as a mapped image would be. 129// bound by the api set XCurl.dll imports them from, as a mapped image would be.
@@ -136,6 +162,9 @@ void check_run_time_load() {
136 SetLastError(0); 162 SetLastError(0);
137 check(get_proc(rt_mod, "NoSuchRuntimeFunction") == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND, 163 check(get_proc(rt_mod, "NoSuchRuntimeFunction") == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND,
138 "an unserved name is NULL with ERROR_PROC_NOT_FOUND, as from a real module"); 164 "an unserved name is NULL with ERROR_PROC_NOT_FOUND, as from a real module");
165 SetLastError(0);
166 check(get_proc(rt_mod, nullptr) == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND,
167 "a null proc name is NULL with ERROR_PROC_NOT_FOUND");
139 168
140 struct Options { 169 struct Options {
141 uint32_t unknown; 170 uint32_t unknown;
@@ -162,6 +191,10 @@ void check_run_time_load() {
162 "GetProcAddress on a host module is the host's"); 191 "GetProcAddress on a host module is the host's");
163 check(free_lib(rt_mod) == TRUE && load_w(L"xgameruntime.dll") == rt_mod, 192 check(free_lib(rt_mod) == TRUE && load_w(L"xgameruntime.dll") == rt_mod,
164 "FreeLibrary on the runtime succeeds and keeps it loaded"); 193 "FreeLibrary on the runtime succeeds and keeps it loaded");
194
195 g_teardown_rt_mod = rt_mod;
196 g_teardown_get_proc = get_proc;
197 g_teardown_free_lib = free_lib;
165} 198}
166 199
167} // namespace 200} // namespace
@@ -262,6 +295,7 @@ int main() {
262 check(init() == S_OK, "XGameRuntimeInitialize works again after balanced uninitialize calls"); 295 check(init() == S_OK, "XGameRuntimeInitialize works again after balanced uninitialize calls");
263 uninit(); 296 uninit();
264 297
298 std::atexit(check_late_teardown);
265 check_run_time_load(); 299 check_run_time_load();
266 300
267 if (g_failures) { 301 if (g_failures) {
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 429261e98..f115b6655 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -70,7 +70,7 @@ namespace xs = rt::d3d12_xs;
70 70
71// ---- Mocks ---- 71// ---- Mocks ----
72 72
73enum class Kind { device, queue, fence, resource }; 73enum class Kind { device, queue, fence, resource, allocator };
74 74
75constexpr unsigned kMockSlots = 128; 75constexpr unsigned kMockSlots = 128;
76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens 76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens
@@ -84,6 +84,7 @@ struct Mock {
84 long refs; 84 long refs;
85 int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only) 85 int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only)
86 bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do 86 bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do
87 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do
87 bool create_null; // device: creation returns create_result with no object 88 bool create_null; // device: creation returns create_result with no object
88 HRESULT create_result; // device: what creation returns (S_OK makes the object) 89 HRESULT create_result; // device: what creation returns (S_OK makes the object)
89 Mock* last_child; // device: the object its last creation or open made 90 Mock* last_child; // device: the object its last creation or open made
@@ -126,6 +127,9 @@ bool mock_has(const Mock* m, REFIID iid) {
126 case Kind::fence: 127 case Kind::fence:
127 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); 128 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1)));
128 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); 129 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource));
130 case Kind::allocator:
131 return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) ||
132 (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag));
129 default: return false; 133 default: return false;
130 } 134 }
131} 135}
@@ -148,6 +152,7 @@ HRESULT mock_create(Mock* device, Kind kind, std::uint64_t riid, std::uint64_t o
148 if (device->create_null || FAILED(device->create_result)) return device->create_result; 152 if (device->create_null || FAILED(device->create_result)) return device->create_result;
149 Mock* child = new_mock(kind); 153 Mock* child = new_mock(kind);
150 child->fence1 = device->fence1; 154 child->fence1 = device->fence1;
155 child->allocator_tag = device->allocator_tag;
151 device->last_child = child; 156 device->last_child = child;
152 return mock_query(child, reinterpret_cast<const IID*>(riid), out); 157 return mock_query(child, reinterpret_cast<const IID*>(riid), out);
153} 158}
@@ -163,6 +168,7 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) {
163 if (m->kind == Kind::device) { 168 if (m->kind == Kind::device) {
164 switch (slot) { 169 switch (slot) {
165 case 8: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue 170 case 8: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue
171 case 9: return static_cast<std::uint32_t>(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator
166 case 75: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1 172 case 75: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1
167 case 36: return static_cast<std::uint32_t>(mock_create(m, Kind::fence, a3, a4)); // CreateFence 173 case 36: return static_cast<std::uint32_t>(mock_create(m, Kind::fence, a3, a4)); // CreateFence
168 case 32: // OpenSharedHandle 174 case 32: // OpenSharedHandle
@@ -248,10 +254,11 @@ const IID kDevice1Iid = __uuidof(ID3D12Device1);
248const D3D12_COMMAND_QUEUE_DESC kQueueDesc{}; 254const D3D12_COMMAND_QUEUE_DESC kQueueDesc{};
249 255
250// A device proxy over a new mock device. The proxy takes the mock's one reference. 256// A device proxy over a new mock device. The proxy takes the mock's one reference.
251void* make_device(Mock*& mock, int level, bool fence1) { 257void* make_device(Mock*& mock, int level, bool fence1, bool allocator_tag = true) {
252 mock = new_mock(Kind::device); 258 mock = new_mock(Kind::device);
253 mock->device_level = level; 259 mock->device_level = level;
254 mock->fence1 = fence1; 260 mock->fence1 = fence1;
261 mock->allocator_tag = allocator_tag;
255 mock->refs = 1; 262 mock->refs = 1;
256 void* device = nullptr; 263 void* device = nullptr;
257 if (FAILED(xs::create_device_proxy(reinterpret_cast<ID3D12Device*>(mock), __uuidof(ID3D12Device), &device))) 264 if (FAILED(xs::create_device_proxy(reinterpret_cast<ID3D12Device*>(mock), __uuidof(ID3D12Device), &device)))
@@ -563,7 +570,85 @@ int check_alloc_failures() {
563 return 0; 570 return 0;
564} 571}
565 572
566// ---- 6. The refused tail and the guard region ---- 573// ---- 6. Command allocators (device slot 9) ----
574
575int check_allocators() {
576 const IID allocator_iid = __uuidof(ID3D12CommandAllocator);
577 // An allocator that answers Leonida's tag (its lists resolve a proxy) comes back wrapped.
578 {
579 Mock* mock = nullptr;
580 void* device = make_device(mock, 9, true, true);
581 EXPECT(device);
582 const unsigned long device_refs = xs::device_proxy_ref_count(device);
583 void* allocator = nullptr;
584 EXPECT(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&allocator))) == S_OK);
585 Mock* const real = mock->last_child;
586 EXPECT(xs::is_allocator_proxy(allocator) && word(xs::allocator_proxy_real_allocator(allocator)) == word(real));
587 EXPECT(mock->args[9][0] == D3D12_COMMAND_LIST_TYPE_DIRECT && real->refs == 1);
588 EXPECT(xs::allocator_proxy_slot_count(allocator) == 9 && xs::device_proxy_ref_count(device) == device_refs + 1);
589 // Reset (slot 8) reaches the real allocator; every slot past it up to the table end is refused.
590 EXPECT(hr_of(raw(allocator, 8)) == S_OK && real->calls[8] == 1);
591 for (unsigned slot = 9; slot < xs::allocator_proxy_table_size(); ++slot)
592 EXPECT(hr_of(raw(allocator, slot)) == E_NOTIMPL && real->calls[slot] == 0);
593 // The tag and the real object stay hidden: QueryInterface answers only the modelled interfaces.
594 void* found = reinterpret_cast<void*>(1);
595 EXPECT(hr_of(raw(allocator, 0, word(&xs::kLeonidaCommandAllocatorTag), word(&found))) == E_NOINTERFACE &&
596 !found);
597 EXPECT(hr_of(raw(allocator, 0, word(&allocator_iid), word(&found))) == S_OK && found == allocator);
598 EXPECT(release(found) == 1);
599 // An allocator is a pageable: MakeResident gives the real runtime the real allocator.
600 const std::uint64_t objects[1] = {word(allocator)};
601 EXPECT(hr_of(raw(device, 34, 1, word(objects))) == S_OK && mock->array[34][0] == word(real));
602 EXPECT(release(allocator) == 0 && real->refs == 0);
603 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
604 // Null IID, null output, a failing or empty creation, an IID the allocator lacks.
605 void* out = reinterpret_cast<void*>(1);
606 EXPECT(hr_of(raw(device, 9, 0, 0, word(&out))) == E_POINTER && !out);
607 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), 0)) == S_FALSE); // the device's own answer
608 mock->create_result = E_OUTOFMEMORY;
609 out = reinterpret_cast<void*>(1);
610 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out))) == E_OUTOFMEMORY && !out);
611 mock->create_result = S_OK;
612 mock->create_null = true;
613 out = reinterpret_cast<void*>(1);
614 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out))) == E_FAIL && !out);
615 mock->create_null = false;
616 const IID fence_iid = __uuidof(ID3D12Fence);
617 out = reinterpret_cast<void*>(1);
618 EXPECT(hr_of(raw(device, 9, 0, word(&fence_iid), word(&out))) == E_NOINTERFACE && !out);
619 EXPECT(mock->last_child->refs == 0);
620 // A refused allocation for the proxy: E_OUTOFMEMORY, and the real allocator is released.
621 g_fail_news = 1;
622 out = reinterpret_cast<void*>(1);
623 const HRESULT starved = hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out)));
624 g_fail_news = 0;
625 EXPECT(starved == E_OUTOFMEMORY && !out && mock->last_child->refs == 0);
626 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
627 EXPECT(release(device) == 0 && mock->refs == 0);
628 }
629 // An allocator without the tag (a PC runtime allocator, whose lists could not resolve a proxy) comes back as it
630 // is, as the interface asked for.
631 {
632 Mock* mock = nullptr;
633 void* device = make_device(mock, 9, true, false);
634 EXPECT(device);
635 void* allocator = nullptr;
636 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK);
637 EXPECT(allocator == mock->last_child && !xs::is_allocator_proxy(allocator) && mock->last_child->refs == 1);
638 Mock* const real = mock->last_child;
639 EXPECT(release(allocator) == 0 && real->refs == 0);
640 const IID fence_iid = __uuidof(ID3D12Fence);
641 void* out = reinterpret_cast<void*>(1);
642 EXPECT(hr_of(raw(device, 9, 0, word(&fence_iid), word(&out))) == E_NOINTERFACE && !out);
643 EXPECT(mock->last_child->refs == 0);
644 EXPECT(release(device) == 0 && mock->refs == 0);
645 }
646 std::printf("%s: allocators answering Leonida's tag are wrapped (Reset forwarded, tail refused, residency "
647 "unwrapped, references balanced); others come back unwrapped; failures leave no reference\n", g_label);
648 return 0;
649}
650
651// ---- 7. The refused tail and the guard region ----
567 652
568int check_tail(bool want_guarded) { 653int check_tail(bool want_guarded) {
569 Mock* mock = nullptr; 654 Mock* mock = nullptr;
@@ -686,7 +771,7 @@ int main(int argc, char** argv) {
686 if (argc == 2) return run_fault_mode(argv[1]); 771 if (argc == 2) return run_fault_mode(argv[1]);
687 if (argc != 1) return 2; 772 if (argc != 1) return 2;
688 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || 773 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() ||
689 check_alloc_failures()) 774 check_alloc_failures() || check_allocators())
690 return 1; 775 return 1;
691 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 776 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
692 return 0; 777 return 0;