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:
authorTomgamer <tomanhorak22@gmail.com>2026-11-22 16:32:05 +0100
committerTomgamer <tomanhorak22@gmail.com>2026-11-22 16:32:05 +0100
commiteb35aed2e7e8ea1d4a11fd4e42ab80d853f05169 (patch)
tree22bd0e6fa6363235d1feedc1c9be678ab63bee4b /runtime/test
parent759a90c42e58886153f67dcd2d5d41c44face012 (diff)
parent4eb6155d3ac4f9d3fadb0d095c4ce13e76783615 (diff)
Merge origin/main into shader-309-wave64-lds-limit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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/bink_audio_test.cpp2
-rw-r--r--runtime/test/check_d3d12_trace.py2
-rw-r--r--runtime/test/check_texture_readback_sync.cmake3
-rw-r--r--runtime/test/check_vk_pipeline_cli.cmake34
-rw-r--r--runtime/test/d3d12_buffer_uav_test.cpp699
-rw-r--r--runtime/test/d3d12_compute_test.cpp183
-rw-r--r--runtime/test/d3d12_copy_compare.h25
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp77
-rw-r--r--runtime/test/d3d12_draw_test.cpp3
-rw-r--r--runtime/test/d3d12_gcl8_test.cpp4
-rw-r--r--runtime/test/d3d12_m2_textured_test.cpp24
-rw-r--r--runtime/test/d3d12_m4_compute_test.cpp395
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp316
-rw-r--r--runtime/test/d3d12_present_test.cpp13
-rw-r--r--runtime/test/d3d12_translated_draw_test.cpp26
-rw-r--r--runtime/test/d3d12_typeless_rtv_test.cpp249
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp673
-rw-r--r--runtime/test/d3d12_xdxr_rt_test.cpp157
-rw-r--r--runtime/test/descriptor_table_test.cpp51
-rw-r--r--runtime/test/device_proxy_test.cpp41
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp227
-rw-r--r--runtime/test/file_system_test.cpp11
-rw-r--r--runtime/test/fixtures/tiny_gdk_load.cpp21
-rw-r--r--runtime/test/fsr_dispatch_test.cpp4
-rw-r--r--runtime/test/glsl/cs_user_data.comp14
-rw-r--r--runtime/test/process_cmdline_test.cpp70
-rw-r--r--runtime/test/shader_library_corpus_test.cpp159
-rw-r--r--runtime/test/shaders/build.py45
-rw-r--r--runtime/test/shaders/check.py84
-rw-r--r--runtime/test/shaders/cs_buf_counter.asm40
-rw-r--r--runtime/test/shaders/cs_buf_typed.asm63
-rw-r--r--runtime/test/shaders/cs_lds_b64_cmpst.asm132
-rw-r--r--runtime/test/shaders/cs_m4_fill.asm51
-rw-r--r--runtime/test/shaders/cs_m4_indirect.asm28
-rw-r--r--runtime/test/shaders/cs_tbuffer_store.asm275
-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_mandelbrot.asm46
-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/vs_w64_a_skip.asm45
-rw-r--r--runtime/test/shaders/vs_w64_b_ballot_atomic.asm42
-rw-r--r--runtime/test/shaders/vs_w64_b_readlane_uniform.asm33
-rw-r--r--runtime/test/shaders/vs_w64_b_waterfall.asm35
-rw-r--r--runtime/test/shaders/vs_w64_c_bcnt_export.asm23
-rw-r--r--runtime/test/shaders/vs_w64_c_lane_id.asm21
-rw-r--r--runtime/test/shaders/vs_w64_c_readlane.asm23
-rw-r--r--runtime/test/shaders/w64_graphics.py98
-rw-r--r--runtime/test/typeless_rtv_test.cpp24
-rw-r--r--runtime/test/vk_bc_zero_init_test.cpp388
-rw-r--r--runtime/test/vk_bindless_test.cpp181
-rw-r--r--runtime/test/vk_descriptor_bench.cpp42
-rw-r--r--runtime/test/vk_harness.cpp23
-rw-r--r--runtime/test/vk_overlapping_occlusion_test.cpp74
-rw-r--r--runtime/test/vk_pipeline_check.cpp335
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp62
-rw-r--r--runtime/test/vk_test_device.h84
-rw-r--r--runtime/test/vk_xdxr_build_test.cpp183
-rw-r--r--runtime/test/xgameruntime_test.cpp158
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp93
62 files changed, 6509 insertions, 260 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/bink_audio_test.cpp b/runtime/test/bink_audio_test.cpp
index 2156e5eff..8616d9165 100644
--- a/runtime/test/bink_audio_test.cpp
+++ b/runtime/test/bink_audio_test.cpp
@@ -237,7 +237,7 @@ int main() {
237 header.flags[i]); 237 header.flags[i]);
238 if (!header.audio_tracks) { 238 if (!header.audio_tracks) {
239 std::printf("SKIP (movie has no audio tracks)\n"); 239 std::printf("SKIP (movie has no audio tracks)\n");
240 return 0; 240 return 77; // nothing was checked: a ctest SKIP (SKIP_RETURN_CODE 77), not a pass
241 } 241 }
242 242
243 try { 243 try {
diff --git a/runtime/test/check_d3d12_trace.py b/runtime/test/check_d3d12_trace.py
index c32536464..d24e02058 100644
--- a/runtime/test/check_d3d12_trace.py
+++ b/runtime/test/check_d3d12_trace.py
@@ -50,6 +50,8 @@ 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",
diff --git a/runtime/test/check_texture_readback_sync.cmake b/runtime/test/check_texture_readback_sync.cmake
index f82156789..81ef3f24e 100644
--- a/runtime/test/check_texture_readback_sync.cmake
+++ b/runtime/test/check_texture_readback_sync.cmake
@@ -1,10 +1,11 @@
1# Run with -DTOOL=<vk_texture_test> -DSPIRV=<directory built by the GPU suite> 1# Run with -DTOOL=<vk_texture_test> -DSPIRV=<directory built by the GPU suite>
2# -DOUTPUT=<readback file> -P runtime/test/check_texture_readback_sync.cmake. 2# -DOUTPUT=<readback file> -P runtime/test/check_texture_readback_sync.cmake.
3# For a cross build, pass the configured emulator as "-DRUNNER=<emulator;args>".
3# Requires the Khronos validation layer and a device that supports the texture harness. 4# Requires the Khronos validation layer and a device that supports the texture harness.
4execute_process( 5execute_process(
5 COMMAND "${CMAKE_COMMAND}" -E env VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation 6 COMMAND "${CMAKE_COMMAND}" -E env VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation
6 VK_LOADER_DEBUG=layer VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT 7 VK_LOADER_DEBUG=layer VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT
7 "${TOOL}" cube "${OUTPUT}" 8 ${RUNNER} "${TOOL}" cube "${OUTPUT}"
8 WORKING_DIRECTORY "${SPIRV}" TIMEOUT 90 9 WORKING_DIRECTORY "${SPIRV}" TIMEOUT 90
9 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log) 10 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log)
10if(NOT code STREQUAL "0" OR NOT log MATCHES "vk_texture_test cube: PASSED" 11if(NOT code STREQUAL "0" OR NOT log MATCHES "vk_texture_test cube: PASSED"
diff --git a/runtime/test/check_vk_pipeline_cli.cmake b/runtime/test/check_vk_pipeline_cli.cmake
new file mode 100644
index 000000000..8c98ba1eb
--- /dev/null
+++ b/runtime/test/check_vk_pipeline_cli.cmake
@@ -0,0 +1,34 @@
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)
31# The index parser names the file and where it stopped (#1847: "index.json: expected '{' at byte 0").
32if(NOT code STREQUAL "2" OR NOT log MATCHES "index.json: ")
33 message(FATAL_ERROR "Expected valid arguments to reach the malformed index, got ${code}\n${log}")
34endif()
diff --git a/runtime/test/d3d12_buffer_uav_test.cpp b/runtime/test/d3d12_buffer_uav_test.cpp
new file mode 100644
index 000000000..cf936012a
--- /dev/null
+++ b/runtime/test/d3d12_buffer_uav_test.cpp
@@ -0,0 +1,699 @@
1// Typed buffer UAVs and UAV counters (docs/d3d12_vulkan.md section 3.4, "Buffer UAVs"), through the D3D12 API on the
2// proxy, with compute shaders that are translator output (test/shaders/cs_buf_typed.asm and cs_buf_counter.asm,
3// hand-written RDNA2), plus D3D12-only behaviour compared with the host runtime on the same adapter.
4//
5// Part 1, one DIRECT list: a compute root signature (four root constants and a table of six UAVs), two compute PSOs.
6// cs_buf_typed writes typed buffer views (R32_UINT with an atomic add, R16G16B16A16_FLOAT, R8G8B8A8_UNORM from
7// FirstElement 16, R32G32B32A32_UINT, R32_SINT) and reads an R32_FLOAT view. Two views are shorter
8// than the dispatch (240 and 250 elements of 256): the V#'s NUM_RECORDS is the bound, so stores past
9// it leave the buffer's sentinel and loads past it give 0.
10// cs_buf_counter a structured UAV with a counter at CounterOffsetInBytes 4096 of another buffer: 256 lanes append
11// (buffer_atomic_add on the counter V# in the slot's upper half, store at the returned index), then
12// 128 lanes consume (buffer_atomic_sub, load the record just below). "CopyStructureCount" in D3D12
13// is CopyBufferRegion of the counter's 4 bytes into a buffer: read after the append (256) and after
14// the consume (128). Lane order is up to the GPU, so records are compared as sets.
15// Everything is compared with a CPU reference, word by word, error 0.
16// Part 2, the layer's device (no proxy) and the host runtime on the SAME adapter (LUID): typed buffer UAVs created with
17// CreateUnorderedAccessView and cleared with ClearUnorderedAccessViewUint / Float (thirteen formats, sub-ranges, an
18// element range ending off a word boundary), and a structured UAV with a counter: a clear of the structured view and
19// of the counter's own word through a raw view. The bytes read back are compared with the host's; with no host D3D12
20// the layer's are compared with the model of uav_clear.h.
21// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
22#include "vk_test_device.h"
23#include "d3d12_test_shaders.h"
24#include "d3d12_copy_compare.h"
25#include "../shims/d3d12_com.h"
26#include "../shims/d3d12_xs_device.h"
27#include "../src/gfx10_descriptors.h"
28#include "../src/shader_library.h"
29#include "../src/uav_clear.h"
30
31#include <algorithm>
32#include <array>
33#include <bit>
34#include <cmath>
35#include <cstring>
36
37#ifndef LEONIDA_TEST_BUFFER_UAV_DIR
38#error "LEONIDA_TEST_BUFFER_UAV_DIR must name the folder build.py wrote (spirv/index.json, fssm/cs_*.fssm)"
39#endif
40
41#define EXPECT(condition) do { \
42 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
43} while (0)
44
45using namespace d3d12test;
46using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
47namespace g = leonida::gfx10;
48namespace uc = leonida::uav_clear;
49
50namespace {
51
52std::vector<std::uint8_t> read_file(const std::filesystem::path& path) {
53 std::ifstream in(path, std::ios::binary);
54 return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
55}
56
57constexpr UINT lanes = 256;
58constexpr UINT seed = 0x00c0ffee, multiplier = 0x01000193;
59constexpr std::uint32_t sentinel = 0xa5a5a5a5u;
60constexpr UINT out0_elements = 240, in4_elements = 250, out2_first = 16;
61constexpr UINT64 counter_offset = 4096, counter_buffer_bytes = 8192;
62constexpr UINT consumed = 128;
63
64// The buffers of part 1: sizes, in the order of their slices of the upload and of the readback buffer.
65enum Buf { out0, out1, out2, out3, in4, out5, records, counter, consumed_out, buffer_count };
66constexpr UINT64 sizes[buffer_count] = {lanes * 4, lanes * 8, (out2_first + lanes) * 4, lanes * 16, lanes * 4,
67 lanes * 4, lanes * 8, counter_buffer_bytes, consumed * 8};
68constexpr UINT64 slice(Buf which) {
69 UINT64 at = 0;
70 for (int i = 0; i < which; ++i) at += (sizes[i] + 255) / 256 * 256;
71 return at;
72}
73constexpr UINT64 total_bytes = slice(consumed_out) + (sizes[consumed_out] + 255) / 256 * 256;
74constexpr UINT64 count_after_append = total_bytes, count_after_consume = total_bytes + 4;
75constexpr UINT64 readback_bytes = total_bytes + 8;
76
77std::uint16_t half_bits(float value) { // exact for the values the reference uses (finite, in the normal range)
78 const std::uint32_t f = std::bit_cast<std::uint32_t>(value);
79 if (!(f & 0x7fffffffu)) return std::uint16_t(f >> 16);
80 const int exponent = int((f >> 23) & 0xff) - 127 + 15;
81 return std::uint16_t(((f >> 16) & 0x8000) | (exponent << 10) | ((f >> 13) & 0x3ff));
82}
83
84float input_value(UINT g) { return float(g) - 100.5f; }
85
86struct Reference {
87 std::vector<std::uint32_t> words[buffer_count];
88};
89
90Reference reference() {
91 Reference ref;
92 for (int i = 0; i < buffer_count; ++i) ref.words[i].assign(sizes[i] / 4, sentinel);
93 for (UINT g = 0; g < lanes; ++g) {
94 if (g < out0_elements) ref.words[out0][g] = (g * multiplier + seed) + g;
95 const float x = float(g);
96 ref.words[out1][g * 2] = half_bits(x) | std::uint32_t(half_bits(x + 0.5f)) << 16;
97 ref.words[out1][g * 2 + 1] = half_bits(-1.0f - x) | std::uint32_t(half_bits(0.25f)) << 16;
98 const std::uint32_t k = g & 255;
99 ref.words[out2][out2_first + g] = k | (255 - k) << 8 | 0xff000000u;
100 ref.words[out3][g * 4 + 0] = g;
101 ref.words[out3][g * 4 + 1] = g ^ 0xffff;
102 ref.words[out3][g * 4 + 2] = g * 7;
103 ref.words[out3][g * 4 + 3] = 0xa5;
104 ref.words[in4][g] = std::bit_cast<std::uint32_t>(input_value(g));
105 ref.words[out5][g] = g < in4_elements ? std::uint32_t(int(2.0f * input_value(g))) : 0;
106 }
107 return ref;
108}
109
110D3D12_RESOURCE_BARRIER uav_barrier(ID3D12Resource* resource) {
111 D3D12_RESOURCE_BARRIER b{};
112 b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
113 b.UAV.pResource = resource;
114 return b;
115}
116
117D3D12_UNORDERED_ACCESS_VIEW_DESC buffer_view(DXGI_FORMAT format, UINT64 first, UINT count, UINT stride,
118 UINT64 counter_at = 0, D3D12_BUFFER_UAV_FLAGS flags = D3D12_BUFFER_UAV_FLAG_NONE) {
119 D3D12_UNORDERED_ACCESS_VIEW_DESC view{};
120 view.Format = format;
121 view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
122 view.Buffer = {first, count, stride, counter_at, flags};
123 return view;
124}
125
126// What a V# in a slot says, as the shader loads it.
127struct Vsharp {
128 std::uint64_t address;
129 std::uint32_t stride, records, format, oob;
130};
131Vsharp vsharp(const void* slot_pointer, unsigned dword = 0) {
132 std::uint32_t w[4];
133 std::memcpy(w, static_cast<const std::uint32_t*>(slot_pointer) + dword, sizeof(w));
134 return {(std::uint64_t(w[1] & 0xffff) << 32) | w[0], w[1] >> 16 & 0x3fff, w[2], w[3] >> 12 & 0x7f, w[3] >> 28 & 3};
135}
136
137// ---- part 1 -----------------------------------------------------------------------------------------------------
138
139int run_shaders(vktest::Device& d, const std::filesystem::path& root_dir, unsigned& words_checked) {
140 leonida::ShaderLibrary library;
141 EXPECT(library.load((root_dir / "spirv").string()));
142 const auto program = [&](const char* name) { return read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); };
143 const auto typed_fssm = program("cs_buf_typed"), counter_fssm = program("cs_buf_counter");
144 EXPECT(typed_fssm.size() >= 0x150 && counter_fssm.size() >= 0x150 && typed_fssm != counter_fssm);
145 EXPECT(library.find("cs", leonida::sha256_hex(typed_fssm)) && library.find("cs", leonida::sha256_hex(counter_fssm)));
146 const auto typed_container = shader_container(typed_fssm), counter_container = shader_container(counter_fssm);
147
148 rt::d3d12::VulkanDeviceInfo info{};
149 info.get_instance_proc = d.instance_proc;
150 info.instance = d.instance;
151 info.physical = d.physical;
152 info.device = d.device;
153 info.queue = d.queue;
154 info.queue_family = d.family;
155 info.buffer_device_address = true;
156 info.bindless = d.bindless;
157 info.bindless_partially_bound = d.partially_bound;
158 info.image_view_min_lod = d.image_view_min_lod;
159 info.shader_dir = (root_dir / "spirv").string();
160 ID3D12Device* inner = nullptr;
161 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
162 Ref<ID3D12Device> device;
163 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
164 reinterpret_cast<void**>(&device.p))));
165 rt::d3d12::set_device_outer(inner, device.p);
166 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
167
168 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 6, 0, 0, 0};
169 D3D12_ROOT_PARAMETER params[2] = {};
170 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
171 params[0].Constants = {0, 0, 4};
172 params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
173 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
174 params[1].DescriptorTable = {1, &uav_range};
175 params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
176 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
177 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
178 root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
179 const auto root_blob = serialize_root_signature(root_desc);
180 EXPECT(!root_blob.empty());
181 Ref<ID3D12RootSignature> root;
182 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
183 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
184 pso_desc.pRootSignature = root.p;
185 pso_desc.CS = {typed_container.data(), typed_container.size()};
186 Ref<ID3D12PipelineState> pso_typed, pso_counter;
187 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_typed.p))));
188 pso_desc.CS = {counter_container.data(), counter_container.size()};
189 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_counter.p))));
190
191 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD},
192 readback_heap{D3D12_HEAP_TYPE_READBACK};
193 Ref<ID3D12Resource> upload, readback, buf[buffer_count];
194 const auto create = [&](Ref<ID3D12Resource>& out, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes,
195 D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) {
196 const auto desc = buffer_desc(bytes, flags);
197 return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
198 IID_PPV_ARGS(&out.p)));
199 };
200 EXPECT(create(upload, upload_heap, total_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ));
201 EXPECT(create(readback, readback_heap, readback_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST));
202 for (int i = 0; i < buffer_count; ++i)
203 EXPECT(create(buf[i], default_heap, sizes[i], D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
204 D3D12_RESOURCE_STATE_COPY_DEST));
205 Reference want = reference();
206 {
207 std::uint8_t* mapped = nullptr;
208 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped))));
209 for (UINT64 i = 0; i < total_bytes / 4; ++i) std::memcpy(mapped + i * 4, &sentinel, 4);
210 // The input buffer holds floats; the counter's own word starts at 0 (the rest of its buffer is sentinel).
211 std::memcpy(mapped + slice(in4), want.words[in4].data(), sizes[in4]);
212 std::memset(mapped + slice(counter) + counter_offset, 0, 4);
213 upload->Unmap(0, nullptr);
214 }
215
216 // The table: slots 0..5 typed views for cs_buf_typed; slot 6 a structured UAV with a counter, slot 7 a raw output
217 // for cs_buf_counter (its table starts at slot 6).
218 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 12,
219 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
220 Ref<ID3D12DescriptorHeap> heap;
221 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
222 const std::uint64_t cpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 9))(heap.p);
223 const std::uint64_t gpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p);
224 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
225 EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step == 32); // the shaders step 32 bytes a slot
226 const auto handle = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + std::uint64_t(i) * step)}; };
227 const auto make = [&](UINT i, Buf which, const D3D12_UNORDERED_ACCESS_VIEW_DESC& view, ID3D12Resource* counter_res = nullptr) {
228 device->CreateUnorderedAccessView(buf[which].p, counter_res, &view, handle(i));
229 };
230 make(0, out0, buffer_view(DXGI_FORMAT_R32_UINT, 0, out0_elements, 0));
231 make(1, out1, buffer_view(DXGI_FORMAT_R16G16B16A16_FLOAT, 0, lanes, 0));
232 make(2, out2, buffer_view(DXGI_FORMAT_R8G8B8A8_UNORM, out2_first, lanes, 0));
233 make(3, out3, buffer_view(DXGI_FORMAT_R32G32B32A32_UINT, 0, lanes, 0));
234 make(4, in4, buffer_view(DXGI_FORMAT_R32_FLOAT, 0, in4_elements, 0));
235 make(5, out5, buffer_view(DXGI_FORMAT_R32_SINT, 0, lanes, 0));
236 make(6, records, buffer_view(DXGI_FORMAT_UNKNOWN, 0, lanes, 8, counter_offset), buf[counter].p);
237 make(7, consumed_out, buffer_view(DXGI_FORMAT_R32_TYPELESS, 0, consumed * 2, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW));
238
239 // The V#s the shaders load: format code, element size as stride, element count, OOB_SELECT 1 (structured); the
240 // R8G8B8A8 view starts 16 elements in; the counter V# is raw (stride 0, 4 bytes, OOB_SELECT 3) in the slot's upper half.
241 const auto at = [&](UINT i) { return reinterpret_cast<const void*>(handle(i).ptr); };
242 const auto expect_typed = [&](UINT i, Buf which, UINT code, UINT bytes, UINT elements, UINT first) {
243 const Vsharp v = vsharp(at(i));
244 return v.address == buf[which]->GetGPUVirtualAddress() + UINT64(first) * bytes && v.stride == bytes &&
245 v.records == elements && v.format == code && v.oob == 1;
246 };
247 EXPECT(expect_typed(0, out0, 20, 4, out0_elements, 0)); // GFX10_FORMAT_32_UINT
248 EXPECT(expect_typed(1, out1, 71, 8, lanes, 0)); // 16_16_16_16_FLOAT
249 EXPECT(expect_typed(2, out2, 56, 4, lanes, out2_first)); // 8_8_8_8_UNORM
250 EXPECT(expect_typed(3, out3, 75, 16, lanes, 0)); // 32_32_32_32_UINT
251 EXPECT(expect_typed(4, in4, 22, 4, in4_elements, 0)); // 32_FLOAT
252 EXPECT(expect_typed(5, out5, 21, 4, lanes, 0)); // 32_SINT
253 {
254 const Vsharp v = vsharp(at(6)), c = vsharp(at(6), 4);
255 EXPECT(v.address == buf[records]->GetGPUVirtualAddress() && v.stride == 8 && v.records == lanes && v.format == 0 &&
256 v.oob == 0);
257 EXPECT(c.address == buf[counter]->GetGPUVirtualAddress() + counter_offset && c.stride == 0 && c.records == 4 &&
258 c.format == 0 && c.oob == 3);
259 const Vsharp r = vsharp(at(7));
260 EXPECT(r.address == buf[consumed_out]->GetGPUVirtualAddress() && r.stride == 0 && r.records == consumed * 8 &&
261 r.oob == 3);
262 // A view with no counter leaves the slot's upper half zero.
263 const Vsharp none = vsharp(at(7), 4);
264 EXPECT(!none.address && !none.records);
265 }
266
267 D3D12_COMMAND_QUEUE_DESC queue_desc{};
268 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
269 Ref<ID3D12CommandQueue> queue;
270 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
271 Ref<ID3D12CommandAllocator> allocator;
272 Ref<ID3D12GraphicsCommandList> list;
273 Ref<ID3D12Fence> fence;
274 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
275 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
276 IID_PPV_ARGS(&list.p))));
277 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
278
279 constexpr auto uav_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
280 for (int i = 0; i < buffer_count; ++i) list->CopyBufferRegion(buf[i].p, 0, upload.p, slice(Buf(i)), sizes[i]);
281 D3D12_RESOURCE_BARRIER barriers[buffer_count];
282 for (int i = 0; i < buffer_count; ++i) barriers[i] = transition(buf[i].p, D3D12_RESOURCE_STATE_COPY_DEST, uav_state);
283 list->ResourceBarrier(buffer_count, barriers);
284 ID3D12DescriptorHeap* heaps[] = {heap.p};
285 list->SetDescriptorHeaps(1, heaps);
286 list->SetComputeRootSignature(root.p);
287 const auto constants = [&](std::uint32_t a, std::uint32_t b) {
288 const std::uint32_t values[4] = {a, b, 0, 0};
289 list->SetComputeRoot32BitConstants(0, 4, values, 0);
290 };
291 list->SetPipelineState(pso_typed.p);
292 constants(seed, multiplier);
293 list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu});
294 list->Dispatch(lanes / 64, 1, 1);
295 list->SetPipelineState(pso_counter.p);
296 constants(0, 0); // append
297 list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 6ull * step});
298 list->Dispatch(lanes / 64, 1, 1);
299 D3D12_RESOURCE_BARRIER sync[2] = {uav_barrier(buf[records].p), uav_barrier(buf[counter].p)};
300 list->ResourceBarrier(2, sync);
301 // CopyStructureCount: the counter's 4 bytes into a buffer, after the append.
302 D3D12_RESOURCE_BARRIER to_copy = transition(buf[counter].p, uav_state, D3D12_RESOURCE_STATE_COPY_SOURCE);
303 list->ResourceBarrier(1, &to_copy);
304 list->CopyBufferRegion(readback.p, count_after_append, buf[counter].p, counter_offset, 4);
305 D3D12_RESOURCE_BARRIER back = transition(buf[counter].p, D3D12_RESOURCE_STATE_COPY_SOURCE, uav_state);
306 list->ResourceBarrier(1, &back);
307 constants(1, 0); // consume
308 list->Dispatch(consumed / 64, 1, 1);
309 for (int i = 0; i < buffer_count; ++i) barriers[i] = transition(buf[i].p, uav_state, D3D12_RESOURCE_STATE_COPY_SOURCE);
310 list->ResourceBarrier(buffer_count, barriers);
311 for (int i = 0; i < buffer_count; ++i) list->CopyBufferRegion(readback.p, slice(Buf(i)), buf[i].p, 0, sizes[i]);
312 list->CopyBufferRegion(readback.p, count_after_consume, buf[counter].p, counter_offset, 4);
313 EXPECT(list->Close() == S_OK);
314 ID3D12CommandList* lists[] = {list.p};
315 queue->ExecuteCommandLists(1, lists);
316 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
317 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
318 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
319 EXPECT(event != nullptr);
320 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, event)));
321 if (WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) {
322 std::fprintf(stderr, "the fence never reached 1\n");
323 return 1;
324 }
325 CloseHandle(event);
326
327 std::vector<std::uint8_t> got;
328 {
329 void* mapped = nullptr;
330 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
331 got.assign(static_cast<const std::uint8_t*>(mapped), static_cast<const std::uint8_t*>(mapped) + readback_bytes);
332 readback->Unmap(0, nullptr);
333 }
334 const auto word_at = [&](UINT64 offset) {
335 std::uint32_t value = 0;
336 std::memcpy(&value, got.data() + offset, 4);
337 return value;
338 };
339
340 unsigned mismatches = 0;
341 const auto compare = [&](const char* what, Buf which, const std::vector<std::uint32_t>& expected) {
342 unsigned bad = 0;
343 for (std::size_t i = 0; i < expected.size(); ++i) {
344 ++words_checked;
345 const std::uint32_t value = word_at(slice(which) + i * 4);
346 if (value == expected[i]) continue;
347 ++mismatches;
348 if (bad++ < 4) std::fprintf(stderr, "%s word %zu: got %08x want %08x\n", what, i, value, expected[i]);
349 }
350 if (bad) std::fprintf(stderr, "%s: %u of %zu words differ\n", what, bad, expected.size());
351 };
352 compare("R32_UINT store + atomic add (240 of 256 elements)", out0, want.words[out0]);
353 compare("R16G16B16A16_FLOAT store", out1, want.words[out1]);
354 compare("R8G8B8A8_UNORM store (FirstElement 16)", out2, want.words[out2]);
355 compare("R32G32B32A32_UINT store", out3, want.words[out3]);
356 compare("R32_FLOAT input untouched", in4, want.words[in4]);
357 compare("R32_FLOAT load -> R32_SINT store (250 of 256 loads in range)", out5, want.words[out5]);
358
359 // The counter: 256 after the append, 128 after the consume, and nothing else of its buffer touched.
360 ++words_checked;
361 if (word_at(count_after_append) != lanes) {
362 std::fprintf(stderr, "counter after the append: %u, want %u\n", word_at(count_after_append), lanes);
363 ++mismatches;
364 }
365 ++words_checked;
366 if (word_at(count_after_consume) != lanes - consumed) {
367 std::fprintf(stderr, "counter after the consume: %u, want %u\n", word_at(count_after_consume), lanes - consumed);
368 ++mismatches;
369 }
370 for (UINT64 i = 0; i < counter_buffer_bytes / 4; ++i) {
371 ++words_checked;
372 const std::uint32_t expected = i == counter_offset / 4 ? lanes - consumed : sentinel;
373 if (word_at(slice(counter) + i * 4) != expected && mismatches++ < 12)
374 std::fprintf(stderr, "counter buffer word %llu: got %08x want %08x\n", static_cast<unsigned long long>(i),
375 word_at(slice(counter) + i * 4), expected);
376 }
377 // The appended records: every g exactly once with its second field, in whatever order the lanes took the counter.
378 std::vector<std::array<std::uint32_t, 2>> appended, taken;
379 for (UINT i = 0; i < lanes; ++i)
380 appended.push_back({word_at(slice(records) + i * 8), word_at(slice(records) + i * 8 + 4)});
381 std::vector<std::array<std::uint32_t, 2>> sorted = appended;
382 std::sort(sorted.begin(), sorted.end());
383 for (UINT i = 0; i < lanes; ++i) {
384 ++words_checked;
385 if (sorted[i][0] != i || sorted[i][1] != i * 3 + 1) {
386 if (mismatches++ < 12)
387 std::fprintf(stderr, "appended record %u (sorted): { %u, %u }, want { %u, %u }\n", i, sorted[i][0],
388 sorted[i][1], i, i * 3 + 1);
389 }
390 }
391 // The consumed ones: the records at indices 128..255 (the counter went from 256 down to 128), each once.
392 for (UINT i = 0; i < consumed; ++i)
393 taken.push_back({word_at(slice(consumed_out) + i * 8), word_at(slice(consumed_out) + i * 8 + 4)});
394 std::vector<std::array<std::uint32_t, 2>> tail(appended.begin() + (lanes - consumed), appended.end());
395 std::sort(taken.begin(), taken.end());
396 std::sort(tail.begin(), tail.end());
397 for (UINT i = 0; i < consumed; ++i) {
398 ++words_checked;
399 if (taken[i] != tail[i] && mismatches++ < 12)
400 std::fprintf(stderr, "consumed record %u (sorted): { %u, %u }, want { %u, %u }\n", i, taken[i][0], taken[i][1],
401 tail[i][0], tail[i][1]);
402 }
403 EXPECT(!mismatches);
404
405 for (auto& b : buf) b.reset();
406 upload.reset(); readback.reset(); list.reset(); allocator.reset(); fence.reset(); queue.reset();
407 pso_typed.reset(); pso_counter.reset(); root.reset(); heap.reset();
408 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
409 return 0;
410}
411
412// ---- part 2 -----------------------------------------------------------------------------------------------------
413
414struct ClearCase {
415 DXGI_FORMAT format;
416 VkFormat vulkan; // for the model
417 bool is_float;
418 std::array<std::uint32_t, 4> values;
419 UINT64 byte_offset;
420 UINT elements;
421};
422std::uint32_t fb(float f) { return std::bit_cast<std::uint32_t>(f); }
423
424// Values in the domain D3D12 defines the same on every driver: no exact .5 ties in a float -> UNORM rounding (the RTX 5070's
425// D3D12 rounds 127.5 down, the layer and the spec's round-to-nearest up) and no integer wider than its channel (the low bits
426// are kept here, one vendor clamps).
427const ClearCase clear_cases[] = {
428 {DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, false, {0x12345678, 0, 0, 0}, 0, 16},
429 {DXGI_FORMAT_R32_SINT, VK_FORMAT_R32_SINT, false, {0xfffffff0, 0, 0, 0}, 256, 8},
430 {DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, true, {fb(1.5f), 0, 0, 0}, 512, 8},
431 {DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, true, {fb(1.0f), fb(0.5f), fb(-2.0f), fb(0.25f)}, 768, 8},
432 {DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, true, {fb(1.0f), fb(0.4f), fb(0.2f), fb(2.0f)}, 1024, 16},
433 {DXGI_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_UINT, false, {0xf1, 2, 3, 0x80}, 1280, 16},
434 {DXGI_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_UINT, false, {1, 2, 3, 4}, 1536, 4},
435 {DXGI_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, true, {fb(0.25f), 0, 0, 0}, 1792, 16},
436 {DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, true, {fb(0.2f), 0, 0, 0}, 2048, 21}, // ends off a word boundary
437 {DXGI_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, true, {fb(0.25f), fb(0.4f), fb(0.75f), fb(1.0f)}, 2304, 8},
438 {DXGI_FORMAT_R11G11B10_FLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, true, {fb(1.0f), fb(2.0f), fb(0.5f), 0}, 2560, 8},
439 {DXGI_FORMAT_R16G16_FLOAT, VK_FORMAT_R16G16_SFLOAT, true, {fb(1.5f), fb(-0.5f), 0, 0}, 2816, 8},
440 {DXGI_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_UINT, false, {0xaa, 0xbb, 0, 0}, 3072, 10},
441};
442constexpr UINT64 api_data_bytes = 4096, api_records_bytes = 4096;
443constexpr UINT api_readback = api_data_bytes + api_records_bytes + counter_buffer_bytes;
444
445// The same scenario on `device`: bytes read back, or empty on failure. host: a real heap pair (a non-shader-visible one the
446// views are made in, a shader-visible one the clear's GPU handle comes from), as the PC runtime wants; the layer takes the
447// CPU handle and ignores the GPU one.
448bool run_api(ID3D12Device* device, bool host, std::vector<std::uint8_t>& out, std::vector<bool>& supported_by_host) {
449 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD},
450 readback_heap{D3D12_HEAP_TYPE_READBACK};
451 const auto create = [&](Ref<ID3D12Resource>& r, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes,
452 D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) {
453 const auto desc = buffer_desc(bytes, flags);
454 return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
455 IID_PPV_ARGS(&r.p)));
456 };
457 constexpr auto uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
458 Ref<ID3D12Resource> data, structured, counter_buffer, upload, readback;
459 if (!create(data, default_heap, api_data_bytes, uav_flag, D3D12_RESOURCE_STATE_UNORDERED_ACCESS) ||
460 !create(structured, default_heap, api_records_bytes, uav_flag, D3D12_RESOURCE_STATE_COPY_DEST) ||
461 !create(counter_buffer, default_heap, counter_buffer_bytes, uav_flag, D3D12_RESOURCE_STATE_COPY_DEST) ||
462 !create(upload, upload_heap, api_records_bytes + counter_buffer_bytes, D3D12_RESOURCE_FLAG_NONE,
463 D3D12_RESOURCE_STATE_GENERIC_READ) ||
464 !create(readback, readback_heap, api_readback, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST))
465 return std::fprintf(stderr, "resource creation failed\n"), false;
466 {
467 std::uint8_t* mapped = nullptr;
468 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
469 std::memset(mapped, 0x11, api_records_bytes + counter_buffer_bytes);
470 const std::uint32_t seven = 7;
471 std::memcpy(mapped + api_records_bytes + counter_offset, &seven, 4); // the counter's word
472 upload->Unmap(0, nullptr);
473 }
474 constexpr UINT slots = 24;
475 Ref<ID3D12DescriptorHeap> cpu_heap, gpu_heap;
476 D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, slots, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
477 if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&cpu_heap.p)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
478 if (host) {
479 desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
480 if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&gpu_heap.p)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
481 }
482 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
483 const auto cpu = [&](UINT i) {
484 D3D12_CPU_DESCRIPTOR_HANDLE h = cpu_heap->GetCPUDescriptorHandleForHeapStart();
485 h.ptr += SIZE_T(i) * step;
486 return h;
487 };
488 const auto gpu = [&](UINT i) {
489 if (!host) return D3D12_GPU_DESCRIPTOR_HANDLE{0};
490 D3D12_GPU_DESCRIPTOR_HANDLE h = gpu_heap->GetGPUDescriptorHandleForHeapStart();
491 h.ptr += UINT64(i) * step;
492 return h;
493 };
494 UINT next_slot = 0;
495 const auto make = [&](ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC& view) {
496 const UINT i = next_slot++;
497 device->CreateUnorderedAccessView(resource, counter, &view, cpu(i));
498 if (host) {
499 D3D12_CPU_DESCRIPTOR_HANDLE visible = gpu_heap->GetCPUDescriptorHandleForHeapStart();
500 visible.ptr += SIZE_T(i) * step;
501 device->CopyDescriptorsSimple(1, visible, cpu(i), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
502 }
503 return i;
504 };
505
506 Ref<ID3D12CommandQueue> queue;
507 Ref<ID3D12CommandAllocator> allocator;
508 Ref<ID3D12GraphicsCommandList> list;
509 Ref<ID3D12Fence> fence;
510 const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT};
511 if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) ||
512 FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) ||
513 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p))) ||
514 FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
515 return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
516 ID3D12DescriptorHeap* heaps[] = {gpu_heap.p};
517 if (host) list->SetDescriptorHeaps(1, heaps);
518
519 const auto clear = [&](UINT slot_index, ID3D12Resource* resource, bool is_float, const std::array<std::uint32_t, 4>& v) {
520 if (is_float) {
521 const float f[4] = {std::bit_cast<float>(v[0]), std::bit_cast<float>(v[1]), std::bit_cast<float>(v[2]),
522 std::bit_cast<float>(v[3])};
523 list->ClearUnorderedAccessViewFloat(gpu(slot_index), cpu(slot_index), resource, f, 0, nullptr);
524 } else {
525 list->ClearUnorderedAccessViewUint(gpu(slot_index), cpu(slot_index), resource, v.data(), 0, nullptr);
526 }
527 const D3D12_RESOURCE_BARRIER barrier = uav_barrier(resource);
528 list->ResourceBarrier(1, &barrier);
529 };
530 // The whole buffer 0xcdcdcdcd through a raw view, then each case's elements through a typed view.
531 clear(make(data.p, nullptr, buffer_view(DXGI_FORMAT_R32_TYPELESS, 0, api_data_bytes / 4, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW)),
532 data.p, false, {0xcdcdcdcd, 0, 0, 0});
533 supported_by_host.assign(std::size(clear_cases), true);
534 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
535 const ClearCase& test = clear_cases[c];
536 if (host) {
537 D3D12_FEATURE_DATA_FORMAT_SUPPORT support{test.format};
538 supported_by_host[c] = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) &&
539 (support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE);
540 }
541 if (!supported_by_host[c]) continue;
542 const UINT size = uc::layout(test.vulkan)->bytes;
543 clear(make(data.p, nullptr, buffer_view(test.format, test.byte_offset / size, test.elements, 0)), data.p,
544 test.is_float, test.values);
545 }
546 // A structured view with a counter. The clear writes the records and leaves the counter (preset to 7) alone ...
547 list->CopyBufferRegion(structured.p, 0, upload.p, 0, api_records_bytes);
548 list->CopyBufferRegion(counter_buffer.p, 0, upload.p, api_records_bytes, counter_buffer_bytes);
549 D3D12_RESOURCE_BARRIER to_uav[2] = {transition(structured.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
550 transition(counter_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST,
551 D3D12_RESOURCE_STATE_UNORDERED_ACCESS)};
552 list->ResourceBarrier(2, to_uav);
553 clear(make(structured.p, counter_buffer.p, buffer_view(DXGI_FORMAT_UNKNOWN, 0, 256, 16, counter_offset)), structured.p,
554 false, {0xab, 0xcd, 0xef, 0x01});
555 // ... and a raw view of the counter's own word (element 1024) clears it, as a game resets its counter.
556 clear(make(counter_buffer.p, nullptr, buffer_view(DXGI_FORMAT_R32_TYPELESS, counter_offset / 4, 1, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW)),
557 counter_buffer.p, false, {3, 0, 0, 0});
558 D3D12_RESOURCE_BARRIER to_copy[3] = {
559 transition(data.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
560 transition(structured.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
561 transition(counter_buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)};
562 list->ResourceBarrier(3, to_copy);
563 list->CopyBufferRegion(readback.p, 0, data.p, 0, api_data_bytes);
564 list->CopyBufferRegion(readback.p, api_data_bytes, structured.p, 0, api_records_bytes);
565 list->CopyBufferRegion(readback.p, api_data_bytes + api_records_bytes, counter_buffer.p, 0, counter_buffer_bytes);
566 if (const HRESULT hr = list->Close(); FAILED(hr)) return std::fprintf(stderr, "Close: %08lx\n", static_cast<unsigned long>(hr)), false;
567 ID3D12CommandList* lists[] = {list.p};
568 queue->ExecuteCommandLists(1, lists);
569 if (!host && rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success)
570 return std::fprintf(stderr, "replay result %d\n", int(rt::d3d12::last_execute_result(queue.p))), false;
571 if (FAILED(queue->Signal(fence.p, 1))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
572 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
573 if (!event || FAILED(fence->SetEventOnCompletion(1, event)) || WaitForSingleObject(event, 20000) != WAIT_OBJECT_0)
574 return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
575 CloseHandle(event);
576 void* mapped = nullptr;
577 if (FAILED(readback->Map(0, nullptr, &mapped))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
578 out.assign(static_cast<const std::uint8_t*>(mapped), static_cast<const std::uint8_t*>(mapped) + api_readback);
579 readback->Unmap(0, nullptr);
580 return true;
581}
582
583// What D3D12 says the same sequence leaves, from uav_clear.h: the model for a run with no host runtime to compare with.
584std::vector<std::uint8_t> model(const std::vector<bool>& supported) {
585 std::vector<std::uint8_t> bytes(api_readback, 0x11);
586 std::fill(bytes.begin(), bytes.begin() + api_data_bytes, std::uint8_t(0xcd));
587 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
588 const ClearCase& test = clear_cases[c];
589 uc::Element e{};
590 if (!supported[c] || !uc::encode(test.vulkan, test.is_float, test.values, e)) continue;
591 for (UINT64 i = 0; i < UINT64(test.elements) * e.size; ++i) bytes[test.byte_offset + i] = e.bytes[i % e.size];
592 }
593 // A structured view clears every 32-bit word to the first value (D3D12 ignores the other three).
594 for (UINT64 i = 0; i < api_records_bytes; ++i) bytes[api_data_bytes + i] = i % 4 == 0 ? 0xab : 0;
595 const std::uint32_t three = 3;
596 std::memcpy(bytes.data() + api_data_bytes + api_records_bytes + counter_offset, &three, 4);
597 return bytes;
598}
599
600} // namespace
601
602int main() {
603 vktest::Device d;
604 const auto device_status = d.initialize();
605 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
606 if (device_status != vktest::DeviceStatus::ready) return 1;
607 if (!d.bindless) {
608 std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n");
609 return 77;
610 }
611 const std::filesystem::path root_dir = LEONIDA_TEST_BUFFER_UAV_DIR;
612
613 unsigned words = 0;
614 if (const int status = run_shaders(d, root_dir, words)) return status;
615
616 // Part 2: the layer's device and the host's on the same adapter.
617 std::vector<std::uint8_t> ours, host_bytes;
618 std::vector<bool> supported;
619 {
620 rt::d3d12::VulkanDeviceInfo info{};
621 info.get_instance_proc = d.instance_proc;
622 info.instance = d.instance;
623 info.physical = d.physical;
624 info.device = d.device;
625 info.queue = d.queue;
626 info.queue_family = d.family;
627 info.buffer_device_address = true; // the V# holds the buffer's address
628 Ref<ID3D12Device> device;
629 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
630 EXPECT(run_api(device.p, false, ours, supported));
631 }
632 std::string host_name = "none";
633 bool compared = false;
634 {
635 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
636 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
637 d.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(d.physical, &properties);
638 copycmp::Ptr<ID3D12Device> host;
639 LUID luid{};
640 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
641 if (id.deviceLUIDValid && copycmp::try_create_host(host, host_name, &luid)) {
642 std::vector<bool> host_supported;
643 EXPECT(run_api(host.p, true, host_bytes, host_supported));
644 supported = host_supported;
645 compared = true;
646 }
647 }
648 if (!compared) {
649 std::printf("no host D3D12 device on the layer's adapter: the layer's bytes are compared with uav_clear.h\n");
650 host_bytes = model(supported);
651 host_name = "the uav_clear.h model";
652 } else {
653 // The layer ran every case; the host only those its adapter can store typed. Mask the others in both.
654 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
655 if (supported[c]) continue;
656 const ClearCase& test = clear_cases[c];
657 const UINT size = uc::layout(test.vulkan)->bytes;
658 std::fill_n(ours.begin() + test.byte_offset, UINT64(test.elements) * size, std::uint8_t(0));
659 std::fill_n(host_bytes.begin() + test.byte_offset, UINT64(test.elements) * size, std::uint8_t(0));
660 std::printf("host adapter has no typed UAV store for DXGI format %d: that case is not compared\n",
661 int(test.format));
662 }
663 }
664 EXPECT(ours.size() == api_readback && host_bytes.size() == api_readback);
665 unsigned differing = 0;
666 for (std::size_t i = 0; i < ours.size(); ++i) {
667 ++words;
668 if (ours[i] == host_bytes[i]) continue;
669 if (differing++ < 12) {
670 const char* where = i < api_data_bytes ? "typed clears" : i < api_data_bytes + api_records_bytes ? "structured clear with a counter" : "counter buffer";
671 std::fprintf(stderr, "%s byte %zu: layer %02x, %s %02x\n", where, i, ours[i], host_name.c_str(), host_bytes[i]);
672 }
673 }
674 if (differing) {
675 // Say which clear case the first differing byte belongs to.
676 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
677 const ClearCase& test = clear_cases[c];
678 const UINT size = uc::layout(test.vulkan)->bytes;
679 for (UINT64 i = 0; i < UINT64(test.elements) * size; ++i)
680 if (ours[test.byte_offset + i] != host_bytes[test.byte_offset + i]) {
681 std::fprintf(stderr, "case %zu (DXGI format %d) differs\n", c, int(test.format));
682 break;
683 }
684 }
685 std::fprintf(stderr, "%u bytes differ\n", differing);
686 return 1;
687 }
688 if (d.validation_errors()) {
689 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
690 return 1;
691 }
692 std::printf("Buffer UAVs: typed views (R32_UINT with an atomic, R16G16B16A16_FLOAT, R8G8B8A8_UNORM from FirstElement 16, "
693 "R32G32B32A32_UINT, R32_FLOAT loads, R32_SINT) written by a translated compute shader with NUM_RECORDS "
694 "as the bound, and a structured UAV with a counter at offset 4096 appended to by 256 lanes and consumed "
695 "by 128 (counter 256 then 128 through CopyBufferRegion) matched the CPU reference; typed-buffer and "
696 "counter clears matched %s: %u values compared, error 0\n",
697 host_name.c_str(), words);
698 return 0;
699}
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index a2011d3c2..2d9dff03f 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;
@@ -221,6 +225,40 @@ int main() {
221 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);
222 pso_desc.CS = {container.data(), container.size()}; 226 pso_desc.CS = {container.data(), container.size()};
223 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
224 // 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
225 // 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).
226 { 264 {
@@ -344,7 +382,131 @@ int main() {
344 std::memcpy(first.data(), results, bytes); 382 std::memcpy(first.data(), results, bytes);
345 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);
346 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
347 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset(); 507 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset();
508 pso67.reset();
509 unknown67.reset();
348 pso.reset(); 510 pso.reset();
349 root.reset(); 511 root.reset();
350 heap.reset(); 512 heap.reset();
@@ -364,6 +526,27 @@ int main() {
364 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b); 526 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b);
365 } 527 }
366 EXPECT(!mismatches); 528 EXPECT(!mismatches);
529 UINT cbv_b_diff = 0, cbv_null_diff = 0;
530 for (std::uint32_t i = 0; i < elements; ++i) {
531 const std::uint32_t want_a = 0x10000u + i;
532 const std::uint32_t want_oob = i < 32 ? (0x10000u + 32u + i) : 0u;
533 const std::uint32_t want_b = 0x20000u + i;
534 if (cbv_a_out[i] != want_a && mismatches++ < 4)
535 std::fprintf(stderr, "CBV A[%u]: got 0x%x want 0x%x\n", i, cbv_a_out[i], want_a);
536 if (cbv_oob_out[i] != want_oob && mismatches++ < 4)
537 std::fprintf(stderr, "CBV OOB[%u]: got 0x%x want 0x%x\n", i, cbv_oob_out[i], want_oob);
538 if (cbv_b_out[i] != want_b && mismatches++ < 4)
539 std::fprintf(stderr, "CBV B[%u]: got 0x%x want 0x%x\n", i, cbv_b_out[i], want_b);
540 if (cbv_null_out[i] != 0u && mismatches++ < 4)
541 std::fprintf(stderr, "CBV null[%u]: got 0x%x want 0\n", i, cbv_null_out[i]);
542 if (cbv_b_out[i] != cbv_a_out[i]) ++cbv_b_diff;
543 if (cbv_null_out[i] != cbv_a_out[i]) ++cbv_null_diff;
544 }
545 EXPECT(!mismatches);
546 EXPECT(cbv_b_diff == elements && cbv_null_diff == elements);
547 std::printf("CreateConstantBufferView: 64/64 dwords matched for CBV A, 32 in-bounds + 32 OOB-zero matched at "
548 "+128, negative controls flipped %u/%u (CBV B) and %u/%u (null CBV)\n",
549 cbv_b_diff, elements, cbv_null_diff, elements);
367 if (d.validation_errors()) { 550 if (d.validation_errors()) {
368 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 551 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
369 return 1; 552 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 64ef24da6..13c10d043 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -698,6 +698,42 @@ int main() {
698 const auto null_at = [&](UINT i) { 698 const auto null_at = [&](UINT i) {
699 return std::all_of(view_bytes(i), view_bytes(i) + step, [](std::uint8_t byte) { return byte == 0; }); 699 return std::all_of(view_bytes(i), view_bytes(i) + step, [](std::uint8_t byte) { return byte == 0; });
700 }; 700 };
701 // An explicit D3D12_SRV_DIMENSION_TEXTURE1D view on a 1D texture array selects layer zero (like TEXTURE2D
702 // and TEXTURE2DMS on 2D arrays), while a default (nullptr) SRV on a 1D array remains a null descriptor.
703 {
704 auto line_array_desc = line_desc;
705 line_array_desc.DepthOrArraySize = 3;
706 Ref<ID3D12Resource> line_array;
707 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &line_array_desc,
708 D3D12_RESOURCE_STATE_COMMON, nullptr,
709 IID_PPV_ARGS(&line_array.p))));
710 D3D12_DESCRIPTOR_HEAP_DESC la_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2,
711 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
712 Ref<ID3D12DescriptorHeap> la_heap;
713 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&la_heap_desc, IID_PPV_ARGS(&la_heap.p))));
714 const std::uint64_t la_cpu = reinterpret_cast<XboxHeapHandleFn>(slot(la_heap.p, 9))(la_heap.p);
715 const D3D12_CPU_DESCRIPTOR_HANDLE la_default{SIZE_T(la_cpu)}, la_slice0{SIZE_T(la_cpu + step)};
716 std::memset(reinterpret_cast<void*>(la_default.ptr), 0x77, step);
717 device->CreateShaderResourceView(line_array.p, nullptr, la_default);
718 EXPECT(std::all_of(reinterpret_cast<const std::uint8_t*>(la_default.ptr),
719 reinterpret_cast<const std::uint8_t*>(la_default.ptr) + step,
720 [](std::uint8_t byte) { return byte == 0; }));
721 D3D12_SHADER_RESOURCE_VIEW_DESC la_view{};
722 la_view.Format = DXGI_FORMAT_UNKNOWN;
723 la_view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
724 la_view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
725 la_view.Texture1D = {1, 1, 0};
726 device->CreateShaderResourceView(line_array.p, &la_view, la_slice0);
727 g::ImageWords la_words{};
728 std::memcpy(la_words.data(), reinterpret_cast<const void*>(la_slice0.ptr), sizeof(la_words));
729 g::Image la_image{};
730 EXPECT(g::is_image(la_words) && g::decode(la_words, la_image) &&
731 la_image.type == g::ImageType::image_1d && la_image.first_mip == 1 && la_image.mip_count == 1 &&
732 la_image.first_layer == 0 && la_image.layer_count == 1);
733 std::uint32_t la_key[8]{};
734 std::memcpy(la_key, la_words.data(), sizeof(la_key));
735 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, la_key) != 0);
736 }
701 D3D12_RESOURCE_DESC ms_desc = texture_desc; 737 D3D12_RESOURCE_DESC ms_desc = texture_desc;
702 ms_desc.Width = ms_desc.Height = 4; 738 ms_desc.Width = ms_desc.Height = 4;
703 ms_desc.SampleDesc.Count = 4; 739 ms_desc.SampleDesc.Count = 4;
@@ -2166,6 +2202,47 @@ int main() {
2166#endif 2202#endif
2167 } 2203 }
2168 2204
2205 // Cross-family castable SRV: write_image_descriptor must pass resource.has_view_format_list() into a single
2206 // bind_image call so a listed R8G8B8A8_UINT -> R32_UINT view registers cleanly without a spurious first-pass
2207 // failure (and without double-binding every view).
2208 if (d.bindless) {
2209 Ref<ID3D12Device10> inner10;
2210 EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&inner10.p))));
2211 D3D12_RESOURCE_DESC1 cast_desc{};
2212 cast_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
2213 cast_desc.Width = 4;
2214 cast_desc.Height = 4;
2215 cast_desc.DepthOrArraySize = 1;
2216 cast_desc.MipLevels = 1;
2217 cast_desc.Format = DXGI_FORMAT_R8G8B8A8_UINT;
2218 cast_desc.SampleDesc = {1, 0};
2219 cast_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
2220 const DXGI_FORMAT cast_formats[] = {DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R32_UINT};
2221 Ref<ID3D12Resource> cast_tex;
2222 EXPECT(SUCCEEDED(inner10->CreateCommittedResource3(
2223 &default_heap, D3D12_HEAP_FLAG_NONE, &cast_desc, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr,
2224 2, cast_formats, IID_PPV_ARGS(&cast_tex.p))));
2225 const D3D12_DESCRIPTOR_HEAP_DESC cast_hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1,
2226 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
2227 Ref<ID3D12DescriptorHeap> cast_heap;
2228 EXPECT(SUCCEEDED(inner10->CreateDescriptorHeap(&cast_hd, IID_PPV_ARGS(&cast_heap.p))));
2229 const D3D12_CPU_DESCRIPTOR_HANDLE cast_slot = cast_heap->GetCPUDescriptorHandleForHeapStart();
2230 D3D12_SHADER_RESOURCE_VIEW_DESC cast_srv{};
2231 cast_srv.Format = DXGI_FORMAT_R32_UINT;
2232 cast_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2233 cast_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2234 cast_srv.Texture2D.MipLevels = 1;
2235 inner10->CreateShaderResourceView(cast_tex.p, &cast_srv, cast_slot);
2236 g::ImageWords cast_words{};
2237 std::memcpy(cast_words.data(), reinterpret_cast<const void*>(cast_slot.ptr), sizeof(cast_words));
2238 g::Image decoded{};
2239 EXPECT(g::decode(cast_words, decoded) && decoded.type == g::ImageType::image_2d);
2240 EXPECT(decoded.format == g::format_from_vulkan(VK_FORMAT_R32_UINT));
2241 std::uint32_t cast_key[8]{};
2242 std::memcpy(cast_key, cast_words.data(), sizeof(cast_key));
2243 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, cast_key) != 0);
2244 }
2245
2169 upload.reset(); 2246 upload.reset();
2170 array_texture.reset(); 2247 array_texture.reset();
2171 line.reset(); 2248 line.reset();
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 1c29d3822..12a1c71cf 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -630,7 +630,8 @@ int main() {
630 EXPECT(list->Close() == S_OK); 630 EXPECT(list->Close() == S_OK);
631 queue->ExecuteCommandLists(1, lists); 631 queue->ExecuteCommandLists(1, lists);
632 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 632 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
633 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)));
634 const auto* result = static_cast<const std::uint8_t*>(mapped); 635 const auto* result = static_cast<const std::uint8_t*>(mapped);
635 for (UINT row = 0; row < size; ++row) { 636 for (UINT row = 0; row < size; ++row) {
636 for (UINT col = 0; col < size; ++col) { 637 for (UINT col = 0; col < size; ++col) {
diff --git a/runtime/test/d3d12_gcl8_test.cpp b/runtime/test/d3d12_gcl8_test.cpp
index 5872a624f..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();
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_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp
new file mode 100644
index 000000000..bd3a555fd
--- /dev/null
+++ b/runtime/test/d3d12_m4_compute_test.cpp
@@ -0,0 +1,395 @@
1// Milestone M4, the synthetic part (docs/d3d12_vulkan.md section 6): a compute workload with the structure a game's asset
2// streaming and compute passes have, through the D3D12 API on the proxy, with compute shaders that are translator output
3// (test/shaders/cs_m4_fill.asm and cs_m4_indirect.asm, hand-written RDNA2).
4// Three queues' worth of work, each its own command list type:
5// COPY queue streams an input buffer: CopyBufferRegion from an UPLOAD buffer into a DEFAULT buffer that was created
6// in COMMON (promoted to COPY_DEST there), then Signal(copy fence, 1).
7// COMPUTE queue Wait(copy fence, 1), then one list: a barrier COMMON -> UNORDERED_ACCESS for the input, a compute root
8// signature (four root constants and a descriptor table of five UAVs: a structured buffer, a raw
9// buffer, an R32_UINT RWTexture2D, the raw input and a raw output), a compute PSO, and Dispatch with
10// four groups. That shader fills the structured buffer and the image from the input and writes the
11// arguments of the next dispatch into the raw buffer. Barriers (a transition of the argument buffer to
12// INDIRECT_ARGUMENT and UAV barriers on the buffer and the image) and ExecuteIndirect with a dispatch
13// command signature runs a second PSO whose group count is that buffer's first word: it reads the
14// structured buffer and the image back and writes the raw output. Everything then goes to COMMON and
15// the queue does Signal(compute fence, 1).
16// COPY queue Wait(compute fence, 1), a COPY list that copies the five results (four buffers and the image through
17// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with
18// SetEventOnCompletion and an event.
19// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are
20// real cross-queue semaphores); with one, they share it. Either way the three batches are submitted in dependency order.
21// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the
22// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the
23// first dispatch asked for ran).
24// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
25#include "vk_test_device.h"
26#include "d3d12_test_shaders.h"
27#include "../shims/d3d12_com.h"
28#include "../shims/d3d12_xs_device.h"
29#include "../src/shader_library.h"
30
31#include <array>
32#include <cstring>
33
34#ifndef LEONIDA_TEST_M4_DIR
35#error "LEONIDA_TEST_M4_DIR must name the folder build.py wrote (spirv/index.json, fssm/cs_*.fssm)"
36#endif
37
38#define EXPECT(condition) do { \
39 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
40} while (0)
41
42using namespace d3d12test;
43using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
44
45namespace {
46
47std::vector<std::uint8_t> read_file(const std::filesystem::path& path) {
48 std::ifstream in(path, std::ios::binary);
49 return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
50}
51
52constexpr UINT records = 256; // fill: 4 groups of 64
53constexpr UINT second_groups = 3; // the indirect dispatch: 3 groups of 64
54constexpr UINT image_dim = 16; // 16 x 16 R32_UINT, one texel a record
55constexpr UINT seed = 0x00c0ffee, multiplier = 0x01000193;
56// The readback buffer: the structured buffer, the argument buffer's 16 bytes, the second output, the input, the image.
57constexpr UINT64 data_bytes = records * 16, args_bytes = 16, out2_bytes = second_groups * 64 * 8, in_bytes = records * 4;
58constexpr UINT64 offset_data = 0, offset_args = offset_data + data_bytes, offset_out2 = offset_args + args_bytes,
59 offset_in = offset_out2 + out2_bytes;
60constexpr UINT64 offset_image = (offset_in + in_bytes + 511) / 512 * 512;
61constexpr UINT image_pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
62constexpr UINT64 readback_bytes = offset_image + UINT64(image_dim) * image_pitch;
63
64std::uint32_t rotr(std::uint32_t v, unsigned n) { return (v >> n) | (v << (32 - n)); }
65std::uint32_t input_word(UINT g) { return (g + 1) * 0x9e3779b1u ^ (g << 7); }
66
67struct Reference {
68 std::vector<std::uint32_t> data, args, in, image, out2;
69};
70Reference reference() {
71 Reference ref;
72 ref.args = {second_groups, 1, 1, 0xc0de0001u};
73 ref.data.resize(records * 4);
74 ref.image.resize(image_dim * image_dim);
75 for (UINT g = 0; g < records; ++g) {
76 const std::uint32_t in = input_word(g);
77 ref.in.push_back(in);
78 ref.data[g * 4 + 0] = in + seed;
79 ref.data[g * 4 + 1] = g * multiplier;
80 ref.data[g * 4 + 2] = in ^ (g << 8);
81 ref.data[g * 4 + 3] = rotr(in, 13);
82 const UINT x = g & 15, y = g >> 4;
83 ref.image[y * image_dim + x] = in * 3 + x * 0x10001u + y;
84 }
85 for (UINT g = 0; g < second_groups * 64; ++g) {
86 const std::uint32_t t = ref.image[g]; // (g & 15, g >> 4) is texel g of the row-major image
87 ref.out2.push_back((ref.data[g * 4 + 0] + t) ^ ref.data[g * 4 + 3]);
88 ref.out2.push_back((ref.data[g * 4 + 2] ^ t) + ref.data[g * 4 + 1]);
89 }
90 return ref;
91}
92
93} // namespace
94
95int main() {
96 vktest::Device d;
97 d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two
98 const auto device_status = d.initialize();
99 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
100 if (device_status != vktest::DeviceStatus::ready) return 1;
101 if (!d.bindless) {
102 std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n");
103 return 77;
104 }
105
106 const std::filesystem::path root_dir = LEONIDA_TEST_M4_DIR;
107 leonida::ShaderLibrary library;
108 EXPECT(library.load((root_dir / "spirv").string()));
109 const auto program = [&](const char* name) { return read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); };
110 const auto fill = program("cs_m4_fill"), indirect = program("cs_m4_indirect");
111 EXPECT(fill.size() >= 0x150 && indirect.size() >= 0x150 && fill != indirect);
112 EXPECT(library.find("cs", leonida::sha256_hex(fill)) && library.find("cs", leonida::sha256_hex(indirect)));
113 const auto fill_container = shader_container(fill), indirect_container = shader_container(indirect);
114
115 const bool distinct_queues = d.queues.size() >= 2;
116 Reference want = reference();
117 std::vector<std::uint8_t> got;
118 {
119 rt::d3d12::VulkanDeviceInfo info{};
120 info.get_instance_proc = d.instance_proc;
121 info.instance = d.instance;
122 info.physical = d.physical;
123 info.device = d.device;
124 info.queue = d.queue;
125 info.queue_family = d.family;
126 if (distinct_queues) info.command_queues = d.queues;
127 info.buffer_device_address = true;
128 info.bindless = d.bindless;
129 info.bindless_partially_bound = d.partially_bound;
130 info.image_view_min_lod = d.image_view_min_lod;
131 info.shader_dir = (root_dir / "spirv").string();
132 ID3D12Device* inner = nullptr;
133 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
134 Ref<ID3D12Device> device;
135 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
136 reinterpret_cast<void**>(&device.p))));
137 rt::d3d12::set_device_outer(inner, device.p);
138 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
139
140 // [0] four 32-bit constants (s0..s3), [1] a table of five UAVs (s[4:5]).
141 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 5, 0, 0, 0};
142 D3D12_ROOT_PARAMETER params[2] = {};
143 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
144 params[0].Constants = {0, 0, 4};
145 params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
146 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
147 params[1].DescriptorTable = {1, &uav_range};
148 params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
149 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
150 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
151 root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
152 const auto root_blob = serialize_root_signature(root_desc);
153 EXPECT(!root_blob.empty());
154 Ref<ID3D12RootSignature> root;
155 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
156
157 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
158 pso_desc.pRootSignature = root.p;
159 pso_desc.CS = {fill_container.data(), fill_container.size()};
160 Ref<ID3D12PipelineState> pso_fill, pso_indirect;
161 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_fill.p))));
162 pso_desc.CS = {indirect_container.data(), indirect_container.size()};
163 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p))));
164
165 D3D12_INDIRECT_ARGUMENT_DESC argument{};
166 argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
167 D3D12_COMMAND_SIGNATURE_DESC signature_desc{};
168 signature_desc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS);
169 signature_desc.NumArgumentDescs = 1;
170 signature_desc.pArgumentDescs = &argument;
171 Ref<ID3D12CommandSignature> signature;
172 EXPECT(SUCCEEDED(device->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p))));
173
174 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
175 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
176 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
177 constexpr auto uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
178 constexpr auto uav_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
179 constexpr auto common = D3D12_RESOURCE_STATE_COMMON;
180 Ref<ID3D12Resource> upload, input, data, args, out2, image, readback;
181 const auto create_buffer = [&](Ref<ID3D12Resource>& out, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes,
182 D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) {
183 const auto desc = buffer_desc(bytes, flags);
184 return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
185 IID_PPV_ARGS(&out.p)));
186 };
187 EXPECT(create_buffer(upload, upload_heap, in_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ));
188 EXPECT(create_buffer(input, default_heap, in_bytes, uav_flag, common));
189 EXPECT(create_buffer(data, default_heap, data_bytes, uav_flag, uav_state));
190 EXPECT(create_buffer(args, default_heap, 256, uav_flag, uav_state));
191 EXPECT(create_buffer(out2, default_heap, out2_bytes, uav_flag, uav_state));
192 EXPECT(create_buffer(readback, readback_heap, readback_bytes, D3D12_RESOURCE_FLAG_NONE,
193 D3D12_RESOURCE_STATE_COPY_DEST));
194 D3D12_RESOURCE_DESC image_desc{};
195 image_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
196 image_desc.Width = image_desc.Height = image_dim;
197 image_desc.DepthOrArraySize = 1;
198 image_desc.MipLevels = 1;
199 image_desc.Format = DXGI_FORMAT_R32_UINT;
200 image_desc.SampleDesc.Count = 1;
201 image_desc.Flags = uav_flag;
202 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &image_desc, uav_state,
203 nullptr, IID_PPV_ARGS(&image.p))));
204 {
205 std::uint32_t* mapped = nullptr;
206 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped))));
207 for (UINT g = 0; g < records; ++g) mapped[g] = input_word(g);
208 upload->Unmap(0, nullptr);
209 }
210
211 // The table: slot 0 structured buffer (stride 16), 1 raw argument buffer, 2 image, 3 raw input, 4 raw output.
212 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5,
213 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
214 Ref<ID3D12DescriptorHeap> heap;
215 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
216 const std::uint64_t cpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 9))(heap.p);
217 const std::uint64_t gpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p);
218 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
219 EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step == 32); // the shaders step 32 bytes a slot
220 const auto handle = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + std::uint64_t(i) * step)}; };
221 const auto buffer_view = [](DXGI_FORMAT format, UINT count, UINT stride, D3D12_BUFFER_UAV_FLAGS flags) {
222 D3D12_UNORDERED_ACCESS_VIEW_DESC view{};
223 view.Format = format;
224 view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
225 view.Buffer = {0, count, stride, 0, flags};
226 return view;
227 };
228 auto view = buffer_view(DXGI_FORMAT_UNKNOWN, records, 16, D3D12_BUFFER_UAV_FLAG_NONE);
229 device->CreateUnorderedAccessView(data.p, nullptr, &view, handle(0));
230 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, 4, 0, D3D12_BUFFER_UAV_FLAG_RAW); // the 16 bytes of arguments
231 device->CreateUnorderedAccessView(args.p, nullptr, &view, handle(1));
232 D3D12_UNORDERED_ACCESS_VIEW_DESC image_view{};
233 image_view.Format = DXGI_FORMAT_R32_UINT;
234 image_view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
235 device->CreateUnorderedAccessView(image.p, nullptr, &image_view, handle(2));
236 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, records, 0, D3D12_BUFFER_UAV_FLAG_RAW);
237 device->CreateUnorderedAccessView(input.p, nullptr, &view, handle(3));
238 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, UINT(out2_bytes / 4), 0, D3D12_BUFFER_UAV_FLAG_RAW);
239 device->CreateUnorderedAccessView(out2.p, nullptr, &view, handle(4));
240 // The V# of the structured view and the T# of the image view are what the shader loads from the table.
241 std::uint32_t v_data[4], v_args[4];
242 std::memcpy(v_data, reinterpret_cast<const void*>(handle(0).ptr), sizeof(v_data));
243 std::memcpy(v_args, reinterpret_cast<const void*>(handle(1).ptr), sizeof(v_args));
244 EXPECT(v_data[0] == std::uint32_t(data->GetGPUVirtualAddress()) && (v_data[1] >> 16 & 0x3fff) == 16 &&
245 v_data[2] == records);
246 EXPECT(v_args[0] == std::uint32_t(args->GetGPUVirtualAddress()) && (v_args[1] >> 16 & 0x3fff) == 0 &&
247 v_args[2] == 16);
248
249 D3D12_COMMAND_QUEUE_DESC queue_desc{};
250 Ref<ID3D12CommandQueue> copy_queue, compute_queue;
251 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
252 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&copy_queue.p))));
253 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
254 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&compute_queue.p))));
255 Ref<ID3D12CommandAllocator> stream_alloc, compute_alloc, readback_alloc;
256 Ref<ID3D12GraphicsCommandList> stream_list, compute_list, readback_list;
257 Ref<ID3D12Fence> copy_fence, compute_fence;
258 const auto make_list = [&](D3D12_COMMAND_LIST_TYPE type, Ref<ID3D12CommandAllocator>& alloc,
259 Ref<ID3D12GraphicsCommandList>& list) {
260 return SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&alloc.p))) &&
261 SUCCEEDED(device->CreateCommandList(0, type, alloc.p, nullptr, IID_PPV_ARGS(&list.p)));
262 };
263 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, stream_alloc, stream_list));
264 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, compute_alloc, compute_list));
265 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, readback_alloc, readback_list));
266 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&copy_fence.p))));
267 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&compute_fence.p))));
268
269 // Copy list 1: stream the input in (the buffer is in COMMON and is promoted to COPY_DEST by the copy). This is the
270 // first submission after the UAV views were written, and a copy queue: it must not initialize the storage image
271 // (the compute queue does, in the submission that dispatches), or the data written later would be at risk.
272 stream_list->CopyBufferRegion(input.p, 0, upload.p, 0, in_bytes);
273 EXPECT(stream_list->Close() == S_OK);
274
275 D3D12_TEXTURE_COPY_LOCATION dst{}, src{};
276 dst.pResource = readback.p;
277 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
278 dst.PlacedFootprint = {offset_image, {DXGI_FORMAT_R32_UINT, image_dim, image_dim, 1, image_pitch}};
279 src.pResource = image.p;
280 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
281
282 // Compute list.
283 ID3D12DescriptorHeap* heaps[] = {heap.p};
284 D3D12_RESOURCE_BARRIER acquire = transition(input.p, common, uav_state);
285 compute_list->ResourceBarrier(1, &acquire);
286 compute_list->SetDescriptorHeaps(1, heaps);
287 compute_list->SetComputeRootSignature(root.p);
288 compute_list->SetPipelineState(pso_fill.p);
289 const std::uint32_t constants[4] = {seed, multiplier, second_groups, 0};
290 compute_list->SetComputeRoot32BitConstants(0, 4, constants, 0);
291 compute_list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu});
292 compute_list->Dispatch(records / 64, 1, 1);
293 D3D12_RESOURCE_BARRIER between[3] = {transition(args.p, uav_state, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
294 {}, {}};
295 for (int i : {1, 2}) {
296 between[i].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
297 between[i].UAV.pResource = i == 1 ? data.p : image.p;
298 }
299 compute_list->ResourceBarrier(3, between);
300 compute_list->SetPipelineState(pso_indirect.p); // the root arguments stay
301 compute_list->ExecuteIndirect(signature.p, 1, args.p, 0, nullptr, 0);
302 D3D12_RESOURCE_BARRIER release[5] = {transition(data.p, uav_state, common),
303 transition(args.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, common),
304 transition(out2.p, uav_state, common),
305 transition(input.p, uav_state, common),
306 transition(image.p, uav_state, common)};
307 compute_list->ResourceBarrier(5, release);
308 EXPECT(compute_list->Close() == S_OK);
309
310 // Copy list 2: the results to the readback buffer, once the compute queue is done.
311 readback_list->CopyBufferRegion(readback.p, offset_data, data.p, 0, data_bytes);
312 readback_list->CopyBufferRegion(readback.p, offset_args, args.p, 0, args_bytes);
313 readback_list->CopyBufferRegion(readback.p, offset_out2, out2.p, 0, out2_bytes);
314 readback_list->CopyBufferRegion(readback.p, offset_in, input.p, 0, in_bytes);
315 readback_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
316 EXPECT(readback_list->Close() == S_OK);
317
318 const auto execute = [&](ID3D12CommandQueue* queue, ID3D12GraphicsCommandList* list) {
319 ID3D12CommandList* lists[] = {list};
320 queue->ExecuteCommandLists(1, lists);
321 return rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success;
322 };
323 const auto submit_copy = [&] {
324 return execute(copy_queue.p, stream_list.p) && SUCCEEDED(copy_queue->Signal(copy_fence.p, 1));
325 };
326 const auto submit_readback = [&] {
327 return SUCCEEDED(copy_queue->Wait(compute_fence.p, 1)) && execute(copy_queue.p, readback_list.p) &&
328 SUCCEEDED(copy_queue->Signal(copy_fence.p, 2));
329 };
330 const auto submit_compute = [&] {
331 return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) &&
332 SUCCEEDED(compute_queue->Signal(compute_fence.p, 1));
333 };
334 // In dependency order: the layer replays a list at ExecuteCommandLists and tracks every image's layout in that
335 // order, so a list that waits for another queue's signal has to be submitted after the list it waits for
336 // (the Wait-before-Signal order d3d12_queue_wait_test covers, without a resource handed over).
337 EXPECT(submit_copy() && submit_compute() && submit_readback());
338
339 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
340 EXPECT(event != nullptr);
341 EXPECT(SUCCEEDED(copy_fence->SetEventOnCompletion(2, event)));
342 if (WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) {
343 std::fprintf(stderr, "the copy fence never reached 2 (compute fence at %llu)\n",
344 static_cast<unsigned long long>(compute_fence->GetCompletedValue()));
345 return 1;
346 }
347 CloseHandle(event);
348 EXPECT(copy_fence->GetCompletedValue() >= 2 && compute_fence->GetCompletedValue() >= 1);
349
350 void* mapped = nullptr;
351 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
352 got.assign(static_cast<const std::uint8_t*>(mapped), static_cast<const std::uint8_t*>(mapped) + readback_bytes);
353 readback->Unmap(0, nullptr);
354
355 for (auto* r : {&upload, &input, &data, &args, &out2, &image, &readback}) r->reset();
356 stream_list.reset(); compute_list.reset(); readback_list.reset();
357 stream_alloc.reset(); compute_alloc.reset(); readback_alloc.reset();
358 copy_fence.reset(); compute_fence.reset();
359 signature.reset(); pso_fill.reset(); pso_indirect.reset(); root.reset(); heap.reset();
360 copy_queue.reset(); compute_queue.reset();
361 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
362 }
363
364 unsigned mismatches = 0, words = 0;
365 const auto compare = [&](const char* what, UINT64 offset, const std::vector<std::uint32_t>& expected, UINT pitch,
366 UINT row_words) {
367 unsigned bad = 0;
368 for (std::size_t i = 0; i < expected.size(); ++i) {
369 std::uint32_t value = 0;
370 const UINT64 at = offset + (pitch ? (i / row_words) * pitch + (i % row_words) * 4 : i * 4);
371 std::memcpy(&value, got.data() + at, 4);
372 ++words;
373 if (value == expected[i]) continue;
374 ++mismatches;
375 if (bad++ < 4) std::fprintf(stderr, "%s word %zu: got %08x want %08x\n", what, i, value, expected[i]);
376 }
377 if (bad) std::fprintf(stderr, "%s: %u of %zu words differ\n", what, bad, expected.size());
378 };
379 compare("input (copy queue round trip)", offset_in, want.in, 0, 0);
380 compare("structured buffer", offset_data, want.data, 0, 0);
381 compare("dispatch arguments", offset_args, want.args, 0, 0);
382 compare("image", offset_image, want.image, image_pitch, image_dim);
383 compare("indirect dispatch output", offset_out2, want.out2, 0, 0);
384 EXPECT(!mismatches);
385 if (d.validation_errors()) {
386 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
387 return 1;
388 }
389 std::printf("M4: a COPY queue streamed an input buffer in, a COMPUTE queue ran a compute PSO over a UAV table "
390 "(structured buffer, raw buffers, an R32_UINT storage image) and a second dispatch through "
391 "ExecuteIndirect from arguments the first wrote, and a COPY queue behind a cross-queue fence read the "
392 "results back (%s): %u words matched the CPU reference (error 0)\n",
393 distinct_queues ? "two VkQueues" : "one VkQueue", words);
394 return 0;
395}
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
new file mode 100644
index 000000000..cd7b411e5
--- /dev/null
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -0,0 +1,316 @@
1// Synthetic GPU test for ID3D12Device1::CreatePipelineLibrary and ID3D12PipelineLibrary / ID3D12PipelineLibrary1:
2// - empty library creation (0-byte blob), null-output capability check (S_FALSE), and invalid/foreign/corrupt
3// blob rejection (E_INVALIDARG for null pointer with non-zero size, D3D12_ERROR_DRIVER_VERSION_MISMATCH for
4// unrecognized or corrupt headers);
5// - StorePipeline (unique names, duplicate rejection, null/empty name rejection, null/foreign PSO rejection);
6// - LoadComputePipeline, LoadGraphicsPipeline, and ID3D12PipelineLibrary1::LoadPipeline (including cross-type
7// mismatch rejection when a compute PSO is requested through LoadGraphicsPipeline or vice versa);
8// - GetSerializedSize + Serialize round-trip into a second CreatePipelineLibrary;
9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1.
10// No game data.
11#include "vk_test_device.h"
12#include "d3d12_test_shaders.h"
13#include "../shims/d3d12_com.h"
14#include "../src/shader_library.h"
15
16#include <cstring>
17#include <filesystem>
18#include <fstream>
19#include <vector>
20
21#if !defined(LEONIDA_TEST_CS_SPV) || !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV)
22#error "LEONIDA_TEST_CS_SPV, LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must be defined"
23#endif
24
25#define EXPECT(condition) do { \
26 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
27} while (0)
28
29using namespace d3d12test;
30
31namespace {
32
33struct Vertex {
34 float x, y;
35 std::uint8_t r, g, b, a;
36};
37
38D3D12_RESOURCE_DESC tex2d_desc(UINT w, UINT h, DXGI_FORMAT fmt, D3D12_RESOURCE_FLAGS flags) {
39 D3D12_RESOURCE_DESC d{};
40 d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
41 d.Width = w;
42 d.Height = h;
43 d.DepthOrArraySize = 1;
44 d.MipLevels = 1;
45 d.Format = fmt;
46 d.SampleDesc = {1, 0};
47 d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
48 d.Flags = flags;
49 return d;
50}
51
52} // namespace
53
54int main() {
55 vktest::Device d;
56 const auto status = d.initialize();
57 if (status == vktest::DeviceStatus::unavailable) {
58 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
59 return 77;
60 }
61 EXPECT(status == vktest::DeviceStatus::ready);
62
63 const auto cs_prog = fssm_program({0x43532001, 0xbf810000});
64 const auto vs_prog = fssm_program({0x56532001, 0xbf810000});
65 const auto ps_prog = fssm_program({0x50532001, 0xbf810000});
66 const auto cs_dxbc = shader_container(cs_prog);
67 const auto vs_dxbc = shader_container(vs_prog);
68 const auto ps_dxbc = shader_container(ps_prog);
69
70 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test";
71 std::filesystem::create_directories(lib_dir);
72 std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, lib_dir / "cs.spv",
73 std::filesystem::copy_options::overwrite_existing);
74 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, lib_dir / "vs.spv",
75 std::filesystem::copy_options::overwrite_existing);
76 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, lib_dir / "ps.spv",
77 std::filesystem::copy_options::overwrite_existing);
78 {
79 std::ofstream idx(lib_dir / "index.json", std::ios::binary);
80 idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog)
81 << "\", \"bindings\": [], \"push_constant_bytes\": 144},\n"
82 " \"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog)
83 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": ["
84 "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, "
85 "\"system_value\": 0, \"component_type\": \"float\"}, "
86 "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, "
87 "\"system_value\": 0, \"component_type\": \"float\"}]},\n"
88 " \"ps\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_prog)
89 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}";
90 }
91
92 rt::d3d12::VulkanDeviceInfo info{};
93 info.get_instance_proc = d.instance_proc;
94 info.instance = d.instance;
95 info.physical = d.physical;
96 info.device = d.device;
97 info.queue = d.queue;
98 info.queue_family = d.family;
99 info.buffer_device_address = true;
100 info.shader_dir = lib_dir.string();
101
102 Ref<ID3D12Device1> device;
103 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
104
105 // 1. CreatePipelineLibrary creation, capability check (null output -> S_FALSE), and invalid/corrupt blobs.
106 {
107 EXPECT(device->CreatePipelineLibrary(nullptr, 0, __uuidof(ID3D12PipelineLibrary), nullptr) == S_FALSE);
108 Ref<ID3D12PipelineLibrary> bad;
109 EXPECT(device->CreatePipelineLibrary(nullptr, 16, IID_PPV_ARGS(&bad.p)) == E_INVALIDARG && !bad.p);
110 const std::uint32_t foreign[4] = {0xDEADBEEFu, 1u, 0u, 0u};
111 EXPECT(device->CreatePipelineLibrary(foreign, sizeof(foreign), IID_PPV_ARGS(&bad.p)) ==
112 D3D12_ERROR_DRIVER_VERSION_MISMATCH &&
113 !bad.p);
114 const std::uint8_t tiny[4] = {1, 2, 3, 4};
115 EXPECT(device->CreatePipelineLibrary(tiny, sizeof(tiny), IID_PPV_ARGS(&bad.p)) ==
116 D3D12_ERROR_DRIVER_VERSION_MISMATCH &&
117 !bad.p);
118 }
119
120 // 2. Build one compute PSO and one graphics PSO.
121 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0};
122 D3D12_ROOT_PARAMETER cs_params[3]{};
123 cs_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
124 cs_params[0].Constants = {0, 0, 1};
125 cs_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
126 cs_params[1].Descriptor = {0, 0};
127 cs_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
128 cs_params[2].DescriptorTable = {1, &uav_range};
129 D3D12_VERSIONED_ROOT_SIGNATURE_DESC cs_rs_desc{};
130 cs_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
131 cs_rs_desc.Desc_1_0 = {3, cs_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
132 const auto cs_rs_blob = serialize_root_signature(cs_rs_desc);
133 Ref<ID3D12RootSignature> cs_rs;
134 EXPECT(SUCCEEDED(device->CreateRootSignature(0, cs_rs_blob.data(), cs_rs_blob.size(), IID_PPV_ARGS(&cs_rs.p))));
135
136 D3D12_COMPUTE_PIPELINE_STATE_DESC cs_desc{};
137 cs_desc.pRootSignature = cs_rs.p;
138 cs_desc.CS = {cs_dxbc.data(), cs_dxbc.size()};
139 Ref<ID3D12PipelineState> cs_pso;
140 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&cs_desc, IID_PPV_ARGS(&cs_pso.p))));
141
142 D3D12_ROOT_PARAMETER gfx_params[2]{};
143 gfx_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
144 gfx_params[0].Constants = {0, 0, 2};
145 gfx_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
146 gfx_params[1].Descriptor = {1, 0};
147 D3D12_VERSIONED_ROOT_SIGNATURE_DESC gfx_rs_desc{};
148 gfx_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
149 gfx_rs_desc.Desc_1_0 = {2, gfx_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT};
150 const auto gfx_rs_blob = serialize_root_signature(gfx_rs_desc);
151 Ref<ID3D12RootSignature> gfx_rs;
152 EXPECT(SUCCEEDED(device->CreateRootSignature(0, gfx_rs_blob.data(), gfx_rs_blob.size(), IID_PPV_ARGS(&gfx_rs.p))));
153
154 const D3D12_INPUT_ELEMENT_DESC input_elems[2] = {
155 {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
156 {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT,
157 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
158 };
159 D3D12_GRAPHICS_PIPELINE_STATE_DESC gfx_desc{};
160 gfx_desc.pRootSignature = gfx_rs.p;
161 gfx_desc.VS = {vs_dxbc.data(), vs_dxbc.size()};
162 gfx_desc.PS = {ps_dxbc.data(), ps_dxbc.size()};
163 gfx_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
164 gfx_desc.SampleMask = 0xFFFFFFFFu;
165 gfx_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
166 gfx_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK;
167 gfx_desc.RasterizerState.DepthClipEnable = TRUE;
168 gfx_desc.InputLayout = {input_elems, 2};
169 gfx_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
170 gfx_desc.NumRenderTargets = 1;
171 gfx_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
172 gfx_desc.SampleDesc = {1, 0};
173 Ref<ID3D12PipelineState> gfx_pso;
174 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&gfx_desc, IID_PPV_ARGS(&gfx_pso.p))));
175
176 // 3. Store, load, cross-type rejection, and serialize round-trip.
177 Ref<ID3D12PipelineLibrary1> lib;
178 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(nullptr, 0, IID_PPV_ARGS(&lib.p))) && lib.p);
179 Ref<ID3D12Device> parent_dev;
180 EXPECT(SUCCEEDED(lib->GetDevice(IID_PPV_ARGS(&parent_dev.p))) && parent_dev.p);
181
182 EXPECT(lib->StorePipeline(nullptr, cs_pso.p) == E_INVALIDARG);
183 EXPECT(lib->StorePipeline(L"", cs_pso.p) == E_INVALIDARG);
184 EXPECT(lib->StorePipeline(L"cs", nullptr) == E_INVALIDARG);
185 EXPECT(SUCCEEDED(lib->StorePipeline(L"cs", cs_pso.p)));
186 EXPECT(lib->StorePipeline(L"cs", cs_pso.p) == E_INVALIDARG); // duplicate name
187 EXPECT(SUCCEEDED(lib->StorePipeline(L"gfx", gfx_pso.p)));
188
189 Ref<ID3D12PipelineState> loaded_cs, loaded_gfx, loaded_any, wrong;
190 EXPECT(lib->LoadComputePipeline(L"missing", &cs_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
191 EXPECT(lib->LoadComputePipeline(L"gfx", &cs_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
192 EXPECT(lib->LoadGraphicsPipeline(L"cs", &gfx_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
193 EXPECT(SUCCEEDED(lib->LoadComputePipeline(L"cs", &cs_desc, IID_PPV_ARGS(&loaded_cs.p))) && loaded_cs.p);
194 EXPECT(SUCCEEDED(lib->LoadGraphicsPipeline(L"gfx", &gfx_desc, IID_PPV_ARGS(&loaded_gfx.p))) && loaded_gfx.p);
195
196 std::uint32_t dummy_stream = 0;
197 D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(dummy_stream), &dummy_stream};
198 D3D12_PIPELINE_STATE_STREAM_DESC empty_stream{0, nullptr};
199 EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
200 EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p);
201
202 const SIZE_T blob_size = lib->GetSerializedSize();
203 EXPECT(blob_size >= 16);
204 std::vector<std::uint8_t> blob(blob_size);
205 EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG);
206 EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG);
207 EXPECT(SUCCEEDED(lib->Serialize(blob.data(), blob_size)));
208
209 Ref<ID3D12PipelineLibrary> reloaded;
210 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p);
211
212 // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU.
213 Ref<ID3D12CommandQueue> queue;
214 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
215 EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))));
216 Ref<ID3D12CommandAllocator> alloc;
217 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))));
218 Ref<ID3D12GraphicsCommandList> list;
219 EXPECT(SUCCEEDED(
220 device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p))));
221 Ref<ID3D12Fence> fence;
222 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
223
224 constexpr UINT W = 16, H = 16;
225 const D3D12_HEAP_PROPERTIES hp_def{D3D12_HEAP_TYPE_DEFAULT};
226 const D3D12_HEAP_PROPERTIES hp_up{D3D12_HEAP_TYPE_UPLOAD};
227 const D3D12_HEAP_PROPERTIES hp_rb{D3D12_HEAP_TYPE_READBACK};
228 const auto rtd = tex2d_desc(W, H, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
229 const Vertex verts[4] = {
230 {-1.0f, 1.0f, 255, 0, 0, 255},
231 { 0.0f, 1.0f, 255, 0, 0, 255},
232 { 0.0f, 0.0f, 255, 0, 0, 255},
233 {-1.0f, 0.0f, 255, 0, 0, 255},
234 };
235 const std::uint16_t indices[6] = {0, 1, 2, 0, 2, 3};
236 const float tint[4] = {1.0f, 0.0f, 1.0f, 1.0f};
237 const auto vbd = buffer_desc(sizeof(verts));
238 const auto ibd = buffer_desc(sizeof(indices));
239 const auto cbd = buffer_desc(256);
240 Ref<ID3D12Resource> rt, vb, ib, cb, rb;
241 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_def, D3D12_HEAP_FLAG_NONE, &rtd,
242 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&rt.p))));
243 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &vbd,
244 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vb.p))));
245 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &ibd,
246 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&ib.p))));
247 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &cbd,
248 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&cb.p))));
249 void* p = nullptr;
250 EXPECT(SUCCEEDED(vb->Map(0, nullptr, &p)));
251 std::memcpy(p, verts, sizeof(verts));
252 vb->Unmap(0, nullptr);
253 EXPECT(SUCCEEDED(ib->Map(0, nullptr, &p)));
254 std::memcpy(p, indices, sizeof(indices));
255 ib->Unmap(0, nullptr);
256 EXPECT(SUCCEEDED(cb->Map(0, nullptr, &p)));
257 std::memcpy(p, tint, sizeof(tint));
258 cb->Unmap(0, nullptr);
259
260 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
261 UINT64 total_bytes = 0;
262 device->GetCopyableFootprints(&rtd, 0, 1, 0, &fp, nullptr, nullptr, &total_bytes);
263 const auto rbd = buffer_desc(total_bytes);
264 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_rb, D3D12_HEAP_FLAG_NONE, &rbd,
265 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&rb.p))));
266
267 Ref<ID3D12DescriptorHeap> rtv_heap;
268 const D3D12_DESCRIPTOR_HEAP_DESC rhd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
269 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rhd, IID_PPV_ARGS(&rtv_heap.p))));
270 const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart();
271 device->CreateRenderTargetView(rt.p, nullptr, rtv);
272
273 const float blue[4] = {0.0f, 0.0f, 1.0f, 1.0f};
274 list->ClearRenderTargetView(rtv, blue, 0, nullptr);
275 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
276 const D3D12_VIEWPORT vp{0, 0, float(W), float(H), 0.0f, 1.0f};
277 const D3D12_RECT sc{0, 0, LONG(W), LONG(H)};
278 list->RSSetViewports(1, &vp);
279 list->RSSetScissorRects(1, &sc);
280 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
281 const D3D12_VERTEX_BUFFER_VIEW vbv{vb->GetGPUVirtualAddress(), sizeof(verts), sizeof(Vertex)};
282 const D3D12_INDEX_BUFFER_VIEW ibv{ib->GetGPUVirtualAddress(), sizeof(indices), DXGI_FORMAT_R16_UINT};
283 list->IASetVertexBuffers(0, 1, &vbv);
284 list->IASetIndexBuffer(&ibv);
285 list->SetGraphicsRootSignature(gfx_rs.p);
286 const float offset[2] = {0.0f, 0.0f};
287 list->SetGraphicsRoot32BitConstants(0, 2, offset, 0);
288 list->SetGraphicsRootConstantBufferView(1, cb->GetGPUVirtualAddress());
289 list->SetPipelineState(loaded_gfx.p);
290 list->DrawIndexedInstanced(6, 1, 0, 0, 0);
291
292 const auto to_src = transition(rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
293 list->ResourceBarrier(1, &to_src);
294 D3D12_TEXTURE_COPY_LOCATION src_loc{rt.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}};
295 D3D12_TEXTURE_COPY_LOCATION dst_loc{rb.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
296 dst_loc.PlacedFootprint = fp;
297 list->CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, nullptr);
298 EXPECT(SUCCEEDED(list->Close()));
299 ID3D12CommandList* lists[] = {list.p};
300 queue->ExecuteCommandLists(1, lists);
301 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
302 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
303
304 EXPECT(SUCCEEDED(rb->Map(0, nullptr, &p)));
305 const auto* bytes = static_cast<const std::uint8_t*>(p);
306 std::uint32_t tl = 0, br = 0;
307 std::memcpy(&tl, bytes + 2 * fp.Footprint.RowPitch + 2 * 4, 4);
308 std::memcpy(&br, bytes + 12 * fp.Footprint.RowPitch + 12 * 4, 4);
309 EXPECT(tl == 0xFF0000FFu); // red quad drawn by PSO loaded from PipelineLibrary
310 EXPECT(br == 0xFFFF0000u); // blue background clear
311 rb->Unmap(0, nullptr);
312
313 EXPECT(d.validation_errors() == 0);
314 std::printf("d3d12_pipeline_library_test: ok\n");
315 return 0;
316}
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index 8b28eb67a..f01fb902b 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -115,6 +115,8 @@ int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore fr
115bool 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
116bool observe_next_swapchain = false; 116bool observe_next_swapchain = false;
117bool report_undefined_extent = false; // armed: surface capabilities reports undefined extent (0xFFFFFFFF) 117bool report_undefined_extent = false; // armed: surface capabilities reports undefined extent (0xFFFFFFFF)
118bool undefined_extent_queried = false;
119VkExtent2D last_swapchain_extent{};
118VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE; 120VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE;
119VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE; 121VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE;
120unsigned out_of_date = 0; // presents the real driver reported out of date 122unsigned out_of_date = 0; // presents the real driver reported out of date
@@ -170,6 +172,7 @@ VKAPI_ATTR VkResult VKAPI_CALL surface_formats(VkPhysicalDevice physical, VkSurf
170 172
171VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice device, const VkSwapchainCreateInfoKHR* info, 173VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice device, const VkSwapchainCreateInfoKHR* info,
172 const VkAllocationCallbacks* allocator, VkSwapchainKHR* out) { 174 const VkAllocationCallbacks* allocator, VkSwapchainKHR* out) {
175 if (info) last_swapchain_extent = info->imageExtent;
173 if (observe_next_swapchain) { 176 if (observe_next_swapchain) {
174 observed_old_swapchain = info->oldSwapchain; 177 observed_old_swapchain = info->oldSwapchain;
175 observe_next_swapchain = false; 178 observe_next_swapchain = false;
@@ -185,6 +188,7 @@ VKAPI_ATTR VkResult VKAPI_CALL get_surface_capabilities(VkPhysicalDevice physica
185 if (result == VK_SUCCESS && report_undefined_extent && caps) { 188 if (result == VK_SUCCESS && report_undefined_extent && caps) {
186 caps->currentExtent.width = 0xFFFFFFFF; 189 caps->currentExtent.width = 0xFFFFFFFF;
187 caps->currentExtent.height = 0xFFFFFFFF; 190 caps->currentExtent.height = 0xFFFFFFFF;
191 undefined_extent_queried = true;
188 } 192 }
189 return result; 193 return result;
190} 194}
@@ -409,9 +413,14 @@ int main() {
409 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); 413 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr)));
410 414
411 // 4. Undefined surface extent (0xFFFFFFFF, reported by Intel UHD graphics / Win32 WSI; D3D-165): 415 // 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. 416 // switch vsync to 0 to force swapchain recreation, verifying that vkGetPhysicalDeviceSurfaceCapabilitiesKHR
417 // is reached while armed and that vkCreateSwapchainKHR receives the clamped client extent (400x300)
418 // instead of 0xFFFFFFFF.
413 driver::report_undefined_extent = true; 419 driver::report_undefined_extent = true;
414 EXPECT(frame(1)); 420 driver::undefined_extent_queried = false;
421 EXPECT(frame(0));
422 EXPECT(driver::undefined_extent_queried);
423 EXPECT(driver::last_swapchain_extent.width == 400 && driver::last_swapchain_extent.height == 300);
415 EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300); 424 EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300);
416 driver::report_undefined_extent = false; 425 driver::report_undefined_extent = false;
417 426
diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp
index 80bd911c1..c6b660dda 100644
--- a/runtime/test/d3d12_translated_draw_test.cpp
+++ b/runtime/test/d3d12_translated_draw_test.cpp
@@ -63,8 +63,8 @@ struct Vertex {
63}; 63};
64 64
65using Pixel = std::array<float, 4>; 65using Pixel = std::array<float, 4>;
66constexpr UINT extent = 64; 66constexpr UINT target_extent = 64;
67constexpr UINT pitch = extent * sizeof(Pixel); // 1024, a multiple of 256 67constexpr UINT pitch = target_extent * sizeof(Pixel); // 1024, a multiple of 256
68 68
69// A V# for the vertex records: stride 32, `records` records, format 32_32_32_32_FLOAT, identity swizzle. The 69// A V# for the vertex records: stride 32, `records` records, format 32_32_32_32_FLOAT, identity swizzle. The
70// out-of-range mode is structured (an index checked against num_records), which is what the hardware does with an 70// out-of-range mode is structured (an index checked against num_records), which is what the hardware does with an
@@ -113,7 +113,7 @@ int main() {
113 vertex(-1, 0, c2), vertex(-1, -1, c2), vertex(0, -1, c2)}; 113 vertex(-1, 0, c2), vertex(-1, -1, c2), vertex(0, -1, c2)};
114 static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 288); 114 static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 288);
115 115
116 std::vector<Pixel> pixels(extent * extent); 116 std::vector<Pixel> pixels(target_extent * target_extent);
117 { 117 {
118 rt::d3d12::VulkanDeviceInfo info{}; 118 rt::d3d12::VulkanDeviceInfo info{};
119 info.get_instance_proc = d.instance_proc; 119 info.get_instance_proc = d.instance_proc;
@@ -178,13 +178,13 @@ int main() {
178 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, 178 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc,
179 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, 179 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
180 IID_PPV_ARGS(&upload.p)))); 180 IID_PPV_ARGS(&upload.p))));
181 const auto readback_desc = buffer_desc(pitch * extent); 181 const auto readback_desc = buffer_desc(pitch * target_extent);
182 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, 182 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
183 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, 183 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
184 IID_PPV_ARGS(&readback.p)))); 184 IID_PPV_ARGS(&readback.p))));
185 D3D12_RESOURCE_DESC rt_desc{}; 185 D3D12_RESOURCE_DESC rt_desc{};
186 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; 186 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
187 rt_desc.Width = rt_desc.Height = extent; 187 rt_desc.Width = rt_desc.Height = target_extent;
188 rt_desc.DepthOrArraySize = 1; 188 rt_desc.DepthOrArraySize = 1;
189 rt_desc.MipLevels = 1; 189 rt_desc.MipLevels = 1;
190 rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; 190 rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
@@ -245,8 +245,8 @@ int main() {
245 ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; 245 ID3D12DescriptorHeap* heaps[] = {srv_heap.p};
246 list->SetDescriptorHeaps(1, heaps); 246 list->SetDescriptorHeaps(1, heaps);
247 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); 247 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
248 const D3D12_VIEWPORT viewport{0, 0, float(extent), float(extent), 0, 1}; 248 const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1};
249 const D3D12_RECT scissor{0, 0, LONG(extent), LONG(extent)}; 249 const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)};
250 list->RSSetViewports(1, &viewport); 250 list->RSSetViewports(1, &viewport);
251 list->RSSetScissorRects(1, &scissor); 251 list->RSSetScissorRects(1, &scissor);
252 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); 252 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
@@ -271,7 +271,7 @@ int main() {
271 D3D12_TEXTURE_COPY_LOCATION dst{}; 271 D3D12_TEXTURE_COPY_LOCATION dst{};
272 dst.pResource = readback.p; 272 dst.pResource = readback.p;
273 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; 273 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
274 dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, extent, extent, 1, pitch}}; 274 dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}};
275 D3D12_TEXTURE_COPY_LOCATION src{}; 275 D3D12_TEXTURE_COPY_LOCATION src{};
276 src.pResource = target.p; 276 src.pResource = target.p;
277 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; 277 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
@@ -302,10 +302,10 @@ int main() {
302 const Pixel top_left = {0.125f, 1.0f, 0.75f, 1.0f}, bottom_right = {0.25f, 1.125f, 0.875f, 1.0f}; 302 const Pixel top_left = {0.125f, 1.0f, 0.75f, 1.0f}, bottom_right = {0.25f, 1.125f, 0.875f, 1.0f};
303 const Pixel bottom_left = {0.75f, 0.25f, 0.75f, 1.0f}; 303 const Pixel bottom_left = {0.75f, 0.25f, 0.75f, 1.0f};
304 unsigned mismatches = 0, edge = 0, edge_triangle = 0, edge_clear = 0; 304 unsigned mismatches = 0, edge = 0, edge_triangle = 0, edge_clear = 0;
305 for (UINT row = 0; row < extent; ++row) { 305 for (UINT row = 0; row < target_extent; ++row) {
306 for (UINT col = 0; col < extent; ++col) { 306 for (UINT col = 0; col < target_extent; ++col) {
307 const bool top = row < extent / 2, left = col < extent / 2; 307 const bool top = row < target_extent / 2, left = col < target_extent / 2;
308 const Pixel& got = pixels[row * extent + col]; 308 const Pixel& got = pixels[row * target_extent + col];
309 const auto bits_equal = [&](const Pixel& want) { return std::memcmp(&got, &want, sizeof(Pixel)) == 0; }; 309 const auto bits_equal = [&](const Pixel& want) { return std::memcmp(&got, &want, sizeof(Pixel)) == 0; };
310 const Pixel* want; 310 const Pixel* want;
311 if (top) { 311 if (top) {
@@ -340,6 +340,6 @@ int main() {
340 "pixels on the triangle's diagonal (%u its colour, %u the clear colour). User data from a descriptor " 340 "pixels on the triangle's diagonal (%u its colour, %u the clear colour). User data from a descriptor "
341 "table and root constants, V# vertex fetch from the arena, PS constants " 341 "table and root constants, V# vertex fetch from the arena, PS constants "
342 "through the code base\n", 342 "through the code base\n",
343 extent * extent - edge, extent * extent, edge, edge_triangle, edge_clear); 343 target_extent * target_extent - edge, target_extent * target_extent, edge, edge_triangle, edge_clear);
344 return 0; 344 return 0;
345} 345}
diff --git a/runtime/test/d3d12_typeless_rtv_test.cpp b/runtime/test/d3d12_typeless_rtv_test.cpp
index cc6054f85..d8b8d841e 100644
--- a/runtime/test/d3d12_typeless_rtv_test.cpp
+++ b/runtime/test/d3d12_typeless_rtv_test.cpp
@@ -213,19 +213,36 @@ bool clear_and_read(ID3D12Device* device, DXGI_FORMAT whole_format, DXGI_FORMAT
213 return true; 213 return true;
214} 214}
215bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view, 215bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view,
216 UINT16 mips = 1, UINT16 layers = 1) { 216 UINT16 mips = 1, UINT16 layers = 1, UINT samples = 1,
217 const DXGI_FORMAT* cast_list = nullptr, UINT32 cast_count = 0) {
217 Ref<ID3D12Resource> resource; 218 Ref<ID3D12Resource> resource;
218 D3D12_HEAP_PROPERTIES heap_properties{D3D12_HEAP_TYPE_DEFAULT}; 219 D3D12_HEAP_PROPERTIES heap_properties{D3D12_HEAP_TYPE_DEFAULT};
219 D3D12_RESOURCE_DESC texture{}; 220 if (cast_count) {
220 texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; 221 Ref<ID3D12Device10> device10;
221 texture.Width = texture.Height = 4; 222 CHECK(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device10.p))));
222 texture.DepthOrArraySize = layers; 223 D3D12_RESOURCE_DESC1 tex1{};
223 texture.MipLevels = mips; 224 tex1.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
224 texture.Format = resource_format; 225 tex1.Width = tex1.Height = 4;
225 texture.SampleDesc.Count = 1; 226 tex1.DepthOrArraySize = layers;
226 texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; 227 tex1.MipLevels = mips;
227 CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture, 228 tex1.Format = resource_format;
228 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&resource.p)))); 229 tex1.SampleDesc.Count = samples;
230 tex1.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
231 CHECK(SUCCEEDED(device10->CreateCommittedResource3(&heap_properties, D3D12_HEAP_FLAG_NONE, &tex1,
232 D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, cast_count, cast_list,
233 IID_PPV_ARGS(&resource.p))));
234 } else {
235 D3D12_RESOURCE_DESC texture{};
236 texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
237 texture.Width = texture.Height = 4;
238 texture.DepthOrArraySize = layers;
239 texture.MipLevels = mips;
240 texture.Format = resource_format;
241 texture.SampleDesc.Count = samples;
242 texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
243 CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture,
244 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&resource.p))));
245 }
229 Ref<ID3D12DescriptorHeap> heap; 246 Ref<ID3D12DescriptorHeap> heap;
230 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; 247 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
231 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)))); 248 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p))));
@@ -237,7 +254,7 @@ bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12
237 const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); 254 const auto handle = heap->GetCPUDescriptorHandleForHeapStart();
238 // For the supported shape, overwrite a valid slot too: rejection must not leave its old RTV active. 255 // For the supported shape, overwrite a valid slot too: rejection must not leave its old RTV active.
239 D3D12_RENDER_TARGET_VIEW_DESC seed{}; 256 D3D12_RENDER_TARGET_VIEW_DESC seed{};
240 seed.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; 257 seed.ViewDimension = samples > 1 ? D3D12_RTV_DIMENSION_TEXTURE2DMS : D3D12_RTV_DIMENSION_TEXTURE2D;
241 seed.Format = resource_format == DXGI_FORMAT_R8G8B8A8_TYPELESS ? DXGI_FORMAT_R8G8B8A8_UNORM : resource_format; 258 seed.Format = resource_format == DXGI_FORMAT_R8G8B8A8_TYPELESS ? DXGI_FORMAT_R8G8B8A8_UNORM : resource_format;
242 device->CreateRenderTargetView(resource.p, &seed, handle); 259 device->CreateRenderTargetView(resource.p, &seed, handle);
243 device->CreateRenderTargetView(resource.p, view, handle); 260 device->CreateRenderTargetView(resource.p, view, handle);
@@ -246,6 +263,150 @@ bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12
246 CHECK(list->Close() == E_INVALIDARG); // The invalid list is never sent to the GPU. 263 CHECK(list->Close() == E_INVALIDARG); // The invalid list is never sent to the GPU.
247 return true; 264 return true;
248} 265}
266
267bool clear_and_read_msaa(ID3D12Device* device, DXGI_FORMAT resource_format,
268 const DXGI_FORMAT* cast_list, UINT32 cast_count,
269 DXGI_FORMAT whole_format, DXGI_FORMAT rect_format, bool partial,
270 bool array, UINT first_layer, UINT layer_count,
271 std::vector<unsigned char>& pixels) {
272 Ref<ID3D12CommandQueue> queue;
273 Ref<ID3D12CommandAllocator> allocator;
274 Ref<ID3D12GraphicsCommandList> list;
275 Ref<ID3D12Fence> fence;
276 D3D12_COMMAND_QUEUE_DESC queue_desc{};
277 CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
278 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
279 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
280 IID_PPV_ARGS(&list.p))));
281 CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
282
283 constexpr UINT width = 5, height = 3;
284 const UINT16 layers = array ? 4 : 1;
285 Ref<ID3D12Resource> msaa, resolved, readback;
286 D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
287 if (cast_count) {
288 Ref<ID3D12Device10> device10;
289 CHECK(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device10.p))));
290 D3D12_RESOURCE_DESC1 tex1{};
291 tex1.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
292 tex1.Width = width;
293 tex1.Height = height;
294 tex1.DepthOrArraySize = layers;
295 tex1.MipLevels = 1;
296 tex1.Format = resource_format;
297 tex1.SampleDesc.Count = 4;
298 tex1.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
299 CHECK(SUCCEEDED(device10->CreateCommittedResource3(&default_heap, D3D12_HEAP_FLAG_NONE, &tex1,
300 D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, cast_count, cast_list,
301 IID_PPV_ARGS(&msaa.p))));
302 } else {
303 D3D12_RESOURCE_DESC tex{};
304 tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
305 tex.Width = width;
306 tex.Height = height;
307 tex.DepthOrArraySize = layers;
308 tex.MipLevels = 1;
309 tex.Format = resource_format;
310 tex.SampleDesc.Count = 4;
311 tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
312 CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex,
313 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&msaa.p))));
314 }
315 D3D12_RESOURCE_DESC resolved_desc{};
316 resolved_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
317 resolved_desc.Width = width;
318 resolved_desc.Height = height;
319 resolved_desc.DepthOrArraySize = layers;
320 resolved_desc.MipLevels = 1;
321 resolved_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
322 resolved_desc.SampleDesc.Count = 1;
323 CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &resolved_desc,
324 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr, IID_PPV_ARGS(&resolved.p))));
325
326 std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placed(layers);
327 UINT64 total = 0;
328 device->GetCopyableFootprints(&resolved_desc, 0, layers, 0, placed.data(), nullptr, nullptr, &total);
329 D3D12_RESOURCE_DESC buf{};
330 buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
331 buf.Width = total;
332 buf.Height = buf.SampleDesc.Count = 1;
333 buf.DepthOrArraySize = buf.MipLevels = 1;
334 buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
335 D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK};
336 CHECK(SUCCEEDED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &buf,
337 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p))));
338
339 Ref<ID3D12DescriptorHeap> rtv_heap;
340 const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
341 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap.p))));
342 const auto h0 = rtv_heap->GetCPUDescriptorHandleForHeapStart();
343 const D3D12_CPU_DESCRIPTOR_HANDLE h1{h0.ptr + device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)};
344
345 D3D12_RENDER_TARGET_VIEW_DESC view{};
346 view.ViewDimension = array ? D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY : D3D12_RTV_DIMENSION_TEXTURE2DMS;
347 if (array) {
348 view.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
349 for (UINT layer = 0; layer < layers; ++layer) {
350 view.Texture2DMSArray = {layer, 1};
351 device->CreateRenderTargetView(msaa.p, &view, h0);
352 const FLOAT seed[] = {FLOAT(layer + 1) * 0.1f, 0.2f, 0.3f, 1.0f};
353 list->ClearRenderTargetView(h0, seed, 0, nullptr);
354 }
355 view.Texture2DMSArray = {first_layer, layer_count};
356 }
357 view.Format = whole_format;
358 device->CreateRenderTargetView(msaa.p, &view, h0);
359 view.Format = rect_format;
360 device->CreateRenderTargetView(msaa.p, &view, h1);
361 const FLOAT full[4] = {0.25f, 0.5f, 0.75f, 0.25f};
362 const FLOAT part[4] = {0.0031308f, 0.18f, 0.5f, 0.75f};
363 list->ClearRenderTargetView(h0, full, 0, nullptr);
364 const D3D12_RECT rect{1, 1, 4, 3};
365 if (partial) list->ClearRenderTargetView(h1, part, 1, &rect);
366
367 D3D12_RESOURCE_BARRIER b{};
368 b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
369 b.Transition = {msaa.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
370 D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE};
371 list->ResourceBarrier(1, &b);
372 for (UINT layer = 0; layer < layers; ++layer)
373 list->ResolveSubresource(resolved.p, layer, msaa.p, layer, DXGI_FORMAT_R8G8B8A8_UNORM);
374 b.Transition = {resolved.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
375 D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
376 list->ResourceBarrier(1, &b);
377 D3D12_TEXTURE_COPY_LOCATION src{}, dst{};
378 src.pResource = resolved.p;
379 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
380 dst.pResource = readback.p;
381 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
382 for (UINT layer = 0; layer < layers; ++layer) {
383 src.SubresourceIndex = layer;
384 dst.PlacedFootprint = placed[layer];
385 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
386 }
387 CHECK(SUCCEEDED(list->Close()));
388 ID3D12CommandList* lists[] = {list.p};
389 queue->ExecuteCommandLists(1, lists);
390 CHECK(SUCCEEDED(queue->Signal(fence.p, 1)));
391 Event event;
392 CHECK(event.handle);
393 CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle)));
394 CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0);
395 void* mapped = nullptr;
396 const D3D12_RANGE range{0, SIZE_T(total)};
397 CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped);
398 pixels.clear();
399 for (const auto& footprint : placed) {
400 const auto& f = footprint.Footprint;
401 for (UINT y = 0; y < f.Height; ++y) {
402 const auto* row = static_cast<unsigned char*>(mapped) + footprint.Offset + y * f.RowPitch;
403 pixels.insert(pixels.end(), row, row + f.Width * 4);
404 }
405 }
406 const D3D12_RANGE none{};
407 readback->Unmap(0, &none);
408 return true;
409}
249} // namespace 410} // namespace
250 411
251int main() { 412int main() {
@@ -452,8 +613,10 @@ int main() {
452 regressions, vk.conditional_rendering ? "enabled" : "unavailable (predicated cases skipped)"); 613 regressions, vk.conditional_rendering ? "enabled" : "unavailable (predicated cases skipped)");
453 if (mismatches) return 1; 614 if (mismatches) return 1;
454 const auto rejects = [&](DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view, 615 const auto rejects = [&](DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view,
455 UINT16 mips = 1, UINT16 layers = 1) { 616 UINT16 mips = 1, UINT16 layers = 1, UINT samples = 1,
456 if (!rejects_view(ours.p, resource_format, view, mips, layers)) return false; 617 const DXGI_FORMAT* cast_list = nullptr, UINT32 cast_count = 0) {
618 if (!rejects_view(ours.p, resource_format, view, mips, layers, samples, cast_list, cast_count))
619 return false;
457 ++rejected; 620 ++rejected;
458 return true; 621 return true;
459 }; 622 };
@@ -501,6 +664,64 @@ int main() {
501 invalid.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; 664 invalid.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
502 invalid.Texture2DArray = {1, 1, 2, 1}; 665 invalid.Texture2DArray = {1, 1, 2, 1};
503 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &invalid, 3, 4)) return 1; 666 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &invalid, 3, 4)) return 1;
667
668 // 4x MSAA typeless and castable RGBA8 RTVs (TEXTURE2DMS / TEXTURE2DMSARRAY) compared against WARP.
669 {
670 const DXGI_FORMAT srgb_list[] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
671 const auto compare_msaa = [&](DXGI_FORMAT resource_format, const DXGI_FORMAT* cast_list,
672 UINT32 cast_count, DXGI_FORMAT full, DXGI_FORMAT rect, bool partial,
673 bool array, UINT first_layer, UINT layer_count) {
674 std::vector<unsigned char> actual, expected;
675 if (!clear_and_read_msaa(ours.p, resource_format, cast_list, cast_count, full, rect, partial, array,
676 first_layer, layer_count, actual) ||
677 !clear_and_read_msaa(host.p, resource_format, cast_list, cast_count, full, rect, partial, array,
678 first_layer, layer_count, expected))
679 return false;
680 ++comparisons;
681 if (actual.size() != expected.size()) return false;
682 for (std::size_t i = 0; i < actual.size(); ++i) {
683 if (std::abs(int(actual[i]) - int(expected[i])) > 1) {
684 std::fprintf(stderr, "MSAA RTV mismatch fmt %d full %d rect %d array %d byte %zu: ours %u WARP %u\n",
685 int(resource_format), int(full), int(rect), int(array), i, unsigned(actual[i]),
686 unsigned(expected[i]));
687 ++mismatches;
688 return false;
689 }
690 }
691 return true;
692 };
693 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_TYPELESS, nullptr, 0, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
694 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, false, false, 0, 1))
695 return 1;
696 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_TYPELESS, nullptr, 0, DXGI_FORMAT_R8G8B8A8_UNORM,
697 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, true, false, 0, 1))
698 return 1;
699 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_TYPELESS, nullptr, 0, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
700 DXGI_FORMAT_R8G8B8A8_UNORM, true, true, 1, 2))
701 return 1;
702 Ref<ID3D12Device10> host10;
703 if (SUCCEEDED(host->QueryInterface(IID_PPV_ARGS(&host10.p)))) {
704 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_UNORM, srgb_list, 2, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
705 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, false, false, 0, 1))
706 return 1;
707 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_UNORM, srgb_list, 2, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
708 DXGI_FORMAT_R8G8B8A8_UNORM, true, true, 1, 2))
709 return 1;
710 }
711 // MSAA vs 1x view-dimension mismatches, out-of-range MSAA array slices, and unlisted castable formats.
712 D3D12_RENDER_TARGET_VIEW_DESC bad_msaa{};
713 bad_msaa.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
714 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
715 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &bad_msaa, 1, 1, 4)) return 1;
716 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
717 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &bad_msaa, 1, 1, 1)) return 1;
718 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
719 bad_msaa.Texture2DMSArray = {3, 2};
720 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &bad_msaa, 1, 4, 4)) return 1;
721 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
722 bad_msaa.Format = DXGI_FORMAT_R8G8B8A8_UINT;
723 if (!rejects(DXGI_FORMAT_R8G8B8A8_UNORM, &bad_msaa, 1, 1, 4, srgb_list, 2)) return 1;
724 }
504 } 725 }
505 if (vk.validation_errors()) return 1; 726 if (vk.validation_errors()) return 1;
506 std::printf("typeless RTV: %u WARP readbacks matched, descriptor snapshots and format-cache order checked; %u unsupported/invalid views rejected\n", 727 std::printf("typeless RTV: %u WARP readbacks matched, descriptor snapshots and format-cache order checked; %u unsupported/invalid views rejected\n",
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 556ab1566..9d49740e0 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;
@@ -785,6 +785,9 @@ int compare_allocation_info(ID3D12Device* ours) {
785 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; 785 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
786 return d; 786 return d;
787 }(), 0}, 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},
788 }; 791 };
789 int mismatches = 0; 792 int mismatches = 0;
790 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,
@@ -797,6 +800,18 @@ int compare_allocation_info(ID3D12Device* ours) {
797 for (const Case& c : cases) { 800 for (const Case& c : cases) {
798 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);
799 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 }
800 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) { 815 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) {
801 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))
802 mismatch(c.name, a, b); 817 mismatch(c.name, a, b);
@@ -1597,6 +1612,15 @@ int compare_feature_support(ID3D12Device* ours) {
1597 1612
1598// 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
1599// 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
1600bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical, 1624bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical,
1601 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host, 1625 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host,
1602 std::string& adapter_name) { 1626 std::string& adapter_name) {
@@ -2205,6 +2229,32 @@ HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uui
2205 return released(device->CreateFence(0, flags, riid, &out), &out); 2229 return released(device->CreateFence(0, flags, riid, &out), &out);
2206} 2230}
2207 2231
2232// A 64 KiB heap description for the CreateHeap/CreateHeap1 cases (D3D-238).
2233D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT},
2234 D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) {
2235 D3D12_HEAP_DESC desc{};
2236 desc.SizeInBytes = size;
2237 desc.Properties = properties;
2238 desc.Alignment = alignment;
2239 desc.Flags = flags;
2240 return desc;
2241}
2242
2243HRESULT heap_create(ID3D12Device* device, D3D12_HEAP_DESC desc) {
2244 void* out = nullptr;
2245 return released(device->CreateHeap(&desc, __uuidof(ID3D12Heap), &out), &out);
2246}
2247
2248// CreateHeap1 without a protected session; E_NOINTERFACE when the device has no ID3D12Device4.
2249HRESULT heap_create1(ID3D12Device* device, D3D12_HEAP_DESC desc) {
2250 ID3D12Device4* device4 = nullptr;
2251 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device4)))) return E_NOINTERFACE;
2252 void* out = nullptr;
2253 const HRESULT hr = device4->CreateHeap1(&desc, nullptr, __uuidof(ID3D12Heap), &out);
2254 device4->Release();
2255 return released(hr, &out);
2256}
2257
2208// Map on a fresh committed resource; `range` is the read range, or null. 2258// Map on a fresh committed resource; `range` is the read range, or null.
2209HRESULT map(ID3D12Device* device, D3D12_HEAP_PROPERTIES heap, D3D12_RESOURCE_DESC desc, D3D12_RESOURCE_STATES state, 2259HRESULT map(ID3D12Device* device, D3D12_HEAP_PROPERTIES heap, D3D12_RESOURCE_DESC desc, D3D12_RESOURCE_STATES state,
2210 UINT subresource, const D3D12_RANGE* range, bool want_pointer = true) { 2260 UINT subresource, const D3D12_RANGE* range, bool want_pointer = true) {
@@ -2238,6 +2288,21 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2238 struct Case { 2288 struct Case {
2239 const char* name; 2289 const char* name;
2240 InvalidCase call; 2290 InvalidCase call;
2291 bool (*comparable)(ID3D12Device*) = nullptr;
2292 };
2293 const auto device10 = [](ID3D12Device* d) {
2294 Ref<ID3D12Device10> newer;
2295 return SUCCEEDED(d->QueryInterface(IID_PPV_ARGS(&newer.p)));
2296 };
2297 const auto not_elevated = [](ID3D12Device*) {
2298 HANDLE token = nullptr;
2299 TOKEN_ELEVATION elevation{};
2300 DWORD size = 0;
2301 const bool elevated = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
2302 GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size) &&
2303 elevation.TokenIsElevated;
2304 if (token) CloseHandle(token);
2305 return !elevated;
2241 }; 2306 };
2242 static const Case cases[] = { 2307 static const Case cases[] = {
2243 // CreateCommittedResource: arguments. 2308 // CreateCommittedResource: arguments.
@@ -2315,7 +2380,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2315 }}, 2380 }},
2316 {"committed: upload buffer in COMMON", [](ID3D12Device* d) { 2381 {"committed: upload buffer in COMMON", [](ID3D12Device* d) {
2317 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2382 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2318 }}, 2383 }, +device10},
2319 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) { 2384 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) {
2320 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST); 2385 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST);
2321 }}, 2386 }},
@@ -2441,7 +2506,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2441 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) { 2506 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) {
2442 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2507 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2443 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE)); 2508 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE));
2444 }}, 2509 }, host_supports_unaligned_block_textures},
2445 {"committed: render target and depth stencil", [](ID3D12Device* d) { 2510 {"committed: render target and depth stencil", [](ID3D12Device* d) {
2446 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2511 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2447 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT, 2512 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT,
@@ -2513,7 +2578,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2513 }}, 2578 }},
2514 {"committed: readback buffer in COMMON", [](ID3D12Device* d) { 2579 {"committed: readback buffer in COMMON", [](ID3D12Device* d) {
2515 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2580 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2516 }}, 2581 }, +device10},
2517 {"committed: readback buffer with UAV", [](ID3D12Device* d) { 2582 {"committed: readback buffer with UAV", [](ID3D12Device* d) {
2518 auto desc = buffer_desc(256); 2583 auto desc = buffer_desc(256);
2519 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; 2584 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
@@ -2673,7 +2738,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2673 }}, 2738 }},
2674 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) { 2739 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) {
2675 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED); 2740 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED);
2676 }}, 2741 }, +device10},
2677 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) { 2742 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) {
2678 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH); 2743 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH);
2679 }}, 2744 }},
@@ -2728,7 +2793,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2728 auto desc = buffer_desc(256); 2793 auto desc = buffer_desc(256);
2729 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2794 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2730 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2795 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2731 }}, 2796 }, +device10},
2732 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) { 2797 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) {
2733 auto desc = buffer_desc(256); 2798 auto desc = buffer_desc(256);
2734 desc.Flags = D3D12_RESOURCE_FLAGS(0x200); 2799 desc.Flags = D3D12_RESOURCE_FLAGS(0x200);
@@ -2756,15 +2821,15 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2756 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) { 2821 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) {
2757 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2822 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2758 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2823 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2759 }}, 2824 }, +device10},
2760 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) { 2825 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) {
2761 auto desc = buffer_desc(256); 2826 auto desc = buffer_desc(256);
2762 desc.Flags = D3D12_RESOURCE_FLAGS(0x400); 2827 desc.Flags = D3D12_RESOURCE_FLAGS(0x400);
2763 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2828 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2764 }}, 2829 }, +device10},
2765 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) { 2830 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) {
2766 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400))); 2831 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400)));
2767 }}, 2832 }, +device10},
2768 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first. 2833 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first.
2769 {"committed: heap type 99, null output", [](ID3D12Device* d) { 2834 {"committed: heap type 99, null output", [](ID3D12Device* d) {
2770 const H heap{D3D12_HEAP_TYPE(99)}; 2835 const H heap{D3D12_HEAP_TYPE(99)};
@@ -2779,6 +2844,42 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2779 return d->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 2844 return d->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON,
2780 nullptr, __uuidof(ID3D12Resource), nullptr); 2845 nullptr, __uuidof(ID3D12Resource), nullptr);
2781 }}, 2846 }},
2847 // CreateHeap and CreateHeap1 (D3D-238): the four descriptions the host refused on an RX 5700 and WARP, the
2848 // heap-property rules CreateCommittedResource shares. A refusal needs no arena; the valid neighbours do, so
2849 // compare_heap_neighbours compares them on the standalone device.
2850 {"heap: alignment 4096", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(4096)); }},
2851 {"heap1: alignment 4096", [](ID3D12Device* d) { return heap_create1(d, heap_desc_of(4096)); }},
2852 {"heap: custom heap, unknown page property", [](ID3D12Device* d) {
2853 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
2854 D3D12_MEMORY_POOL_L0}));
2855 }},
2856 {"heap1: custom heap, unknown page property", [](ID3D12Device* d) {
2857 return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
2858 D3D12_MEMORY_POOL_L0}));
2859 }},
2860 {"heap: all three DENY flags", [](ID3D12Device* d) {
2861 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT},
2862 D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES |
2863 D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES));
2864 }},
2865 {"heap1: all three DENY flags", [](ID3D12Device* d) {
2866 return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT},
2867 D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES |
2868 D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES));
2869 }},
2870 {"heap: type 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE(0)})); }},
2871 {"heap1: type 0", [](ID3D12Device* d) { return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE(0)})); }},
2872 {"heap: custom heap, unknown pool", [](ID3D12Device* d) {
2873 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
2874 D3D12_MEMORY_POOL_UNKNOWN}));
2875 }},
2876 {"heap: default heap with a CPU page property", [](ID3D12Device* d) {
2877 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK}));
2878 }},
2879 {"heap: default heap with a memory pool", [](ID3D12Device* d) {
2880 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
2881 D3D12_MEMORY_POOL_L0}));
2882 }},
2782 // CreateDescriptorHeap. A null description faults in the host runtime, so it is not compared. 2883 // CreateDescriptorHeap. A null description faults in the host runtime, so it is not compared.
2783 {"descriptor heap: null output", [](ID3D12Device* d) { 2884 {"descriptor heap: null output", [](ID3D12Device* d) {
2784 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4}; 2885 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4};
@@ -2817,7 +2918,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2817 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) { 2918 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) {
2818 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049, 2919 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049,
2819 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2920 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
2820 }}, 2921 }, +device10},
2821 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) { 2922 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) {
2822 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048, 2923 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048,
2823 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2924 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
@@ -2862,7 +2963,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2862 }}, 2963 }},
2863 {"command queue: global realtime priority", [](ID3D12Device* d) { 2964 {"command queue: global realtime priority", [](ID3D12Device* d) {
2864 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME}); 2965 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME});
2865 }}, 2966 }, +not_elevated},
2866 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }}, 2967 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }},
2867 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }}, 2968 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }},
2868 {"command queue: high priority", [](ID3D12Device* d) { 2969 {"command queue: high priority", [](ID3D12Device* d) {
@@ -2952,6 +3053,11 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2952 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 3053 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
2953 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 3054 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
2954 if (a == b) continue; 3055 if (a == b) continue;
3056 if (c.comparable && !c.comparable(host.p)) {
3057 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
3058 a, b);
3059 continue;
3060 }
2955 ++mismatches; 3061 ++mismatches;
2956 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); 3062 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
2957 } 3063 }
@@ -3009,6 +3115,59 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3009 return mismatches; 3115 return mismatches;
3010} 3116}
3011 3117
3118// D3D-238: the valid neighbours of the CreateHeap/CreateHeap1 refusals in compare_invalid_arguments, compared
3119// with the host on a device that has the GPU address arena (without it the layer answers every heap E_NOTIMPL).
3120int compare_heap_neighbours(ID3D12Device* ours) {
3121 Ref<ID3D12Device> host;
3122 if (!create_host_device(host)) return -1;
3123 struct Case {
3124 const char* name;
3125 InvalidCase call;
3126 };
3127 static const Case cases[] = {
3128 {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }},
3129 {"heap: alignment 64 KiB", [](ID3D12Device* d) {
3130 return heap_create(d, heap_desc_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT));
3131 }},
3132 {"heap: alignment 4 MiB", [](ID3D12Device* d) {
3133 return heap_create(d, heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
3134 {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE,
3135 D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT));
3136 }},
3137 {"heap1: alignment 4 MiB", [](ID3D12Device* d) {
3138 return heap_create1(d, heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
3139 {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE,
3140 D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT));
3141 }},
3142 {"heap: size 1000", [](ID3D12Device* d) {
3143 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1000));
3144 }},
3145 {"heap: upload", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD})); }},
3146 {"heap: readback", [](ID3D12Device* d) {
3147 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_READBACK}));
3148 }},
3149 {"heap: custom write-combine L0", [](ID3D12Device* d) {
3150 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
3151 D3D12_MEMORY_POOL_L0}));
3152 }},
3153 {"heap1: custom write-combine L0", [](ID3D12Device* d) {
3154 return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
3155 D3D12_MEMORY_POOL_L0}));
3156 }},
3157 {"heap: ALLOW_ONLY_BUFFERS (two DENY flags)", [](ID3D12Device* d) {
3158 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS));
3159 }},
3160 };
3161 int mismatches = 0;
3162 for (const Case& c : cases) {
3163 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
3164 if (a == b) continue;
3165 ++mismatches;
3166 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
3167 }
3168 return mismatches;
3169}
3170
3012} // namespace 3171} // namespace
3013 3172
3014int main() { 3173int main() {
@@ -3016,6 +3175,18 @@ int main() {
3016 const auto status = d.initialize(); 3175 const auto status = d.initialize();
3017 if (status == vktest::DeviceStatus::unavailable) return 77; 3176 if (status == vktest::DeviceStatus::unavailable) return 77;
3018 if (status == vktest::DeviceStatus::failed) return 1; 3177 if (status == vktest::DeviceStatus::failed) return 1;
3178 {
3179 // The host comparisons (create_host_device, the copies) run on the layer's own adapter, not D3D12's default
3180 // one, which on a PC with two GPUs can be the other GPU (copycmp::layer_adapter).
3181 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
3182 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
3183 d.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(d.physical, &properties);
3184 if (id.deviceLUIDValid) {
3185 LUID luid{};
3186 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
3187 copycmp::layer_adapter() = luid;
3188 }
3189 }
3019 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)); 3190 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT));
3020 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0; 3191 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0;
3021 { 3192 {
@@ -3422,6 +3593,68 @@ int main() {
3422 std::printf("invalid arguments: no host D3D12 device to compare with, skipped\n"); 3593 std::printf("invalid arguments: no host D3D12 device to compare with, skipped\n");
3423 EXPECT(argument_mismatches <= 0); 3594 EXPECT(argument_mismatches <= 0);
3424 3595
3596 // D3D-236: CreateCommandQueue with D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME requires
3597 // SeIncreaseBasePriorityPrivilege enabled in the token, matching the Windows D3D12 runtime.
3598 {
3599 const D3D12_COMMAND_QUEUE_DESC rt_desc{
3600 D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME,
3601 D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
3602 struct RestoreOverride {
3603 ~RestoreOverride() { rt::d3d12::set_global_realtime_privilege_override_for_test(-1); }
3604 } restore_override;
3605
3606 rt::d3d12::set_global_realtime_privilege_override_for_test(0);
3607 EXPECT(!rt::d3d12::has_global_realtime_privilege());
3608 Ref<ID3D12CommandQueue> denied_q;
3609 EXPECT(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&denied_q.p)) == DXGI_ERROR_ACCESS_DENIED);
3610 EXPECT(!denied_q.p);
3611 EXPECT(device->CreateCommandQueue(&rt_desc, __uuidof(ID3D12CommandQueue), nullptr) ==
3612 DXGI_ERROR_ACCESS_DENIED);
3613
3614 rt::d3d12::set_global_realtime_privilege_override_for_test(1);
3615 EXPECT(rt::d3d12::has_global_realtime_privilege());
3616 EXPECT(device->CreateCommandQueue(&rt_desc, __uuidof(ID3D12CommandQueue), nullptr) == E_UNEXPECTED);
3617 Ref<ID3D12CommandQueue> granted_q;
3618 EXPECT(SUCCEEDED(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&granted_q.p))) && granted_q.p);
3619 if (granted_q.p) {
3620 EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME);
3621 }
3622 granted_q.reset();
3623 rt::d3d12::set_global_realtime_privilege_override_for_test(-1);
3624
3625 // When the process token holds SeIncreaseBasePriorityPrivilege (e.g. an elevated session), toggle the
3626 // real token privilege and verify both states against the host D3D12 runtime.
3627 HANDLE token = nullptr;
3628 LUID luid{};
3629 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
3630 if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) {
3631 TOKEN_PRIVILEGES tp{}, prev{};
3632 DWORD prev_len = 0;
3633 tp.PrivilegeCount = 1;
3634 tp.Privileges[0].Luid = luid;
3635 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
3636 if (AdjustTokenPrivileges(token, FALSE, &tp, sizeof(prev), &prev, &prev_len) &&
3637 GetLastError() == ERROR_SUCCESS) {
3638 EXPECT(rt::d3d12::has_global_realtime_privilege());
3639 EXPECT(command_queue(device.p, rt_desc) == S_OK);
3640 Ref<ID3D12Device> host;
3641 if (create_host_device(host)) {
3642 EXPECT(command_queue(host.p, rt_desc) == S_OK);
3643 }
3644 tp.Privileges[0].Attributes = 0;
3645 if (AdjustTokenPrivileges(token, FALSE, &tp, 0, nullptr, nullptr) &&
3646 GetLastError() == ERROR_SUCCESS) {
3647 EXPECT(!rt::d3d12::has_global_realtime_privilege());
3648 EXPECT(command_queue(device.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED);
3649 if (host.p) EXPECT(command_queue(host.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED);
3650 }
3651 AdjustTokenPrivileges(token, FALSE, &prev, 0, nullptr, nullptr);
3652 }
3653 }
3654 CloseHandle(token);
3655 }
3656 }
3657
3425 const int depth_quality_mismatches = compare_depth_multisample_quality_levels(device.p, depth_sample_counts); 3658 const int depth_quality_mismatches = compare_depth_multisample_quality_levels(device.p, depth_sample_counts);
3426 if (depth_quality_mismatches < 0) 3659 if (depth_quality_mismatches < 0)
3427 std::printf("Depth/stencil MSAA quality queries: no host D3D12 device to compare with, skipped\n"); 3660 std::printf("Depth/stencil MSAA quality queries: no host D3D12 device to compare with, skipped\n");
@@ -4741,6 +4974,44 @@ int main() {
4741 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes))); 4974 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes)));
4742 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64); 4975 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64);
4743 zeroes->Unmap(0, nullptr); 4976 zeroes->Unmap(0, nullptr);
4977
4978 // Placed buffers carry their console VA in VulkanContext (so VA-resolved commands like WriteBufferImmediate
4979 // find them) and placed readback buffers mark host_readable (so the submission flushes GPU writes to host).
4980 {
4981 D3D12_HEAP_DESC rb_heap_desc{};
4982 rb_heap_desc.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4983 rb_heap_desc.SizeInBytes = 65536;
4984 rb_heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
4985 Ref<ID3D12Heap> rb_heap;
4986 Ref<ID3D12Resource> placed_rb;
4987 EXPECT(SUCCEEDED(standalone->CreateHeap(&rb_heap_desc, IID_PPV_ARGS(&rb_heap.p))));
4988 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(rb_heap.p, 0, &placed_buffer,
4989 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
4990 IID_PPV_ARGS(&placed_rb.p))));
4991 Ref<ID3D12GraphicsCommandList2> placed_list2;
4992 EXPECT(SUCCEEDED(placed_list->QueryInterface(IID_PPV_ARGS(&placed_list2.p))));
4993 EXPECT(SUCCEEDED(placed_allocator->Reset()) && SUCCEEDED(placed_list->Reset(placed_allocator.p, nullptr)));
4994 const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER wp{placed_va + 16, 0xCAFEBABEu};
4995 const D3D12_WRITEBUFFERIMMEDIATE_MODE wm = D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT;
4996 placed_list2->WriteBufferImmediate(1, &wp, &wm);
4997 D3D12_RESOURCE_BARRIER b{};
4998 b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
4999 b.Transition = {placed_a.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
5000 D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
5001 placed_list->ResourceBarrier(1, &b);
5002 placed_list->CopyBufferRegion(placed_rb.p, 0, placed_a.p, 0, 64);
5003 EXPECT(SUCCEEDED(placed_list->Close()));
5004 queue->ExecuteCommandLists(1, placed_lists);
5005 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
5006 EXPECT(SUCCEEDED(queue->Signal(fence.p, 7)) && SUCCEEDED(fence->SetEventOnCompletion(7, nullptr)));
5007 void* rb_bytes = nullptr;
5008 EXPECT(SUCCEEDED(placed_rb->Map(0, nullptr, &rb_bytes)));
5009 std::uint32_t word = 0;
5010 std::memcpy(&word, static_cast<const std::uint8_t*>(rb_bytes) + 16, sizeof(word));
5011 EXPECT(word == 0xCAFEBABEu);
5012 placed_rb->Unmap(0, nullptr);
5013 }
5014
4744 // The heap owns the range: releasing it puts the next heap of that size back at the same place. 5015 // The heap owns the range: releasing it puts the next heap of that size back at the same place.
4745 placed_image.reset(); 5016 placed_image.reset();
4746 placed_b.reset(); 5017 placed_b.reset();
@@ -4762,6 +5033,52 @@ int main() {
4762 upload_heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD; 5033 upload_heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4763 EXPECT(SUCCEEDED(standalone->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p)))); 5034 EXPECT(SUCCEEDED(standalone->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p))));
4764 5035
5036 // D3D-238: heap descriptions the host refuses (RX 5700 and WARP), from CreateHeap and CreateHeap1 alike, and
5037 // their valid neighbours. compare_invalid_arguments and compare_heap_neighbours check them against a host.
5038 {
5039 const D3D12_HEAP_FLAGS deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES |
5040 D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;
5041 const D3D12_HEAP_DESC refused_heaps[] = {
5042 heap_desc_of(4096),
5043 heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_L0}),
5044 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, deny_all),
5045 heap_desc_of(0, {D3D12_HEAP_TYPE(0)}),
5046 heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
5047 D3D12_MEMORY_POOL_UNKNOWN}),
5048 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK}),
5049 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 0),
5050 };
5051 for (const D3D12_HEAP_DESC& hd : refused_heaps) {
5052 EXPECT(heap_create(standalone.p, hd) == E_INVALIDARG);
5053 EXPECT(heap_create1(standalone.p, hd) == E_INVALIDARG);
5054 }
5055 const D3D12_HEAP_DESC accepted_heaps[] = {
5056 heap_desc_of(0),
5057 heap_desc_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT),
5058 heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, {D3D12_HEAP_TYPE_DEFAULT},
5059 D3D12_HEAP_FLAG_NONE, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT),
5060 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1000),
5061 heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD}),
5062 heap_desc_of(0, {D3D12_HEAP_TYPE_READBACK}),
5063 heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0}),
5064 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS),
5065 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT},
5066 D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES),
5067 };
5068 for (const D3D12_HEAP_DESC& hd : accepted_heaps) {
5069 EXPECT(heap_create(standalone.p, hd) == S_OK);
5070 EXPECT(heap_create1(standalone.p, hd) == S_OK);
5071 }
5072 Ref<ID3D12Device4> device4;
5073 Ref<ID3D12Heap> unused;
5074 EXPECT(SUCCEEDED(standalone->QueryInterface(IID_PPV_ARGS(&device4.p))));
5075 EXPECT(device4->CreateHeap1(&placed_heap_desc, nullptr, IID_PPV_ARGS(&unused.p)) == S_OK && unused.p);
5076 const int heap_mismatches = compare_heap_neighbours(standalone.p);
5077 if (heap_mismatches < 0)
5078 std::printf("CreateHeap valid neighbours: no host D3D12 device to compare with, skipped\n");
5079 EXPECT(heap_mismatches <= 0);
5080 }
5081
4765 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags, 5082 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags,
4766 UINT64 align = 0) { 5083 UINT64 align = 0) {
4767 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips); 5084 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
@@ -4846,13 +5163,6 @@ int main() {
4846 EXPECT(!fail.p); 5163 EXPECT(!fail.p);
4847 } 5164 }
4848 { 5165 {
4849 const D3D12_RESOURCE_DESC valid_4x = tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
4850 Ref<ID3D12Resource> fail;
4851 EXPECT(standalone->CreatePlacedResource(tiled_heap.p, 0, &valid_4x, D3D12_RESOURCE_STATE_COMMON, nullptr,
4852 IID_PPV_ARGS(&fail.p)) == E_NOTIMPL);
4853 EXPECT(!fail.p);
4854 }
4855 {
4856 Ref<ID3D12Resource> fail; 5166 Ref<ID3D12Resource> fail;
4857 EXPECT(standalone->CreatePlacedResource(upload_placed_heap.p, 0, &tiled_rt_desc, 5167 EXPECT(standalone->CreatePlacedResource(upload_placed_heap.p, 0, &tiled_rt_desc,
4858 D3D12_RESOURCE_STATE_COMMON, nullptr, 5168 D3D12_RESOURCE_STATE_COMMON, nullptr,
@@ -4900,7 +5210,7 @@ int main() {
4900 ID3D12CommandList* tiled_lists[] = {tiled_list.p}; 5210 ID3D12CommandList* tiled_lists[] = {tiled_list.p};
4901 queue->ExecuteCommandLists(1, tiled_lists); 5211 queue->ExecuteCommandLists(1, tiled_lists);
4902 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 5212 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
4903 EXPECT(SUCCEEDED(queue->Signal(fence.p, 7)) && SUCCEEDED(fence->SetEventOnCompletion(7, nullptr))); 5213 EXPECT(SUCCEEDED(queue->Signal(fence.p, 8)) && SUCCEEDED(fence->SetEventOnCompletion(8, nullptr)));
4904 void* tiled_bytes = nullptr; 5214 void* tiled_bytes = nullptr;
4905 EXPECT(SUCCEEDED(tiled_rb->Map(0, nullptr, &tiled_bytes))); 5215 EXPECT(SUCCEEDED(tiled_rb->Map(0, nullptr, &tiled_bytes)));
4906 const std::uint8_t want_rgba[4] = {64, 128, 191, 255}; 5216 const std::uint8_t want_rgba[4] = {64, 128, 191, 255};
@@ -4922,15 +5232,15 @@ int main() {
4922 tiled_3d_desc, 5232 tiled_3d_desc,
4923 }; 5233 };
4924 for (int idx = 0; idx < int(std::size(host_cases)); ++idx) { 5234 for (int idx = 0; idx < int(std::size(host_cases)); ++idx) {
4925 const D3D12_RESOURCE_DESC& d = host_cases[idx]; 5235 const D3D12_RESOURCE_DESC& host_desc = host_cases[idx];
4926 if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && 5236 if (host_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D &&
4927 host_opts.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_3) 5237 host_opts.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_3)
4928 continue; 5238 continue;
4929 Ref<ID3D12Resource> our_r, host_r; 5239 Ref<ID3D12Resource> our_r, host_r;
4930 const HRESULT our_hr = standalone->CreatePlacedResource( 5240 const HRESULT our_hr = standalone->CreatePlacedResource(
4931 tiled_heap.p, 0, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p)); 5241 tiled_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
4932 const HRESULT host_hr = host_dev->CreatePlacedResource( 5242 const HRESULT host_hr = host_dev->CreatePlacedResource(
4933 host_heap.p, 0, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p)); 5243 host_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
4934 if (FAILED(host_hr)) continue; 5244 if (FAILED(host_hr)) continue;
4935 EXPECT(SUCCEEDED(our_hr)); 5245 EXPECT(SUCCEEDED(our_hr));
4936 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout); 5246 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
@@ -4948,6 +5258,259 @@ int main() {
4948 } 5258 }
4949 } 5259 }
4950 } 5260 }
5261
5262 // D3D-222: multisampled placed textures (UNKNOWN and 4x tiled).
5263 D3D12_HEAP_DESC msaa_heap_desc{};
5264 msaa_heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
5265 msaa_heap_desc.SizeInBytes = 16 * 1024 * 1024;
5266 msaa_heap_desc.Alignment = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT;
5267 Ref<ID3D12Heap> msaa_heap;
5268 EXPECT(SUCCEEDED(standalone->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&msaa_heap.p))));
5269 D3D12_HEAP_DESC deny_rt_desc = tiled_heap_desc;
5270 deny_rt_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
5271 Ref<ID3D12Heap> deny_rt_heap;
5272 EXPECT(SUCCEEDED(standalone->CreateHeap(&deny_rt_desc, IID_PPV_ARGS(&deny_rt_heap.p))));
5273
5274 auto msaa_desc = [&](UINT w, UINT h, UINT samples, UINT64 align, D3D12_TEXTURE_LAYOUT layout,
5275 D3D12_RESOURCE_FLAGS flags, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM,
5276 UINT16 mips = 1) {
5277 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
5278 d.Alignment = align;
5279 d.SampleDesc.Count = samples;
5280 d.Layout = layout;
5281 return d;
5282 };
5283 const D3D12_RESOURCE_DESC msaa_unk_rt_desc =
5284 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5285 const D3D12_RESOURCE_DESC msaa_unk_small_desc = msaa_desc(
5286 256, 256, 4, D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5287 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5288 const D3D12_RESOURCE_DESC msaa_unk_ds_desc =
5289 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
5290 DXGI_FORMAT_D32_FLOAT);
5291 const D3D12_RESOURCE_DESC msaa_tiled_rt_desc = tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5292 D3D12_RESOURCE_DESC msaa_xbox_rt_desc = msaa_tiled_rt_desc;
5293 msaa_xbox_rt_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
5294
5295 Ref<ID3D12Resource> msaa_unk_rt, msaa_unk_small, msaa_unk_ds, msaa_tiled_rt, msaa_xbox_rt, msaa_cast_rt;
5296 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
5297 &msaa_unk_rt_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
5298 IID_PPV_ARGS(&msaa_unk_rt.p))));
5299 EXPECT(msaa_unk_rt->GetGPUVirtualAddress() == 0);
5300 EXPECT(msaa_unk_rt->GetDesc().Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5301 EXPECT(msaa_unk_rt->GetDesc().SampleDesc.Count == 4);
5302 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_unk_small_desc,
5303 D3D12_RESOURCE_STATE_COMMON, nullptr,
5304 IID_PPV_ARGS(&msaa_unk_small.p))));
5305 EXPECT(msaa_unk_small->GetDesc().Alignment == D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5306 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, 8 * 1024 * 1024, &msaa_unk_ds_desc,
5307 D3D12_RESOURCE_STATE_COMMON, nullptr,
5308 IID_PPV_ARGS(&msaa_unk_ds.p))));
5309 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_tiled_rt_desc,
5310 D3D12_RESOURCE_STATE_COMMON, nullptr,
5311 IID_PPV_ARGS(&msaa_tiled_rt.p))));
5312 EXPECT(msaa_tiled_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5313 UINT msaa_tiles = 0;
5314 D3D12_TILE_SHAPE msaa_shape{};
5315 standalone->GetResourceTiling(msaa_tiled_rt.p, &msaa_tiles, nullptr, &msaa_shape, nullptr, 0, nullptr);
5316 EXPECT(msaa_tiles == 16 && msaa_shape.WidthInTexels == 64 && msaa_shape.HeightInTexels == 64);
5317 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_xbox_rt_desc,
5318 D3D12_RESOURCE_STATE_COMMON, nullptr,
5319 IID_PPV_ARGS(&msaa_xbox_rt.p))));
5320 EXPECT(msaa_xbox_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5321 EXPECT(static_cast<UINT>(msaa_xbox_rt->GetDesc().Layout) == 0x101);
5322
5323 {
5324 Ref<ID3D12Device10> standalone10;
5325 EXPECT(SUCCEEDED(standalone->QueryInterface(IID_PPV_ARGS(&standalone10.p))));
5326 D3D12_RESOURCE_DESC1 cast_msaa{};
5327 cast_msaa.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5328 cast_msaa.Width = 64;
5329 cast_msaa.Height = 64;
5330 cast_msaa.DepthOrArraySize = 1;
5331 cast_msaa.MipLevels = 1;
5332 cast_msaa.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS;
5333 cast_msaa.SampleDesc.Count = 4;
5334 cast_msaa.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
5335 const DXGI_FORMAT cast_list[] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
5336 EXPECT(SUCCEEDED(standalone10->CreatePlacedResource2(
5337 msaa_heap.p, 0, &cast_msaa, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 2, cast_list,
5338 IID_PPV_ARGS(&msaa_cast_rt.p))));
5339 }
5340
5341 // Refusals matching host D3D12 for MSAA placed resources.
5342 {
5343 struct BadMsaaCase {
5344 ID3D12Heap* heap;
5345 UINT64 offset;
5346 D3D12_RESOURCE_DESC desc;
5347 };
5348 D3D12_RESOURCE_DESC msaa_3d =
5349 msaa_desc(16, 16, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5350 msaa_3d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
5351 msaa_3d.DepthOrArraySize = 8;
5352 const BadMsaaCase bad_msaa[] = {
5353 // 4 MiB-aligned UNKNOWN MSAA fails on a 64 KiB heap (even at offset 0) and at misaligned offsets.
5354 {tiled_heap.p, 0, msaa_unk_rt_desc},
5355 {msaa_heap.p, 65536, msaa_unk_rt_desc},
5356 {msaa_heap.p, msaa_heap_desc.SizeInBytes - 65536, msaa_unk_small_desc},
5357 {upload_placed_heap.p, 0, msaa_unk_small_desc},
5358 {deny_rt_heap.p, 0, msaa_unk_small_desc},
5359 {deny_rt_heap.p, 0, tiled_rt_desc},
5360 {msaa_heap.p, 0,
5361 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE)},
5362 {msaa_heap.p, 0,
5363 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5364 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)},
5365 {msaa_heap.p, 0,
5366 msaa_desc(64, 64, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
5367 DXGI_FORMAT_R8G8B8A8_UNORM, 0)},
5368 {msaa_heap.p, 0, msaa_3d},
5369 };
5370 for (const BadMsaaCase& bad : bad_msaa) {
5371 Ref<ID3D12Resource> fail;
5372 EXPECT(standalone->CreatePlacedResource(bad.heap, bad.offset, &bad.desc, D3D12_RESOURCE_STATE_COMMON,
5373 nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
5374 EXPECT(!fail.p);
5375 }
5376 D3D12_HEAP_DESC only_rt_desc = tiled_heap_desc;
5377 only_rt_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
5378 Ref<ID3D12Heap> only_rt_heap;
5379 EXPECT(SUCCEEDED(standalone->CreateHeap(&only_rt_desc, IID_PPV_ARGS(&only_rt_heap.p))));
5380 for (const D3D12_RESOURCE_DESC& bad_only_rt :
5381 {texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1),
5382 buffer_desc(4096)}) {
5383 Ref<ID3D12Resource> fail;
5384 EXPECT(standalone->CreatePlacedResource(only_rt_heap.p, 0, &bad_only_rt, D3D12_RESOURCE_STATE_COMMON,
5385 nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
5386 EXPECT(!fail.p);
5387 }
5388 }
5389
5390 // Clear placed 4x MSAA RTVs (UNKNOWN + tiled) and DSV, resolve, and read back to verify GPU execution.
5391 {
5392 const D3D12_RESOURCE_DESC resolved_desc =
5393 texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1);
5394 Ref<ID3D12Resource> msaa_resolved_unk, msaa_resolved_tiled;
5395 D3D12_HEAP_PROPERTIES def_hp{D3D12_HEAP_TYPE_DEFAULT};
5396 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5397 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5398 IID_PPV_ARGS(&msaa_resolved_unk.p))));
5399 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5400 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5401 IID_PPV_ARGS(&msaa_resolved_tiled.p))));
5402
5403 D3D12_DESCRIPTOR_HEAP_DESC msaa_rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5404 D3D12_DESCRIPTOR_HEAP_DESC msaa_dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5405 Ref<ID3D12DescriptorHeap> msaa_rtv_heap, msaa_dsv_heap;
5406 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_rtv_hd, IID_PPV_ARGS(&msaa_rtv_heap.p))));
5407 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_dsv_hd, IID_PPV_ARGS(&msaa_dsv_heap.p))));
5408 const UINT rtv_step = standalone->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
5409 const D3D12_CPU_DESCRIPTOR_HANDLE rtv0 = msaa_rtv_heap->GetCPUDescriptorHandleForHeapStart();
5410 const D3D12_CPU_DESCRIPTOR_HANDLE rtv1{rtv0.ptr + rtv_step};
5411 standalone->CreateRenderTargetView(msaa_unk_rt.p, nullptr, rtv0);
5412 standalone->CreateRenderTargetView(msaa_tiled_rt.p, nullptr, rtv1);
5413 standalone->CreateDepthStencilView(msaa_unk_ds.p, nullptr, msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart());
5414
5415 EXPECT(SUCCEEDED(tiled_alloc->Reset()) && SUCCEEDED(tiled_list->Reset(tiled_alloc.p, nullptr)));
5416 D3D12_RESOURCE_BARRIER barriers[] = {
5417 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5418 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5419 transition(msaa_unk_ds.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE),
5420 };
5421 tiled_list->ResourceBarrier(3, barriers);
5422 tiled_list->ClearRenderTargetView(rtv0, tiled_color, 0, nullptr);
5423 tiled_list->ClearRenderTargetView(rtv1, tiled_color, 0, nullptr);
5424 tiled_list->ClearDepthStencilView(msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart(),
5425 D3D12_CLEAR_FLAG_DEPTH, 0.5f, 0, 0, nullptr);
5426 D3D12_RESOURCE_BARRIER to_resolve[] = {
5427 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5428 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5429 };
5430 tiled_list->ResourceBarrier(2, to_resolve);
5431 tiled_list->ResolveSubresource(msaa_resolved_unk.p, 0, msaa_unk_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5432 tiled_list->ResolveSubresource(msaa_resolved_tiled.p, 0, msaa_tiled_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5433 D3D12_RESOURCE_BARRIER to_copy[] = {
5434 transition(msaa_resolved_unk.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5435 transition(msaa_resolved_tiled.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5436 };
5437 tiled_list->ResourceBarrier(2, to_copy);
5438 Ref<ID3D12Resource> msaa_rb;
5439 const D3D12_RESOURCE_DESC msaa_rb_desc = buffer_desc(1024);
5440 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&rb_props, D3D12_HEAP_FLAG_NONE, &msaa_rb_desc,
5441 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
5442 IID_PPV_ARGS(&msaa_rb.p))));
5443 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp_unk{}, fp_tiled{};
5444 fp_unk.Offset = 0;
5445 fp_unk.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT};
5446 fp_tiled = fp_unk;
5447 fp_tiled.Offset = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
5448 const D3D12_TEXTURE_COPY_LOCATION dst_unk = footprint(msaa_rb.p, fp_unk);
5449 const D3D12_TEXTURE_COPY_LOCATION src_unk = subresource(msaa_resolved_unk.p, 0);
5450 const D3D12_TEXTURE_COPY_LOCATION dst_tiled = footprint(msaa_rb.p, fp_tiled);
5451 const D3D12_TEXTURE_COPY_LOCATION src_tiled = subresource(msaa_resolved_tiled.p, 0);
5452 tiled_list->CopyTextureRegion(&dst_unk, 0, 0, 0, &src_unk, &box);
5453 tiled_list->CopyTextureRegion(&dst_tiled, 0, 0, 0, &src_tiled, &box);
5454 EXPECT(SUCCEEDED(tiled_list->Close()));
5455 queue->ExecuteCommandLists(1, tiled_lists);
5456 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
5457 EXPECT(SUCCEEDED(queue->Signal(fence.p, 9)) && SUCCEEDED(fence->SetEventOnCompletion(9, nullptr)));
5458 void* msaa_bytes = nullptr;
5459 EXPECT(SUCCEEDED(msaa_rb->Map(0, nullptr, &msaa_bytes)));
5460 const auto* out_bytes = static_cast<const std::uint8_t*>(msaa_bytes);
5461 report("placed MSAA UNKNOWN RTV resolve", 0, out_bytes, want_rgba, 4);
5462 report("placed MSAA tiled RTV resolve", 0, out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4);
5463 EXPECT(std::memcmp(out_bytes, want_rgba, 4) == 0);
5464 EXPECT(std::memcmp(out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4) == 0);
5465 msaa_rb->Unmap(0, nullptr);
5466 }
5467
5468 // Host parity for MSAA placed acceptance/refusals, layout, alignment, heap flags and tiled 4x shape.
5469 if (host_dev.p) {
5470 Ref<ID3D12Heap> host_heap64, host_heap4m;
5471 if (SUCCEEDED(host_dev->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&host_heap64.p))) &&
5472 SUCCEEDED(host_dev->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&host_heap4m.p)))) {
5473 struct MsaaParityCase {
5474 ID3D12Heap* our_heap;
5475 ID3D12Heap* host_heap;
5476 UINT64 offset;
5477 D3D12_RESOURCE_DESC desc;
5478 };
5479 const MsaaParityCase parity[] = {
5480 {tiled_heap.p, host_heap64.p, 0, msaa_unk_rt_desc},
5481 {msaa_heap.p, host_heap4m.p, 65536, msaa_unk_rt_desc},
5482 {msaa_heap.p, host_heap4m.p, 0, msaa_unk_rt_desc},
5483 {tiled_heap.p, host_heap64.p, 65536, msaa_unk_small_desc},
5484 {tiled_heap.p, host_heap64.p, 65536, msaa_tiled_rt_desc},
5485 };
5486 for (const MsaaParityCase& mc : parity) {
5487 Ref<ID3D12Resource> our_r, host_r;
5488 const HRESULT our_hr = standalone->CreatePlacedResource(
5489 mc.our_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
5490 const HRESULT host_hr = host_dev->CreatePlacedResource(
5491 mc.host_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
5492 EXPECT(SUCCEEDED(our_hr) == SUCCEEDED(host_hr));
5493 if (FAILED(host_hr)) {
5494 EXPECT(our_hr == host_hr);
5495 continue;
5496 }
5497 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
5498 EXPECT(our_r->GetDesc().Alignment == host_r->GetDesc().Alignment);
5499 EXPECT(our_r->GetDesc().SampleDesc.Count == host_r->GetDesc().SampleDesc.Count);
5500 D3D12_HEAP_PROPERTIES ohp{}, hhp{};
5501 EXPECT(SUCCEEDED(our_r->GetHeapProperties(&ohp, nullptr)) &&
5502 SUCCEEDED(host_r->GetHeapProperties(&hhp, nullptr)));
5503 EXPECT(ohp.Type == hhp.Type);
5504 if (mc.desc.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
5505 D3D12_TILE_SHAPE os{}, hs{};
5506 standalone->GetResourceTiling(our_r.p, nullptr, nullptr, &os, nullptr, 0, nullptr);
5507 host_dev->GetResourceTiling(host_r.p, nullptr, nullptr, &hs, nullptr, 0, nullptr);
5508 EXPECT(os.WidthInTexels == hs.WidthInTexels && os.HeightInTexels == hs.HeightInTexels &&
5509 os.DepthInTexels == hs.DepthInTexels);
5510 }
5511 }
5512 }
5513 }
4951 } 5514 }
4952 5515
4953 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as 5516 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as
@@ -5179,6 +5742,15 @@ int main() {
5179 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0); 5742 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0);
5180 } 5743 }
5181 5744
5745 // The tolerance host_side applies, pinned here so every GPU checks it: its accept side only runs where the
5746 // host rounds differently (Intel's SRGB clear), so a change to it would otherwise stay green elsewhere.
5747 // One code either side of a near-tie is accepted; two codes, or a code past 0.6 ULP, are not.
5748 EXPECT(within_06_ulp(187, 188, ideal_srgb(0.5) * 255.0) && within_06_ulp(127, 128, 127.5));
5749 EXPECT(!within_06_ulp(186, 188, ideal_srgb(0.5) * 255.0) && !within_06_ulp(126, 128, 127.5));
5750 EXPECT(!within_06_ulp(224, 225, ideal_srgb(0.75) * 255.0) &&
5751 !within_06_ulp(136, 137, ideal_srgb(0.25) * 255.0));
5752 EXPECT(!within_06_ulp(254, 255, 255.0));
5753
5182 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise. 5754 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise.
5183 bool compared = false; 5755 bool compared = false;
5184 const char* source = "no host"; 5756 const char* source = "no host";
@@ -5188,33 +5760,44 @@ int main() {
5188 if (!placed_cast_scenario(device10, false, host.data())) return false; 5760 if (!placed_cast_scenario(device10, false, host.data())) return false;
5189 if (!placed_cast_refusals(device10, host_refusals)) return false; 5761 if (!placed_cast_refusals(device10, host_refusals)) return false;
5190 unsigned differences = 0; 5762 unsigned differences = 0;
5191 // D3D12 does not pin float -> UNORM at a tie: the D3D11.3 functional spec (3.2.3.6 FLOAT -> UNORM) 5763 // D3D12 does not pin float -> UNORM or float -> SRGB to one code: the D3D11.3 functional spec
5192 // computes c * (2^n - 1) + 0.5 and drops the fraction, but permits a tolerance of 0.6 ULP on the integer 5764 // (3.2.3.6 FLOAT -> UNORM, 3.2.3.8 FLOAT -> SRGB) permits a tolerance of 0.6 ULP on the integer side, so
5193 // side, so a value exactly halfway between two codes (0.5 * 255 = 127.5) may map to either. WARP and AMD 5765 // a value near halfway between two codes may map to either. The plain clear's 0.5 * 255 = 127.5 is a
5194 // give the upper code; NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080 616.64, RTX 3090 5766 // tie: WARP and AMD give the upper code, NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080
5195 // 610.88 and RTX 5070 Laptop 617.42). On the layer's own adapter (same LUID) the comparison stays exact; 5767 // 616.64, RTX 3090 610.88 and RTX 5070 Laptop 617.42). The SRGB-cast clear's 0.5 encodes to 187.516:
5196 // against another adapter or WARP the plain clear accepts either code on a tie channel. 5768 // WARP and NVIDIA's Vulkan driver give 188, Intel's Vulkan driver 187 (UHD 770 101.7092), both within
5769 // 0.6 ULP. On the layer's own adapter (same LUID) the comparison stays exact; against another adapter
5770 // or WARP a byte may differ when both sides are within 0.6 ULP of the ideal value.
5197 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour 5771 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour
5198 unsigned tie_bytes_other_way = 0; 5772 const auto within_tolerance = [&](std::uint8_t ours_byte, std::uint8_t host_byte, double ideal) {
5773 return !same_adapter && within_06_ulp(ours_byte, host_byte, ideal);
5774 };
5775 unsigned plain_within = 0, srgb_within = 0;
5199 for (UINT row = 0; row < 4; ++row) 5776 for (UINT row = 0; row < 4; ++row)
5200 for (UINT i = 0; i < 16; ++i) { 5777 for (UINT i = 0; i < 16; ++i) {
5201 const UINT a = row * 256 + i, b = 1024 + row * 256 + i; 5778 const UINT a = row * 256 + i, b = 1024 + row * 256 + i;
5202 const double scaled = double(clear_value[i % 4]) * 255.0; 5779 const double c = clear_value[i % 4];
5203 const bool tie = !same_adapter && scaled - std::floor(scaled) == 0.5; 5780 const double plain_ideal = c * 255.0;
5204 if (tie && std::abs(int(ours[b]) - int(host[b])) == 1) { 5781 const double srgb_ideal = (i % 4 == 3 ? c : ideal_srgb(c)) * 255.0; // alpha stays linear
5205 ++tie_bytes_other_way; 5782 if (ours[b] != host[b]) {
5206 } else if (ours[b] != host[b] && differences++ < 8) { 5783 if (within_tolerance(ours[b], host[b], plain_ideal))
5207 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i, 5784 ++plain_within;
5208 ours[b], host[b]); 5785 else if (differences++ < 8)
5786 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i,
5787 ours[b], host[b]);
5788 }
5789 if (ours[a] != host[a]) {
5790 if (within_tolerance(ours[a], host[a], srgb_ideal))
5791 ++srgb_within;
5792 else if (differences++ < 8)
5793 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n",
5794 row, i, ours[a], host[a]);
5209 } 5795 }
5210 if (ours[a] != host[a] && differences++ < 8)
5211 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n", row,
5212 i, ours[a], host[a]);
5213 } 5796 }
5214 if (tie_bytes_other_way) 5797 if (plain_within || srgb_within)
5215 std::printf("placed plain clear: the host rounds the exact .5 tie the other way in %u bytes (within " 5798 std::printf("placed clears: %u plain and %u SRGB-cast bytes differ from the host by one code, both "
5216 "the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6)\n", 5799 "within the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6 and 3.2.3.8\n",
5217 tie_bytes_other_way); 5800 plain_within, srgb_within);
5218 for (UINT i = 0; i < 3; ++i) 5801 for (UINT i = 0; i < 3; ++i)
5219 if (our_refusals[i] != host_refusals[i]) { 5802 if (our_refusals[i] != host_refusals[i]) {
5220 ++differences; 5803 ++differences;
diff --git a/runtime/test/d3d12_xdxr_rt_test.cpp b/runtime/test/d3d12_xdxr_rt_test.cpp
index 9499dbe0d..51f357fc1 100644
--- a/runtime/test/d3d12_xdxr_rt_test.cpp
+++ b/runtime/test/d3d12_xdxr_rt_test.cpp
@@ -2,7 +2,10 @@
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; then its postbuild COMPACTED_SIZE and a TLAS rebuild's CURRENT_SIZE are
7// checked against the prebuild sizes, and the BLAS is compacted (CopyRaytracingAccelerationStructure COMPACT) into a
8// buffer of exactly that size, written as d3d12_blas_compacted 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: 9// `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. 10// 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" 11#include "../shims/d3d12_com.h"
@@ -153,6 +156,7 @@ int main(int argc, char** argv) {
153 156
154 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; 157 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{};
155 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; 158 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
159 blas_inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE; // updated below
156 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; 160 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
157 blas_inputs.NumDescs = 2; 161 blas_inputs.NumDescs = 2;
158 blas_inputs.pGeometryDescs = geometries; 162 blas_inputs.pGeometryDescs = geometries;
@@ -239,7 +243,7 @@ int main(int argc, char** argv) {
239 ID3D12CommandList* lists[] = {list.p}; 243 ID3D12CommandList* lists[] = {list.p};
240 queue->ExecuteCommandLists(1, lists); 244 queue->ExecuteCommandLists(1, lists);
241 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal"); 245 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal");
242 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 246 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // reused for the update below
243 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) && 247 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) &&
244 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; 248 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
245 if (event) CloseHandle(event); 249 if (event) CloseHandle(event);
@@ -258,31 +262,35 @@ int main(int argc, char** argv) {
258 rb->Unmap(0, nullptr); 262 rb->Unmap(0, nullptr);
259 return ok; 263 return ok;
260 }; 264 };
261 std::string tris = "["; 265 // The BLAS's triangles as the reference sees them, for the soup's current positions.
262 bool first = true; 266 auto triangles_json = [&](const std::vector<float>& soup_now) {
263 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) { 267 std::string tris = "[";
264 tris += first ? "\n [" : ",\n ["; 268 bool first = true;
265 first = false; 269 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) {
266 for (int k = 0; k < 3; ++k) 270 tris += first ? "\n [" : ",\n [";
267 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]"; 271 first = false;
268 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]"; 272 for (int k = 0; k < 3; ++k)
269 }; 273 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]";
270 for (UINT t = 0; t < soup_tris; ++t) { 274 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]";
271 float v[3][3]; 275 };
272 for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup[9 * t + k]; 276 for (UINT t = 0; t < soup_tris; ++t) {
273 add_tri(v, 0, t); 277 float v[3][3];
274 } 278 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) { 279 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 } 280 }
283 add_tri(v, 1, t); 281 for (UINT t = 0; t < indices.size() / 3; ++t) {
284 } 282 float v[3][3];
285 tris += "]"; 283 for (int k = 0; k < 3; ++k) {
284 const float* p = &grid[4 * indices[3 * t + k]];
285 for (int r = 0; r < 3; ++r)
286 v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] +
287 transform[4 * r + 3];
288 }
289 add_tri(v, 1, t);
290 }
291 return tris + "]";
292 };
293 const std::string tris = triangles_json(soup);
286 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas", 294 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas",
287 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + 295 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
288 ", \"triangles\": " + tris + "}\n")) 296 ", \"triangles\": " + tris + "}\n"))
@@ -298,6 +306,103 @@ int main(int argc, char** argv) {
298 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + 306 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) +
299 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n")) 307 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n"))
300 return fail("TLAS readback"); 308 return fail("TLAS readback");
309
310 // ---- PERFORM_UPDATE in place: the soup moves (every vertex), the grid stays; the BLAS is refitted ----
311 std::vector<float> moved = soup;
312 std::uniform_real_distribution<float> nudge(-1.0f, 1.0f);
313 for (std::size_t v = 0; v < moved.size(); v += 3) {
314 moved[v] = moved[v] * 1.3f + nudge(rng);
315 moved[v + 1] = moved[v + 1] * 0.7f + nudge(rng);
316 moved[v + 2] += nudge(rng);
317 }
318 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return fail("Map upload for the update");
319 std::memcpy(mapped + (soup_va - upload->GetGPUVirtualAddress()), moved.data(), std::size_t(soup_bytes));
320 upload->Unmap(0, nullptr);
321 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for the update");
322 build.Inputs = blas_inputs;
323 build.Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
324 build.DestAccelerationStructureData = blas->GetGPUVirtualAddress();
325 build.SourceAccelerationStructureData = blas->GetGPUVirtualAddress();
326 list->BuildRaytracingAccelerationStructure(&build, 0, nullptr);
327 list->ResourceBarrier(1, &barrier);
328 list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes);
329 if (FAILED(hr = list->Close())) return fail("Close (update)", hr);
330 queue->ExecuteCommandLists(1, lists);
331 if (FAILED(queue->Signal(fence.p, 2))) return fail("Signal (update)");
332 event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
333 const bool updated = event && SUCCEEDED(fence->SetEventOnCompletion(2, event)) &&
334 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
335 if (event) CloseHandle(event);
336 if (!updated) return fail("the update did not complete");
337 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas_update",
338 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
339 ", \"triangles\": " + triangles_json(moved) + "}\n"))
340 return fail("BLAS readback after the update");
341
342 // ---- postbuild info and compaction: EmitRaytracingAccelerationStructurePostbuildInfo for both structures, a
343 // TLAS rebuild with a CURRENT_SIZE postbuild desc, then COMPACT the BLAS into a buffer of exactly its size ----
344 auto submit = [&](UINT64 value) {
345 if (FAILED(list->Close())) return false;
346 queue->ExecuteCommandLists(1, lists);
347 if (FAILED(queue->Signal(fence.p, value))) return false;
348 HANDLE e = CreateEventW(nullptr, FALSE, FALSE, nullptr);
349 const bool ok = e && SUCCEEDED(fence->SetEventOnCompletion(value, e)) &&
350 WaitForSingleObject(e, 10000) == WAIT_OBJECT_0;
351 if (e) CloseHandle(e);
352 return ok;
353 };
354 Ref<ID3D12Resource> info, info_rb;
355 if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, 24, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, info.put())) ||
356 FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, 24, D3D12_RESOURCE_STATE_COPY_DEST,
357 D3D12_RESOURCE_FLAG_NONE, info_rb.put())))
358 return fail("postbuild buffers", hr);
359 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for postbuild");
360 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC compacted_desc{
361 info->GetGPUVirtualAddress(), D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE};
362 const D3D12_GPU_VIRTUAL_ADDRESS both[2] = {blas->GetGPUVirtualAddress(), tlas->GetGPUVirtualAddress()};
363 list->EmitRaytracingAccelerationStructurePostbuildInfo(&compacted_desc, 2, both);
364 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC current_desc{
365 info->GetGPUVirtualAddress() + 16, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE};
366 build = {};
367 build.Inputs = tlas_inputs;
368 build.DestAccelerationStructureData = tlas->GetGPUVirtualAddress();
369 build.ScratchAccelerationStructureData = scratch->GetGPUVirtualAddress();
370 list->BuildRaytracingAccelerationStructure(&build, 1, &current_desc);
371 list->ResourceBarrier(1, &barrier);
372 list->CopyBufferRegion(info_rb.p, 0, info.p, 0, 24);
373 if (!submit(3)) return fail("postbuild submission");
374 UINT64 sizes[3] = {};
375 {
376 void* p = nullptr;
377 if (FAILED(info_rb->Map(0, nullptr, &p))) return fail("Map postbuild");
378 std::memcpy(sizes, p, sizeof sizes);
379 info_rb->Unmap(0, nullptr);
380 }
381 // the builds are exactly their prebuild size, so the compacted size is that size
382 if (sizes[0] != blas_info.ResultDataMaxSizeInBytes || sizes[1] != tlas_info.ResultDataMaxSizeInBytes ||
383 sizes[2] != tlas_info.ResultDataMaxSizeInBytes) {
384 std::fprintf(stderr, "postbuild sizes %llu %llu %llu, prebuild %llu %llu\n",
385 static_cast<unsigned long long>(sizes[0]), static_cast<unsigned long long>(sizes[1]),
386 static_cast<unsigned long long>(sizes[2]),
387 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
388 static_cast<unsigned long long>(tlas_info.ResultDataMaxSizeInBytes));
389 return fail("postbuild sizes");
390 }
391 Ref<ID3D12Resource> compacted, compacted_rb;
392 if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, sizes[0], as_state, uav, compacted.put())) ||
393 FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, sizes[0], D3D12_RESOURCE_STATE_COPY_DEST,
394 D3D12_RESOURCE_FLAG_NONE, compacted_rb.put())))
395 return fail("compacted buffers", hr);
396 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for compaction");
397 list->CopyRaytracingAccelerationStructure(compacted->GetGPUVirtualAddress(), blas->GetGPUVirtualAddress(),
398 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT);
399 list->ResourceBarrier(1, &barrier);
400 list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, sizes[0]);
401 if (!submit(4)) return fail("compaction submission");
402 if (!dump(compacted_rb.p, sizes[0], "d3d12_blas_compacted",
403 "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) +
404 ", \"triangles\": " + triangles_json(moved) + "}\n"))
405 return fail("compacted BLAS readback");
301 std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n", 406 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), 407 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
303 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), 408 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp
index a24a9c6e2..26fb39083 100644
--- a/runtime/test/descriptor_table_test.cpp
+++ b/runtime/test/descriptor_table_test.cpp
@@ -233,7 +233,7 @@ int test_clear_resets_table() {
233 return 0; 233 return 0;
234} 234}
235 235
236int test_erase_and_cluster_compact() { 236int test_erase_and_reinsert() {
237 DescriptorTable table(16); 237 DescriptorTable table(16);
238 238
239 const std::uint32_t k1[8] = {1, 10, 100, 1000, 2, 20, 200, 2000}; 239 const std::uint32_t k1[8] = {1, 10, 100, 1000, 2, 20, 200, 2000};
@@ -310,12 +310,12 @@ int test_change_tracking() {
310 EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot); 310 EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot);
311 EXPECT(table.read_slot(slot, read) && read[8] == 43); 311 EXPECT(table.read_slot(slot, read) && read[8] == 43);
312 312
313 // Erasing marks the slot it was in and the ones the cluster compaction moved. 313 // Erasing marks only the slot it was in: no other entry moves.
314 EXPECT(table.insert(k2, 7)); 314 EXPECT(table.insert(k2, 7));
315 table.take_changes(); 315 table.take_changes();
316 EXPECT(table.erase(k1)); 316 EXPECT(table.erase(k1));
317 changes = table.take_changes(); 317 changes = table.take_changes();
318 EXPECT(!changes.all && !changes.slots.empty() && changes.slots.front() == slot); 318 EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot);
319 319
320 // Growth changes the mask, so everything re-uploads. 320 // Growth changes the mask, so everything re-uploads.
321 const std::size_t before = table.capacity(); 321 const std::size_t before = table.capacity();
@@ -366,6 +366,48 @@ int test_relocation_marks_both_slots() {
366 return 0; 366 return 0;
367} 367}
368 368
369// Shaders keep probing the GPU copy of the table while an erase is uploaded without waiting for idle
370// (BindlessSet::flush_needs_idle), so an erase must leave every other key's slot exactly as it was.
371int test_erase_moves_no_other_entry() {
372 DescriptorTable table(64);
373 const std::uint32_t slots = std::uint32_t(table.capacity());
374 // Five keys with one home: they fill five consecutive slots, the cluster the old erase compacted.
375 std::array<DescriptorKey, 5> keys{};
376 for (std::uint32_t i = 0; i < keys.size(); ++i) {
377 auto& key = keys[i];
378 key[0] = i + 1;
379 while ((hash_descriptor_key(key) & (slots - 1)) != slots - 2) ++key[7]; // the cluster wraps the end
380 EXPECT(table.insert_or_update(key.data(), 200 + i) == DescriptorTable::InsertResult::added);
381 }
382 table.take_changes();
383 const auto before = table.build_gpu_buffer();
384
385 EXPECT(table.erase(keys[1].data()));
386 const DescriptorTable::Changes changes = table.take_changes();
387 EXPECT(!changes.all && changes.slots.size() == 1);
388 const std::uint32_t hole = changes.slots.front();
389 const auto after = table.build_gpu_buffer();
390 for (std::uint32_t s = 0; s < slots; ++s) {
391 const bool same = std::memcmp(&before[1 + s * 10], &after[1 + s * 10], 10 * sizeof(std::uint32_t)) == 0;
392 EXPECT(same == (s != hole));
393 }
394 for (std::uint32_t w = 0; w < 10; ++w) EXPECT(after[1 + hole * 10 + w] == 0); // an empty slot: a miss
395 for (std::uint32_t i = 0; i < keys.size(); ++i) EXPECT(table.lookup(keys[i]) == (i == 1 ? 0u : 200 + i));
396
397 // Keys past the hole are still found after more erases, and a new key of the same home reuses the hole.
398 EXPECT(table.erase(keys[0].data()));
399 EXPECT(table.lookup(keys[4]) == 204 && table.lookup(keys[3]) == 203);
400 DescriptorKey extra = keys[0];
401 extra[0] = 100;
402 while ((hash_descriptor_key(extra) & (slots - 1)) != slots - 2) ++extra[7];
403 table.take_changes();
404 EXPECT(table.insert_or_update(extra.data(), 300) == DescriptorTable::InsertResult::added);
405 const DescriptorTable::Changes reuse = table.take_changes();
406 EXPECT(reuse.slots.size() == 1 && reuse.slots.front() == slots - 2); // the first hole of the probe window
407 EXPECT(table.lookup(extra) == 300 && table.size() == 4);
408 return 0;
409}
410
369int main() { 411int main() {
370 EXPECT(test_fnv1a_hash_matches_contract() == 0); 412 EXPECT(test_fnv1a_hash_matches_contract() == 0);
371 EXPECT(test_ssharp_key_padding() == 0); 413 EXPECT(test_ssharp_key_padding() == 0);
@@ -376,9 +418,10 @@ int main() {
376 EXPECT(test_gpu_buffer_serialization() == 0); 418 EXPECT(test_gpu_buffer_serialization() == 0);
377 EXPECT(test_change_tracking() == 0); 419 EXPECT(test_change_tracking() == 0);
378 EXPECT(test_relocation_marks_both_slots() == 0); 420 EXPECT(test_relocation_marks_both_slots() == 0);
421 EXPECT(test_erase_moves_no_other_entry() == 0);
379 EXPECT(test_multithreaded_insert_and_lookup() == 0); 422 EXPECT(test_multithreaded_insert_and_lookup() == 0);
380 EXPECT(test_clear_resets_table() == 0); 423 EXPECT(test_clear_resets_table() == 0);
381 EXPECT(test_erase_and_cluster_compact() == 0); 424 EXPECT(test_erase_and_reinsert() == 0);
382 425
383 std::printf("descriptor_table_test: all tests passed (0 failures)\n"); 426 std::printf("descriptor_table_test: all tests passed (0 failures)\n");
384 return 0; 427 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 3b23b3579..c22397d90 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -276,6 +276,18 @@ int main() {
276 scd.BufferCount = 2; 276 scd.BufferCount = 2;
277 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; 277 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
278 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
279 IDXGISwapChain1* sc1 = nullptr; 291 IDXGISwapChain1* sc1 = nullptr;
280 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1) 292 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1)
281 return fail("CreateSwapChainForHwnd"); 293 return fail("CreateSwapChainForHwnd");
@@ -421,12 +433,34 @@ int main() {
421 return 0; 433 return 0;
422 }; 434 };
423 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
424 // 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.
425 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};
426 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;
427 458
428 // Frame 2: ResizeBuffers to explicit 37x19 on the unchanged 128x128 HWND, clear to green, read back all 703 pixels, Present. 459 // Frame 2: ResizeBuffers to explicit 37x19 on the unchanged 128x128 HWND, clear to green, read back all 703 pixels, Present.
429 if (FAILED(sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers"); 460 if (FAILED(sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers");
461 DXGI_SWAP_CHAIN_DESC1 preserved_format{};
462 if (FAILED(sc->GetDesc1(&preserved_format)) || preserved_format.Format != scd.Format)
463 return fail("ResizeBuffers with DXGI_FORMAT_UNKNOWN changed the format");
430 const float green[4] = {0.0f, 1.0f, 0.0f, 1.0f}; 464 const float green[4] = {0.0f, 1.0f, 0.0f, 1.0f};
431 if (run_clear_readback_present(37, 19, green, 0, 255, 0) != 0) return 1; 465 if (run_clear_readback_present(37, 19, green, 0, 255, 0) != 0) return 1;
432 466
@@ -587,9 +621,28 @@ int main() {
587 return fail("GetRotation(nullptr) should return E_INVALIDARG"); 621 return fail("GetRotation(nullptr) should return E_INVALIDARG");
588 } 622 }
589 623
590 // Unsupported swapchain format must fail explicitly instead of silently downgrading to BGRA8. 624 constexpr DXGI_FORMAT invalid_formats[] = {
591 if (sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_R32_UINT, 0) != DXGI_ERROR_UNSUPPORTED) 625 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
592 return fail("ResizeBuffers should reject unsupported format DXGI_FORMAT_R32_UINT"); 626 DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R32_UINT,
627 };
628 {
629 DXGI_SWAP_CHAIN_DESC1 before{}, after{};
630 if (FAILED(sc->GetDesc1(&before))) return fail("GetDesc1 before invalid formats");
631 const UINT node_masks[2] = {1, 1};
632 IUnknown* const present_queues[2] = {queue, queue};
633 for (DXGI_FORMAT format : invalid_formats) {
634 if (sc->ResizeBuffers(2, 64, 64, format, 0) != E_INVALIDARG ||
635 sc->ResizeBuffers1(2, 64, 64, format, 0, node_masks, present_queues) != E_INVALIDARG)
636 return fail("ResizeBuffers and ResizeBuffers1 should reject invalid flip-model formats");
637 }
638 if (FAILED(sc->GetDesc1(&after)) || after.Format != before.Format || after.BufferCount != before.BufferCount ||
639 after.Width != before.Width || after.Height != before.Height)
640 return fail("Invalid format changed the existing swapchain");
641 ID3D12Resource* buffer = nullptr;
642 if (FAILED(sc->GetBuffer(sc->GetCurrentBackBufferIndex(), IID_PPV_ARGS(&buffer))) || !buffer)
643 return fail("GetBuffer after invalid swapchain formats");
644 buffer->Release();
645 }
593 646
594 // Measured on host DXGI (RTX 5070 and WARP): DXGI_PRESENT_TEST returns S_OK without presenting, so the back 647 // Measured on host DXGI (RTX 5070 and WARP): DXGI_PRESENT_TEST returns S_OK without presenting, so the back
595 // buffer index and last present count stay; a sync interval above 4 is DXGI_ERROR_INVALID_CALL and presents nothing. 648 // buffer index and last present count stay; a sync interval above 4 is DXGI_ERROR_INVALID_CALL and presents nothing.
@@ -747,6 +800,8 @@ int main() {
747 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at 800 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at
748 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size. 801 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size.
749 { 802 {
803 DXGI_SWAP_CHAIN_DESC1 before_zero{};
804 if (FAILED(sc->GetDesc1(&before_zero))) return fail("GetDesc1 before zero-count resize");
750 RECT wr{0, 0, 300, 200}; 805 RECT wr{0, 0, 300, 200};
751 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); 806 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
752 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER); 807 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER);
@@ -754,7 +809,8 @@ int main() {
754 GetClientRect(hwnd, &cr); 809 GetClientRect(hwnd, &cr);
755 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)"); 810 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)");
756 DXGI_SWAP_CHAIN_DESC1 d{}; 811 DXGI_SWAP_CHAIN_DESC1 d{};
757 sc->GetDesc1(&d); 812 if (FAILED(sc->GetDesc1(&d)) || d.BufferCount != before_zero.BufferCount)
813 return fail("ResizeBuffers(0, 0, 0) changed the buffer count");
758 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) { 814 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) {
759 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height, 815 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height,
760 cr.right, cr.bottom); 816 cr.right, cr.bottom);
@@ -764,6 +820,21 @@ int main() {
764 HWND hwnd2 = create_test_window(200, 150); 820 HWND hwnd2 = create_test_window(200, 150);
765 if (!hwnd2) return fail("CreateWindowExW (second)"); 821 if (!hwnd2) return fail("CreateWindowExW (second)");
766 GetClientRect(hwnd2, &cr); 822 GetClientRect(hwnd2, &cr);
823 const auto rejects_creation_format = [&](DXGI_FORMAT format) {
824 DXGI_SWAP_CHAIN_DESC1 invalid = scd;
825 invalid.Format = format;
826 IDXGISwapChain1* rejected = nullptr;
827 const HRESULT hr = factory->CreateSwapChainForHwnd(queue, hwnd2, &invalid, nullptr, nullptr, &rejected);
828 if (rejected) {
829 rejected->Release();
830 return false;
831 }
832 return hr == DXGI_ERROR_INVALID_CALL;
833 };
834 if (!rejects_creation_format(DXGI_FORMAT_UNKNOWN))
835 return fail("CreateSwapChainForHwnd accepted DXGI_FORMAT_UNKNOWN");
836 for (DXGI_FORMAT format : invalid_formats)
837 if (!rejects_creation_format(format)) return fail("CreateSwapChainForHwnd invalid flip-model format");
767 DXGI_SWAP_CHAIN_DESC1 zd = scd; 838 DXGI_SWAP_CHAIN_DESC1 zd = scd;
768 zd.Width = 0; 839 zd.Width = 0;
769 zd.Height = 0; 840 zd.Height = 0;
@@ -794,11 +865,31 @@ int main() {
794 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG"); 865 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG");
795 factory5->Release(); 866 factory5->Release();
796 867
868 constexpr UINT tearing_flag = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
869 constexpr UINT waitable_flag = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
870 constexpr UINT both_flags = tearing_flag | waitable_flag;
871 const UINT node_masks[2] = {1, 1};
872 IUnknown* const present_queues[2] = {queue, queue};
873 const auto rejects_flag_change = [&](IDXGISwapChain3* chain, UINT flags) {
874 DXGI_SWAP_CHAIN_DESC1 before{}, after{};
875 if (FAILED(chain->GetDesc1(&before))) return false;
876 const UINT width = before.Width + 1;
877 return chain->ResizeBuffers(0, width, before.Height, DXGI_FORMAT_UNKNOWN, flags) == E_INVALIDARG &&
878 chain->ResizeBuffers1(2, width, before.Height, DXGI_FORMAT_UNKNOWN, flags,
879 node_masks, present_queues) == E_INVALIDARG &&
880 SUCCEEDED(chain->GetDesc1(&after)) && after.Flags == before.Flags &&
881 after.BufferCount == before.BufferCount && after.Width == before.Width &&
882 after.Height == before.Height;
883 };
884
797 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected. 885 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected.
886 for (UINT flags : {waitable_flag, tearing_flag, both_flags})
887 if (!rejects_flag_change(sc, flags)) return fail("Resize accepted adding a creation-only flag");
798 if (sc->GetFrameLatencyWaitableObject() != nullptr) 888 if (sc->GetFrameLatencyWaitableObject() != nullptr)
799 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject"); 889 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject");
800 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL) 890 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL)
801 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL"); 891 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL");
892 if (FAILED(sc->Present(0, 0))) return fail("Present after rejected resize on a plain swapchain");
802 893
803 HWND hwnd3 = create_test_window(128, 96); 894 HWND hwnd3 = create_test_window(128, 96);
804 if (!hwnd3) return fail("CreateWindowExW (third)"); 895 if (!hwnd3) return fail("CreateWindowExW (third)");
@@ -806,7 +897,7 @@ int main() {
806 wdesc.Width = 128; 897 wdesc.Width = 128;
807 wdesc.Height = 96; 898 wdesc.Height = 96;
808 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer 899 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer
809 wdesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; 900 wdesc.Flags = both_flags;
810 IDXGISwapChain1* wsc1 = nullptr; 901 IDXGISwapChain1* wsc1 = nullptr;
811 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1) 902 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1)
812 return fail("CreateSwapChainForHwnd (tearing + waitable)"); 903 return fail("CreateSwapChainForHwnd (tearing + waitable)");
@@ -814,6 +905,8 @@ int main() {
814 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)"); 905 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)");
815 wsc1->Release(); 906 wsc1->Release();
816 907
908 for (UINT flags : {0u, waitable_flag, tearing_flag})
909 if (!rejects_flag_change(wsc, flags)) return fail("Resize accepted removing a creation-only flag");
817 DXGI_SWAP_CHAIN_DESC1 got_desc{}; 910 DXGI_SWAP_CHAIN_DESC1 got_desc{};
818 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags) 911 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags)
819 return fail("Waitable swapchain GetDesc1 did not preserve Flags"); 912 return fail("Waitable swapchain GetDesc1 did not preserve Flags");
@@ -836,11 +929,131 @@ int main() {
836 if (!check_statistics_disjoint(wsc)) return fail("first statistics query after Present should be disjoint"); 929 if (!check_statistics_disjoint(wsc)) return fail("first statistics query after Present should be disjoint");
837 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0) 930 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
838 return fail("Post-Present WaitForSingleObject on waitable swapchain failed"); 931 return fail("Post-Present WaitForSingleObject on waitable swapchain failed");
932 if (FAILED(wsc->ResizeBuffers(0, wdesc.Width + 1, wdesc.Height, DXGI_FORMAT_UNKNOWN, both_flags)) ||
933 FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Width != wdesc.Width + 1 || got_desc.Flags != both_flags)
934 return fail("ResizeBuffers with matching creation flags failed");
935 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)) ||
936 WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
937 return fail("Present or wait after resizing the waitable swapchain failed");
839 CloseHandle(waitable); 938 CloseHandle(waitable);
840 wsc->Release(); 939 wsc->Release();
841 DestroyWindow(hwnd3); 940 DestroyWindow(hwnd3);
842 } 941 }
843 942
943 // CreateSwapChainForCoreWindow & Occlusion status registration
944 {
945 // 1. Parameter validation
946 IDXGISwapChain1* sc_dummy = nullptr;
947 if (factory->CreateSwapChainForCoreWindow(queue, nullptr, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
948 return fail("CreateSwapChainForCoreWindow(null window) should return E_INVALIDARG");
949 if (factory->CreateSwapChainForCoreWindow(nullptr, queue, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
950 return fail("CreateSwapChainForCoreWindow(null device) should return E_INVALIDARG");
951 if (factory->CreateSwapChainForCoreWindow(queue, queue, nullptr, nullptr, &sc_dummy) != E_INVALIDARG)
952 return fail("CreateSwapChainForCoreWindow(null desc) should return E_INVALIDARG");
953 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, nullptr) != E_POINTER)
954 return fail("CreateSwapChainForCoreWindow(null out) should return E_POINTER");
955
956 // Non-CoreWindow IUnknown
957 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL)
958 return fail("CreateSwapChainForCoreWindow with non-CoreWindow should return DXGI_ERROR_INVALID_CALL");
959
960 // 2. Mock ICoreWindow with ICoreWindowInterop
961 static constexpr GUID kIID_ICoreWindowInterop = {
962 0x45D64A29, 0xA63E, 0x4CB6, {0xB4, 0x98, 0x57, 0x81, 0xD2, 0x98, 0xCB, 0x4F}};
963 struct MockCoreWindow final : public IUnknown {
964 HWND window_handle = nullptr;
965 std::atomic<ULONG> refs{1};
966
967 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
968 if (!out) return E_POINTER;
969 if (riid == IID_IUnknown || riid == kIID_ICoreWindowInterop) {
970 *out = this;
971 AddRef();
972 return S_OK;
973 }
974 *out = nullptr;
975 return E_NOINTERFACE;
976 }
977 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
978 ULONG STDMETHODCALLTYPE Release() override {
979 ULONG r = --refs;
980 if (!r) delete this;
981 return r;
982 }
983 virtual HRESULT STDMETHODCALLTYPE get_WindowHandle(HWND* hwnd) {
984 if (!hwnd) return E_POINTER;
985 *hwnd = window_handle;
986 return S_OK;
987 }
988 virtual HRESULT STDMETHODCALLTYPE put_MessageHandled(unsigned char) { return S_OK; }
989 };
990
991 auto* mock_cw = new MockCoreWindow();
992 // Null HWND in interop
993 if (factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL) {
994 mock_cw->Release();
995 return fail("CreateSwapChainForCoreWindow with null HWND should return DXGI_ERROR_INVALID_CALL");
996 }
997
998 // Valid HWND in mock CoreWindow
999 HWND hwnd4 = create_test_window(160, 120);
1000 if (!hwnd4) {
1001 mock_cw->Release();
1002 return fail("CreateWindowExW (fourth)");
1003 }
1004 mock_cw->window_handle = hwnd4;
1005 IDXGISwapChain1* cw_sc1 = nullptr;
1006 if (FAILED(factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &cw_sc1)) || !cw_sc1) {
1007 mock_cw->Release();
1008 DestroyWindow(hwnd4);
1009 return fail("CreateSwapChainForCoreWindow with valid MockCoreWindow failed");
1010 }
1011 IDXGISwapChain3* cw_sc = nullptr;
1012 if (FAILED(cw_sc1->QueryInterface(IID_PPV_ARGS(&cw_sc))) || !cw_sc) {
1013 cw_sc1->Release();
1014 mock_cw->Release();
1015 DestroyWindow(hwnd4);
1016 return fail("QI IDXGISwapChain3 on CoreWindow swapchain failed");
1017 }
1018 cw_sc1->Release();
1019 DXGI_SWAP_CHAIN_DESC1 cw_desc{};
1020 if (FAILED(cw_sc->GetDesc1(&cw_desc)) || cw_desc.Width != scd.Width || cw_desc.Height != scd.Height) {
1021 cw_sc->Release();
1022 mock_cw->Release();
1023 DestroyWindow(hwnd4);
1024 return fail("GetDesc1 on CoreWindow swapchain mismatch");
1025 }
1026 if (FAILED(cw_sc->Present(0, 0))) {
1027 cw_sc->Release();
1028 mock_cw->Release();
1029 DestroyWindow(hwnd4);
1030 return fail("Present on CoreWindow swapchain failed");
1031 }
1032 cw_sc->Release();
1033 mock_cw->Release();
1034 DestroyWindow(hwnd4);
1035
1036 // 3. Occlusion status registration
1037 DWORD cookie1 = 0, cookie2 = 0;
1038 if (factory->RegisterOcclusionStatusWindow(nullptr, WM_USER, &cookie1) != DXGI_ERROR_INVALID_CALL)
1039 return fail("RegisterOcclusionStatusWindow(null hwnd) should return DXGI_ERROR_INVALID_CALL");
1040 if (factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, nullptr) != DXGI_ERROR_INVALID_CALL)
1041 return fail("RegisterOcclusionStatusWindow(null cookie) should return DXGI_ERROR_INVALID_CALL");
1042 if (FAILED(factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, &cookie1)) || cookie1 == 0)
1043 return fail("RegisterOcclusionStatusWindow failed");
1044
1045 HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1046 if (factory->RegisterOcclusionStatusEvent(nullptr, &cookie2) != DXGI_ERROR_INVALID_CALL)
1047 return fail("RegisterOcclusionStatusEvent(null event) should return DXGI_ERROR_INVALID_CALL");
1048 if (factory->RegisterOcclusionStatusEvent(ev, nullptr) != DXGI_ERROR_INVALID_CALL)
1049 return fail("RegisterOcclusionStatusEvent(null cookie) should return DXGI_ERROR_INVALID_CALL");
1050 if (FAILED(factory->RegisterOcclusionStatusEvent(ev, &cookie2)) || cookie2 == 0 || cookie2 == cookie1)
1051 return fail("RegisterOcclusionStatusEvent failed or duplicated cookie");
1052 factory->UnregisterOcclusionStatus(cookie1);
1053 factory->UnregisterOcclusionStatus(cookie2);
1054 CloseHandle(ev);
1055 }
1056
844 rtv_heap->Release(); 1057 rtv_heap->Release();
845 sc->Release(); 1058 sc->Release();
846 fence->Release(); 1059 fence->Release();
@@ -860,7 +1073,7 @@ int main() {
860 return 1; 1073 return 1;
861 } 1074 }
862 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off"); 1075 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off");
863 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, GetBuffer+GetDesc, clear+readback, Present, " 1076 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, CreateSwapChainForCoreWindow, occlusion status, "
864 "ResizeBuffers; 0 validation errors)\n"); 1077 "GetBuffer+GetDesc, clear+readback, Present, ResizeBuffers; 0 validation errors)\n");
865 return 0; 1078 return 0;
866} 1079}
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/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp
index 780b10edb..291d3a5d7 100644
--- a/runtime/test/fixtures/tiny_gdk_load.cpp
+++ b/runtime/test/fixtures/tiny_gdk_load.cpp
@@ -51,10 +51,27 @@ int main() {
51 HRESULT hr = init(0, 0, 0x02, &options); 51 HRESULT hr = init(0, 0, 0x02, &options);
52 if (hr != S_OK) return fail("InitializeApiImplEx2", static_cast<unsigned long>(hr)); 52 if (hr != S_OK) return fail("InitializeApiImplEx2", static_cast<unsigned long>(hr));
53 53
54 // XThreadingImpl, the first class XCurl.dll references (docs/runtime_imports.md); not provided offline yet. 54 // XThreadingImpl, the first class XCurl.dll references (docs/runtime_imports.md), used as its thunks do: the
55 // class id as both ids, a slot with `this` first, then Release (slot 2). Slot 12 is XTaskQueueCreate, 17
56 // XTaskQueueCloseHandle.
55 const GUID threading = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}}; 57 const GUID threading = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}};
58 void* obj = nullptr;
59 hr = query(&threading, threading, &obj);
60 if (hr != S_OK || !obj) return fail("QueryApiImpl hands out XThreadingImpl", static_cast<unsigned long>(hr));
61 void* const* vtable = *static_cast<void* const* const*>(obj);
62 using Create = HRESULT(STDMETHODCALLTYPE*)(void*, UINT32, UINT32, void**);
63 using Close = void(STDMETHODCALLTYPE*)(void*, void*);
64 using Release = ULONG(STDMETHODCALLTYPE*)(void*);
65 void* queue = nullptr;
66 hr = reinterpret_cast<Create>(vtable[12])(obj, 0, 0, &queue); // XTaskQueueDispatchMode::Manual twice
67 if (hr != S_OK || !queue) return fail("XThreadingImpl slot 12 (XTaskQueueCreate)", static_cast<unsigned long>(hr));
68 reinterpret_cast<Close>(vtable[17])(obj, queue);
69 reinterpret_cast<Release>(vtable[2])(obj);
70
71 // A class not served yet (XNetworkingImpl) is refused, with the out pointer cleared.
72 const GUID networking = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}};
56 void* out = reinterpret_cast<void*>(1); 73 void* out = reinterpret_cast<void*>(1);
57 hr = query(&threading, threading, &out); 74 hr = query(&networking, networking, &out);
58 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr) 75 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr)
59 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr)); 76 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr));
60 hr = uninit(); 77 hr = uninit();
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/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/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/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/shaders/build.py b/runtime/test/shaders/build.py
index c9796f244..7ec6608d6 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -20,6 +20,8 @@ With LEONIDA_FMA=khr (or glsl), the fused multiply-adds are translated with --fm
20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl. 20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl.
21With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and 21With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and
22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). 22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py).
23Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR
24inputs, and check.py reports it as SKIP.
23""" 25"""
24import json 26import json
25import os 27import os
@@ -38,6 +40,8 @@ import mc_command # noqa: E402
38 40
39MC = mc_command.mc_command() 41MC = mc_command.mc_command()
40RSRC2, GROUP = 0x8088, (64, 1, 1) 42RSRC2, GROUP = 0x8088, (64, 1, 1)
43# Not built under LEONIDA_BARY_FALLBACK=1 or LEONIDA_F16_INTERP_FALLBACK=1 (see main).
44NEEDS_PER_VERTEX_INPUTS = ("ps_ij_computed",)
41sys.path.insert(0, HERE) # this script is also run with python -I 45sys.path.insert(0, HERE) # this script is also run with python -I
42from compute_fixture import compute_header # noqa: E402 46from compute_fixture import compute_header # noqa: E402
43 47
@@ -58,8 +62,8 @@ def asm_mattr(path):
58CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} 62CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1}
59 63
60 64
61def asm_fssm(path): 65def asm_fssm_fields(path):
62 """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None.""" 66 """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them."""
63 at, words = None, [] 67 at, words = None, []
64 for ln in Path(path).read_text(encoding="utf-8").splitlines(): 68 for ln in Path(path).read_text(encoding="utf-8").splitlines():
65 s = ln.strip() 69 s = ln.strip()
@@ -71,11 +75,27 @@ def asm_fssm(path):
71 m = re.match(r";\s*fssm-data:\s*(.*)", s) 75 m = re.match(r";\s*fssm-data:\s*(.*)", s)
72 if m: 76 if m:
73 words += [int(w, 0) for w in m.group(1).split()] 77 words += [int(w, 0) for w in m.group(1).split()]
78 return at, words
79
80
81def asm_fssm(path):
82 """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None."""
83 at, words = asm_fssm_fields(path)
74 if at is None or not words or at < 4 or at % 4: 84 if at is None or not words or at < 4 or at % 4:
75 return None 85 return None
76 return b"FSSM" + bytes(at - 4) + b"".join(struct.pack("<I", w) for w in words) 86 return b"FSSM" + bytes(at - 4) + b"".join(struct.pack("<I", w) for w in words)
77 87
78 88
89def cs_fssm_extra(path):
90 """A compute shader's "fssm-at"/"fssm-data" words (at 0x148 or later, after compute_header's header), or None.
91 Two compute shaders with the same group size and RSRC2 would otherwise share one FSSM hash, which is what the
92 layer finds a PSO's shader by."""
93 at, words = asm_fssm_fields(path)
94 if at is None or not words or at < 0x148 or at % 4:
95 return None
96 return at, b"".join(struct.pack("<I", w) for w in words)
97
98
79def shader_source(name): 99def shader_source(name):
80 return "vs_clip" if name in CLIP_CASES else name 100 return "vs_clip" if name in CLIP_CASES else name
81 101
@@ -108,12 +128,16 @@ def translate_tests(work, names):
108 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}") 128 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}")
109 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first. 129 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first.
110 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 130 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
111 (disasm / (n + ".s")).write_text(f"; {n} hand-written test\n{code}", encoding="utf-8") 131 (disasm / (n + ".s")).write_text(f"; {n} hand-written test\n{code}", encoding="utf-8", newline="\n")
112 program = None if n.startswith("cs_") else asm_fssm(asm_path) 132 program = None if n.startswith("cs_") else asm_fssm(asm_path)
113 if program: # where the translator looks for a program to hash, as in the game's work folder 133 if program: # where the translator looks for a program to hash, as in the game's work folder
114 (fssm / (n + ".fssm")).write_bytes(program) 134 (fssm / (n + ".fssm")).write_bytes(program)
115 if n.startswith("cs_"): 135 if n.startswith("cs_"):
116 (fssm / (n + ".fssm")).write_bytes(compute_header(asm_path)) 136 program = bytes(compute_header(asm_path))
137 extra = cs_fssm_extra(asm_path)
138 if extra:
139 program += bytes(extra[0] - len(program)) + extra[1]
140 (fssm / (n + ".fssm")).write_bytes(program)
117 elif n in CLIP_CASES and n != "vs_clip_undeclared": 141 elif n in CLIP_CASES and n != "vs_clip_undeclared":
118 (work / (n + ".dxbc")).write_bytes(clip_container()) 142 (work / (n + ".dxbc")).write_bytes(clip_container())
119 else: 143 else:
@@ -149,6 +173,14 @@ def main():
149 if skipped: 173 if skipped:
150 print("not built (need a DXBC container with signatures):", ", ".join(skipped)) 174 print("not built (need a DXBC container with signatures):", ", ".join(skipped))
151 names = [n for n in names if n not in skipped] 175 names = [n for n in names if n not in skipped]
176 # A computed I/J pair needs PerVertexKHR inputs, which both fallbacks take away: the translator refuses it there,
177 # and check.py and run_gpu_tests.py report it as SKIP. Leave it out instead of losing the whole batch.
178 if os.environ.get("LEONIDA_BARY_FALLBACK") == "1" or os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1":
179 per_vertex = [n for n in names if n in NEEDS_PER_VERTEX_INPUTS]
180 if per_vertex:
181 print("not built (computed I/J pairs need PerVertexKHR inputs, off under the fallback):",
182 ", ".join(per_vertex))
183 names = [n for n in names if n not in per_vertex]
152 if not names: 184 if not names:
153 return 0 185 return 0
154 out.mkdir(parents=True, exist_ok=True) 186 out.mkdir(parents=True, exist_ok=True)
@@ -168,13 +200,14 @@ def main():
168 published_index = spirv / index.name 200 published_index = spirv / index.name
169 combined = json.loads(published_index.read_text(encoding="utf-8")) if published_index.exists() else {} 201 combined = json.loads(published_index.read_text(encoding="utf-8")) if published_index.exists() else {}
170 combined.update(validated) 202 combined.update(validated)
171 index.write_text(json.dumps(combined, indent=2) + "\n", encoding="utf-8") 203 index.write_text(json.dumps(combined, indent=2) + "\n", encoding="utf-8", newline="\n")
172 for n in validated: 204 for n in validated:
173 for suffix in (".spv", ".spvasm"): 205 for suffix in (".spv", ".spvasm"):
174 artifact = built / (n + suffix) 206 artifact = built / (n + suffix)
175 artifact.replace(spirv / artifact.name) 207 artifact.replace(spirv / artifact.name)
176 sidecar = work / "fssm" / (n + ".fssm") 208 sidecar = work / "fssm" / (n + ".fssm")
177 if not n.startswith("cs_") and sidecar.is_file(): 209 published = not n.startswith("cs_") or cs_fssm_extra(os.path.join(HERE, n + ".asm"))
210 if published and sidecar.is_file():
178 (out / "fssm").mkdir(exist_ok=True) 211 (out / "fssm").mkdir(exist_ok=True)
179 sidecar.replace(out / "fssm" / sidecar.name) 212 sidecar.replace(out / "fssm" / sidecar.name)
180 index.replace(published_index) 213 index.replace(published_index)
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 2f2853175..3985f85e4 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -81,14 +81,14 @@ 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", "cs_w32_sincos") 84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst")
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
88# otherwise pick a narrower size and return different words (#774). 88# otherwise pick a narrower size and return different words (#774).
89WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} 89WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"}
90WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const", 90WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const",
91 "cs_w32_mask_imm") 91 "cs_w32_mask_imm", "cs_lds_b64_cmpst")
92CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), 92CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]),
93 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), 93 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]),
94 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), 94 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]),
@@ -116,6 +116,9 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
116 ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]), 116 ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]),
117 # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept 117 # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept
118 ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]), 118 ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]),
119 # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header)
120 ("cs_lds_b64_cmpst", [0x11110001, 0x22220002, 0x33330003, 0x44440004,
121 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC]),
119 # constant EXEC: each lane takes its own bit (Intel got 16-bit constants wrong for lanes 16-31) 122 # constant EXEC: each lane takes its own bit (Intel got 16-bit constants wrong for lanes 16-31)
120 ("cs_exec_const", [16, 8, 2, 16, 0, 16]), 123 ("cs_exec_const", [16, 8, 2, 16, 0, 16]),
121 # a constant lane mask (saveexec, wrexec, s_and/s_not/s_mov_b64 into EXEC or VCC) gives lane L its bit L, 124 # a constant lane mask (saveexec, wrexec, s_and/s_not/s_mov_b64 into EXEC or VCC) gives lane L its bit L,
@@ -188,6 +191,16 @@ FMT_XY_XYZ_WORDS = [
188 0x3F800000, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0x0000FFFF, 0xA5A50294, 0xA5A50298, 0xA5A5029C, 191 0x3F800000, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0x0000FFFF, 0xA5A50294, 0xA5A50298, 0xA5A5029C,
189 0x0003FF01, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0xA5A502B0, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC, 192 0x0003FF01, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0xA5A502B0, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC,
190 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC] 193 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC]
194# cs_tbuffer_store.asm: 13 tbuffer_store_format_* regions read back, as a Radeon 680M (gfx1035) gives them
195# natively. Layout and rules in the .asm header.
196TBUFFER_STORE_WORDS = [
197 0x3F800000, 0x40000000, 0x40400000, 0x40800000, 0x40003C00, 0x00000000, 0xA5A50218, 0xA5A5021C,
198 0x00030201, 0xA5A50224, 0xA5A50228, 0xA5A5022C, 0xA5A5FF30, 0xA5A50234, 0xA5A50238, 0xA5A5023C,
199 0x40000240, 0xA5A50244, 0xA5A50248, 0xA5A5024C, 0xD00003FF, 0xA5A50254, 0xA5A50258, 0xA5A5025C,
200 0x3F800000, 0x40000000, 0xA5A50268, 0xA5A5026C, 0x40003C00, 0xA5A50274, 0xA5A50278, 0xA5A5027C,
201 0xFF0080FF, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0xA5A50290, 0xA5A50294, 0xA5A50298, 0xA5A5029C,
202 0xA5A502FF, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0x3F800000, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC,
203 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC]
191# Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups make a 0x2800-byte heap that holds 204# Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups make a 0x2800-byte heap that holds
192# both the right addresses and the 4096-lower ones; only group 0 thread 0 runs, so no wave64 requirement. 205# both the right addresses and the 4096-lower ones; only group 0 thread 0 runs, so no wave64 requirement.
193GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 206GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4,
@@ -257,6 +270,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
257 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000), 270 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000),
258 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000), 271 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000),
259 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), 272 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203),
273 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
274 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
260 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000), 275 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000),
261 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000), 276 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000),
262 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers) 277 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers)
@@ -316,7 +331,8 @@ CLIP_TESTS = ("vs_clip", "vs_clip_param4", "vs_clip_undeclared")
316# One definition: a later assignment used to drop ps_texoff (and any entry added by an earlier assignment) from 331# One definition: a later assignment used to drop ps_texoff (and any entry added by an earlier assignment) from
317# the standalone run. Keep every pixel fixture in this tuple. 332# the standalone run. Keep every pixel fixture in this tuple.
318PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", "ps_texoff_implicit", 333PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", "ps_texoff_implicit",
319 "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high", "ps_ij_computed")) 334 "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high", "ps_ij_computed",
335 "ps_mandelbrot"))
320# Pixel fixtures drawn with another vertex shader than vs_ids. 336# Pixel fixtures drawn with another vertex shader than vs_ids.
321PIXEL_VERTEX = {"ps_interp_f16_high": "vs_f16_pack", 337PIXEL_VERTEX = {"ps_interp_f16_high": "vs_f16_pack",
322 "ps_interp_f32_mods": "vs_interp_consts", "ps_interp_mov_mods": "vs_interp_consts"} 338 "ps_interp_f32_mods": "vs_interp_consts", "ps_interp_mov_mods": "vs_interp_consts"}
@@ -465,6 +481,12 @@ def fmt_xy_xyz_test(tools, spirv, env=None):
465 return dump_test(tools, spirv, "cs_fmt_xy_xyz", FMT_XY_XYZ_WORDS + [0xEEEEEEEE] * 44, 192, env) 481 return dump_test(tools, spirv, "cs_fmt_xy_xyz", FMT_XY_XYZ_WORDS + [0xEEEEEEEE] * 44, 192, env)
466 482
467 483
484def tbuffer_store_test(tools, spirv, env=None):
485 """The 52 region words tbuffer_store_format_* leaves and the untouched words after them, up to the regions at
486 0x200. The heap needs 0x2d0 bytes, so it is 192 words."""
487 return dump_test(tools, spirv, "cs_tbuffer_store", TBUFFER_STORE_WORDS + [0xEEEEEEEE] * 76, 192, env)
488
489
468class Skip(str): 490class Skip(str):
469 """A result that is neither a pass nor a failure: the device can't run the test.""" 491 """A result that is neither a pass nor a failure: the device can't run the test."""
470 492
@@ -659,6 +681,8 @@ def cvt_f32_sat_test(tools, spirv):
659 for bits, unsigned, signed in CVT_F32_SAT_CASES: 681 for bits, unsigned, signed in CVT_F32_SAT_CASES:
660 problem = compute_test(tools, spirv, "cs_cvt_f32_sat", "1", "dump", expected_words=[unsigned, signed], 682 problem = compute_test(tools, spirv, "cs_cvt_f32_sat", "1", "dump", expected_words=[unsigned, signed],
661 env={"VKC_SGPRS": f"{bits:#010x}"}) 683 env={"VKC_SGPRS": f"{bits:#010x}"})
684 if problem is None or isinstance(problem, Skip):
685 return problem # the device can't run it as recorded (wave size not pinnable): the same for every input
662 if problem: 686 if problem:
663 wrong.append(f"{bits:#010x}: {problem}") 687 wrong.append(f"{bits:#010x}: {problem}")
664 return f"{len(wrong)} of {len(CVT_F32_SAT_CASES)} inputs wrong, first {wrong[0]}" if wrong else "" 688 return f"{len(wrong)} of {len(CVT_F32_SAT_CASES)} inputs wrong, first {wrong[0]}" if wrong else ""
@@ -707,9 +731,10 @@ def subgroup_size(spirv, name):
707 return None 731 return None
708 732
709 733
710def bindless_test(tools, spirv): 734def bindless_test(tools, spirv, pixel="ps_tex"):
711 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).""" 735 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).
712 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_tex")] 736 ps_imgatomic: image atomics in a pixel shader through the set's r32ui storage arrays, checked per texel."""
737 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", pixel)]
713 for path in shaders: 738 for path in shaders:
714 if not os.path.isfile(path): 739 if not os.path.isfile(path):
715 return f"missing {os.path.basename(path)}" 740 return f"missing {os.path.basename(path)}"
@@ -717,6 +742,9 @@ def bindless_test(tools, spirv):
717 if code == UNSUPPORTED: 742 if code == UNSUPPORTED:
718 m = re.search(r"unsupported: .*", out) 743 m = re.search(r"unsupported: .*", out)
719 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") 744 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})")
745 if pixel == "ps_imgatomic":
746 m = re.search(r"ps_imgatomic: (\d+) of \d+ texels wrong.*; (\d+) of \d+ render-target pixels wrong", out)
747 return "" if code == 0 and m and m.group(1) == "0" and m.group(2) == "0" else failure(code, out, 3)
720 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out) 748 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out)
721 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3) 749 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3)
722 750
@@ -1098,6 +1126,46 @@ def wide_pixel_skip(name, out):
1098 return Skip(f"SKIP (this device cannot require a {want}-wide fragment subgroup{seen})") 1126 return Skip(f"SKIP (this device cannot require a {want}-wide fragment subgroup{seen})")
1099 1127
1100 1128
1129def f32(x):
1130 """x rounded to the nearest float32. One double add or multiply of two float32 values, then this, is the exact
1131 IEEE float32 result, so a model built from it matches the GPU bit for bit."""
1132 return struct.unpack("<f", struct.pack("<f", x))[0]
1133
1134
1135def mandelbrot_counts(w):
1136 """ps_mandelbrot.asm's iteration counts over a w x w frame, in the shader's order of float32 operations."""
1137 counts = []
1138 for y in range(w):
1139 cy = f32(f32(3.0 * f32((y + 0.5) / w)) - 1.5)
1140 for x in range(w):
1141 cx = f32(f32(3.0 * f32((x + 0.5) / w)) - 2.25)
1142 zx = zy = 0.0
1143 n = 0
1144 while n < 64:
1145 zx2, zy2 = f32(zx * zx), f32(zy * zy)
1146 if not 4.0 >= f32(zx2 + zy2):
1147 break
1148 xy = f32(zx * zy)
1149 zx, zy = f32(f32(zx2 - zy2) + cx), f32(f32(xy + xy) + cy)
1150 n += 1
1151 counts.append(n)
1152 return counts
1153
1154
1155def mandelbrot_problem(px):
1156 """ps_mandelbrot: channel 3 is the lane's iteration count. A lane that leaves EXEC too early or late, or a loop
1157 that ends on the wrong branch, changes counts; the colour channels are only for looking at the frame."""
1158 w = int(len(px) ** 0.5)
1159 if w * w != len(px):
1160 return f"{len(px)} pixels is not a square frame"
1161 want = mandelbrot_counts(w)
1162 wrong = [(i, p[3], e) for i, (p, e) in enumerate(zip(px, want)) if p[3] != e]
1163 if not wrong:
1164 return ""
1165 i, got, e = wrong[0]
1166 return f"{len(wrong)} of {len(px)} iteration counts differ, e.g. pixel ({i % w}, {i // w}) {got} instead of {e}"
1167
1168
1101def pixel_test(tools, spirv, name): 1169def pixel_test(tools, spirv, name):
1102 path = os.path.join(spirv, name + ".spv") 1170 path = os.path.join(spirv, name + ".spv")
1103 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES): 1171 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES):
@@ -1164,6 +1232,8 @@ def pixel_test(tools, spirv, name):
1164 c = collections.Counter((a, b) for a, b, _, _ in px) 1232 c = collections.Counter((a, b) for a, b, _, _ in px)
1165 fine = c[(8, 1)] and c[(8, 0)] and c[(7, 0)] and set(c) <= {(8, 1), (8, 0), (7, 0)} 1233 fine = c[(8, 1)] and c[(8, 0)] and c[(7, 0)] and set(c) <= {(8, 1), (8, 0), (7, 0)}
1166 return "" if fine else f"(s5, bit) counts {dict(c)}" 1234 return "" if fine else f"(s5, bit) counts {dict(c)}"
1235 if name == "ps_mandelbrot":
1236 return mandelbrot_problem(px)
1167 return "no check written for this shader" 1237 return "no check written for this shader"
1168 1238
1169 1239
@@ -1217,6 +1287,7 @@ def main():
1217 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv))) 1287 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv)))
1218 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv))) 1288 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv)))
1219 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv))) 1289 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv)))
1290 results.append(("cs_tbuffer_store", tbuffer_store_test(tools, spirv)))
1220 for name, groups, want in GLOBAL_OFFSET: 1291 for name, groups, want in GLOBAL_OFFSET:
1221 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want))) 1292 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want)))
1222 results.append(("cs_user_sgprs", compute_test(tools, spirv, "cs_user_sgprs", "1", "dump", 1293 results.append(("cs_user_sgprs", compute_test(tools, spirv, "cs_user_sgprs", "1", "dump",
@@ -1254,6 +1325,7 @@ def main():
1254 results.append((name, texture_constant_test(tools, spirv, name))) 1325 results.append((name, texture_constant_test(tools, spirv, name)))
1255 results.append(("ps_tex", bindless_test(tools, spirv))) 1326 results.append(("ps_tex", bindless_test(tools, spirv)))
1256 results.append(("ps_ssharp", sampler_test(tools, spirv))) 1327 results.append(("ps_ssharp", sampler_test(tools, spirv)))
1328 results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic")))
1257 for name in MIP_TEST_PASSES: 1329 for name in MIP_TEST_PASSES:
1258 results.append((name, texture_mip_test(tools, spirv, name))) 1330 results.append((name, texture_mip_test(tools, spirv, name)))
1259 for name in GRADIENT_TESTS: 1331 for name in GRADIENT_TESTS:
diff --git a/runtime/test/shaders/cs_buf_counter.asm b/runtime/test/shaders/cs_buf_counter.asm
new file mode 100644
index 000000000..9bbe84bea
--- /dev/null
+++ b/runtime/test/shaders/cs_buf_counter.asm
@@ -0,0 +1,40 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x4e554f43 0x3d524554
5; UAV counters (D3D12 CreateUnorderedAccessView with pCounterResource): AppendStructuredBuffer and
6; ConsumeStructuredBuffer as hand-written RDNA2, the way docs/d3d12_vulkan.md section 3.4 describes the contract:
7; the counter is a second, raw 4-byte V# in the upper 16 bytes of the view's descriptor slot, and append and consume
8; are buffer atomics on it. Run: d3d12_buffer_uav_test (a compute PSO found by the SHA-256 of its synthetic FSSM header).
9; The branch skips the 10 dwords of the append path (checked with llvm-mc -show-encoding).
10; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of six UAVs, TGID_X in s6:
11; s0 = mode: 0 append, 1 consume s[4:5] = console VA of the table's first slot (32 bytes a slot)
12; slot 0 (+0x00): V#, structured buffer, stride 8, 256 records; the counter V# in +0x10 (raw, 4 bytes)
13; slot 1 (+0x20): V#, raw buffer, 128 records of 8 bytes (written by consume)
14; g = 64 * group + lane
15; append: i = counter++ (buffer_atomic_add, glc returns the old value); record i = { g, g * 3 + 1 }
16; consume: i = --counter (the old value of buffer_atomic_sub, minus one); out[g] = record i
17s_load_dwordx8 s[8:15], s[4:5], 0x0
18s_load_dwordx4 s[16:19], s[4:5], 0x20
19s_lshl_b32 s7, s6, 6
20s_waitcnt lgkmcnt(0)
21v_add_nc_u32_e32 v1, s7, v0
22v_mov_b32_e32 v2, 1
23s_cmp_eq_u32 s0, 0
24s_cbranch_scc0 10
25buffer_atomic_add v2, off, s[12:15], 0 glc
26s_waitcnt vmcnt(0)
27v_mul_lo_u32 v6, v1, 3
28v_add_nc_u32_e32 v6, 1, v6
29v_mov_b32_e32 v5, v1
30buffer_store_dwordx2 v[5:6], v2, s[8:11], 0 idxen
31s_endpgm
32; consume:
33buffer_atomic_sub v2, off, s[12:15], 0 glc
34s_waitcnt vmcnt(0)
35v_add_nc_u32_e32 v2, -1, v2
36buffer_load_dwordx2 v[5:6], v2, s[8:11], 0 idxen
37s_waitcnt vmcnt(0)
38v_lshlrev_b32_e32 v7, 3, v1
39buffer_store_dwordx2 v[5:6], v7, s[16:19], 0 offen
40s_endpgm
diff --git a/runtime/test/shaders/cs_buf_typed.asm b/runtime/test/shaders/cs_buf_typed.asm
new file mode 100644
index 000000000..b101343e8
--- /dev/null
+++ b/runtime/test/shaders/cs_buf_typed.asm
@@ -0,0 +1,63 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x44505954 0x3d424655
5; Typed buffer UAVs (D3D12 CreateUnorderedAccessView with a Format on a BUFFER view): hand-written RDNA2 the way a
6; translated `RWBuffer<T>` shader reads and writes them. Run: d3d12_buffer_uav_test (a compute PSO found by the
7; SHA-256 of its synthetic FSSM header, as for the other cs_ shaders).
8; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of six UAVs. RSRC2 0x808c =
9; six user SGPRs and TGID_X, so the group index is s6:
10; s0 = seed s1 = multiplier s[4:5] = console VA of the table's first slot (a slot is 32 bytes, a V# in its first 16)
11; slot 0 (+0x00): V#, typed R32_UINT, 240 elements of a 256-element buffer (written, then atomically added to)
12; slot 1 (+0x20): V#, typed R16G16B16A16_FLOAT, 256 elements (written)
13; slot 2 (+0x40): V#, typed R8G8B8A8_UNORM, 256 elements from element 16 of the buffer (written)
14; slot 3 (+0x60): V#, typed R32G32B32A32_UINT, 256 elements (written)
15; slot 4 (+0x80): V#, typed R32_FLOAT, 250 elements of a 256-element buffer (read)
16; slot 5 (+0xa0): V#, typed R32_SINT, 256 elements (written)
17; g = 64 * group + lane, 0..255 (an index past a view's NUM_RECORDS is out of range: a load gives 0, a store or an
18; atomic touches nothing):
19; slot 0: element g = g * mul + seed, then += g
20; slot 1: element g = { f16(g), f16(g + 0.5), f16(-1 - g), f16(0.25) }
21; slot 2: element g = unorm8 { (g & 255) / 255, (255 - (g & 255)) / 255, 0, 1 }
22; slot 3: element g = { g, g ^ 0xffff, g * 7, 0xa5 }
23; slot 5: element g = (int)(2 * input[g]), input[g] = g - 100.5
24s_load_dwordx4 s[8:11], s[4:5], 0x0
25s_load_dwordx4 s[12:15], s[4:5], 0x20
26s_load_dwordx4 s[16:19], s[4:5], 0x40
27s_load_dwordx4 s[20:23], s[4:5], 0x60
28s_load_dwordx4 s[24:27], s[4:5], 0x80
29s_load_dwordx4 s[28:31], s[4:5], 0xa0
30s_lshl_b32 s7, s6, 6
31s_waitcnt lgkmcnt(0)
32v_add_nc_u32_e32 v1, s7, v0
33v_mul_lo_u32 v2, v1, s1
34v_add_nc_u32_e32 v2, s0, v2
35buffer_store_format_x v2, v1, s[8:11], 0 idxen
36v_mov_b32_e32 v3, v1
37buffer_atomic_add v3, v1, s[8:11], 0 idxen
38v_cvt_f32_u32_e32 v4, v1
39v_add_f32_e32 v5, 0.5, v4
40v_sub_f32_e32 v6, -1.0, v4
41v_mov_b32_e32 v7, 0x3e800000
42buffer_store_format_xyzw v[4:7], v1, s[12:15], 0 idxen
43v_and_b32_e32 v8, 255, v1
44v_cvt_f32_ubyte0_e32 v9, v8
45v_mov_b32_e32 v10, 0x3b808081
46v_mul_f32_e32 v11, v9, v10
47v_sub_nc_u32_e32 v12, 255, v8
48v_cvt_f32_ubyte0_e32 v12, v12
49v_mul_f32_e32 v12, v12, v10
50v_mov_b32_e32 v13, 0
51v_mov_b32_e32 v14, 1.0
52buffer_store_format_xyzw v[11:14], v1, s[16:19], 0 idxen
53v_mov_b32_e32 v15, v1
54v_xor_b32_e32 v16, 0xffff, v1
55v_mul_lo_u32 v17, v1, 7
56v_mov_b32_e32 v18, 0xa5
57buffer_store_format_xyzw v[15:18], v1, s[20:23], 0 idxen
58buffer_load_format_x v19, v1, s[24:27], 0 idxen
59s_waitcnt vmcnt(0)
60v_add_f32_e32 v19, v19, v19
61v_cvt_i32_f32_e32 v19, v19
62buffer_store_format_x v19, v1, s[28:31], 0 idxen
63s_endpgm
diff --git a/runtime/test/shaders/cs_lds_b64_cmpst.asm b/runtime/test/shaders/cs_lds_b64_cmpst.asm
new file mode 100644
index 000000000..0998d8576
--- /dev/null
+++ b/runtime/test/shaders/cs_lds_b64_cmpst.asm
@@ -0,0 +1,132 @@
1; GPU test for the two LDS families that docs/design.md lists as not GPU-verified:
2; ds_cmpst_b32 (the non-returning compare-and-store) and the b64 2-address forms
3; (ds_read2_b64 / ds_write2_b64 and their st64 variants).
4;
5; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. The output words are
6; derived from the RDNA2 ISA's 2-address and DS_CMPST_B32 pseudocode:
7;
8; out[0..3] ds_write2_b64 then ds_read2_b64 at base 0x20, offset0:1 offset1:3,
9; writes A at 0x28 and B at 0x38 (unit 8), reads the same two elements:
10; A.lo A.hi B.lo B.hi
11; out[4] ds_read2st64_b64 at base 0x100, offset0:0 offset1:1 (unit 512):
12; XOR of the four dwords seeded at 0x100 and 0x300
13; out[5] ds_write2st64_b64 at base 0x100, offset0:0 offset1:1, then plain
14; ds_read_b32 at 0x100/0x104/0x300/0x304: XOR of the four dwords
15; out[6] ds_read2_b64 v[2:5], v2 at base 0x200 (vdst overlaps vaddr): the
16; second element's low dword, 0xBBBB000B, read before v2 is overwritten
17; out[7] ds_cmpst_b32 hit (mem 0x13572468 -> 0x2468ABCD) XOR the miss case's
18; unchanged word (0x11111111): 0x3579BADC
19;
20; Run: vk_compute_test cs_lds_b64_cmpst.spv 1 dump
21; -> out[0..7] = 0x11110001 0x22220002 0x33330003 0x44440004
22; 0xCCCC000C 0x44440004 0xBBBB000B 0x3579BADC
23; rsrc2: 0x40088
24; group: 32,1,1
25; mattr: +wavefrontsize32,-wavefrontsize64
26v_cmpx_eq_u32_e32 0, v0
27
28; --- ds_write2_b64 / ds_read2_b64, unit 8 bytes ---
29v_mov_b32_e32 v2, 0x20
30v_mov_b32_e32 v4, 0x11110001
31v_mov_b32_e32 v5, 0x22220002
32v_mov_b32_e32 v6, 0x33330003
33v_mov_b32_e32 v7, 0x44440004
34ds_write2_b64 v2, v[4:5], v[6:7] offset0:1 offset1:3
35s_waitcnt lgkmcnt(0)
36ds_read2_b64 v[10:13], v2 offset0:1 offset1:3
37s_waitcnt lgkmcnt(0)
38v_mov_b32_e32 v21, 0
39buffer_store_dword v10, v21, s[0:3], 0 offen
40v_mov_b32_e32 v21, 4
41buffer_store_dword v11, v21, s[0:3], 0 offen
42v_mov_b32_e32 v21, 8
43buffer_store_dword v12, v21, s[0:3], 0 offen
44v_mov_b32_e32 v21, 12
45buffer_store_dword v13, v21, s[0:3], 0 offen
46
47; --- ds_read2st64_b64, unit 512 bytes: seed 0x100 and 0x300 ---
48v_mov_b32_e32 v1, 0x100
49v_mov_b32_e32 v3, 0x55550005
50ds_write_b32 v1, v3
51v_mov_b32_e32 v1, 0x104
52v_mov_b32_e32 v3, 0x66660006
53ds_write_b32 v1, v3
54v_mov_b32_e32 v1, 0x300
55v_mov_b32_e32 v3, 0x77770007
56ds_write_b32 v1, v3
57v_mov_b32_e32 v1, 0x304
58v_mov_b32_e32 v3, 0x88880008
59ds_write_b32 v1, v3
60s_waitcnt lgkmcnt(0)
61v_mov_b32_e32 v2, 0x100
62ds_read2st64_b64 v[10:13], v2 offset0:0 offset1:1
63s_waitcnt lgkmcnt(0)
64v_xor_b32_e32 v14, v10, v11
65v_xor_b32_e32 v14, v14, v12
66v_xor_b32_e32 v14, v14, v13
67v_mov_b32_e32 v21, 16
68buffer_store_dword v14, v21, s[0:3], 0 offen
69
70; --- ds_write2st64_b64, unit 512 bytes: A at 0x100, B at 0x300 ---
71v_mov_b32_e32 v2, 0x100
72ds_write2st64_b64 v2, v[4:5], v[6:7] offset0:0 offset1:1
73s_waitcnt lgkmcnt(0)
74v_mov_b32_e32 v1, 0x100
75ds_read_b32 v10, v1
76v_mov_b32_e32 v1, 0x104
77ds_read_b32 v11, v1
78v_mov_b32_e32 v1, 0x300
79ds_read_b32 v12, v1
80v_mov_b32_e32 v1, 0x304
81ds_read_b32 v13, v1
82s_waitcnt lgkmcnt(0)
83v_xor_b32_e32 v15, v10, v11
84v_xor_b32_e32 v15, v15, v12
85v_xor_b32_e32 v15, v15, v13
86v_mov_b32_e32 v21, 20
87buffer_store_dword v15, v21, s[0:3], 0 offen
88
89; --- ds_read2_b64 with vdst overlapping vaddr: v[2:5] <- base v2 ---
90v_mov_b32_e32 v1, 0x200
91v_mov_b32_e32 v3, 0x99990009
92ds_write_b32 v1, v3
93v_mov_b32_e32 v1, 0x204
94v_mov_b32_e32 v3, 0xAAAA000A
95ds_write_b32 v1, v3
96v_mov_b32_e32 v1, 0x208
97v_mov_b32_e32 v3, 0xBBBB000B
98ds_write_b32 v1, v3
99v_mov_b32_e32 v1, 0x20C
100v_mov_b32_e32 v3, 0xCCCC000C
101ds_write_b32 v1, v3
102s_waitcnt lgkmcnt(0)
103v_mov_b32_e32 v2, 0x200
104ds_read2_b64 v[2:5], v2 offset0:0 offset1:1
105s_waitcnt lgkmcnt(0)
106v_mov_b32_e32 v21, 24
107buffer_store_dword v4, v21, s[0:3], 0 offen
108
109; --- ds_cmpst_b32: hit at 0x400, miss at 0x404 ---
110v_mov_b32_e32 v1, 0x400
111v_mov_b32_e32 v3, 0x13572468
112ds_write_b32 v1, v3
113v_mov_b32_e32 v1, 0x404
114v_mov_b32_e32 v3, 0x11111111
115ds_write_b32 v1, v3
116s_waitcnt lgkmcnt(0)
117v_mov_b32_e32 v1, 0x400
118v_mov_b32_e32 v3, 0x13572468
119v_mov_b32_e32 v4, 0x2468ABCD
120ds_cmpst_b32 v1, v3, v4
121s_waitcnt lgkmcnt(0)
122ds_read_b32 v10, v1
123v_mov_b32_e32 v1, 0x404
124v_mov_b32_e32 v3, 0
125v_mov_b32_e32 v4, 0xFFFFFFFF
126ds_cmpst_b32 v1, v3, v4
127s_waitcnt lgkmcnt(0)
128ds_read_b32 v11, v1
129v_xor_b32_e32 v16, v10, v11
130v_mov_b32_e32 v21, 28
131buffer_store_dword v16, v21, s[0:3], 0 offen
132s_endpgm
diff --git a/runtime/test/shaders/cs_m4_fill.asm b/runtime/test/shaders/cs_m4_fill.asm
new file mode 100644
index 000000000..1af46dac9
--- /dev/null
+++ b/runtime/test/shaders/cs_m4_fill.asm
@@ -0,0 +1,51 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x4c4c4946 0x3d344d5f
5; M4 compute shader 1: fills a structured UAV buffer and a typed UAV image from a raw input buffer, and writes the
6; arguments of the next (indirect) dispatch. Run: d3d12_m4_compute_test (a compute PSO found by the SHA-256 of its
7; synthetic FSSM header, as for the other cs_ shaders).
8; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of five UAVs. RSRC2 0x808c =
9; six user SGPRs and TGID_X, so the group index is s6:
10; s0 = seed s1 = multiplier s2 = group count of the indirect dispatch s3 = unused
11; s[4:5] = console VA of the table's first slot. A slot is 32 bytes: a V# in its first 16 bytes or a T# in all 32.
12; slot 0 (+0x00): V#, structured buffer, stride 16, 256 records (written)
13; slot 1 (+0x20): V#, raw buffer, the arguments of the indirect dispatch (written)
14; slot 2 (+0x40): T#, 16x16 R32_UINT image (written)
15; slot 3 (+0x60): V#, raw buffer, 256 input words (read)
16; slot 4 (+0x80): V#, raw buffer, the second shader's output (not used here)
17; g = 64 * group + lane, 0..255: in = input[g]
18; record g = { in + seed, g * mul, in ^ (g << 8), rotr(in, 13) }
19; image(x = g & 15, y = g >> 4) = in * 3 + x * 0x10001 + y
20; g == 0 also writes the arguments { s2, 1, 1, 0xc0de0001 }
21s_load_dwordx4 s[8:11], s[4:5], 0x0
22s_load_dwordx4 s[12:15], s[4:5], 0x20
23s_load_dwordx8 s[16:23], s[4:5], 0x40
24s_load_dwordx4 s[24:27], s[4:5], 0x60
25s_lshl_b32 s7, s6, 6
26s_waitcnt lgkmcnt(0)
27v_add_nc_u32_e32 v1, s7, v0
28v_lshlrev_b32_e32 v2, 2, v1
29buffer_load_dword v3, v2, s[24:27], 0 offen
30s_waitcnt vmcnt(0)
31v_add_nc_u32_e32 v4, s0, v3
32v_mul_lo_u32 v5, v1, s1
33v_lshlrev_b32_e32 v6, 8, v1
34v_xor_b32_e32 v6, v3, v6
35v_alignbit_b32 v7, v3, v3, 13
36buffer_store_dwordx4 v[4:7], v1, s[8:11], 0 idxen
37v_and_b32_e32 v8, 15, v1
38v_lshrrev_b32_e32 v9, 4, v1
39v_mul_u32_u24_e32 v10, 0x10001, v8
40v_mul_lo_u32 v11, v3, 3
41v_add_nc_u32_e32 v10, v10, v11
42v_add_nc_u32_e32 v10, v10, v9
43image_store v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
44v_cmpx_eq_u32_e32 0, v1
45v_mov_b32_e32 v12, 0
46v_mov_b32_e32 v13, s2
47v_mov_b32_e32 v14, 1
48v_mov_b32_e32 v15, 1
49v_mov_b32_e32 v16, 0xc0de0001
50buffer_store_dwordx4 v[13:16], v12, s[12:15], 0 offen
51s_endpgm
diff --git a/runtime/test/shaders/cs_m4_indirect.asm b/runtime/test/shaders/cs_m4_indirect.asm
new file mode 100644
index 000000000..8a23596bf
--- /dev/null
+++ b/runtime/test/shaders/cs_m4_indirect.asm
@@ -0,0 +1,28 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x44444e49 0x3d344d5f
5; M4 compute shader 2: runs under ExecuteIndirect with the arguments cs_m4_fill wrote ({ groups, 1, 1 }), reads the
6; structured buffer and the image the first dispatch wrote, and writes a raw output buffer. Run:
7; d3d12_m4_compute_test. Same root signature, user data and table as cs_m4_fill (see there):
8; slot 0: structured buffer (read) slot 2: R32_UINT image (read, image_load) slot 4: raw output (written)
9; g = 64 * group + lane; t = image(g & 15, g >> 4); record g = { w0, w1, w2, w3 }
10; out[g] = { (w0 + t) ^ w3, (w2 ^ t) + w1 } at byte offset 8 * g
11s_load_dwordx4 s[8:11], s[4:5], 0x0
12s_load_dwordx8 s[16:23], s[4:5], 0x40
13s_load_dwordx4 s[12:15], s[4:5], 0x80
14s_lshl_b32 s7, s6, 6
15s_waitcnt lgkmcnt(0)
16v_add_nc_u32_e32 v1, s7, v0
17buffer_load_dwordx4 v[4:7], v1, s[8:11], 0 idxen
18v_and_b32_e32 v8, 15, v1
19v_lshrrev_b32_e32 v9, 4, v1
20image_load v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
21s_waitcnt vmcnt(0)
22v_add_nc_u32_e32 v11, v4, v10
23v_xor_b32_e32 v11, v11, v7
24v_xor_b32_e32 v12, v6, v10
25v_add_nc_u32_e32 v12, v12, v5
26v_lshlrev_b32_e32 v13, 3, v1
27buffer_store_dwordx2 v[11:12], v13, s[12:15], 0 offen
28s_endpgm
diff --git a/runtime/test/shaders/cs_tbuffer_store.asm b/runtime/test/shaders/cs_tbuffer_store.asm
new file mode 100644
index 000000000..a6e0e78e5
--- /dev/null
+++ b/runtime/test/shaders/cs_tbuffer_store.asm
@@ -0,0 +1,275 @@
1; tbuffer_store_format_* and its d16 forms. Every expected word was measured by running this body natively on a Radeon
2; 680M (gfx1035, RDNA2) through tools/hw_oracle's kernel wrapper, with s[0:3] set to the V# vk_compute_test passes;
3; wave32 and wave64 gave the same 52 words. One thread runs.
4; - The instruction's format replaces the V#'s, for the encoding, the element size and the bounds check alike. No
5; format modifier means GFX10's default, BUF_FMT_8_UNORM: one byte, its neighbours kept.
6; - A store writes its format's whole element: components the format has but the instruction doesn't give are 0
7; (xy into 16_16_16_16 leaves z = w = 0); components the format doesn't have are dropped (xyzw into 32_32 writes
8; x, y; into 32 only x).
9; - d16 data is two 16-bit values per VGPR, low half first.
10; - Bounds (OOB_SELECT 3): the instruction's element must end inside num_records. With NR 0x298, an xy store of a
11; 16-byte element at 0x290 writes nothing, though a V# that says 32_FLOAT has a 4-byte element; with NR 0x2a1, an
12; 8_UNORM byte at 0x2a0 is written, though the V#'s 16-byte element would not fit.
13; - A V# whose FORMAT is 0 (INVALID) disables the store, though the instruction brings its own format.
14; Store regions 0x200..0x2cf start as 0xa5a50000 | address; out[0..51] are the 13 regions read back, in source order.
15; Run: VKC_OUT_WORDS=192 VKC_DUMP=<file> vk_compute_test cs_tbuffer_store.spv 1 dump; check.py compares words 0..127 of
16; the dump with TBUFFER_STORE_WORDS and 76 untouched 0xeeeeeeee words.
17v_cmpx_eq_u32_e32 0, v0
18; the store regions 0x200..0x2cf hold 0xa5a50000 | their address
19v_mov_b32_e32 v1, 0xa5a50200
20v_mov_b32_e32 v2, 0xa5a50204
21v_mov_b32_e32 v3, 0xa5a50208
22v_mov_b32_e32 v4, 0xa5a5020c
23v_mov_b32_e32 v5, 0x200
24buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
25v_mov_b32_e32 v1, 0xa5a50210
26v_mov_b32_e32 v2, 0xa5a50214
27v_mov_b32_e32 v3, 0xa5a50218
28v_mov_b32_e32 v4, 0xa5a5021c
29v_mov_b32_e32 v5, 0x210
30buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
31v_mov_b32_e32 v1, 0xa5a50220
32v_mov_b32_e32 v2, 0xa5a50224
33v_mov_b32_e32 v3, 0xa5a50228
34v_mov_b32_e32 v4, 0xa5a5022c
35v_mov_b32_e32 v5, 0x220
36buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
37v_mov_b32_e32 v1, 0xa5a50230
38v_mov_b32_e32 v2, 0xa5a50234
39v_mov_b32_e32 v3, 0xa5a50238
40v_mov_b32_e32 v4, 0xa5a5023c
41v_mov_b32_e32 v5, 0x230
42buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
43v_mov_b32_e32 v1, 0xa5a50240
44v_mov_b32_e32 v2, 0xa5a50244
45v_mov_b32_e32 v3, 0xa5a50248
46v_mov_b32_e32 v4, 0xa5a5024c
47v_mov_b32_e32 v5, 0x240
48buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
49v_mov_b32_e32 v1, 0xa5a50250
50v_mov_b32_e32 v2, 0xa5a50254
51v_mov_b32_e32 v3, 0xa5a50258
52v_mov_b32_e32 v4, 0xa5a5025c
53v_mov_b32_e32 v5, 0x250
54buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
55v_mov_b32_e32 v1, 0xa5a50260
56v_mov_b32_e32 v2, 0xa5a50264
57v_mov_b32_e32 v3, 0xa5a50268
58v_mov_b32_e32 v4, 0xa5a5026c
59v_mov_b32_e32 v5, 0x260
60buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
61v_mov_b32_e32 v1, 0xa5a50270
62v_mov_b32_e32 v2, 0xa5a50274
63v_mov_b32_e32 v3, 0xa5a50278
64v_mov_b32_e32 v4, 0xa5a5027c
65v_mov_b32_e32 v5, 0x270
66buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
67v_mov_b32_e32 v1, 0xa5a50280
68v_mov_b32_e32 v2, 0xa5a50284
69v_mov_b32_e32 v3, 0xa5a50288
70v_mov_b32_e32 v4, 0xa5a5028c
71v_mov_b32_e32 v5, 0x280
72buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
73v_mov_b32_e32 v1, 0xa5a50290
74v_mov_b32_e32 v2, 0xa5a50294
75v_mov_b32_e32 v3, 0xa5a50298
76v_mov_b32_e32 v4, 0xa5a5029c
77v_mov_b32_e32 v5, 0x290
78buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
79v_mov_b32_e32 v1, 0xa5a502a0
80v_mov_b32_e32 v2, 0xa5a502a4
81v_mov_b32_e32 v3, 0xa5a502a8
82v_mov_b32_e32 v4, 0xa5a502ac
83v_mov_b32_e32 v5, 0x2a0
84buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
85v_mov_b32_e32 v1, 0xa5a502b0
86v_mov_b32_e32 v2, 0xa5a502b4
87v_mov_b32_e32 v3, 0xa5a502b8
88v_mov_b32_e32 v4, 0xa5a502bc
89v_mov_b32_e32 v5, 0x2b0
90buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
91v_mov_b32_e32 v1, 0xa5a502c0
92v_mov_b32_e32 v2, 0xa5a502c4
93v_mov_b32_e32 v3, 0xa5a502c8
94v_mov_b32_e32 v4, 0xa5a502cc
95v_mov_b32_e32 v5, 0x2c0
96buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
97s_waitcnt_vscnt null, 0x0
98s_mov_b32 s4, s0
99s_mov_b32 s5, s1
100; 0x200: tbuffer_store_format_xyzw, xyzw, 32_32_32_32_FLOAT over a V# that says 32_FLOAT: all four dwords
101v_mov_b32_e32 v20, 0x3f800000
102v_mov_b32_e32 v21, 0x40000000
103v_mov_b32_e32 v22, 0x40400000
104v_mov_b32_e32 v23, 0x40800000
105s_mov_b32 s6, 0xffffffff
106s_mov_b32 s7, 0x31016fac
107v_mov_b32_e32 v5, 0x200
108tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen
109; 0x210: tbuffer_store_format_xy, xy, 16_16_16_16_FLOAT over a V# that says 32_32_32_32_FLOAT: the 8-byte element, z = w = 0
110v_mov_b32_e32 v20, 0x3f800000
111v_mov_b32_e32 v21, 0x40000000
112s_mov_b32 s6, 0xffffffff
113s_mov_b32 s7, 0x3104dfac
114v_mov_b32_e32 v5, 0x210
115tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen
116; 0x220: tbuffer_store_format_xyz, xyz, 8_8_8_8_UINT over a V# that says 32_FLOAT
117v_mov_b32_e32 v20, 0x1
118v_mov_b32_e32 v21, 0x2
119v_mov_b32_e32 v22, 0x3
120s_mov_b32 s6, 0xffffffff
121s_mov_b32 s7, 0x31016fac
122v_mov_b32_e32 v5, 0x220
123tbuffer_store_format_xyz v[20:22], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UINT] offen
124; 0x230: tbuffer_store_format_x, x, no format modifier (GFX10 default 8_UNORM) at byte 1, over a V# that says 32_32_32_32_FLOAT
125v_mov_b32_e32 v20, 0x3f800000
126s_mov_b32 s6, 0xffffffff
127s_mov_b32 s7, 0x3104dfac
128v_mov_b32_e32 v5, 0x231
129tbuffer_store_format_x v20, v5, s[4:7], 0 offen
130; 0x240: tbuffer_store_format_x, x, 16_FLOAT at byte 2 (the high half)
131v_mov_b32_e32 v20, 0x40000000
132s_mov_b32 s6, 0xffffffff
133s_mov_b32 s7, 0x31016fac
134v_mov_b32_e32 v5, 0x242
135tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_16_FLOAT] offen
136; 0x250: tbuffer_store_format_xyzw, xyzw, 2_10_10_10_UNORM (1.0, 0.0, 0.25, 1.0)
137v_mov_b32_e32 v20, 0x3f800000
138v_mov_b32_e32 v21, 0x0
139v_mov_b32_e32 v22, 0x3e800000
140v_mov_b32_e32 v23, 0x3f800000
141s_mov_b32 s6, 0xffffffff
142s_mov_b32 s7, 0x31016fac
143v_mov_b32_e32 v5, 0x250
144tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_2_10_10_10_UNORM] offen
145; 0x260: tbuffer_store_format_xyzw, xyzw into 32_32_FLOAT: only x, y
146v_mov_b32_e32 v20, 0x3f800000
147v_mov_b32_e32 v21, 0x40000000
148v_mov_b32_e32 v22, 0x40400000
149v_mov_b32_e32 v23, 0x40800000
150s_mov_b32 s6, 0xffffffff
151s_mov_b32 s7, 0x3104dfac
152v_mov_b32_e32 v5, 0x260
153tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen
154; 0x270: tbuffer_store_format_d16_xy, d16_xy, 16_16_FLOAT (packed 1.0, 2.0)
155v_mov_b32_e32 v20, 0x40003c00
156s_mov_b32 s6, 0xffffffff
157s_mov_b32 s7, 0x3104dfac
158v_mov_b32_e32 v5, 0x270
159tbuffer_store_format_d16_xy v20, v5, s[4:7], 0 format:[BUF_FMT_16_16_FLOAT] offen
160; 0x280: tbuffer_store_format_d16_xyzw, d16_xyzw, 8_8_8_8_UNORM (packed 1.0, 0.5, 0.0, 1.0)
161v_mov_b32_e32 v20, 0x38003c00
162v_mov_b32_e32 v21, 0x3c000000
163s_mov_b32 s6, 0xffffffff
164s_mov_b32 s7, 0x31016fac
165v_mov_b32_e32 v5, 0x280
166tbuffer_store_format_d16_xyzw v[20:21], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen
167; 0x290: tbuffer_store_format_xy, xy, 32_32_32_32_FLOAT, NR 0x298 over a V# that says 32_FLOAT: x, y end at 0x298, the element at 0x2a0
168v_mov_b32_e32 v20, 0x3f800000
169v_mov_b32_e32 v21, 0x40000000
170s_mov_b32 s6, 0x298
171s_mov_b32 s7, 0x31016fac
172v_mov_b32_e32 v5, 0x290
173tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen
174; 0x2a0: tbuffer_store_format_x, x, 8_UNORM, NR 0x2a1 over a V# that says 32_32_32_32_FLOAT: the byte fits, the V#'s element would not
175v_mov_b32_e32 v20, 0x3f800000
176s_mov_b32 s6, 0x2a1
177s_mov_b32 s7, 0x3104dfac
178v_mov_b32_e32 v5, 0x2a0
179tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_8_UNORM] offen
180; 0x2b0: tbuffer_store_format_xyzw, xyzw into 32_FLOAT (one channel) over a V# that says 32_32_32_32_FLOAT: only x
181v_mov_b32_e32 v20, 0x3f800000
182v_mov_b32_e32 v21, 0x40000000
183v_mov_b32_e32 v22, 0x40400000
184v_mov_b32_e32 v23, 0x40800000
185s_mov_b32 s6, 0xffffffff
186s_mov_b32 s7, 0x3104dfac
187v_mov_b32_e32 v5, 0x2b0
188tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_FLOAT] offen
189; 0x2c0: tbuffer_store_format_xy, xy, 32_32_FLOAT over a V# whose FORMAT is 0 (INVALID): nothing
190v_mov_b32_e32 v20, 0x3f800000
191v_mov_b32_e32 v21, 0x40000000
192s_mov_b32 s6, 0xffffffff
193s_mov_b32 s7, 0x31000fac
194v_mov_b32_e32 v5, 0x2c0
195tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen
196s_waitcnt_vscnt null, 0x0
197; out[0..3]: the 16 bytes at 0x200
198v_mov_b32_e32 v5, 0x200
199buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
200s_waitcnt vmcnt(0)
201v_mov_b32_e32 v6, 0x0
202buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
203; out[4..7]: the 16 bytes at 0x210
204v_mov_b32_e32 v5, 0x210
205buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
206s_waitcnt vmcnt(0)
207v_mov_b32_e32 v6, 0x10
208buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
209; out[8..11]: the 16 bytes at 0x220
210v_mov_b32_e32 v5, 0x220
211buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
212s_waitcnt vmcnt(0)
213v_mov_b32_e32 v6, 0x20
214buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
215; out[12..15]: the 16 bytes at 0x230
216v_mov_b32_e32 v5, 0x230
217buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
218s_waitcnt vmcnt(0)
219v_mov_b32_e32 v6, 0x30
220buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
221; out[16..19]: the 16 bytes at 0x240
222v_mov_b32_e32 v5, 0x240
223buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
224s_waitcnt vmcnt(0)
225v_mov_b32_e32 v6, 0x40
226buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
227; out[20..23]: the 16 bytes at 0x250
228v_mov_b32_e32 v5, 0x250
229buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
230s_waitcnt vmcnt(0)
231v_mov_b32_e32 v6, 0x50
232buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
233; out[24..27]: the 16 bytes at 0x260
234v_mov_b32_e32 v5, 0x260
235buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
236s_waitcnt vmcnt(0)
237v_mov_b32_e32 v6, 0x60
238buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
239; out[28..31]: the 16 bytes at 0x270
240v_mov_b32_e32 v5, 0x270
241buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
242s_waitcnt vmcnt(0)
243v_mov_b32_e32 v6, 0x70
244buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
245; out[32..35]: the 16 bytes at 0x280
246v_mov_b32_e32 v5, 0x280
247buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
248s_waitcnt vmcnt(0)
249v_mov_b32_e32 v6, 0x80
250buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
251; out[36..39]: the 16 bytes at 0x290
252v_mov_b32_e32 v5, 0x290
253buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
254s_waitcnt vmcnt(0)
255v_mov_b32_e32 v6, 0x90
256buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
257; out[40..43]: the 16 bytes at 0x2a0
258v_mov_b32_e32 v5, 0x2a0
259buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
260s_waitcnt vmcnt(0)
261v_mov_b32_e32 v6, 0xa0
262buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
263; out[44..47]: the 16 bytes at 0x2b0
264v_mov_b32_e32 v5, 0x2b0
265buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
266s_waitcnt vmcnt(0)
267v_mov_b32_e32 v6, 0xb0
268buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
269; out[48..51]: the 16 bytes at 0x2c0
270v_mov_b32_e32 v5, 0x2c0
271buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
272s_waitcnt vmcnt(0)
273v_mov_b32_e32 v6, 0xc0
274buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
275s_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_mandelbrot.asm b/runtime/test/shaders/ps_mandelbrot.asm
new file mode 100644
index 000000000..98c70f6cc
--- /dev/null
+++ b/runtime/test/shaders/ps_mandelbrot.asm
@@ -0,0 +1,46 @@
1; Mandelbrot set: a divergent backward loop with EXEC masking. Each lane iterates z = z^2 + c until |z|^2 > 4 or
2; 64 iterations, with c from attr0.xy (u, v 0..1 over the image) mapped to [-2.25, 0.75] x [-1.5, 1.5]. A lane that
3; escapes drops out of EXEC (s_and_b32 exec_lo, exec_lo, vcc_lo); s_cbranch_execz leaves the loop once every lane has
4; escaped, else the uniform counter s10 ends it after 64 rounds. EXEC is restored from s20 before the export.
5; Only v_mul/v_add/v_sub (no FMA), so a float32 model on the CPU gives the same counts.
6; Branch offsets are dwords from the next instruction: execz +9 forward to the restore, scc1 -15 back to the loop top.
7; Run: vk_harness vs_ids.spv ps_mandelbrot.spv out.raw
8; -> mrt0 = (sqrt(t), t*t, 4t(1-t), iteration count as raw bits) with t = count / 64
9v_interp_p1_f32_e32 v2, v0, attr0.x
10v_interp_p2_f32_e32 v2, v1, attr0.x
11v_interp_p1_f32_e32 v3, v0, attr0.y
12v_interp_p2_f32_e32 v3, v1, attr0.y
13v_mul_f32_e32 v4, 0x40400000, v2
14v_add_f32_e32 v4, 0xc0100000, v4
15v_mul_f32_e32 v5, 0x40400000, v3
16v_add_f32_e32 v5, 0xbfc00000, v5
17v_mov_b32_e32 v6, 0
18v_mov_b32_e32 v7, 0
19v_mov_b32_e32 v8, 0
20s_mov_b32 s10, 0
21s_mov_b32 s20, exec_lo
22v_mul_f32_e32 v9, v6, v6
23v_mul_f32_e32 v10, v7, v7
24v_add_f32_e32 v11, v9, v10
25v_cmp_ge_f32_e32 vcc_lo, 4.0, v11
26s_and_b32 exec_lo, exec_lo, vcc_lo
27s_cbranch_execz 9
28v_sub_f32_e32 v12, v9, v10
29v_mul_f32_e32 v13, v6, v7
30v_add_f32_e32 v13, v13, v13
31v_add_f32_e32 v6, v12, v4
32v_add_f32_e32 v7, v13, v5
33v_add_nc_u32_e32 v8, 1, v8
34s_add_u32 s10, s10, 1
35s_cmp_lt_u32 s10, 64
36s_cbranch_scc1 -15
37s_mov_b32 exec_lo, s20
38v_cvt_f32_u32_e32 v14, v8
39v_mul_f32_e32 v14, 0x3c800000, v14
40v_sqrt_f32_e32 v15, v14
41v_mul_f32_e32 v16, v14, v14
42v_sub_f32_e32 v17, 1.0, v14
43v_mul_f32_e32 v17, v14, v17
44v_mul_f32_e32 v17, 4.0, v17
45exp mrt0 v15, v16, v17, v8 done vm
46s_endpgm
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/vs_w64_a_skip.asm b/runtime/test/shaders/vs_w64_a_skip.asm
new file mode 100644
index 000000000..dac0d885e
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_a_skip.asm
@@ -0,0 +1,45 @@
1; TEST-251 (SHADER-10 tier A, vertex stage): the skip regions and the loop of ps_w64_a_skip in a wave64 vertex shader,
2; without its whole-quad mask (vertex quads are lanes, not pixels). Vertex v (v0 = vertex index) has x = v & 63 and
3; y = v >> 6, so every word is a function of v and not of the lane the vertex landed on. It stores (r0, r1, r2, r3)
4; to its record at heap 0x1000 + 16 * v through the V# in s[0:3].
5; (1) a skip region behind s_cbranch_execz: only lanes with x % 4 == 1 run it. r0 = x % 4 == 1 ? 7 * y + x : 1000 + x.
6; (2) r1 = x % 4 == 1 (the VCC of (1), per lane).
7; (3) s_cbranch_vccz over a region that narrows EXEC to that VCC. r2 = 2000 + y + (y % 4 == 2 ? 9 : 0).
8; (4) a loop closed by s_cbranch_execnz, no scalar state carried. r3 = x % 4 + 1.
9; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
10; vs_w64_a_skip.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: equal records, and equal
11; to the expected words.
12; mattr: +wavefrontsize64,-wavefrontsize32
13v_and_b32_e32 v2, 63, v0
14v_lshrrev_b32_e32 v3, 6, v0
15s_mov_b64 s[10:11], exec
16v_add_nc_u32_e32 v6, 0x3e8, v2
17v_and_b32_e32 v4, 3, v2
18v_cmp_eq_u32_e32 vcc, 1, v4
19v_cndmask_b32_e64 v7, 0, 1, vcc
20s_and_saveexec_b64 s[12:13], vcc
21s_cbranch_execz 2
22v_mul_u32_u24_e32 v6, 7, v3
23v_add_nc_u32_e32 v6, v6, v2
24s_or_b64 exec, exec, s[12:13]
25v_and_b32_e32 v5, 3, v3
26v_add_nc_u32_e32 v8, 0x7d0, v3
27v_cmp_eq_u32_e32 vcc, 2, v5
28s_cbranch_vccz 3
29s_and_saveexec_b64 s[16:17], vcc
30v_add_nc_u32_e32 v8, 9, v8
31s_or_b64 exec, exec, s[16:17]
32v_add_nc_u32_e32 v10, 1, v4
33v_mov_b32_e32 v9, 0
34v_add_nc_u32_e32 v9, 1, v9
35v_cmp_lt_u32_e32 vcc, v9, v10
36s_and_b64 exec, exec, vcc
37s_cbranch_execnz -4
38s_mov_b64 exec, s[10:11]
39v_lshlrev_b32_e32 v12, 4, v0
40v_add_nc_u32_e32 v12, 0x1000, v12
41buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
42v_mov_b32_e32 v5, 0
43exp pos0 v5, v5, v5, v5 done
44exp param0 v5, v5, v5, v5
45s_endpgm
diff --git a/runtime/test/shaders/vs_w64_b_ballot_atomic.asm b/runtime/test/shaders/vs_w64_b_ballot_atomic.asm
new file mode 100644
index 000000000..f718c25f8
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_b_ballot_atomic.asm
@@ -0,0 +1,42 @@
1; TEST-251 (SHADER-10 tier B, vertex stage): the wave-aggregated atomic of ps_w64_b_ballot_atomic in a wave64 vertex
2; shader. Vertex v (v0 = vertex index) has x = v & 63; vertices with x % 4 == 1 are the "wanted" lanes. EXEC = the
3; wanted lanes; n = s_bcnt1_i32_b64 exec; rank = v_mbcnt_lo/hi of EXEC; the lane of rank 0 does buffer_atomic_add of n
4; to the counter at heap offset 0 and gets the old value back; v_readfirstlane broadcasts it as the base; every wanted
5; vertex stores v + 1 at heap offset 0x100 + 4 * (base + rank). Whatever the wave size and the packing, every wanted
6; vertex gets a slot of its own and the counter ends at the number of wanted vertices (240 of 960); which vertex gets
7; which slot depends on the packing, so the slots are compared as a set. Its record at heap 0x1000 + 16 * v holds
8; (x % 4 == 1, 0, 0, 0).
9; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
10; vs_w64_b_ballot_atomic.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32.
11; mattr: +wavefrontsize64,-wavefrontsize32
12v_and_b32_e32 v2, 63, v0
13v_and_b32_e32 v4, 3, v2
14s_mov_b64 s[10:11], exec
15v_cmp_eq_u32_e32 vcc, 1, v4
16v_cndmask_b32_e64 v6, 0, 1, vcc
17s_and_saveexec_b64 s[12:13], vcc
18s_bcnt1_i32_b64 s6, exec
19v_mbcnt_lo_u32_b32 v10, exec_lo, 0
20v_mbcnt_hi_u32_b32 v10, exec_hi, v10
21v_cmp_eq_u32_e32 vcc, 0, v10
22s_and_saveexec_b64 s[14:15], vcc
23v_mov_b32_e32 v11, s6
24v_mov_b32_e32 v13, 0
25buffer_atomic_add v11, v13, s[0:3], 0 offen glc
26s_or_b64 exec, exec, s[14:15]
27v_readfirstlane_b32 s7, v11
28v_add_nc_u32_e32 v13, s7, v10
29v_lshlrev_b32_e32 v13, 2, v13
30v_add_nc_u32_e32 v14, 1, v0
31buffer_store_dword v14, v13, s[0:3], 0 offen offset:256
32s_mov_b64 exec, s[10:11]
33v_mov_b32_e32 v7, 0
34v_mov_b32_e32 v8, 0
35v_mov_b32_e32 v9, 0
36v_lshlrev_b32_e32 v12, 4, v0
37v_add_nc_u32_e32 v12, 0x1000, v12
38buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
39v_mov_b32_e32 v5, 0
40exp pos0 v5, v5, v5, v5 done
41exp param0 v5, v5, v5, v5
42s_endpgm
diff --git a/runtime/test/shaders/vs_w64_b_readlane_uniform.asm b/runtime/test/shaders/vs_w64_b_readlane_uniform.asm
new file mode 100644
index 000000000..0fb85008d
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_b_readlane_uniform.asm
@@ -0,0 +1,33 @@
1; TEST-251 (SHADER-10 tier B, vertex stage): v_readfirstlane and v_readlane (lanes 40 and 63) of wave-uniform VGPRs
2; in a wave64 vertex shader, the vertex twin of ps_w64_b_readfirstlane and ps_w64_b_readlane_uniform. s4 is a user
3; SGPR (VKH_SGPRS sets it to 123), copied to a VGPR and read back; so is the constant 77. Every lane holds the same
4; value, so the scalar does not depend on which lane is read, on the wave size or on how many vertices a wave got.
5; Vertex v (v0 = vertex index) has x = v & 63. r0 = x + 123 (readfirstlane), r1 = 123 + 77 (readlane 40 and 63),
6; r2 = x + 123 (readlane 40), r3 = 77 * 2 + 123 (readfirstlane), stored to its record at heap 0x1000 + 16 * v
7; through the V# in s[0:3].
8; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000,123 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
9; vs_w64_b_readlane_uniform.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: equal, and
10; equal to the expected words.
11; mattr: +wavefrontsize64,-wavefrontsize32
12v_and_b32_e32 v2, 63, v0
13s_mov_b64 s[10:11], exec
14v_mov_b32_e32 v5, s4
15v_mov_b32_e32 v4, 77
16v_readfirstlane_b32 s20, v5
17v_add_nc_u32_e32 v6, s20, v2
18v_readlane_b32 s21, v5, 40
19v_readlane_b32 s22, v4, 63
20s_add_u32 s23, s21, s22
21v_mov_b32_e32 v7, s23
22v_add_nc_u32_e32 v8, s21, v2
23v_readfirstlane_b32 s24, v4
24s_lshl_b32 s24, s24, 1
25s_add_u32 s24, s24, s20
26v_mov_b32_e32 v9, s24
27v_lshlrev_b32_e32 v12, 4, v0
28v_add_nc_u32_e32 v12, 0x1000, v12
29buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
30v_mov_b32_e32 v5, 0
31exp pos0 v5, v5, v5, v5 done
32exp param0 v5, v5, v5, v5
33s_endpgm
diff --git a/runtime/test/shaders/vs_w64_b_waterfall.asm b/runtime/test/shaders/vs_w64_b_waterfall.asm
new file mode 100644
index 000000000..814259842
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_b_waterfall.asm
@@ -0,0 +1,35 @@
1; TEST-251 (SHADER-10 tier B, vertex stage): the waterfall loop of ps_w64_b_waterfall in a wave64 vertex shader.
2; Vertex v (v0 = vertex index) has x = v & 63, y = v >> 6 and the key a = x % 4 + 4 * (y % 4). The loop takes
3; v_readfirstlane of the key, runs the lanes holding it (v_cmp_eq, s_and_saveexec), retires them (s_xor exec) and
4; repeats while lanes are left (s_cbranch_execnz); the scalar is used only inside the body. It runs once per distinct
5; key of the wave or of the 32-lane subgroup, and every vertex ends with r0 = 17 * a + x, r1 = a, r2 = r3 = 0, stored
6; to its record at heap 0x1000 + 16 * v through the V# in s[0:3].
7; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
8; vs_w64_b_waterfall.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: equal, and equal to
9; the expected words.
10; mattr: +wavefrontsize64,-wavefrontsize32
11v_and_b32_e32 v2, 63, v0
12v_lshrrev_b32_e32 v3, 6, v0
13v_and_b32_e32 v4, 3, v2
14v_and_b32_e32 v5, 3, v3
15v_lshl_add_u32 v4, v5, 2, v4
16v_mov_b32_e32 v6, 0
17s_mov_b64 s[10:11], exec
18v_readfirstlane_b32 s20, v4
19v_cmp_eq_u32_e32 vcc, s20, v4
20s_and_saveexec_b64 s[12:13], vcc
21s_mul_i32 s21, s20, 17
22v_add_nc_u32_e32 v6, s21, v2
23s_xor_b64 exec, exec, s[12:13]
24s_cbranch_execnz -7
25s_mov_b64 exec, s[10:11]
26v_mov_b32_e32 v7, v4
27v_mov_b32_e32 v8, 0
28v_mov_b32_e32 v9, 0
29v_lshlrev_b32_e32 v12, 4, v0
30v_add_nc_u32_e32 v12, 0x1000, v12
31buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
32v_mov_b32_e32 v5, 0
33exp pos0 v5, v5, v5, v5 done
34exp param0 v5, v5, v5, v5
35s_endpgm
diff --git a/runtime/test/shaders/vs_w64_c_bcnt_export.asm b/runtime/test/shaders/vs_w64_c_bcnt_export.asm
new file mode 100644
index 000000000..84dd9bf53
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_c_bcnt_export.asm
@@ -0,0 +1,23 @@
1; TEST-251 (SHADER-10 tier C, vertex stage): a lane count used as data. Vertex v (v0 = vertex index) has x = v & 63;
2; s_bcnt1_i32_b64 counts the lanes of its wave with x % 4 == 1, which depends on the wave size and on how many
3; vertices the driver put in the wave. r0 = that count (partition dependent), r1 = x % 4 == 1, r2 = r3 = 0, stored to
4; its record at heap 0x1000 + 16 * v through the V# in s[0:3].
5; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
6; vs_w64_c_bcnt_export.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: r1 equal, r0
7; differs.
8; mattr: +wavefrontsize64,-wavefrontsize32
9v_and_b32_e32 v2, 63, v0
10v_and_b32_e32 v4, 3, v2
11v_cmp_eq_u32_e32 vcc, 1, v4
12s_bcnt1_i32_b64 s6, vcc
13v_mov_b32_e32 v6, s6
14v_cndmask_b32_e64 v7, 0, 1, vcc
15v_mov_b32_e32 v8, 0
16v_mov_b32_e32 v9, 0
17v_lshlrev_b32_e32 v12, 4, v0
18v_add_nc_u32_e32 v12, 0x1000, v12
19buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
20v_mov_b32_e32 v5, 0
21exp pos0 v5, v5, v5, v5 done
22exp param0 v5, v5, v5, v5
23s_endpgm
diff --git a/runtime/test/shaders/vs_w64_c_lane_id.asm b/runtime/test/shaders/vs_w64_c_lane_id.asm
new file mode 100644
index 000000000..c69850333
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_c_lane_id.asm
@@ -0,0 +1,21 @@
1; TEST-251 (SHADER-10 tier C, vertex stage): the raw lane number (v_mbcnt_lo/hi of -1) used as data. Each vertex v
2; (v0 = vertex index) stores (lane id, lane id & 31, v, 0) to its record at heap 0x1000 + 16 * v through the V# in
3; s[0:3]. In a wave64 VS some vertices get lanes 32..63; in a wave32 VS none do, so r0 and r1 depend on how the driver
4; packed the vertices into waves and r2 does not. w64_graphics.py also uses it as its probe: the largest r0 shows the
5; wave size the driver picked (63 by default on RADV GFX12, 31 with RADV_PERFTEST=gewave32).
6; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
7; vs_w64_c_lane_id.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32 (the triangles have
8; zero area, so nothing is drawn).
9; mattr: +wavefrontsize64,-wavefrontsize32
10v_mbcnt_lo_u32_b32 v6, -1, 0
11v_mbcnt_hi_u32_b32 v6, -1, v6
12v_and_b32_e32 v7, 31, v6
13v_mov_b32_e32 v8, v0
14v_mov_b32_e32 v9, 0
15v_lshlrev_b32_e32 v12, 4, v0
16v_add_nc_u32_e32 v12, 0x1000, v12
17buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
18v_mov_b32_e32 v5, 0
19exp pos0 v5, v5, v5, v5 done
20exp param0 v5, v5, v5, v5
21s_endpgm
diff --git a/runtime/test/shaders/vs_w64_c_readlane.asm b/runtime/test/shaders/vs_w64_c_readlane.asm
new file mode 100644
index 000000000..d472b1ee5
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_c_readlane.asm
@@ -0,0 +1,23 @@
1; TEST-251 (SHADER-10 tier C, vertex stage): v_readlane of a varying value (the vertex index) at lanes 40 and 7. In a
2; wave64 VS every lane gets the vertex in hardware lane 40 (or 7) of its wave; in a wave32 VS lane 40 wraps or is
3; undefined and lane 7 is the vertex of another wave. Vertex v (v0 = vertex index): r0 = readlane 40, r1 = v,
4; r2 = readlane 7 (both partition dependent), r3 = 0, stored to its record at heap 0x1000 + 16 * v through the V# in
5; s[0:3].
6; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
7; vs_w64_c_readlane.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: r1 equal, r2 differs.
8; mattr: +wavefrontsize64,-wavefrontsize32
9s_mov_b64 s[10:11], exec
10v_mov_b32_e32 v4, v0
11v_readlane_b32 s6, v4, 40
12v_readlane_b32 s7, v4, 7
13v_mov_b32_e32 v6, s6
14v_mov_b32_e32 v7, v4
15v_mov_b32_e32 v8, s7
16v_mov_b32_e32 v9, 0
17v_lshlrev_b32_e32 v12, 4, v0
18v_add_nc_u32_e32 v12, 0x1000, v12
19buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
20v_mov_b32_e32 v5, 0
21exp pos0 v5, v5, v5, v5 done
22exp param0 v5, v5, v5, v5
23s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index 91424af99..6e281d4b4 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -1,5 +1,5 @@
1"""SHADER-10 GPU checks: wave64 pixel shaders on 32-lane subgroups (docs/design.md, "Wave64 graphics: partition 1"""SHADER-10 GPU checks: wave64 pixel and vertex shaders on 32-lane subgroups (docs/design.md, "Wave64 graphics:
2invariance"). 2partition invariance").
3 3
4 python3 -I runtime/test/shaders/w64_graphics.py <build dir with spirv/> [tools dir] [name ...] 4 python3 -I runtime/test/shaders/w64_graphics.py <build dir with spirv/> [tools dir] [name ...]
5 5
@@ -16,6 +16,13 @@ A device that can require only one size (NVIDIA: 32 only) cannot run the compari
16checked against the derived words (tiers A, B), the tier C check is skipped, and two environment variables let a 16checked against the derived words (tiers A, B), the tier C check is skipped, and two environment variables let a
17second device stand in for the missing size: W64G_SAVE_REF=<dir> stores each 64-lane run of a device that can require 17second device stand in for the missing size: W64G_SAVE_REF=<dir> stores each 64-lane run of a device that can require
18it, and W64G_REF=<dir> compares every run of the other device with those files (equal for A and B, different for C). 18it, and W64G_REF=<dir> compares every run of the other device with those files (equal for A and B, different for C).
19
20The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a vertex subgroup size, so the two sizes
21come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+).
22Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id
23doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs
2462 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run is a repacking, not the two halves of
25the 64-lane waves: a stricter test of tiers A and B, which key every word on the vertex index.
19""" 26"""
20import os 27import os
21import struct 28import struct
@@ -106,6 +113,25 @@ def _c_execz_sgpr(i):
106 return (7 if _on(i) else None, _on(i), 0, 0) # r0 = s5: 7 only where the active side ran 113 return (7 if _on(i) else None, _on(i), 0, 0) # r0 = s5: 7 only where the active side ran
107 114
108 115
116# vs_w64_* fixtures: i is the vertex index, x = i % 64 and y = i // 64 as for a pixel.
117def _vs_a_skip(i):
118 x, y = _x(i), _y(i)
119 return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 == 1), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1)
120
121
122def _vs_b_readlane_uniform(i):
123 return (_x(i) + 123, 200, _x(i) + 123, 277)
124
125
126def _vs_c_lane_id(i):
127 return (None, None, i, 0) # r0, r1 = the lane the vertex got
128
129
130VS_ENV = {"VKH_SGPRS": "0,0,65536,0x30000000", "VKH_HEAP": "0=0"}
131VS_VERTICES = 960 # 15 rows of 64 vertices: several waves at either size, and partial ones
132VS_RECORDS = 0x1000 // 4 # heap word of vertex 0's record (4 words per vertex); below it, the atomic's counter and slots
133
134
109# name -> (tier, expected words per pixel (None = not fixed), environment of the draw) 135# name -> (tier, expected words per pixel (None = not fixed), environment of the draw)
110FIXTURES = { 136FIXTURES = {
111 "ps_w64_a_skip": ("A", _a_skip, {}), 137 "ps_w64_a_skip": ("A", _a_skip, {}),
@@ -122,13 +148,70 @@ FIXTURES = {
122 "ps_w64_c_vote_else": ("C", _c_vote_else, {}), 148 "ps_w64_c_vote_else": ("C", _c_vote_else, {}),
123 "ps_w64_c_scc_vote": ("C", _c_scc_vote, {}), 149 "ps_w64_c_scc_vote": ("C", _c_scc_vote, {}),
124 "ps_w64_c_execz_sgpr": ("C", _c_execz_sgpr, {}), 150 "ps_w64_c_execz_sgpr": ("C", _c_execz_sgpr, {}),
151 "vs_w64_a_skip": ("A", _vs_a_skip, VS_ENV),
152 "vs_w64_b_waterfall": ("B", _b_waterfall, VS_ENV),
153 "vs_w64_b_readlane_uniform": ("B", _vs_b_readlane_uniform, dict(VS_ENV, VKH_SGPRS=VS_ENV["VKH_SGPRS"] + ",123")),
154 "vs_w64_b_ballot_atomic": ("B", _b_ballot, VS_ENV),
155 "vs_w64_c_bcnt_export": ("C", _c_bcnt, VS_ENV),
156 "vs_w64_c_readlane": ("C", _c_readlane, VS_ENV),
157 "vs_w64_c_lane_id": ("C", _vs_c_lane_id, VS_ENV),
125} 158}
126 159
160VS_PROBE = "vs_w64_c_lane_id"
161_vs_applied = {}
162
163
164def _radv_perftest(size):
165 """RADV_PERFTEST for a vertex draw at `size`. Vulkan cannot require a vertex subgroup size (requiredSubgroupSizeStages
166 has no VERTEX on RADV or on the AMD driver), but RADV runs the VS/GS (NGG) stage as wave32 with gewave32 and as
167 wave64 without it on GFX10+. Other drivers ignore the variable; the probe then finds no change."""
168 flags = [f for f in os.environ.get("RADV_PERFTEST", "").split(",") if f and f != "gewave32"]
169 return ",".join(flags + ["gewave32"] * (size == 32))
170
171
172def _vs_wave_size(tools, spirv, size, tmp):
173 """Whether a vertex draw at `size` really ran at that wave size: the largest lane id of VS_PROBE is 32..63 in a
174 wave64 VS and below 32 in a wave32 one. Size 32 also needs size 64 to work, so that the two draws differ."""
175 if size not in _vs_applied:
176 def top(s):
177 words = _draw_vs(tools, spirv, VS_PROBE, s, tmp)[0]
178 return None if words is None else max(w[0] for w in words)
179 lane64, lane32 = top(64), top(32)
180 _vs_applied[64] = lane64 is not None and 32 <= lane64 < 64
181 _vs_applied[32] = _vs_applied[64] and lane32 is not None and lane32 < 32
182 return _vs_applied[size]
183
184
185def _draw_vs(tools, spirv, name, size, tmp):
186 """(records, heap) of one vertex draw at `size` (None: as the environment says), or (None, message)."""
187 env = dict(os.environ, **FIXTURES[name][2])
188 if size:
189 env["RADV_PERFTEST"] = _radv_perftest(size)
190 raw, heap = Path(tmp) / f"{name}.{size}.raw", Path(tmp) / f"{name}.{size}.heap"
191 env.update(VKH_VERTICES=str(VS_VERTICES), VKH_HEAP_DUMP=str(heap))
192 env.pop("VKH_SUBGROUP_SIZE", None)
193 # The triangles have zero area, so no pixel is drawn and any fragment shader does.
194 cmd = [os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, name + ".spv"),
195 os.path.join(spirv, "ps_w64_a_skip.spv"), str(raw)]
196 r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120)
197 out = r.stdout + r.stderr
198 if r.returncode == UNSUPPORTED:
199 return None, "unsupported: " + out.strip().splitlines()[-1]
200 if r.returncode or not heap.is_file():
201 return None, f"exit {r.returncode}: {' | '.join(out.strip().splitlines()[-3:])}"
202 words = list(struct.unpack("<%dI" % (65536 // 4), heap.read_bytes()))
203 return [tuple(words[VS_RECORDS + 4 * v:VS_RECORDS + 4 * v + 4]) for v in range(VS_VERTICES)], words
204
127 205
128def draw(tools, spirv, name, size, tmp): 206def draw(tools, spirv, name, size, tmp):
129 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size 207 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size
130 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message.""" 208 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message."""
131 tier, expect, extra = FIXTURES[name] 209 tier, expect, extra = FIXTURES[name]
210 if name.startswith("vs_"):
211 words, heap = _draw_vs(tools, spirv, name, size, tmp)
212 if words is None:
213 return None, heap, None
214 return words, heap, _vs_wave_size(tools, spirv, size, tmp) if size else None
132 env = dict(os.environ, **extra) 215 env = dict(os.environ, **extra)
133 env.pop("VKH_SUBGROUP_SIZE", None) 216 env.pop("VKH_SUBGROUP_SIZE", None)
134 if size: 217 if size:
@@ -168,15 +251,16 @@ def expected_problem(name, words, heap):
168 if wrong: 251 if wrong:
169 i, w, want = wrong[0] 252 i, w, want = wrong[0]
170 return f"{len(wrong)} of {len(words)} pixels differ from the derived words, first ({_x(i)},{_y(i)}): got {w}, want {want}" 253 return f"{len(wrong)} of {len(words)} pixels differ from the derived words, first ({_x(i)},{_y(i)}): got {w}, want {want}"
171 if name == "ps_w64_b_ballot_atomic": 254 if name.endswith("_b_ballot_atomic"):
172 want = sorted(_y(i) * W + _x(i) + 1 for i in range(W * H) if _x(i) % 4 == 1) 255 want = sorted(i + 1 for i in range(len(words)) if _x(i) % 4 == 1)
173 n = len(want) 256 n = len(want)
174 if heap[0] != n: 257 if heap[0] != n:
175 return f"counter is {heap[0]}, want {n}" 258 return f"counter is {heap[0]}, want {n}"
176 slots = heap[64:64 + n] 259 slots = heap[64:64 + n]
177 if sorted(slots) != want: 260 if sorted(slots) != want:
178 return f"slot words are not the {n} wanted pixel numbers once each ({len(set(slots))} distinct)" 261 return f"slot words are not the {n} wanted pixel numbers once each ({len(set(slots))} distinct)"
179 if any(heap[64 + n:]) or any(heap[1:64]): 262 end = VS_RECORDS if name.startswith("vs_") else len(heap) # the vertex records follow the slots
263 if any(heap[64 + n:end]) or any(heap[1:64]):
180 return "words outside the counter and the slots were written" 264 return "words outside the counter and the slots were written"
181 return "" 265 return ""
182 266
@@ -184,7 +268,7 @@ def expected_problem(name, words, heap):
184def comparable(name, words, heap): 268def comparable(name, words, heap):
185 """What two draws of the same fixture must share when the shader is partition invariant.""" 269 """What two draws of the same fixture must share when the shader is partition invariant."""
186 stable = [tuple(0 if g is None else v for g, v in zip(FIXTURES[name][1](i), w)) for i, w in enumerate(words)] 270 stable = [tuple(0 if g is None else v for g, v in zip(FIXTURES[name][1](i), w)) for i, w in enumerate(words)]
187 if name == "ps_w64_b_ballot_atomic": 271 if name.endswith("_b_ballot_atomic"):
188 return stable, sorted(heap[64:64 + heap[0]]), heap[0] 272 return stable, sorted(heap[64:64 + heap[0]]), heap[0]
189 return stable, None, None 273 return stable, None, None
190 274
@@ -240,7 +324,7 @@ def check(tools, spirv, name):
240 if not partition_dependent(name, ref_words, words): 324 if not partition_dependent(name, ref_words, words):
241 return "tier C but the run equals the 64-lane reference: the detector is wrong" 325 return "tier C but the run equals the 64-lane reference: the detector is wrong"
242 compared = True 326 compared = True
243 elif name != "ps_w64_b_ballot_atomic" and comparable(name, ref_words, None) != comparable(name, words, None): 327 elif not name.endswith("_b_ballot_atomic") and comparable(name, ref_words, None) != comparable(name, words, None):
244 return "the run differs from the 64-lane reference" 328 return "the run differs from the 64-lane reference"
245 if tier == "C" and not compared: 329 if tier == "C" and not compared:
246 return Skip("SKIP (tier C needs a device that can require both 64 and 32, or W64G_REF)") 330 return Skip("SKIP (tier C needs a device that can require both 64 and 32, or W64G_REF)")
diff --git a/runtime/test/typeless_rtv_test.cpp b/runtime/test/typeless_rtv_test.cpp
index be935c123..87fa46acb 100644
--- a/runtime/test/typeless_rtv_test.cpp
+++ b/runtime/test/typeless_rtv_test.cpp
@@ -262,9 +262,27 @@ int main() {
262 EXPECT(rejects(wrong, {1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, ReplayResult::invalid_subresource)); 262 EXPECT(rejects(wrong, {1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, ReplayResult::invalid_subresource));
263 wrong = binding; wrong.volume = true; 263 wrong = binding; wrong.volume = true;
264 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb})); 264 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb}));
265 wrong = binding; wrong.samples = 4; 265 {
266 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_uint})); 266 auto msaa = binding; msaa.samples = 4;
267 checks += 8; 267 for (const auto [format, expected] : formats) {
268 CommandList ms_list;
269 EXPECT(ms_list.clear_render_target({1, 0, 0, 1, format}, color) && ms_list.close());
270 EXPECT(run(ms_list, msaa, vk) == ReplayResult::success);
271 const bool attachment = format != ColorViewFormat::rgba8_unorm;
272 EXPECT(image_clears == (attachment ? 0u : 1u) && attachment_clears == (attachment ? 1u : 0u));
273 EXPECT(!attachment || (requested_format == expected && rendering_layers == 1));
274 ++checks;
275 }
276 auto msaa_layered = layered; msaa_layered.mip_levels = 1; msaa_layered.samples = 4;
277 CommandList ms_layer_list;
278 EXPECT(ms_layer_list.clear_render_target({1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, color) &&
279 ms_layer_list.close());
280 EXPECT(run(ms_layer_list, msaa_layered, vk) == ReplayResult::success);
281 EXPECT(attachment_clears == 1 && requested_format == VK_FORMAT_R8G8B8A8_SRGB);
282 EXPECT(requested_range.baseArrayLayer == 1 && requested_range.layerCount == 2 && rendering_layers == 2);
283 ++checks;
284 }
285 checks += 7;
268 CommandList list; 286 CommandList list;
269 EXPECT(list.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_srgb}, color) && list.close()); 287 EXPECT(list.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_srgb}, color) && list.close());
270 auto unavailable = vk; unavailable.begin_rendering = nullptr; 288 auto unavailable = vk; unavailable.begin_rendering = nullptr;
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..041f6f648 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.
@@ -727,7 +902,7 @@ int main(int argc, char** argv) {
727 // 2. Without its key the T# is a miss: index 0, the fallback image of zeros. 902 // 2. Without its key the T# is a miss: index 0, the fallback image of zeros.
728 const float zeros[4] = {0, 0, 0, 0}; 903 const float zeros[4] = {0, 0, 0, 0};
729 EXPECT(set.erase_key(tsharp) && !set.erase_key(tsharp)); 904 EXPECT(set.erase_key(tsharp) && !set.erase_key(tsharp));
730 EXPECT(set.flush_needs_idle()); // erasing may move the keys behind it; nothing is running here 905 EXPECT(!set.flush_needs_idle()); // erasing empties its slot only: the three keys ahead stay where they are
731 EXPECT(flush() && !set.flush_needs_idle()); 906 EXPECT(flush() && !set.flush_needs_idle());
732 CHECK(draw()); 907 CHECK(draw());
733 compare("2 miss", zeros); 908 compare("2 miss", zeros);
diff --git a/runtime/test/vk_descriptor_bench.cpp b/runtime/test/vk_descriptor_bench.cpp
index 07be76abb..5f5e721c8 100644
--- a/runtime/test/vk_descriptor_bench.cpp
+++ b/runtime/test/vk_descriptor_bench.cpp
@@ -7,7 +7,7 @@
7// dispatch against CPU DescriptorTable::lookup() before timing. 7// dispatch against CPU DescriptorTable::lookup() before timing.
8// 8//
9// Usage: 9// Usage:
10// vk_descriptor_bench [--sizes 1000,10000,100000] [--groups 4096] [--iters 64] [--reps 25] [--warmup 5] 10// vk_descriptor_bench [--sizes 1000,10000,100000] [--groups 4096] [--iters 64] [--reps 25] [--warmup 5] [--warmup-ms 300]
11// [--memory all|device|host|rebar] [--device N] [--list-devices] [--quick] [--csv] 11// [--memory all|device|host|rebar] [--device N] [--list-devices] [--quick] [--csv]
12// [--dump-spv PREFIX] [--self-test] 12// [--dump-spv PREFIX] [--self-test]
13// LEONIDA_VK_VALIDATION=1 enables VK_LAYER_KHRONOS_validation; any validation error fails the run. 13// LEONIDA_VK_VALIDATION=1 enables VK_LAYER_KHRONOS_validation; any validation error fails the run.
@@ -969,6 +969,7 @@ struct Options {
969 std::uint32_t reps = 25u; 969 std::uint32_t reps = 25u;
970 std::uint32_t warmup = 5u; 970 std::uint32_t warmup = 5u;
971 double max_dispatch_ms = 120.0; 971 double max_dispatch_ms = 120.0;
972 double warmup_ms = 300.0; // keep running the timed dispatch until this much time has passed (0 = off)
972 std::optional<std::uint32_t> device_index; 973 std::optional<std::uint32_t> device_index;
973 MemoryFilter mem_filter = MemoryFilter::All; 974 MemoryFilter mem_filter = MemoryFilter::All;
974 bool list_devices = false; 975 bool list_devices = false;
@@ -985,6 +986,8 @@ void print_usage() {
985 " --iters N lookups per invocation per dispatch (default: 64)\n" 986 " --iters N lookups per invocation per dispatch (default: 64)\n"
986 " --reps N timed repetitions per scenario (default: 25)\n" 987 " --reps N timed repetitions per scenario (default: 25)\n"
987 " --warmup N warmup dispatches before timing (default: 5)\n" 988 " --warmup N warmup dispatches before timing (default: 5)\n"
989 " --warmup-ms F then keep dispatching until F ms have passed, so the GPU clocks are up before the\n"
990 " first timed run, 0=off (default: 300; --quick turns it off)\n"
988 " --max-dispatch-ms F auto-scale slow dispatches to avoid OS TDR, 0=off (default: 120)\n" 991 " --max-dispatch-ms F auto-scale slow dispatches to avoid OS TDR, 0=off (default: 120)\n"
989 " --memory MODE all|device|host|rebar (default: all)\n" 992 " --memory MODE all|device|host|rebar (default: all)\n"
990 " --device N select physical device index from --list-devices\n" 993 " --device N select physical device index from --list-devices\n"
@@ -1031,6 +1034,7 @@ bool parse_args(int argc, const char* const* argv, Options& opt, bool& show_help
1031 opt.groups = 16u; 1034 opt.groups = 16u;
1032 opt.iters = 4u; 1035 opt.iters = 4u;
1033 opt.warmup = 1u; 1036 opt.warmup = 1u;
1037 opt.warmup_ms = 0.0;
1034 opt.reps = 3u; 1038 opt.reps = 3u;
1035 } else if (arg == "--groups") { 1039 } else if (arg == "--groups") {
1036 const char* v = nullptr; 1040 const char* v = nullptr;
@@ -1051,6 +1055,13 @@ bool parse_args(int argc, const char* const* argv, Options& opt, bool& show_help
1051 const double val = std::strtod(v, &end); 1055 const double val = std::strtod(v, &end);
1052 if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false; 1056 if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false;
1053 opt.max_dispatch_ms = val; 1057 opt.max_dispatch_ms = val;
1058 } else if (arg == "--warmup-ms") {
1059 const char* v = nullptr;
1060 if (!need_val(v)) return false;
1061 char* end = nullptr;
1062 const double val = std::strtod(v, &end);
1063 if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false;
1064 opt.warmup_ms = val;
1054 } else if (arg == "--device") { 1065 } else if (arg == "--device") {
1055 const char* v = nullptr; 1066 const char* v = nullptr;
1056 std::uint32_t idx = 0u; 1067 std::uint32_t idx = 0u;
@@ -1164,6 +1175,19 @@ int run_self_test() {
1164 return 1; 1175 return 1;
1165 } 1176 }
1166 1177
1178 {
1179 const char* const ok_args[] = {"vk_descriptor_bench", "--warmup-ms", "0"};
1180 const char* const bad_args[] = {"vk_descriptor_bench", "--warmup-ms", "-1"};
1181 const char* const quick_args[] = {"vk_descriptor_bench", "--quick"};
1182 Options o_ok, o_bad, o_quick, o_default;
1183 bool h = false;
1184 if (o_default.warmup_ms != 300.0 || !parse_args(3, ok_args, o_ok, h) || o_ok.warmup_ms != 0.0 ||
1185 parse_args(3, bad_args, o_bad, h) || !parse_args(2, quick_args, o_quick, h) || o_quick.warmup_ms != 0.0) {
1186 std::fprintf(stderr, "self-test: --warmup-ms parsing or its default is wrong\n");
1187 return 1;
1188 }
1189 }
1190
1167 const struct { 1191 const struct {
1168 const char* name; 1192 const char* name;
1169 ShaderKind kind; 1193 ShaderKind kind;
@@ -2134,6 +2158,22 @@ int main(int argc, char** argv) {
2134 } 2158 }
2135 } 2159 }
2136 2160
2161 // A handful of dispatches is not enough to bring the clocks up on every GPU: with --warmup 5 an idle
2162 // RX 7600 measured the first placement ~1.8x slower than with --warmup 200, and the RTX 4050 ~1.3x
2163 // (TEST-277). Keep running the command that is about to be timed for --warmup-ms.
2164 if (opt.warmup_ms > 0.0) {
2165 const auto w0 = std::chrono::steady_clock::now();
2166 for (;;) {
2167 if (!submit_and_wait(bench_cmd)) {
2168 cleanup_all(keys_buf, map_buf);
2169 return 1;
2170 }
2171 const double spent =
2172 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - w0).count();
2173 if (spent >= opt.warmup_ms) break;
2174 }
2175 }
2176
2137 std::vector<double> samples_ms; 2177 std::vector<double> samples_ms;
2138 samples_ms.reserve(eff_reps); 2178 samples_ms.reserve(eff_reps);
2139 for (std::uint32_t r = 0; r < eff_reps; ++r) { 2179 for (std::uint32_t r = 0; r < eff_reps; ++r) {
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index f7f86fa51..360a20fa7 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -240,6 +240,17 @@ int main(int argc, char** argv) {
240 return 2; 240 return 2;
241 } 241 }
242 } 242 }
243 // Translated shaders declare a 144-byte push-constant block (user SGPRs, heap base, code base; see VKH_SGPRS /
244 // VKH_HEAP); --mesh-compute modules and their vertex shaders add the output address (152 bytes). A device with
245 // fewer bytes (128, the Vulkan minimum, as on some Intel Arc drivers and AMD's Windows driver for RDNA2 iGPUs)
246 // cannot take that range: declaring it anyway is invalid, and there a shader reading past the limit crashed or
247 // hung the device. 77, as vk_texture_test and vk_bindless_test: a device limit, not a wrong result (D3D-14).
248 const uint32_t pc_bytes = mesh_compute ? 152u : 144u;
249 if (props.limits.maxPushConstantsSize < pc_bytes) {
250 std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", pc_bytes,
251 props.limits.maxPushConstantsSize);
252 return 77;
253 }
243 // VKH_MESH=1: the first shader is a mesh shader (VK_EXT_mesh_shader), drawn with vkCmdDrawMeshTasksEXT(1,1,1). 254 // VKH_MESH=1: the first shader is a mesh shader (VK_EXT_mesh_shader), drawn with vkCmdDrawMeshTasksEXT(1,1,1).
244 const bool mesh = !mesh_compute && (group_readback || std::getenv("VKH_MESH") != nullptr); 255 const bool mesh = !mesh_compute && (group_readback || std::getenv("VKH_MESH") != nullptr);
245 VkPhysicalDeviceMeshShaderFeaturesEXT meshf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; 256 VkPhysicalDeviceMeshShaderFeaturesEXT meshf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
@@ -454,12 +465,11 @@ int main(int argc, char** argv) {
454 VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; 465 VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF;
455 VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; 466 VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
456 cb.attachmentCount = 1; cb.pAttachments = &cba; 467 cb.attachmentCount = 1; cb.pAttachments = &cba;
457 // Translated shaders declare a 144-byte push-constant block (user SGPRs, heap base, code base; see VKH_SGPRS / 468 // The push-constant block (pc_bytes, checked against the device limit above).
458 // VKH_HEAP); --mesh-compute modules and their vertex shaders add the output address (152 bytes).
459 const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) | 469 const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) |
460 VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0) | 470 VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0) |
461 (mesh_compute ? VK_SHADER_STAGE_COMPUTE_BIT : 0); 471 (mesh_compute ? VK_SHADER_STAGE_COMPUTE_BIT : 0);
462 VkPushConstantRange pcr{pcs, 0, mesh_compute ? 152u : 144u}; 472 VkPushConstantRange pcr{pcs, 0, pc_bytes};
463 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 473 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
464 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 474 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
465 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); 475 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
@@ -564,7 +574,6 @@ int main(int argc, char** argv) {
564 std::memcpy(pc, shifts, sizeof(shifts)); 574 std::memcpy(pc, shifts, sizeof(shifts));
565 } 575 }
566 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants")); 576 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants"));
567 const uint32_t pc_bytes = mesh_compute ? 152u : 144u;
568 if (mesh_compute) { 577 if (mesh_compute) {
569 // The mesh shader as compute, then make its stores visible to the vertex shader's reads. 578 // The mesh shader as compute, then make its stores visible to the vertex shader's reads.
570 LOADD(vkCmdDispatch); LOADD(vkCmdPipelineBarrier); 579 LOADD(vkCmdDispatch); LOADD(vkCmdPipelineBarrier);
@@ -591,7 +600,11 @@ int main(int argc, char** argv) {
591 } 600 }
592 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); 601 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
593 push(cmd, pl, pcs, 0, pc_bytes, pc); 602 push(cmd, pl, pcs, 0, pc_bytes, pc);
594 if (mesh_compute) 603 // VKH_VERTICES=<n>: draw n vertices instead of one triangle, so a vertex shader fills whole waves (TEST-251).
604 const char* vertices_env = std::getenv("VKH_VERTICES");
605 if (const unsigned vertices = vertices_env ? unsigned(std::strtoul(vertices_env, nullptr, 10)) : 0; vertices && !mesh)
606 vkCmdDraw(cmd, vertices, 1, 0, 0);
607 else if (mesh_compute)
595 vkCmdDraw(cmd, uint32_t(mesh_groups * mesh_prims * 3), 1, 0, 0); 608 vkCmdDraw(cmd, uint32_t(mesh_groups * mesh_prims * 3), 1, 0, 0);
596 else if (mesh) 609 else if (mesh)
597 reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]); 610 reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]);
diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp
index cc9372feb..2a510d33a 100644
--- a/runtime/test/vk_overlapping_occlusion_test.cpp
+++ b/runtime/test/vk_overlapping_occlusion_test.cpp
@@ -135,13 +135,14 @@ struct Draws {
135 std::vector<std::uint32_t> extents; 135 std::vector<std::uint32_t> extents;
136 std::size_t next = 0; 136 std::size_t next = 0;
137 bool overflow = false; 137 bool overflow = false;
138 bool every = false; // --bisect: one 1x1 draw before every end, no schedule 138 bool every = false; // --bisect: one 1x1 draw before every end, no schedule
139 bool no_draw = false; // --bisect --no-draw: no draws at all, every query stays empty
139}; 140};
140Draws* draws = nullptr; 141Draws* draws = nullptr;
141 142
142VKAPI_ATTR void VKAPI_CALL end_query_with_draw(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t index) { 143VKAPI_ATTR void VKAPI_CALL end_query_with_draw(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t index) {
143 if (draws->every) { 144 if (draws->every) {
144 draws->fixture.draw(cb, 1); 145 if (!draws->no_draw) draws->fixture.draw(cb, 1);
145 } else if (draws->next == draws->extents.size()) { 146 } else if (draws->next == draws->extents.size()) {
146 draws->overflow = true; 147 draws->overflow = true;
147 } else if (const auto extent = draws->extents[draws->next++]) { 148 } else if (const auto extent = draws->extents[draws->next++]) {
@@ -159,9 +160,13 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device_proc(VkDevice device, const
159// submission is waited for before the next, so the last "running" line before a hang or a lost device names the 160// submission is waited for before the next, so the last "running" line before a hang or a lost device names the
160// pattern. --gated queues them all behind one semaphore the CPU signals afterwards, as the full test does. Named 161// pattern. --gated queues them all behind one semaphore the CPU signals afterwards, as the full test does. Named
161// phases run only those, in the order below. Only completion is checked, not values. 162// phases run only those, in the order below. Only completion is checked, not values.
163// Two switches separate the draw from the resolve: --no-draw leaves every query empty (no rendering scope inside
164// it), --no-resolve records the queries but never copies or sums their results.
162struct Bisect { 165struct Bisect {
163 bool enabled = false; 166 bool enabled = false;
164 bool gated = false; 167 bool gated = false;
168 bool no_draw = false;
169 bool no_resolve = false;
165 std::vector<std::string> phases; 170 std::vector<std::string> phases;
166 bool wants(const char* name) const { 171 bool wants(const char* name) const {
167 return phases.empty() || std::find(phases.begin(), phases.end(), name) != phases.end(); 172 return phases.empty() || std::find(phases.begin(), phases.end(), name) != phases.end();
@@ -184,8 +189,9 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
184 schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1); 189 schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1);
185 // The statistics lists below: a split query (two segments), two unsplit references and a second split query. 190 // The statistics lists below: a split query (two segments), two unsplit references and a second split query.
186 if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {3, 5, 3, 5, 3, 5}); 191 if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {3, 5, 3, 5, 3, 5});
187 schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0}); 192 schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1});
188 schedule.every = bisect.enabled; 193 schedule.every = bisect.enabled;
194 schedule.no_draw = bisect.no_draw;
189 draws = &schedule; 195 draws = &schedule;
190 VulkanContext context(get_device_proc, d.device, true, d.conditional_rendering); 196 VulkanContext context(get_device_proc, d.device, true, d.conditional_rendering);
191 EXPECT(context.loaded()); 197 EXPECT(context.loaded());
@@ -236,30 +242,37 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
236 if (!bisect.wants(name)) return nullptr; 242 if (!bisect.wants(name)) return nullptr;
237 return &lists.emplace_back(name, CommandList{}).second; 243 return &lists.emplace_back(name, CommandList{}).second;
238 }; 244 };
245 const auto resolve = [&](CommandList* l, const ResolveQueries& r) {
246 return bisect.no_resolve || l->resolve_queries(r);
247 };
239 if (auto* l = add("crossing")) { // two queries of one heap overlap; resolve while one is active 248 if (auto* l = add("crossing")) { // two queries of one heap overlap; resolve while one is active
240 EXPECT(l->begin_query({a, occ, 0}) && l->begin_query({a, occ, 1}) && l->end_query({a, occ, 0})); 249 EXPECT(l->begin_query({a, occ, 0}) && l->begin_query({a, occ, 1}) && l->end_query({a, occ, 0}));
241 EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1})); 250 EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1}));
242 EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 24})); 251 EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 24}));
252 }
253 if (auto* l = add("active")) { // a resolve inside one active query, without an overlap
254 EXPECT(l->begin_query({a, occ, 0}) && l->end_query({a, occ, 0}) && l->begin_query({a, occ, 3}));
255 EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 128}) && l->end_query({a, occ, 3}));
243 } 256 }
244 if (auto* l = add("nested")) { // the same index in two heaps, one inside the other 257 if (auto* l = add("nested")) { // the same index in two heaps, one inside the other
245 EXPECT(l->begin_query({a, occ, 2}) && l->begin_query({b, occ, 2})); 258 EXPECT(l->begin_query({a, occ, 2}) && l->begin_query({b, occ, 2}));
246 EXPECT(l->end_query({b, occ, 2}) && l->end_query({a, occ, 2})); 259 EXPECT(l->end_query({b, occ, 2}) && l->end_query({a, occ, 2}));
247 EXPECT(l->resolve_queries({a, occ, 2, 1, dst_id, 40}) && l->resolve_queries({b, occ, 2, 1, dst_id, 48})); 260 EXPECT(resolve(l, {a, occ, 2, 1, dst_id, 40}) && resolve(l, {b, occ, 2, 1, dst_id, 48}));
248 } 261 }
249 if (auto* l = add("unwritten")) { // a query never begun: zero fill 262 if (auto* l = add("unwritten")) { // a query never begun: zero fill
250 EXPECT(l->resolve_queries({b, occ, 0, 1, dst_id, 56})); 263 EXPECT(resolve(l, {b, occ, 0, 1, dst_id, 56}));
251 } 264 }
252 if (auto* l = add("binary")) { // the binary-occlusion compute resolve 265 if (auto* l = add("binary")) { // the binary-occlusion compute resolve
253 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); 266 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3}));
254 EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 64})); 267 EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64}));
255 } 268 }
256 if (d.conditional_rendering) { 269 if (d.conditional_rendering) {
257 if (auto* l = add("predicated")) { // both compute resolves under a false predicate 270 if (auto* l = add("predicated")) { // both compute resolves under a false predicate
258 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); 271 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3}));
259 EXPECT(l->set_predication({predicate_id, 0, d3d12_predication::equal_zero})); 272 EXPECT(l->set_predication({predicate_id, 0, d3d12_predication::equal_zero}));
260 EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 64})); 273 EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64}));
261 EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 72})); 274 EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 72}));
262 EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 80})); 275 EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 80}));
263 EXPECT(copy_control.record(*l)); 276 EXPECT(copy_control.record(*l));
264 } 277 }
265 } 278 }
@@ -267,14 +280,24 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
267 EXPECT(l->begin_query({a, occ, 3})); 280 EXPECT(l->begin_query({a, occ, 3}));
268 for (std::uint32_t i = 0; i < bursts; ++i) EXPECT(l->begin_query({b, occ, 0}) && l->end_query({b, occ, 0})); 281 for (std::uint32_t i = 0; i < bursts; ++i) EXPECT(l->begin_query({b, occ, 0}) && l->end_query({b, occ, 0}));
269 EXPECT(l->end_query({a, occ, 3})); 282 EXPECT(l->end_query({a, occ, 3}));
270 EXPECT(l->resolve_queries({a, occ, 3, 1, dst_id, 88}) && l->resolve_queries({b, occ, 0, 1, dst_id, 96})); 283 EXPECT(resolve(l, {a, occ, 3, 1, dst_id, 88}) && resolve(l, {b, occ, 0, 1, dst_id, 96}));
271 } 284 }
272 if (auto* l = add("replace")) { // every heap query begun and ended again, then resolved 285 if (auto* l = add("replace")) { // every heap query begun and ended again, then resolved
273 for (const auto& [heap, index] : {std::pair{a, 0u}, std::pair{a, 1u}, std::pair{a, 2u}, std::pair{b, 2u}}) 286 for (const auto& [heap, index] : {std::pair{a, 0u}, std::pair{a, 1u}, std::pair{a, 2u}, std::pair{b, 2u}})
274 EXPECT(l->begin_query({heap, occ, index}) && l->end_query({heap, occ, index})); 287 EXPECT(l->begin_query({heap, occ, index}) && l->end_query({heap, occ, index}));
275 EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 112})); 288 EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 112}));
276 } 289 }
277 EXPECT(!lists.empty()); 290 EXPECT(!lists.empty());
291 std::printf("bisect:%s%s%s\n", bisect.gated ? " gated" : " ungated", bisect.no_draw ? " no-draw" : " draws",
292 bisect.no_resolve ? " no-resolve" : " resolves");
293 // After a TDR, AMD's Windows driver lets vkQueueWaitIdle succeed (#1540); every timeline semaphore then reads
294 // UINT64_MAX, so the gate's value is checked as well as what the context has seen.
295 const auto get_value = d.fn<PFN_vkGetSemaphoreCounterValue>("vkGetSemaphoreCounterValue");
296 const auto lost = [&] {
297 std::uint64_t value = 0;
298 return context.is_device_lost() || get_value(d.device, gate.semaphore(), &value) != VK_SUCCESS ||
299 value == UINT64_MAX;
300 };
278 if (bisect.gated) queue.wait(gate.semaphore(), 1); 301 if (bisect.gated) queue.wait(gate.semaphore(), 1);
279 for (auto& [name, list] : lists) { 302 for (auto& [name, list] : lists) {
280 EXPECT(list.close()); 303 EXPECT(list.close());
@@ -286,15 +309,15 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
286 std::printf("%s: execute returned %d\n", name, int(result)); 309 std::printf("%s: execute returned %d\n", name, int(result));
287 return 1; 310 return 1;
288 } 311 }
289 if (!bisect.gated && !queue.idle()) { 312 if (!bisect.gated && (!queue.idle() || lost())) {
290 std::printf("%s: vkQueueWaitIdle failed (device lost?)\n", name); 313 std::printf("%s: device lost\n", name);
291 return 1; 314 return 1;
292 } 315 }
293 } 316 }
294 if (bisect.gated) { 317 if (bisect.gated) {
295 EXPECT(gate.signal(1)); 318 EXPECT(gate.signal(1));
296 if (!queue.idle()) { 319 if (!queue.idle() || lost()) {
297 std::printf("gated: vkQueueWaitIdle failed (device lost?)\n"); 320 std::printf("gated: device lost\n");
298 return 1; 321 return 1;
299 } 322 }
300 } 323 }
@@ -414,13 +437,22 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
414 EXPECT(replace.close()); 437 EXPECT(replace.close());
415 const CommandList* fourth[] = {&replace}; 438 const CommandList* fourth[] = {&replace};
416 EXPECT(queue.execute(fourth) == ReplayResult::success); 439 EXPECT(queue.execute(fourth) == ReplayResult::success);
440
441 // A resolve inside one active query, with no overlap.
442 CommandList single;
443 EXPECT(single.begin_query({a, occ, 3}));
444 EXPECT(single.resolve_queries({a, occ, 0, 1, dst_id, 128}));
445 EXPECT(single.end_query({a, occ, 3}));
446 EXPECT(single.close());
447 const CommandList* fifth[] = {&single};
448 EXPECT(queue.execute(fifth) == ReplayResult::success);
417 EXPECT(!schedule.overflow && schedule.next == schedule.extents.size()); 449 EXPECT(!schedule.overflow && schedule.next == schedule.extents.size());
418 EXPECT(gate.signal(1)); 450 EXPECT(gate.signal(1));
419 EXPECT(queue.idle()); 451 EXPECT(queue.idle());
420 452
421 std::map<VkDeviceSize, std::uint64_t> expected = { 453 std::map<VkDeviceSize, std::uint64_t> expected = {
422 {8, 80}, {24, 80}, {32, 20}, {40, 84}, {48, 16}, {56, 0}, {64, 1}, {72, 80}, {80, 1}, 454 {8, 80}, {24, 80}, {32, 20}, {40, 84}, {48, 16}, {56, 0}, {64, 1}, {72, 80}, {80, 1},
423 {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, 455 {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, {128, 4},
424 }; 456 };
425 if (fixture.statistics) expected[0] = 2 * bursts + 1; // the sum resolved inside the statistics query 457 if (fixture.statistics) expected[0] = 2 * bursts + 1; // the sum resolved inside the statistics query
426 for (VkDeviceSize offset = 0; offset < size; offset += 8) { 458 for (VkDeviceSize offset = 0; offset < size; offset += 8) {
@@ -460,7 +492,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
460 static_cast<unsigned long long>(word(0, 0)), static_cast<unsigned long long>(word(0, 7))); 492 static_cast<unsigned long long>(word(0, 0)), static_cast<unsigned long long>(word(0, 7)));
461 } 493 }
462 std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; " 494 std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; "
463 "offsets and gated overwrites exact\n", 495 "resolve inside an active query 4; offsets and gated overwrites exact\n",
464 2 * bursts + 1); 496 2 * bursts + 1);
465 EXPECT(copy_control.check()); 497 EXPECT(copy_control.check());
466 return 0; 498 return 0;
@@ -468,13 +500,15 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
468 500
469} // namespace 501} // namespace
470 502
471// vk_overlapping_occlusion_test <vert.spv> <frag.spv> [--bisect [--gated] [phase...]] 503// vk_overlapping_occlusion_test <vert.spv> <frag.spv> [--bisect [--gated] [--no-draw] [--no-resolve] [phase...]]
472int main(int argc, char** argv) { 504int main(int argc, char** argv) {
473 EXPECT(argc >= 3); 505 EXPECT(argc >= 3);
474 Bisect bisect; 506 Bisect bisect;
475 for (int i = 3; i < argc; ++i) { 507 for (int i = 3; i < argc; ++i) {
476 if (std::strcmp(argv[i], "--bisect") == 0) bisect.enabled = true; 508 if (std::strcmp(argv[i], "--bisect") == 0) bisect.enabled = true;
477 else if (std::strcmp(argv[i], "--gated") == 0) bisect.gated = true; 509 else if (std::strcmp(argv[i], "--gated") == 0) bisect.gated = true;
510 else if (std::strcmp(argv[i], "--no-draw") == 0) bisect.no_draw = true;
511 else if (std::strcmp(argv[i], "--no-resolve") == 0) bisect.no_resolve = true;
478 else bisect.phases.emplace_back(argv[i]); 512 else bisect.phases.emplace_back(argv[i]);
479 } 513 }
480 EXPECT(argc == 3 || bisect.enabled); 514 EXPECT(argc == 3 || bisect.enabled);
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index bdefac894..f11cc37ff 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -22,6 +22,12 @@
22// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and 22// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and
23// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a 23// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a
24// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. 24// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count.
25// --isolate (POSIX only) check in child processes, --isolate-batch modules at a time (default 256), so a module
26// that kills the driver (SIGFPE, SIGSEGV, ...) is recorded as failed ("MODULE CRASH") and the pass
27// goes on. A crashed batch is bisected to the module. Children run one after the other and share
28// cache.bin. Not compatible with --stats.
29// test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL] raises SIGNAL (default SIGFPE)
30// just before the pipeline of a matching module is created. Only for testing --isolate.
25#include "vulkan_loader.h" 31#include "vulkan_loader.h"
26#include "vk_device_pick.h" 32#include "vk_device_pick.h"
27#include "pipeline_cache_file.h" 33#include "pipeline_cache_file.h"
@@ -32,7 +38,10 @@
32#include <cctype> 38#include <cctype>
33#include <charconv> 39#include <charconv>
34#include <chrono> 40#include <chrono>
41#include <cmath>
35#include <condition_variable> 42#include <condition_variable>
43#include <csignal>
44#include <cstdlib>
36#include <cstdio> 45#include <cstdio>
37#include <cstring> 46#include <cstring>
38#include <fstream> 47#include <fstream>
@@ -48,6 +57,13 @@
48#include <utility> 57#include <utility>
49#include <vector> 58#include <vector>
50 59
60#ifndef _WIN32
61#include <sys/wait.h>
62#include <unistd.h>
63#include <cerrno>
64#include <filesystem>
65#endif
66
51static PFN_vkGetInstanceProcAddr gipa; 67static PFN_vkGetInstanceProcAddr gipa;
52 68
53struct VertexInputMeta { 69struct VertexInputMeta {
@@ -275,11 +291,13 @@ struct JsonParser {
275 291
276std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err) { 292std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err) {
277 std::ifstream f(path, std::ios::binary); 293 std::ifstream f(path, std::ios::binary);
278 std::string s((std::istreambuf_iterator<char>(f)), {});
279 std::map<std::string, ShaderMeta> out; 294 std::map<std::string, ShaderMeta> out;
295 if (!f) { err = "cannot open the file"; return out; } // a missing index must not read as an empty corpus
296 std::string s((std::istreambuf_iterator<char>(f)), {});
297 if (f.bad()) { err = "read error"; return out; }
280 JsonParser p{s, 0}; 298 JsonParser p{s, 0};
281 p.ws(); 299 p.ws();
282 if (p.i >= s.size()) return out; 300 if (p.i >= s.size()) { err = "the file is empty (an intentionally empty index is {})"; return out; }
283 if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; } 301 if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; }
284 while (!p.error && p.i < s.size()) { 302 while (!p.error && p.i < s.size()) {
285 if (p.consume('}')) return out; 303 if (p.consume('}')) return out;
@@ -375,6 +393,116 @@ static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) == 1);
375static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT | 393static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT |
376 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0); 394 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0);
377 395
396// Test hook (see the header): VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL].
397struct SimulatedCrash {
398 bool enabled = false;
399 std::string pattern;
400 int sig = SIGFPE;
401};
402
403int signal_from_name(std::string n) {
404 for (char& c : n) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
405 if (n.rfind("SIG", 0) == 0) n = n.substr(3);
406 if (n == "FPE") return SIGFPE;
407 if (n == "SEGV") return SIGSEGV;
408 if (n == "ABRT") return SIGABRT;
409 if (n == "ILL") return SIGILL;
410 if (n == "TERM") return SIGTERM;
411#ifndef _WIN32
412 if (n == "BUS") return SIGBUS;
413 if (n == "KILL") return SIGKILL;
414#endif
415 return 0;
416}
417
418SimulatedCrash read_simulated_crash() {
419 SimulatedCrash c;
420 const char* env = std::getenv("VK_PIPELINE_CHECK_SIMULATE_CRASH");
421 if (!env || !*env) return c;
422 std::string v = env;
423 const size_t colon = v.rfind(':');
424 if (colon != std::string::npos) {
425 if (const int sig = signal_from_name(v.substr(colon + 1))) {
426 c.sig = sig;
427 v.resize(colon);
428 }
429 }
430 c.enabled = true;
431 c.pattern = v;
432 return c;
433}
434
435#ifndef _WIN32
436std::string signal_label(int sig) {
437 switch (sig) {
438 case SIGFPE: return "SIGFPE";
439 case SIGSEGV: return "SIGSEGV";
440 case SIGABRT: return "SIGABRT";
441 case SIGILL: return "SIGILL";
442 case SIGBUS: return "SIGBUS";
443 case SIGKILL: return "SIGKILL";
444 case SIGTERM: return "SIGTERM";
445 default: return "signal " + std::to_string(sig);
446 }
447}
448
449// --isolate: one child run of this executable over [start, start + count) of the stage-filtered list.
450struct ChildRun {
451 bool ready = false; // reached the work loop (ISO-READY): Vulkan and the cache were set up
452 bool done = false; // finished the pass and saved the cache (ISO-DONE)
453 bool cache_ok = true;
454 int sig = 0; // killed by this signal
455 int status = 0; // exit status when it exited
456 std::string out; // its stdout
457};
458
459ChildRun run_child(const std::string& exe, const std::string& dir, const std::vector<std::string>& pass,
460 const std::string& cache_path, size_t start, size_t count) {
461 ChildRun r;
462 std::vector<std::string> args = {exe, dir};
463 if (!cache_path.empty()) args.push_back(cache_path);
464 for (const auto& a : pass) args.push_back(a);
465 args.insert(args.end(), {"--isolate-child", "--start", std::to_string(start), "--count", std::to_string(count)});
466 std::vector<char*> argv;
467 for (auto& a : args) argv.push_back(a.data());
468 argv.push_back(nullptr);
469 int fds[2];
470 if (pipe(fds) != 0) { r.status = 127; return r; }
471 std::fflush(nullptr);
472 const pid_t pid = fork();
473 if (pid < 0) { close(fds[0]); close(fds[1]); r.status = 127; return r; }
474 if (pid == 0) {
475 dup2(fds[1], 1);
476 close(fds[0]); close(fds[1]);
477 execv(exe.c_str(), argv.data());
478 _exit(127);
479 }
480 close(fds[1]);
481 char buf[4096];
482 for (;;) {
483 const ssize_t n = read(fds[0], buf, sizeof buf);
484 if (n > 0) r.out.append(buf, size_t(n));
485 else if (n < 0 && errno == EINTR) continue;
486 else break;
487 }
488 close(fds[0]);
489 int st = 0;
490 while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {}
491 if (WIFSIGNALED(st)) r.sig = WTERMSIG(st);
492 else r.status = WIFEXITED(st) ? WEXITSTATUS(st) : 1;
493 size_t pos = 0;
494 while (pos < r.out.size()) {
495 size_t e = r.out.find('\n', pos);
496 if (e == std::string::npos) e = r.out.size();
497 const std::string_view line(r.out.data() + pos, e - pos);
498 if (line == "ISO-READY") r.ready = true;
499 else if (line.rfind("ISO-DONE", 0) == 0) { r.done = true; r.cache_ok = line.find("cache_ok=0") == std::string_view::npos; }
500 pos = e + 1;
501 }
502 return r;
503}
504#endif
505
378} // namespace 506} // namespace
379 507
380int main(int argc, char** argv) { 508int main(int argc, char** argv) {
@@ -382,7 +510,7 @@ int main(int argc, char** argv) {
382 std::fprintf(stderr, 510 std::fprintf(stderr,
383 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " 511 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] "
384 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] " 512 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] "
385 "[--stats FILE] [--cache-feedback]\n"); 513 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]]\n");
386 return 2; 514 return 2;
387 } 515 }
388 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen 516 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen
@@ -392,40 +520,67 @@ int main(int argc, char** argv) {
392 size_t large_module_bytes = 4 * 1024 * 1024; 520 size_t large_module_bytes = 4 * 1024 * 1024;
393 double slow = 30.0; 521 double slow = 30.0;
394 std::string stage_filter = "all"; 522 std::string stage_filter = "all";
395 bool cache_feedback = false; 523 bool cache_feedback = false, isolate = false, iso_child = false;
524 size_t isolate_batch = 256;
396 for (int i = 2; i < argc; i++) { 525 for (int i = 2; i < argc; i++) {
397 std::string a = argv[i]; 526 std::string a = argv[i];
398 auto val = [&] { return i + 1 < argc ? std::string(argv[++i]) : std::string("0"); }; 527 auto value = [&]() -> std::string_view {
399 if (a == "--jobs") jobs = std::max(1u, uint32_t(std::stoul(val()))); 528 if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {};
400 else if (a == "--start") start = std::stoull(val()); 529 return argv[++i];
401 else if (a == "--count") count = std::stoull(val()); 530 };
402 else if (a == "--slow") slow = std::stod(val()); 531 auto number = [&](auto& dest) {
403 else if (a == "--stage") stage_filter = val(); 532 const auto text = value();
533 if (text.empty()) return false;
534 const auto end = text.data() + text.size();
535 const auto [ptr, ec] = std::from_chars(text.data(), end, dest);
536 return ec == std::errc{} && ptr == end;
537 };
538 bool valid = true;
539 if (a == "--jobs") {
540 valid = number(jobs);
541 jobs = std::max(1u, jobs);
542 } else if (a == "--start") valid = number(start);
543 else if (a == "--count") valid = number(count);
544 else if (a == "--slow") valid = number(slow) && std::isfinite(slow) && slow >= 0.0;
545 else if (a == "--stage") valid = !(stage_filter = value()).empty();
404 else if (a == "--compute-only") stage_filter = "cs"; 546 else if (a == "--compute-only") stage_filter = "cs";
405 else if (a == "--graphics-only") stage_filter = "graphics"; 547 else if (a == "--graphics-only") stage_filter = "graphics";
406 else if (a == "--max-bytes") max_bytes = std::stoull(val()); 548 else if (a == "--max-bytes") valid = number(max_bytes);
407 else if (a == "--large-module-bytes") { 549 else if (a == "--large-module-bytes") valid = number(large_module_bytes);
408 const std::string_view value = i + 1 < argc ? argv[++i] : ""; 550 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; 551 else if (a == "--cache-feedback") cache_feedback = true;
552 else if (a == "--isolate") isolate = true;
553 else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs
554 else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch
555 valid = number(isolate_batch);
556 isolate_batch = std::max<size_t>(1, isolate_batch);
557 }
418 else cache_path = a; 558 else cache_path = a;
559 if (!valid) {
560 std::fprintf(stderr, "%s requires a valid value\n", a.c_str());
561 return 2;
562 }
419 } 563 }
420 if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") { 564 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()); 565 std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str());
422 return 2; 566 return 2;
423 } 567 }
424 568
569 if (isolate && !stats_path.empty()) {
570 std::fprintf(stderr, "--isolate cannot be combined with --stats\n");
571 return 2;
572 }
573#ifdef _WIN32
574 if (isolate) {
575 std::fprintf(stderr, "--isolate is not supported on Windows (it needs fork/waitpid); run without it\n");
576 return 2;
577 }
578#endif
579
425 std::string index_err; 580 std::string index_err;
426 auto index = read_index(dir + "/index.json", index_err); 581 auto index = read_index(dir + "/index.json", index_err);
427 if (!index_err.empty()) { 582 if (!index_err.empty()) {
428 std::fprintf(stderr, "error: malformed JSON in %s/index.json: %s\n", dir.c_str(), index_err.c_str()); 583 std::fprintf(stderr, "error: cannot use %s/index.json: %s\n", dir.c_str(), index_err.c_str());
429 return 2; 584 return 2;
430 } 585 }
431 std::fprintf(stderr, "%zu shaders in index\n", index.size()); 586 std::fprintf(stderr, "%zu shaders in index\n", index.size());
@@ -441,6 +596,115 @@ int main(int argc, char** argv) {
441 const auto [lo, hi] = shader_slice(all.size(), start, count); 596 const auto [lo, hi] = shader_slice(all.size(), start, count);
442 const std::vector<Item> work(all.begin() + lo, all.begin() + hi); 597 const std::vector<Item> work(all.begin() + lo, all.begin() + hi);
443 598
599#ifndef _WIN32
600 if (isolate) {
601 // Parent: no Vulkan here. Run the check in child processes, one at a time, in batches of --isolate-batch
602 // modules. A child that dies mid-batch has its output discarded and the batch is bisected until the one
603 // module that kills the driver is found; the clean sub-runs partition the rest, so nothing is counted twice.
604 std::string exe = argv[0];
605 std::error_code ec;
606 if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string();
607 std::vector<std::string> pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter,
608 "--max-bytes", std::to_string(max_bytes),
609 "--large-module-bytes", std::to_string(large_module_bytes)};
610 if (cache_feedback) pass.push_back("--cache-feedback");
611 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; };
612 std::map<std::string, Agg> agg;
613 std::vector<std::string> crashes;
614 bool cache_ok = true, setup_failed = false;
615 size_t unreproduced = 0;
616 const auto t_iso = std::chrono::steady_clock::now();
617 std::fprintf(stderr, "isolating %zu shaders [%zu, %zu) (stage=%s) in child processes, %zu per batch\n",
618 work.size(), lo, hi, stage_filter.c_str(), isolate_batch);
619 auto commit = [&](const ChildRun& r) {
620 size_t pos = 0;
621 while (pos < r.out.size()) {
622 size_t e = r.out.find('\n', pos);
623 if (e == std::string::npos) e = r.out.size();
624 const std::string line = r.out.substr(pos, e - pos);
625 pos = e + 1;
626 // The parent prints one cache line at the end instead of one per child.
627 if (line == "ISO-READY" || line.rfind("ISO-DONE", 0) == 0 || line.rfind("pipeline cache: ", 0) == 0) continue;
628 if (line.rfind("ISO-RESULT ", 0) == 0) {
629 char st[16];
630 unsigned v[9] = {};
631 if (std::sscanf(line.c_str(), "ISO-RESULT %15s %u %u %u %u %u %u %u %u %u", st, v, v + 1, v + 2, v + 3,
632 v + 4, v + 5, v + 6, v + 7, v + 8) == 10) {
633 Agg& a = agg[st];
634 a.mod_ok += v[0]; a.mod_bad += v[1]; a.pipe_ok += v[2]; a.pipe_bad += v[3]; a.pipe_skip += v[4];
635 a.big += v[5]; a.fb[0] += v[6]; a.fb[1] += v[7]; a.fb[2] += v[8];
636 }
637 continue;
638 }
639 std::printf("%s\n", line.c_str());
640 }
641 std::fflush(stdout);
642 if (!r.cache_ok) cache_ok = false;
643 };
644 // Returns the number of failures recorded for [s, s + n): crashed modules, or 1 for a crash that vanished.
645 auto bisect = [&](auto&& self, size_t s, size_t n) -> size_t {
646 if (setup_failed) return 0;
647 const ChildRun r = run_child(exe, dir, pass, cache_path, s, n);
648 if (r.done) { commit(r); return 0; }
649 if (!r.ready) { // died or exited before the work loop: not a module's fault
650 std::fputs(r.out.c_str(), stdout);
651 if (r.sig) std::fprintf(stderr, "error: a child process died during setup (%s)\n", signal_label(r.sig).c_str());
652 else std::fprintf(stderr, "error: a child process failed during setup (exit status %d)\n", r.status);
653 setup_failed = true;
654 return 0;
655 }
656 const std::string why = r.sig ? "driver crashed: " + signal_label(r.sig)
657 : "driver exited with status " + std::to_string(r.status);
658 if (n == 1) {
659 const std::string& name = *all[s].first;
660 const std::string& st = all[s].second->stage;
661 std::printf("MODULE CRASH %s (%s, %s)\n", name.c_str(), st.c_str(), why.c_str());
662 std::fflush(stdout);
663 crashes.push_back(name + " (" + st + ", " + why + ")");
664 agg[st].pipe_bad++;
665 agg[st].crashed++;
666 return 1;
667 }
668 std::fprintf(stderr, "child over [%zu, %zu) died (%s); bisecting\n", s, s + n, why.c_str());
669 const size_t half = n / 2;
670 size_t found = self(self, s, half);
671 found += self(self, s + half, n - half);
672 if (found == 0 && !setup_failed) {
673 std::printf("MODULE CRASH [%zu, %zu) not reproduced when split (%s); counted as failed\n", s, s + n, why.c_str());
674 ++unreproduced;
675 return 1;
676 }
677 return found;
678 };
679 for (size_t s = lo; s < hi && !setup_failed; s += isolate_batch) bisect(bisect, s, std::min(isolate_batch, hi - s));
680 if (setup_failed) return 1;
681 bool failed = !crashes.empty() || unreproduced || !cache_ok;
682 for (const auto& [st, a] : agg) {
683 std::printf("%s: %u modules ok, %u failed\n", st.c_str(), a.mod_ok, a.mod_bad);
684 std::printf("%s pipelines: %u ok, %u failed, %u skipped\n", st.c_str(), a.pipe_ok, a.pipe_bad, a.pipe_skip);
685 if (a.crashed) std::printf(" %s crashed the driver: %u (counted as failed)\n", st.c_str(), a.crashed);
686 if (cache_feedback)
687 std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n", st.c_str(), a.fb[0], a.fb[1], a.fb[2]);
688 if (a.mod_bad || a.pipe_bad) failed = true;
689 }
690 uint32_t big_total = 0;
691 for (const auto& [st, a] : agg) big_total += a.big;
692 if (big_total) std::printf("big modules skipped: %u (limit %zu bytes)\n", big_total, max_bytes);
693 if (!crashes.empty()) {
694 std::printf("modules that crashed the driver: %zu\n", crashes.size());
695 for (const auto& c : crashes) std::printf(" %s\n", c.c_str());
696 }
697 if (unreproduced) std::printf("crashes not reproduced after splitting: %zu\n", unreproduced);
698 if (!cache_path.empty()) {
699 const auto sz = std::filesystem::file_size(cache_path, ec);
700 if (!ec) std::printf("pipeline cache: %ju bytes -> %s\n", static_cast<uintmax_t>(sz), cache_path.c_str());
701 }
702 std::printf("wall time: %.1fs (isolated)\n",
703 std::chrono::duration<double>(std::chrono::steady_clock::now() - t_iso).count());
704 return failed ? 1 : 0;
705 }
706#endif
707
444 // Scan selected shaders to request only the optional extensions they actually use. 708 // Scan selected shaders to request only the optional extensions they actually use.
445 bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false; 709 bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false;
446 for (auto& [_, meta] : work) { 710 for (auto& [_, meta] : work) {
@@ -783,6 +1047,15 @@ int main(int argc, char** argv) {
783 if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed()); 1047 if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed());
784 }; 1048 };
785 1049
1050 const SimulatedCrash sim_crash = read_simulated_crash();
1051 auto maybe_simulate_crash = [&](const std::string& name) { // test hook, see the header
1052 if (sim_crash.enabled && name.find(sim_crash.pattern) != std::string::npos) {
1053 std::fprintf(stderr, "simulating signal %d before the pipeline of %s\n", sim_crash.sig, name.c_str());
1054 std::fflush(nullptr);
1055 std::raise(sim_crash.sig);
1056 }
1057 };
1058
786 auto worker = [&] { 1059 auto worker = [&] {
787 for (size_t k; (k = next++) < work.size();) { 1060 for (size_t k; (k = next++) < work.size();) {
788 const std::string& name = *work[k].first; 1061 const std::string& name = *work[k].first;
@@ -846,6 +1119,7 @@ int main(int argc, char** argv) {
846 const auto t0 = std::chrono::steady_clock::now(); 1119 const auto t0 = std::chrono::steady_clock::now();
847 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } 1120 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; }
848 VkPipeline p = VK_NULL_HANDLE; 1121 VkPipeline p = VK_NULL_HANDLE;
1122 maybe_simulate_crash(name);
849 VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p); 1123 VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p);
850 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); 1124 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
851 if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p); 1125 if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p);
@@ -1015,6 +1289,7 @@ int main(int argc, char** argv) {
1015 const auto t0 = std::chrono::steady_clock::now(); 1289 const auto t0 = std::chrono::steady_clock::now();
1016 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } 1290 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; }
1017 VkPipeline p = VK_NULL_HANDLE; 1291 VkPipeline p = VK_NULL_HANDLE;
1292 maybe_simulate_crash(name);
1018 VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p); 1293 VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p);
1019 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); 1294 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
1020 if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p); 1295 if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p);
@@ -1032,6 +1307,8 @@ int main(int argc, char** argv) {
1032 } 1307 }
1033 } 1308 }
1034 }; 1309 };
1310 if (iso_child) std::printf("ISO-READY\n");
1311 std::fflush(stdout);
1035 std::vector<std::thread> pool; 1312 std::vector<std::thread> pool;
1036 for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker); 1313 for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker);
1037 // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes. 1314 // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes.
@@ -1070,6 +1347,20 @@ int main(int argc, char** argv) {
1070 for (auto& [st, _] : modules_bad) all_stages.insert(st); 1347 for (auto& [st, _] : modules_bad) all_stages.insert(st);
1071 for (auto& [st, _] : stats) all_stages.insert(st); 1348 for (auto& [st, _] : stats) all_stages.insert(st);
1072 1349
1350 if (iso_child) { // --isolate child: machine-readable counts; the parent prints the summary
1351 for (const auto& st : all_stages) {
1352 const StageStats* s = stats.count(st) ? &stats[st] : nullptr;
1353 uint32_t big = big_skipped.count(st) ? big_skipped[st] : 0;
1354 std::printf("ISO-RESULT %s %u %u %u %u %u %u %u %u %u\n", st.c_str(), modules_ok[st], modules_bad[st],
1355 s ? s->pipes_ok : 0u, s ? s->pipes_bad : 0u, s ? s->pipes_skipped : 0u, big,
1356 s ? s->feedback[0] : 0u, s ? s->feedback[1] : 0u, s ? s->feedback[2] : 0u);
1357 }
1358 const bool saved = save_cache(true);
1359 std::printf("ISO-DONE cache_ok=%d\n", saved ? 1 : 0);
1360 std::fflush(stdout);
1361 return saved ? 0 : 1;
1362 }
1363
1073 bool check_failed = false; 1364 bool check_failed = false;
1074 for (const auto& st : all_stages) { 1365 for (const auto& st : all_stages) {
1075 std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]); 1366 std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]);
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index 3748aeec7..8f5c7d7d0 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -19,10 +19,14 @@
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>
24#include <condition_variable>
23#include <cstdint> 25#include <cstdint>
24#include <cstdio> 26#include <cstdio>
25#include <cstdlib> 27#include <cstdlib>
28#include <functional>
29#include <mutex>
26#include <string_view> 30#include <string_view>
27#include <thread> 31#include <thread>
28#include <vector> 32#include <vector>
@@ -49,10 +53,12 @@ namespace driver {
49PFN_vkGetInstanceProcAddr real_get_instance = nullptr; 53PFN_vkGetInstanceProcAddr real_get_instance = nullptr;
50PFN_vkGetDeviceProcAddr real_get_device = nullptr; 54PFN_vkGetDeviceProcAddr real_get_device = nullptr;
51PFN_vkQueueSubmit real_submit = nullptr; 55PFN_vkQueueSubmit real_submit = nullptr;
56PFN_vkQueuePresentKHR real_present = nullptr;
52PFN_vkCmdPipelineBarrier real_barrier = nullptr; 57PFN_vkCmdPipelineBarrier real_barrier = nullptr;
53PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; 58PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
54 59
55std::atomic<VkResult> fail_next_submit{VK_SUCCESS}; 60std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
61std::function<void()> on_next_present;
56std::atomic<bool> observe_capture{false}; 62std::atomic<bool> observe_capture{false};
57std::atomic<bool> saw_capture_waw{false}; 63std::atomic<bool> saw_capture_waw{false};
58std::atomic<std::uint32_t> capture_copies{0}; 64std::atomic<std::uint32_t> capture_copies{0};
@@ -65,6 +71,15 @@ VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count,
65 return real_submit(queue, count, submits, fence); 71 return real_submit(queue, count, submits, fence);
66} 72}
67 73
74VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoKHR* info) {
75 if (on_next_present) {
76 auto cb = std::move(on_next_present);
77 on_next_present = {};
78 cb();
79 }
80 return real_present(queue, info);
81}
82
68VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage, 83VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage,
69 VkPipelineStageFlags dst_stage, VkDependencyFlags flags, 84 VkPipelineStageFlags dst_stage, VkDependencyFlags flags,
70 std::uint32_t mem_count, const VkMemoryBarrier* mem, 85 std::uint32_t mem_count, const VkMemoryBarrier* mem,
@@ -100,6 +115,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) { 115VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
101 const std::string_view n = name; 116 const std::string_view n = name;
102 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 117 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
118 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
103 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier); 119 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); 120 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer);
105 return real_get_device(device, name); 121 return real_get_device(device, name);
@@ -114,6 +130,7 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
114 real_get_instance = instance_proc; 130 real_get_instance = instance_proc;
115 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr")); 131 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
116 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit")); 132 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
133 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
117 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier")); 134 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier"));
118 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer")); 135 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer"));
119} 136}
@@ -193,15 +210,52 @@ int main() {
193 EXPECT(presenter.ok()); 210 EXPECT(presenter.ok());
194 EXPECT(presenter.enable_capture()); 211 EXPECT(presenter.enable_capture());
195 212
196 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker. 213 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker (O(1) rollback
214 // even with many live tracked textures), and tracker_mutex_ must be released before vkQueuePresentKHR.
215 for (ResourceId extra = 1000; extra < 1512; ++extra)
216 context.add_resource(extra, side_rb, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
197 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 217 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
198 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); 218 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
199 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY); 219 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY);
200 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 220 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
201 221 EXPECT(context.layout(1000, 0) == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
202 // Next present succeeds, runs the deferred zero-fill, and commits GENERAL. 222
203 EXPECT(presenter.present(1, true) == VK_SUCCESS); 223 // Next present succeeds, runs the deferred zero-fill, commits GENERAL, and unlocks tracker_mutex_ before
224 // vkQueuePresentKHR so other threads' emit() / layout() calls are not blocked by presentation.
225 std::mutex sync_mutex;
226 std::condition_variable sync_cv;
227 bool reader_started = false;
228 bool read_done = false;
229 VkImageLayout seen_during_present = VK_IMAGE_LAYOUT_UNDEFINED;
230 bool unblocked_during_present = false;
231 std::thread reader;
232 driver::on_next_present = [&] {
233 reader = std::thread([&] {
234 {
235 std::lock_guard lk(sync_mutex);
236 reader_started = true;
237 }
238 sync_cv.notify_all();
239 const VkImageLayout layout = context.layout(1, 0);
240 {
241 std::lock_guard lk(sync_mutex);
242 seen_during_present = layout;
243 read_done = true;
244 }
245 sync_cv.notify_all();
246 });
247 std::unique_lock lk(sync_mutex);
248 const bool started = sync_cv.wait_for(lk, std::chrono::seconds(2), [&] { return reader_started; });
249 unblocked_during_present =
250 started && sync_cv.wait_for(lk, std::chrono::milliseconds(500), [&] { return read_done; });
251 };
252 const VkResult present_rc = presenter.present(1, true);
253 if (reader.joinable()) reader.join();
254 EXPECT(present_rc == VK_SUCCESS);
255 EXPECT(unblocked_during_present);
256 EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL);
204 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL); 257 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL);
258 for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra);
205 std::vector<std::uint8_t> pixels; 259 std::vector<std::uint8_t> pixels;
206 VkExtent2D ext{}; 260 VkExtent2D ext{};
207 VkFormat fmt = VK_FORMAT_UNDEFINED; 261 VkFormat fmt = VK_FORMAT_UNDEFINED;
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 635a3107b..1e54a9487 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -1,10 +1,12 @@
1// Shared setup for the GPU tests of the D3D12 layer: a Vulkan 1.3 device with dynamicRendering, synchronization2, 1// Shared setup for the GPU tests of the D3D12 layer: a Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and
2// timelineSemaphore and separateDepthStencilLayouts, images, buffers and one-shot submissions. 2// VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and
3// separateDepthStencilLayouts, images, buffers and one-shot submissions.
3// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; Device::validation_errors() counts errors. 4// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; Device::validation_errors() counts errors.
4#pragma once 5#pragma once
5 6
6#include "vulkan_loader.h" 7#include "vulkan_loader.h"
7#include "../src/vulkan_device_filter.h" 8#include "../src/vulkan_device_filter.h"
9#include "../src/vulkan13_features.h"
8#include "vk_device_pick.h" 10#include "vk_device_pick.h"
9#include "../src/subgroup_size.h" 11#include "../src/subgroup_size.h"
10 12
@@ -82,6 +84,12 @@ public:
82 VkDevice device = VK_NULL_HANDLE; 84 VkDevice device = VK_NULL_HANDLE;
83 VkQueue queue = VK_NULL_HANDLE; 85 VkQueue queue = VK_NULL_HANDLE;
84 std::uint32_t family = 0; 86 std::uint32_t family = 0;
87 // Set before initialize(): how many queues of `family` to create (fewer if the family has fewer). `queues` holds the
88 // handles; queues[0] == queue. A test that wants distinct VkQueues for its D3D12 queues passes them on as
89 // VulkanDeviceInfo::command_queues when there is more than one.
90 std::uint32_t queue_count_wanted = 1;
91 std::uint32_t family_queue_count = 1; // the family's queueCount, known after the device is chosen
92 std::vector<VkQueue> queues;
85 bool validation = false; 93 bool validation = false;
86 bool bc = false; // textureCompressionBC enabled 94 bool bc = false; // textureCompressionBC enabled
87 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device` 95 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device`
@@ -134,9 +142,10 @@ public:
134 reinterpret_cast<PFN_vkDestroyInstance>(instance_proc(instance, "vkDestroyInstance"))(instance, nullptr); 142 reinterpret_cast<PFN_vkDestroyInstance>(instance_proc(instance, "vkDestroyInstance"))(instance, nullptr);
135 } 143 }
136 144
145 // A Vulkan 1.3 function falls back to its KHR name on a 1.2 device.
137 template<typename F> 146 template<typename F>
138 F fn(const char* name) const { 147 F fn(const char* name) const {
139 return reinterpret_cast<F>(device_proc(device, name)); 148 return reinterpret_cast<F>(leonida::device_proc_or_khr(device_proc, device, name));
140 } 149 }
141 150
142 template<typename F> 151 template<typename F>
@@ -263,10 +272,16 @@ public:
263 if (result != VK_SUCCESS) return failure("vkEnumeratePhysicalDevices", result); 272 if (result != VK_SUCCESS) return failure("vkEnumeratePhysicalDevices", result);
264 VkPhysicalDeviceProperties chosen{}; 273 VkPhysicalDeviceProperties chosen{};
265 int best_rank = -1; 274 int best_rank = -1;
275 const auto features2_of = instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2");
276 const auto device_extensions_of =
277 instance_fn<PFN_vkEnumerateDeviceExtensionProperties>("vkEnumerateDeviceExtensionProperties");
278 leonida::Vulkan13Features candidate13;
266 for (auto candidate : devices) { 279 for (auto candidate : devices) {
267 VkPhysicalDeviceProperties props{}; 280 VkPhysicalDeviceProperties props{};
268 properties_of(candidate, &props); 281 properties_of(candidate, &props);
269 if (props.apiVersion < VK_API_VERSION_1_3 || !leonida::vulkan_device_wanted(props.deviceName)) continue; 282 if (!leonida::vulkan_device_wanted(props.deviceName)) continue;
283 candidate13.query(candidate, props.apiVersion, features2_of, device_extensions_of);
284 if (!candidate13.usable()) continue;
270 std::uint32_t family_count = 0; 285 std::uint32_t family_count = 0;
271 families_of(candidate, &family_count, nullptr); 286 families_of(candidate, &family_count, nullptr);
272 std::vector<VkQueueFamilyProperties> families(family_count); 287 std::vector<VkQueueFamilyProperties> families(family_count);
@@ -277,8 +292,10 @@ public:
277 rank > best_rank) { 292 rank > best_rank) {
278 physical = candidate; 293 physical = candidate;
279 family = i; 294 family = i;
295 family_queue_count = families[i].queueCount;
280 chosen = props; 296 chosen = props;
281 best_rank = rank; 297 best_rank = rank;
298 v13_.choose(candidate13);
282 } 299 }
283 break; 300 break;
284 } 301 }
@@ -286,22 +303,25 @@ public:
286 if (!physical) { 303 if (!physical) {
287 if (const std::string filter = leonida::vulkan_device_filter(); !filter.empty()) { 304 if (const std::string filter = leonida::vulkan_device_filter(); !filter.empty()) {
288 // A filter that matches nothing fails the test instead of skipping it. 305 // A filter that matches nothing fails the test instead of skipping it.
289 std::fprintf(stderr, "LEONIDA_VK_DEVICE=%s: no Vulkan 1.3 device with a graphics queue matches\n", 306 std::fprintf(stderr,
307 "LEONIDA_VK_DEVICE=%s: no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and "
308 "VK_KHR_synchronization2) with a graphics queue matches\n",
290 filter.c_str()); 309 filter.c_str());
291 return DeviceStatus::failed; 310 return DeviceStatus::failed;
292 } 311 }
293 std::fprintf(stderr, "no Vulkan 1.3 device with a graphics queue\n"); 312 std::fprintf(stderr, "no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and "
313 "VK_KHR_synchronization2) with a graphics queue\n");
294 return DeviceStatus::unavailable; 314 return DeviceStatus::unavailable;
295 } 315 }
296 std::printf("device: %s%s\n", chosen.deviceName, validation ? " (validation on)" : ""); 316 std::printf("device: %s%s%s\n", chosen.deviceName, v13_.core ? "" : " (Vulkan 1.2 + KHR extensions)",
317 validation ? " (validation on)" : "");
297 318
298 VkPhysicalDeviceVulkan13Features features13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 319 VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
299 VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &features13};
300 VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11}; 320 VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11};
301 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; 321 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12};
302 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &features); 322 features2_of(physical, &features);
303 if (!features13.dynamicRendering || !features13.synchronization2 || !features12.timelineSemaphore || 323 if (!features12.timelineSemaphore || !features12.separateDepthStencilLayouts ||
304 !features12.separateDepthStencilLayouts || !features12.bufferDeviceAddress) { 324 !features12.bufferDeviceAddress) {
305 std::fprintf(stderr, "the device lacks dynamicRendering, synchronization2, timelineSemaphore or " 325 std::fprintf(stderr, "the device lacks dynamicRendering, synchronization2, timelineSemaphore or "
306 "separateDepthStencilLayouts\n"); 326 "separateDepthStencilLayouts\n");
307 return DeviceStatus::unavailable; 327 return DeviceStatus::unavailable;
@@ -327,14 +347,8 @@ public:
327 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; 347 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT};
328 enable_conditional.conditionalRendering = VK_TRUE; 348 enable_conditional.conditionalRendering = VK_TRUE;
329 349
330 VkPhysicalDeviceVulkan13Features enable13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
331 conditional_rendering ? &enable_conditional : nullptr};
332 enable13.dynamicRendering = 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"), 350 leonida::query_subgroup_size_caps(instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2"),
337 physical, features13.subgroupSizeControl, features13.computeFullSubgroups, 351 physical, v13_.subgroup_size_control, v13_.compute_full_subgroups,
338 subgroup); 352 subgroup);
339 std::printf("subgroup sizes: %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " 353 std::printf("subgroup sizes: %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, "
340 "computeFullSubgroups %s\n", 354 "computeFullSubgroups %s\n",
@@ -342,7 +356,8 @@ public:
342 subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off"); 356 subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off");
343 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436 357 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436
344 // (zero-based VS ids) is in; harmless before. 358 // (zero-based VS ids) is in; harmless before.
345 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13}; 359 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
360 v13_.enable(conditional_rendering ? &enable_conditional : nullptr)};
346 enable11.shaderDrawParameters = features11.shaderDrawParameters; 361 enable11.shaderDrawParameters = features11.shaderDrawParameters;
347 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; 362 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11};
348 enable12.timelineSemaphore = VK_TRUE; 363 enable12.timelineSemaphore = VK_TRUE;
@@ -369,11 +384,11 @@ public:
369 enable12.samplerFilterMinmax = sampler_filter_minmax; 384 enable12.samplerFilterMinmax = sampler_filter_minmax;
370 enable12.bufferDeviceAddress = VK_TRUE; 385 enable12.bufferDeviceAddress = VK_TRUE;
371 386
372 const float priority = 1.0f; 387 const std::vector<float> priority(std::max(1u, std::min(queue_count_wanted, family_queue_count)), 1.0f);
373 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; 388 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
374 queue_info.queueFamilyIndex = family; 389 queue_info.queueFamilyIndex = family;
375 queue_info.queueCount = 1; 390 queue_info.queueCount = std::max(1u, std::min(queue_count_wanted, family_queue_count));
376 queue_info.pQueuePriorities = &priority; 391 queue_info.pQueuePriorities = priority.data();
377 VkPhysicalDeviceFeatures enable{}; 392 VkPhysicalDeviceFeatures enable{};
378 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available 393 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available
379 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) 394 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features)
@@ -399,8 +414,8 @@ public:
399 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 414 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
400 image_view_min_lod = min_lod.minLod == VK_TRUE; 415 image_view_min_lod = min_lod.minLod == VK_TRUE;
401 if (image_view_min_lod) { 416 if (image_view_min_lod) {
402 min_lod.pNext = enable13.pNext; 417 min_lod.pNext = *v13_.next();
403 enable13.pNext = &min_lod; 418 *v13_.next() = &min_lod;
404 } 419 }
405 } 420 }
406 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{ 421 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{
@@ -413,8 +428,8 @@ public:
413 } 428 }
414 const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; 429 const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME;
415 if (host_image_copy) { 430 if (host_image_copy) {
416 host_copy.pNext = enable13.pNext; // after the conditional rendering features, if any 431 host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any
417 enable13.pNext = &host_copy; 432 *v13_.next() = &host_copy;
418 } 433 }
419 434
420#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME 435#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
@@ -427,8 +442,8 @@ public:
427 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 442 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
428 shader_fma = fma_features.shaderFmaFloat32 == VK_TRUE; 443 shader_fma = fma_features.shaderFmaFloat32 == VK_TRUE;
429 if (shader_fma) { 444 if (shader_fma) {
430 fma_features.pNext = enable13.pNext; 445 fma_features.pNext = *v13_.next();
431 enable13.pNext = &fma_features; 446 *v13_.next() = &fma_features;
432 } 447 }
433 } 448 }
434#endif 449#endif
@@ -442,6 +457,7 @@ public:
442 device_info.pEnabledFeatures = &enable; 457 device_info.pEnabledFeatures = &enable;
443 enabled = enable; 458 enabled = enable;
444 std::vector<const char*> device_extensions; 459 std::vector<const char*> device_extensions;
460 v13_.add_extensions(device_extensions);
445 if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); 461 if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME);
446 if (conditional_rendering) device_extensions.push_back(conditional_extension); 462 if (conditional_rendering) device_extensions.push_back(conditional_extension);
447 if (host_image_copy) device_extensions.push_back(host_image_copy_name); 463 if (host_image_copy) device_extensions.push_back(host_image_copy_name);
@@ -462,8 +478,8 @@ public:
462 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1}; 478 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1};
463 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 479 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
464 if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) { 480 if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) {
465 swapchain_m1.pNext = enable13.pNext; 481 swapchain_m1.pNext = *v13_.next();
466 enable13.pNext = &swapchain_m1; 482 *v13_.next() = &swapchain_m1;
467 device_extensions.push_back(name); 483 device_extensions.push_back(name);
468 swapchain_maintenance1 = true; 484 swapchain_maintenance1 = true;
469 } 485 }
@@ -478,7 +494,10 @@ public:
478 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); 494 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device);
479 if (result != VK_SUCCESS) return failure("vkCreateDevice", result); 495 if (result != VK_SUCCESS) return failure("vkCreateDevice", result);
480 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr"); 496 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr");
481 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, 0, &queue); 497 queues.resize(queue_info.queueCount);
498 for (std::uint32_t i = 0; i < queue_info.queueCount; ++i)
499 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, i, &queues[i]);
500 queue = queues[0];
482 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical, 501 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical,
483 &memory_); 502 &memory_);
484 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; 503 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
@@ -628,6 +647,7 @@ private:
628 VkDebugUtilsMessengerEXT messenger_ = VK_NULL_HANDLE; 647 VkDebugUtilsMessengerEXT messenger_ = VK_NULL_HANDLE;
629 VkCommandPool pool_ = VK_NULL_HANDLE; 648 VkCommandPool pool_ = VK_NULL_HANDLE;
630 VkPhysicalDeviceMemoryProperties memory_{}; 649 VkPhysicalDeviceMemoryProperties memory_{};
650 leonida::Vulkan13Features v13_; // the chosen device's dynamicRendering/synchronization2 path
631 std::vector<std::pair<VkImage, VkDeviceMemory>> images_; 651 std::vector<std::pair<VkImage, VkDeviceMemory>> images_;
632 std::vector<std::pair<VkBuffer, VkDeviceMemory>> buffers_; 652 std::vector<std::pair<VkBuffer, VkDeviceMemory>> buffers_;
633}; 653};
diff --git a/runtime/test/vk_xdxr_build_test.cpp b/runtime/test/vk_xdxr_build_test.cpp
index 136f49f68..1f4686869 100644
--- a/runtime/test/vk_xdxr_build_test.cpp
+++ b/runtime/test/vk_xdxr_build_test.cpp
@@ -6,10 +6,12 @@
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; clones and a
10// compaction (CopyRaytracingAccelerationStructure) with the postbuild size; 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. 11// 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 12// `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. 13// one submission each, after one warm-up; result and scratch in device-local memory), then in-place updates
14// (refits) of the same structure, and writes nothing.
13#include "vk_test_device.h" 15#include "vk_test_device.h"
14#include "../src/xdxr_build.h" 16#include "../src/xdxr_build.h"
15 17
@@ -117,9 +119,12 @@ struct Built {
117 std::vector<Tri> tris; 119 std::vector<Tri> tris;
118}; 120};
119 121
122// With `moved` (the same geometries with new vertex positions) the BLAS is then updated: refitted in place, or with
123// `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, 124int 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) { 125 const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0,
122 std::vector<Buffer> keep; 126 const std::vector<Geometry>* moved = nullptr, bool into_other = false) {
127 std::vector<Buffer> keep, vertex_buffers;
123 std::vector<XdxrTriangles> descs; 128 std::vector<XdxrTriangles> descs;
124 std::uint32_t total = 0; 129 std::uint32_t total = 0;
125 for (std::size_t g = 0; g < geometries.size(); ++g) { 130 for (std::size_t g = 0; g < geometries.size(); ++g) {
@@ -134,6 +139,7 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
134 d.triangle_count = geo.triangle_count; 139 d.triangle_count = geo.triangle_count;
135 d.flags = 1; 140 d.flags = 1;
136 keep.push_back(v); 141 keep.push_back(v);
142 vertex_buffers.push_back(v);
137 if (!geo.indices.empty()) { 143 if (!geo.indices.empty()) {
138 Buffer ib = make(gpu, geo.indices.size() * 4); 144 Buffer ib = make(gpu, geo.indices.size() * 4);
139 EXPECT(ib.buffer); 145 EXPECT(ib.buffer);
@@ -170,13 +176,41 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
170 return recorded; 176 return recorded;
171 })); 177 }));
172 built.address = base; 178 built.address = base;
173 const auto* bytes = static_cast<const char*>(dst.map) + (base - dst.address); 179 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)); 180 const auto* bytes = static_cast<const char*>(buffer.map) + (at - buffer.address);
175 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(base) + 181 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) +
176 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) + 182 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) +
177 ", \"triangles\": " + tris_json(built.tris) + "}\n"; 183 ", \"triangles\": " + tris_json(tris) + "}\n";
178 EXPECT(write_file(dir + "/" + name + ".json", json.data(), json.size())); 184 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); 185 write_file(dir + "/" + case_name + ".json", json.data(), json.size());
186 };
187 if (!moved) {
188 EXPECT(dump(name, dst, base, built.tris));
189 std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes);
190 return 0;
191 }
192 // the update: new positions in the same vertex buffers, then a refit of the structure just built
193 EXPECT(moved->size() == geometries.size());
194 std::vector<Tri> moved_tris;
195 for (std::size_t g = 0; g < moved->size(); ++g) {
196 EXPECT((*moved)[g].vertex_data.size() == geometries[g].vertex_data.size());
197 std::memcpy(vertex_buffers[g].map, (*moved)[g].vertex_data.data(), (*moved)[g].vertex_data.size() * 4);
198 expand((*moved)[g], std::uint32_t(g), moved_tris);
199 }
200 Buffer other = into_other ? make(gpu, layout.size + 256) : Buffer{};
201 const std::uint64_t target = into_other ? (other.address + 255) & ~std::uint64_t(255) : base;
202 EXPECT(!into_other || other.buffer);
203 EXPECT(gpu.run([&](VkCommandBuffer cb) {
204 recorded = builder.record_blas(cb, layout, descs, target, scratch.address, base);
205 barrier_to_host(gpu, cb);
206 return recorded;
207 }));
208 if (into_other) EXPECT(dump(name + "_source", dst, base, built.tris)); // a refit must not touch its source
209 EXPECT(dump(name, into_other ? other : dst, target, moved_tris));
210 built.tris = moved_tris;
211 built.address = target;
212 std::printf("%s: %u triangles refitted %s, %u bytes\n", name.c_str(), total,
213 into_other ? "into another buffer" : "in place", layout.size);
180 return 0; 214 return 0;
181} 215}
182 216
@@ -234,8 +268,17 @@ int main(int argc, char** argv) {
234 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); 268 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
235 if (rep) best = std::min(best, ms); 269 if (rep) best = std::min(best, ms);
236 } 270 }
237 std::printf("%u triangles: %.2f ms (best of 3), result %u bytes, scratch %llu bytes, sort size %u\n", n, best, 271 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); 272 for (int rep = 0; rep < 4; ++rep) {
273 const auto t0 = std::chrono::steady_clock::now();
274 EXPECT(gpu.run([&](VkCommandBuffer cb) {
275 return builder.record_blas(cb, layout, {d}, dst.address, scratch.address, dst.address);
276 }));
277 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
278 if (rep) refit = std::min(refit, ms);
279 }
280 std::printf("%u triangles: %.2f ms (best of 3), refit %.2f ms, result %u bytes, scratch %llu bytes, sort size %u\n",
281 n, best, refit, layout.size, static_cast<unsigned long long>(layout.scratch), layout.sort_size);
239 return 0; 282 return 0;
240 } 283 }
241 284
@@ -287,10 +330,33 @@ int main(int argc, char** argv) {
287 b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive 330 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; 331 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; 332 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) 333 // many radix-sort tiles (RADIX_TILE elements each), the last one partial (fewer rays: the brute force is slow)
291 Built tiles; 334 Built tiles;
292 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1; 335 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1;
293 336
337 // Updates. Every triangle moves (its own offset, and a stretch), so each box changes; the tree is kept.
338 auto move = [&](Geometry g, float amount) {
339 std::uniform_real_distribution<float> d(-amount, amount);
340 const std::uint32_t floats = g.stride / 4;
341 for (std::size_t v = 0; v + 2 < g.vertex_data.size(); v += floats) {
342 const float dx = d(rng), dy = d(rng);
343 g.vertex_data[v] = g.vertex_data[v] * 1.25f + dx;
344 g.vertex_data[v + 1] = g.vertex_data[v + 1] * 0.8f + dy;
345 if (!g.xy) g.vertex_data[v + 2] += d(rng);
346 }
347 return g;
348 };
349 {
350 Built refitted;
351 const Geometry big = soup(3000); // the radix-sort path
352 const std::vector<Geometry> after = {move(big, 1.5f)};
353 if (build_blas(gpu, builder, dir, "blas_refit_in_place", {big}, refitted, 300, &after)) return 1;
354 Built copied;
355 const Geometry g = grid(12, 4, false); // R32 indices, stride 16; the small-sort path
356 const std::vector<Geometry> after_grid = {move(g, 0.3f)};
357 if (build_blas(gpu, builder, dir, "blas_refit_into_other", {g}, copied, 0, &after_grid, true)) return 1;
358 }
359
294 // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address 360 // 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). 361 // (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. 362 // The instances hold application-style addresses, device address - bias, as the layer's address window does.
@@ -338,6 +404,95 @@ int main(int argc, char** argv) {
338 } 404 }
339 json += "]}\n"; 405 json += "]}\n";
340 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size())); 406 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size()));
407
408 // The TLAS updated in place: every instance moves and turns; the masked and the BLAS-less ones stay so.
409 Inst moved_insts[sizeof insts / sizeof insts[0]];
410 std::memcpy(moved_insts, insts, sizeof insts);
411 const float c2 = std::cos(1.9f), s2 = std::sin(1.9f);
412 const float turned[12] = {c2, 0, s2, 4, 0, 1, 0, -3, -s2, 0, c2, 2};
413 std::memcpy(moved_insts[0].m, turned, sizeof turned);
414 moved_insts[1].m[3] -= 7;
415 moved_insts[1].m[7] += 5;
416 moved_insts[2].m[11] -= 4;
417 for (std::uint32_t i = 0; i < count; ++i) std::memcpy(static_cast<char*>(descs.map) + 64 * i, moved_insts[i].m, 48);
418 EXPECT(gpu.run([&](VkCommandBuffer cb) {
419 recorded = builder.record_tlas(cb, layout, descs.address, base, scratch.address, bias, base);
420 barrier_to_host(gpu, cb);
421 return recorded;
422 }));
423 EXPECT(write_file(dir + "/tlas_refit.bin", static_cast<const char*>(dst.map) + (base - dst.address), layout.size));
424 std::string json2 = "{\"kind\": \"tlas\", \"address\": " + std::to_string(base) + ", \"bias\": " +
425 std::to_string(bias) + ", \"blas\": [\"blas_random\", \"blas_grid_u16_stride16\"], \"instances\": [";
426 for (std::uint32_t i = 0; i < count; ++i) {
427 json2 += i ? ", {" : "{";
428 json2 += "\"transform\": [";
429 for (int k = 0; k < 12; ++k) json2 += (k ? ", " : "") + num(moved_insts[i].m[k]);
430 json2 += "], \"mask\": " + std::to_string(moved_insts[i].id_mask >> 24) + ", \"blas\": " +
431 std::to_string(moved_insts[i].which) + "}";
432 }
433 json2 += "]}\n";
434 EXPECT(write_file(dir + "/tlas_refit.json", json2.data(), json2.size()));
435
436 // CopyRaytracingAccelerationStructure: a clone of blas_random, its COMPACTED_SIZE (postbuild), a compaction into
437 // a buffer of exactly that size, and a clone of the refitted TLAS. The copies are position-independent.
438 {
439 XdxrLayout blas_layout;
440 EXPECT(blas_layout.compute(1000, false));
441 Buffer clone = make(gpu, blas_layout.size + 256), info = make(gpu, 16);
442 EXPECT(clone.buffer && info.buffer);
443 const std::uint64_t clone_at = (clone.address + 255) & ~std::uint64_t(255);
444 std::memset(info.map, 0xab, 16);
445 EXPECT(gpu.run([&](VkCommandBuffer cb) {
446 const bool ok = builder.record_copy(cb, random.address, clone_at, blas_layout.size) &&
447 builder.record_postbuild(cb, random.address, info.address) &&
448 builder.record_postbuild(cb, clone_at, info.address + 8);
449 barrier_to_host(gpu, cb);
450 return ok;
451 }));
452 std::uint64_t compacted = 0, clone_size = 0;
453 std::memcpy(&compacted, info.map, 8);
454 std::memcpy(&clone_size, static_cast<char*>(info.map) + 8, 8);
455 EXPECT(compacted == blas_layout.size); // a build is exactly its layout's size
456 EXPECT(clone_size == compacted);
457 auto dump_blas = [&](const std::string& name, const Buffer& b, std::uint64_t at, std::size_t bytes) {
458 const std::string j = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) +
459 ", \"triangles\": " + tris_json(random.tris) + "}\n";
460 return write_file(dir + "/" + name + ".bin", static_cast<const char*>(b.map) + (at - b.address), bytes) &&
461 write_file(dir + "/" + name + ".json", j.data(), j.size());
462 };
463 EXPECT(dump_blas("blas_clone", clone, clone_at, blas_layout.size));
464 // COMPACT into exactly the compacted size; a guard word after it must survive
465 Buffer packed = make(gpu, std::size_t(compacted) + 256 + 4);
466 EXPECT(packed.buffer);
467 const std::uint64_t packed_at = (packed.address + 255) & ~std::uint64_t(255);
468 const std::uint32_t guard = 0x600dc0deu;
469 std::memcpy(static_cast<char*>(packed.map) + (packed_at - packed.address) + compacted, &guard, 4);
470 EXPECT(gpu.run([&](VkCommandBuffer cb) {
471 const bool ok = builder.record_copy(cb, clone_at, packed_at, compacted + 4); // more room than needed
472 barrier_to_host(gpu, cb);
473 return ok;
474 }));
475 std::uint32_t after = 0;
476 std::memcpy(&after, static_cast<char*>(packed.map) + (packed_at - packed.address) + compacted, 4);
477 EXPECT(after == guard); // the copy stops at the source's own size
478 EXPECT(dump_blas("blas_compacted", packed, packed_at, std::size_t(compacted)));
479
480 Buffer tclone = make(gpu, layout.size + 256);
481 EXPECT(tclone.buffer);
482 const std::uint64_t tclone_at = (tclone.address + 255) & ~std::uint64_t(255);
483 EXPECT(gpu.run([&](VkCommandBuffer cb) {
484 const bool ok = builder.record_copy(cb, base, tclone_at, layout.size);
485 barrier_to_host(gpu, cb);
486 return ok;
487 }));
488 EXPECT(write_file(dir + "/tlas_refit_clone.bin", static_cast<const char*>(tclone.map) + (tclone_at - tclone.address),
489 layout.size));
490 std::string json3 = json2;
491 json3.replace(json3.find(std::to_string(base)), std::to_string(base).size(), std::to_string(tclone_at));
492 EXPECT(write_file(dir + "/tlas_refit_clone.json", json3.data(), json3.size()));
493 std::printf("copies: blas_clone, blas_compacted (%llu bytes), tlas_refit_clone\n",
494 static_cast<unsigned long long>(compacted));
495 }
341 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size); 496 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size);
342 return 0; 497 return 0;
343} 498}
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index ac36f40d9..8f5057662 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -51,8 +51,36 @@ using AsyncCompleteFn = void(__stdcall*)(XAsyncBlock*, HRESULT, size_t);
51using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*); 51using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*);
52using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*); 52using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*);
53 53
54struct XVersion {
55 union {
56 struct {
57 uint16_t major;
58 uint16_t minor;
59 uint16_t build;
60 uint16_t revision;
61 };
62 uint64_t Value;
63 };
64};
65static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes per GDK spec");
66
67struct XSystemAnalyticsInfo {
68 XVersion osVersion;
69 XVersion hostingOsVersion;
70 char family[64];
71 char form[64];
72};
73static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes per GDK spec");
74
75using AnalyticsInfoFn = XSystemAnalyticsInfo(__stdcall*)();
76using PackageIdentifierFn = HRESULT(__stdcall*)(size_t, char*);
77using PackageMountPathFn = HRESULT(__stdcall*)(void*, size_t, char*);
78using PackagedProcessFn = bool(__stdcall*)();
79
54const char* const kNames[] = { 80const char* const kNames[] = {
55 "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId", 81 "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId",
82 "XSystemGetAnalyticsInfo", "XPackageGetCurrentProcessPackageIdentifier", "XPackageGetMountPath",
83 "XPackageIsPackagedProcess",
56 "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle", 84 "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle",
57 "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback", 85 "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback",
58 "XTaskQueueSubmitDelayedCallback", "XTaskQueueRegisterWaiter", "XTaskQueueUnregisterWaiter", 86 "XTaskQueueSubmitDelayedCallback", "XTaskQueueRegisterWaiter", "XTaskQueueUnregisterWaiter",
@@ -182,6 +210,89 @@ void check_run_time_load() {
182 void* out = reinterpret_cast<void*>(1); 210 void* out = reinterpret_cast<void*>(1);
183 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr, 211 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr,
184 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer"); 212 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer");
213
214 // XThreadingImpl and XErrorImpl, driven the way xgameruntime.lib's thunks in the package's DLLs do: QueryApiImpl
215 // with the class id as both ids, one vtable slot with `this` first, then Release (slot 2).
216 const GUID threading = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}};
217 const GUID error_cls = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}};
218 using Fn = void*;
219 auto slot = [](void* obj, int index) { return (*static_cast<Fn* const*>(obj))[index]; };
220 auto release = [&](void* obj) { reinterpret_cast<ULONG(STDMETHODCALLTYPE*)(void*)>(slot(obj, 2))(obj); };
221 auto get = [&](const GUID& cls) {
222 void* p = nullptr;
223 return query(&cls, cls, &p) == S_OK ? p : nullptr;
224 };
225 void* t = get(threading);
226 check(t != nullptr, "QueryApiImpl hands out XThreadingImpl for its class id");
227 if (t) {
228 void* again = get(threading);
229 check(again == t, "XThreadingImpl is one process-wide object");
230 release(again);
231 XTaskQueueHandle queue = nullptr;
232 using Create = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueDispatchMode, XTaskQueueDispatchMode,
233 XTaskQueueHandle*);
234 check(reinterpret_cast<Create>(slot(t, 12))(t, XTaskQueueDispatchMode::Manual, XTaskQueueDispatchMode::Manual,
235 &queue) == S_OK && queue,
236 "slot 12 is XTaskQueueCreate");
237 static std::atomic<int> s_ran{0};
238 using Submit = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueuePort, void*,
239 XTaskQueueCallback*);
240 XTaskQueueCallback* cb = [](void* ctx, bool canceled) {
241 if (!canceled) static_cast<std::atomic<int>*>(ctx)->fetch_add(1);
242 };
243 check(reinterpret_cast<Submit>(slot(t, 18))(t, queue, XTaskQueuePort::Work, &s_ran, cb) == S_OK,
244 "slot 18 is XTaskQueueSubmitCallback");
245 using Dispatch = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueuePort, uint32_t);
246 check(reinterpret_cast<Dispatch>(slot(t, 16))(t, queue, XTaskQueuePort::Work, 0) && s_ran.load() == 1,
247 "slot 16 is XTaskQueueDispatch: the callback ran on the work port");
248 XTaskQueueHandle dup = nullptr;
249 using Dup = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueueHandle*);
250 check(reinterpret_cast<Dup>(slot(t, 15))(t, queue, &dup) == S_OK && dup,
251 "slot 15 is XTaskQueueDuplicateHandle");
252 using Close = void(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle);
253 reinterpret_cast<Close>(slot(t, 17))(t, dup);
254 reinterpret_cast<Close>(slot(t, 17))(t, queue);
255 using SetSensitive = HRESULT(STDMETHODCALLTYPE*)(void*, bool);
256 using IsSensitive = bool(STDMETHODCALLTYPE*)(void*);
257 check(reinterpret_cast<SetSensitive>(slot(t, 27))(t, true) == S_OK &&
258 reinterpret_cast<IsSensitive>(slot(t, 30))(t) &&
259 reinterpret_cast<SetSensitive>(slot(t, 27))(t, false) == S_OK &&
260 !reinterpret_cast<IsSensitive>(slot(t, 30))(t),
261 "slots 27 and 30 set and read this thread's time-sensitive flag");
262 void* unk = nullptr;
263 const GUID iunknown = {0, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}};
264 using QI = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**);
265 check(reinterpret_cast<QI>(slot(t, 0))(t, iunknown, &unk) == S_OK && unk == t &&
266 reinterpret_cast<QI>(slot(t, 0))(t, error_cls, &unk) == E_NOINTERFACE && !unk,
267 "QueryInterface answers IUnknown and the class id, not another class");
268 release(t);
269 release(t);
270 }
271 void* e = get(error_cls);
272 check(e != nullptr, "QueryApiImpl hands out XErrorImpl for its class id");
273 if (e) {
274 struct Seen {
275 HRESULT hr;
276 char msg[32];
277 } seen{};
278 using Callback = bool(CALLBACK*)(HRESULT, const char*, void*);
279 Callback on_error = [](HRESULT hr, const char* msg, void* ctx) {
280 auto* s = static_cast<Seen*>(ctx);
281 s->hr = hr;
282 strncpy_s(s->msg, msg ? msg : "", _TRUNCATE);
283 return true;
284 };
285 using SetCallback = void(STDMETHODCALLTYPE*)(void*, Callback, void*);
286 using Report = void(STDMETHODCALLTYPE*)(void*, HRESULT, const char*);
287 reinterpret_cast<SetCallback>(slot(e, 4))(e, on_error, &seen);
288 reinterpret_cast<Report>(slot(e, 3))(e, E_FAIL, "offline test");
289 check(seen.hr == E_FAIL && std::strcmp(seen.msg, "offline test") == 0,
290 "slot 3 is XErrorReport and reaches the callback slot 4 (XErrorSetCallback) set");
291 reinterpret_cast<SetCallback>(slot(e, 4))(e, nullptr, nullptr);
292 using SetOptions = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, uint32_t);
293 check(reinterpret_cast<SetOptions>(slot(e, 5))(e, 0, 0) == S_OK, "slot 5 is XErrorSetOptions");
294 release(e);
295 }
185 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds"); 296 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds");
186 297
187 HMODULE k32 = load_w(L"kernel32.dll"); 298 HMODULE k32 = load_w(L"kernel32.dll");
@@ -229,6 +340,53 @@ int main() {
229 check(console_id(sizeof(id), id, &used) == S_OK && used == 39 && std::strlen(id) == 38, 340 check(console_id(sizeof(id), id, &used) == S_OK && used == 39 && std::strlen(id) == 38,
230 "XSystemGetConsoleId fills 39 bytes (38 characters and the terminator)"); 341 "XSystemGetConsoleId fills 39 bytes (38 characters and the terminator)");
231 342
343 auto analytics_info = get<AnalyticsInfoFn>("XSystemGetAnalyticsInfo");
344 XSystemAnalyticsInfo info = analytics_info();
345 check(info.osVersion.major == 10 && info.osVersion.minor == 0 && info.osVersion.build == 22000 &&
346 info.osVersion.revision == 0,
347 "XSystemGetAnalyticsInfo returns osVersion 10.0.22000.0");
348 check(info.hostingOsVersion.major == 10 && info.hostingOsVersion.minor == 0 &&
349 info.hostingOsVersion.build == 22000 && info.hostingOsVersion.revision == 0,
350 "XSystemGetAnalyticsInfo returns hostingOsVersion 10.0.22000.0");
351 check(std::strcmp(info.family, "Xbox") == 0, "XSystemGetAnalyticsInfo returns family 'Xbox'");
352 check(std::strcmp(info.form, "Xbox Series X") == 0, "XSystemGetAnalyticsInfo returns form 'Xbox Series X'");
353
354 auto package_id = get<PackageIdentifierFn>("XPackageGetCurrentProcessPackageIdentifier");
355 check(package_id(0, nullptr) == E_INVALIDARG, "XPackageGetCurrentProcessPackageIdentifier rejects null buffer and size 0");
356 char pkg_id[64] = {};
357 check(package_id(0, pkg_id) == E_INVALIDARG, "XPackageGetCurrentProcessPackageIdentifier rejects size 0 with buffer");
358 check(package_id(10, nullptr) == E_INVALIDARG, "XPackageGetCurrentProcessPackageIdentifier rejects null pointer with size");
359 check(package_id(16, pkg_id) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
360 "XPackageGetCurrentProcessPackageIdentifier rejects insufficient buffer");
361 check(package_id(sizeof(pkg_id), pkg_id) == S_OK && std::strlen(pkg_id) == 32,
362 "XPackageGetCurrentProcessPackageIdentifier fills 33-byte package identifier");
363
364 SetEnvironmentVariableA("LEONIDA_PACKAGE_ID", "CustomTestPackageId_123456789012");
365 check(package_id(sizeof(pkg_id), pkg_id) == S_OK &&
366 std::strcmp(pkg_id, "CustomTestPackageId_123456789012") == 0,
367 "XPackageGetCurrentProcessPackageIdentifier respects LEONIDA_PACKAGE_ID override");
368 SetEnvironmentVariableA("LEONIDA_PACKAGE_ID", nullptr);
369
370 auto mount_path = get<PackageMountPathFn>("XPackageGetMountPath");
371 check(mount_path(nullptr, 0, nullptr) == E_INVALIDARG, "XPackageGetMountPath rejects null buffer and size 0");
372 char mnt_path[MAX_PATH] = {};
373 check(mount_path(nullptr, 0, mnt_path) == E_INVALIDARG, "XPackageGetMountPath rejects size 0 with buffer");
374 check(mount_path(nullptr, 10, nullptr) == E_INVALIDARG, "XPackageGetMountPath rejects null pointer with size");
375
376 SetEnvironmentVariableA("LEONIDA_GAME_DIR", "C:\\LeonidaGameDir");
377 check(mount_path(nullptr, 5, mnt_path) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
378 "XPackageGetMountPath rejects insufficient buffer");
379 check(mount_path(nullptr, sizeof(mnt_path), mnt_path) == S_OK &&
380 std::strcmp(mnt_path, "C:\\LeonidaGameDir") == 0,
381 "XPackageGetMountPath returns configured game directory");
382 SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr);
383
384 auto is_packaged = get<PackagedProcessFn>("XPackageIsPackagedProcess");
385 check(is_packaged() == true, "XPackageIsPackagedProcess returns true by default");
386 SetEnvironmentVariableA("LEONIDA_PACKAGED", "0");
387 check(is_packaged() == false, "XPackageIsPackagedProcess respects LEONIDA_PACKAGED=0 override");
388 SetEnvironmentVariableA("LEONIDA_PACKAGED", nullptr);
389
232 // Work on the thread pool, completions dispatched by the "game loop" on this thread. 390 // Work on the thread pool, completions dispatched by the "game loop" on this thread.
233 auto create = get<QueueCreateFn>("XTaskQueueCreate"); 391 auto create = get<QueueCreateFn>("XTaskQueueCreate");
234 auto close = get<QueueCloseFn>("XTaskQueueCloseHandle"); 392 auto close = get<QueueCloseFn>("XTaskQueueCloseHandle");
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;