diff --git a/CMakeLists.txt b/CMakeLists.txt index 26fbe94bb..583818bda 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -915,6 +915,19 @@ foreach(backend IN ITEMS warp hardware) endforeach() set_tests_properties(startup_indirect_dispatch_hardware startup_indirect_root_constants_hardware PROPERTIES SKIP_RETURN_CODE 77) +# Occlusion queries recorded through command-list slots 28 to 30 reach the readback buffer (#870). +add_executable(startup_list_queries tests/startup_list_queries.cpp tests/desktop_gpu.cpp) +target_compile_features(startup_list_queries PRIVATE cxx_std_17) +target_link_libraries(startup_list_queries PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_list_queries_${backend} COMMAND startup_list_queries ${backend}) + set_tests_properties(startup_list_queries_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) + # Negative control: without X2W_D3D12_QUERY_SLOTS=1 the slots stay no-ops and the buffer keeps its sentinel. + add_test(NAME startup_list_queries_default_${backend}_control COMMAND startup_list_queries ${backend} default) + set_tests_properties(startup_list_queries_default_${backend}_control PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "word 0: got 0xa5a5a5a5a5a5a5a5") +endforeach() + add_executable(startup_indirect_draw_indexed tests/startup_indirect_draw_indexed.cpp tests/desktop_gpu.cpp) target_compile_features(startup_indirect_draw_indexed PRIVATE cxx_std_17) target_link_libraries(startup_indirect_draw_indexed PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f20261bc1..f3d1108a1 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -31,6 +31,38 @@ records. The control expects the first blend patch to win and must fail. Command-list slot 24 (`OMSetStencilRef`, the desktop slot) passes its reference to the desktop list, as slots 21 to 23 do for viewports, scissors and the blend factor, so a translated draw whose pipeline enables the stencil test compares against it. A closed list ignores the call. The slot number is the desktop one and has not been seen in a title log; `startup_stream_depth_{warp,hardware}` checks the references 0x5A, 0x5B, 0 and 0xFF against a stencil cleared to the matching value. +## Occlusion queries + +Which console methods sit at command-list slots 28 to 30 is not established by any fixture here. The repository +shows only that four console methods sit in 26 to 31 (32 is `SetDescriptorHeaps`, desktop 28 plus four) and that +the plus-four run has ended by 61 (`ExecuteIndirect`, desktop 59 plus two). As a hypothesis, slots 28 to 30 are +implemented as `BeginQuery(heap, type, index)`, `EndQuery(heap, type, index)` and +`ResolveQueryData(heap, type, start, count, buffer, offset)`. Because that is a hypothesis, the bindings are a +diagnostic opt-in: only with `X2W_D3D12_QUERY_SLOTS=1` (in render mode) are the three slots bound. Unset, they stay +no-ops as before. The fixture below calls those slots directly, so it checks the forwarding, the refusals and the +end at Close, not the numbering. + +The query heap comes from device slot 39 with the desktop desc, which the stand-in keeps. Only occlusion and +binary-occlusion queries on an occlusion heap, recorded on a DIRECT list, are forwarded to the desktop list. A +resolve is forwarded only when every index in its range was ended, with the same query type, on the current +recording; a new `BeginQuery` on an index clears its completion, and Close clears all of them. These calls are +refused and logged (`x2w-render ... refused`, the first 16 of each method): another command-list type, an index +outside the heap, an `EndQuery` without a `BeginQuery` on the same list, a resolve over an index not so ended, and +a resolve to anything but a committed readback buffer without title memory, or past that buffer's end. A query +still open at Close is ended there, since the desktop Close would otherwise fail and drop the list. The readback +buffer stays in `COPY_DEST` and is not moved through the list's state tracking. + +Known limit: a resolve recorded on a later list than the `EndQuery` calls it covers is refused. Whether a caller +resolves on the recording that ended its queries has not been observed. + +`startup_list_queries_{warp,hardware}` sets `X2W_D3D12_QUERY_SLOTS=1`. It resolves a query around a draw over an +8x8 target (64 samples) and an empty one (0) into a readback buffer filled with a sentinel, and reads it through +the console `Map`. It then checks that the refused calls, among them resolves over a never-begun index, a range +with a hole and an index ended with the other occlusion type, leave the sentinel untouched with no debug-layer +error, and it leaves one query open at Close. `startup_list_queries_default_{warp,hardware}_control` runs it +without the switch: the slots stay no-ops and it must report the untouched sentinel in the first word. +`command_list_slot_names.h` still names 56 to 58 as the query methods by the plus-four rule. + ## Default viewport and scissor A desktop command list that never sets a viewport or scissor rectangle draws no pixel. A translated @@ -762,6 +794,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}` and, when needed, RTV variants `req_.rtv`. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | +| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | | `X2W_D3D12_DUMP_SURFACE=` | writes the last presented surface | diff --git a/src/startup_stubs/command_list_slot_names.h b/src/startup_stubs/command_list_slot_names.h index f3fa76523..459026157 100644 --- a/src/startup_stubs/command_list_slot_names.h +++ b/src/startup_stubs/command_list_slot_names.h @@ -9,11 +9,15 @@ // the slots between them (0 to 6, 8, 14 to 19, 24) take the desktop names. // - Slots 10 and 11 are not named. The desktop order puts Reset and ClearState there, but this // console list resets through slot 139, so the desktop order is not known to hold at 10 and 11. -// - Slots 26 to 31 are not named. The slots that follow are the desktop ones moved up by four -// (32 is SetDescriptorHeaps, desktop 28), so four console methods sit somewhere in 26 to 31 and -// which desktop slot is which is not known. -// - Slots 32 to 59 are the desktop slots 28 to 55 plus four. Implemented and checked against the -// desktop order: 32, 34, 36, 40, 42, 44, 47, 48, 50 and 52. +// - Slots 26 to 31 are not named here. The slots that follow are the desktop ones moved up by four +// (32 is SetDescriptorHeaps, desktop 28), so four console methods sit somewhere in 26 to 31. +// As a hypothesis, d3d12_xs_device.cpp binds 28, 29 and 30 as BeginQuery, EndQuery and +// ResolveQueryData, only with the diagnostic X2W_D3D12_QUERY_SLOTS=1. No fixture here establishes +// which console methods sit there. +// - Slots 32 to 59 are named as the desktop slots 28 to 55 plus four. Implemented and checked +// against the desktop order: 32, 34, 36, 40, 42, 44, 47, 48, 50 and 52. Past 52 the rule is not +// checked: ExecuteIndirect (desktop 59) is at 61, desktop plus two, so the run of four has ended +// by then. The 56 to 58 names below are kept as the rule gives them. // - Slots 61 (ExecuteIndirect) and 139 (Reset) are implemented in d3d12_xs_device.cpp. // - Other slots have no confirmed meaning. #pragma once diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b539a1e60..06ebdf0e6 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -119,6 +119,7 @@ struct alignas(16) WrapperOwn { UINT indirect_bytes; // CommandSignature: bytes one command reads (root constants plus the Dispatch record) IndirectGraphicsPipeline indirect_graphics; UINT list_node_mask; + D3D12_QUERY_HEAP_DESC query_heap; // QueryHeap: the desc it was created with (device slot 39) }; static_assert(sizeof(WrapperOwn) % 16 == 0, "the title-visible object must stay 16-byte aligned"); struct Wrapper { @@ -1067,6 +1068,7 @@ HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objec // when the desktop GPU finishes, and the presented surface is read back and shown in the window. // Everything else on a list is still dropped. void release_targets(Wrapper* self); +void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list); void reset_viewport_state(Wrapper* self); void discard_draw_sampler_heaps(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); @@ -1366,6 +1368,7 @@ HRESULT __stdcall list_close(Wrapper* self) return S_OK; } auto* list = static_cast(state.real); + end_open_queries(self, list); release_targets(self); const HRESULT hr = list->Close(); state.list_open = false; @@ -1894,6 +1897,13 @@ struct Pass { // the title flags above so a later render target 0 of another size gets a fresh default. UINT64 default_viewport_w = 0, default_scissor_w = 0; UINT default_viewport_h = 0, default_scissor_h = 0; + // Queries begun on the desktop list by slot 28 and not yet ended (heap, type, index). The heap pointer is + // held without a reference until Close; releasing a heap mid-recording is invalid on desktop too. + struct OpenQuery { ID3D12QueryHeap* heap; UINT type, index; }; + std::vector open_queries; + // Queries ended on this recording by slot 29: what a resolve may cover. A new BeginQuery on the index removes its + // entry, and Close clears the list with the rest of the Pass. + std::vector ended_queries; }; LONG render_draws, render_draws_skipped, render_pipelines_real, render_pipelines_missing; // Heap-indexed title root signatures not set on the desktop list, and real draws refused under one, by decision. @@ -1982,6 +1992,125 @@ void __stdcall list_compute_root(Wrapper* self, void* root) if (pass.compute_root) list->SetComputeRootSignature(pass.compute_root); } +// Query slots 28 to 30, as a hypothesis (command_list_slot_names.h): no fixture here establishes which console +// methods sit there, so they are bound only with X2W_D3D12_QUERY_SLOTS=1. The heap reaches device slot 39 with the +// desktop desc. Only occlusion queries are +// forwarded (shortcut: other heap types are refused until a caller needs them); a call that does not fit the +// heap it names is refused and logged with its values instead of reaching the desktop list. +enum QueryMethod { begin_query, end_query, resolve_query }; +void refuse_query(QueryMethod method, const char* reason, UINT type, UINT index, UINT count) +{ + static const char* const names[] = {"BeginQuery", "EndQuery", "ResolveQueryData"}; + static LONG refusals[3]; // the first 16 refusals of each method are logged + if (first_calls(refusals[method], 16)) + log("x2w-render %s refused: %s (type %u, index %u, count %u)", names[method], reason, type, index, count); +} +// The desktop heap behind a wrapped occlusion heap that holds [index, index + count), or null with the reason. +// Only a DIRECT recording is supported in this first slice. +ID3D12QueryHeap* occlusion_heap(ID3D12GraphicsCommandList* list, void* heap, UINT type, UINT index, UINT count, + const char** reason) +{ + if (!list) return *reason = "list is closed", nullptr; + if (list->GetType() != D3D12_COMMAND_LIST_TYPE_DIRECT) return *reason = "requires a direct command list", nullptr; + const Wrapper* w = as_wrapper(heap); + if (!w || w->own().kind != query_heap_kind || !w->own().real) return *reason = "not a desktop query heap", nullptr; + const auto& desc = w->own().query_heap; + if (desc.Type != D3D12_QUERY_HEAP_TYPE_OCCLUSION) return *reason = "only occlusion heaps are forwarded", nullptr; + if (type != D3D12_QUERY_TYPE_OCCLUSION && type != D3D12_QUERY_TYPE_BINARY_OCCLUSION) + return *reason = "query type does not fit an occlusion heap", nullptr; + if (index >= desc.Count || count > desc.Count - index) return *reason = "outside the heap's count", nullptr; + return static_cast(w->own().real); +} +// List slot 28, BeginQuery(heap, type, index). +void __stdcall list_begin_query(Wrapper* self, void* heap, UINT type, UINT index) +{ + auto* list = recording(self); + const char* reason = nullptr; + ID3D12QueryHeap* real = occlusion_heap(list, heap, type, index, 1, &reason); + if (!real) return refuse_query(begin_query, reason, type, index, 1); + Pass& pass = pass_of(self); + for (const auto& open : pass.open_queries) + if (open.heap == real && open.index == index) return refuse_query(begin_query, "query already begun", type, index, 1); + auto& ended = pass.ended_queries; + ended.erase(std::remove_if(ended.begin(), ended.end(), + [&](const Pass::OpenQuery& q) { return q.heap == real && q.index == index; }), + ended.end()); + pass.open_queries.push_back({real, type, index}); + list->BeginQuery(real, static_cast(type), index); +} +// List slot 29, EndQuery(heap, type, index). Only a query this list began is ended. +void __stdcall list_end_query(Wrapper* self, void* heap, UINT type, UINT index) +{ + auto* list = recording(self); + const char* reason = nullptr; + ID3D12QueryHeap* real = occlusion_heap(list, heap, type, index, 1, &reason); + if (!real) return refuse_query(end_query, reason, type, index, 1); + Pass& pass = pass_of(self); + auto& open = pass.open_queries; + const auto found = std::find_if(open.begin(), open.end(), + [&](const Pass::OpenQuery& q) { return q.heap == real && q.type == type && q.index == index; }); + if (found == open.end()) return refuse_query(end_query, "not begun on this list", type, index, 1); + open.erase(found); + pass.ended_queries.push_back({real, type, index}); + list->EndQuery(real, static_cast(type), index); +} +// At Close: a query begun on the desktop list and never ended would make the desktop Close fail and drop the whole +// list, where the console call it stands for cost nothing more than that query's result. +void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!self->own().pass) return; + auto& open = pass_of(self).open_queries; + for (const auto& query : open) { + refuse_query(end_query, "missing at Close, ended there", query.type, query.index, 1); + list->EndQuery(query.heap, static_cast(query.type), query.index); + } + open.clear(); +} +// List slot 30, ResolveQueryData(heap, type, start, count, destination, offset). The destination is a buffer on +// a readback heap, which stays in COPY_DEST, so it is not moved through the list's COMMON state tracking. +void __stdcall list_resolve_query(Wrapper* self, void* heap, UINT type, UINT start, UINT count, void* destination, u64 offset) +{ + auto* list = recording(self); + const char* reason = nullptr; + ID3D12QueryHeap* real = occlusion_heap(list, heap, type, start, count, &reason); + if (!real) return refuse_query(resolve_query, reason, type, start, count); + // Resolving a query that was never ended, or ended with the other occlusion type, reads uninitialized data and + // can remove the device: every index in the range must have a matching EndQuery on this recording. + const auto& ended = pass_of(self).ended_queries; + for (UINT i = 0; i < count; ++i) + if (std::none_of(ended.begin(), ended.end(), [&](const Pass::OpenQuery& q) { + return q.heap == real && q.index == start + i && q.type == type; + })) + return refuse_query(resolve_query, "an index in the range was not ended with this type on this recording", type, + start, count); + const Wrapper* w = as_wrapper(destination); + if (!w || w->own().kind != resource_kind || !w->own().real) + return refuse_query(resolve_query, "destination has no desktop resource", type, start, count); + // Map of a resource with title memory returns that memory, which a desktop resolve never reaches. + if (w->own().title_memory) + return refuse_query(resolve_query, "destination has title memory", type, start, count); + auto* resource = static_cast(w->own().real); + D3D12_HEAP_PROPERTIES properties{}; + const auto desc = resource->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || FAILED(resource->GetHeapProperties(&properties, nullptr)) || + properties.Type != D3D12_HEAP_TYPE_READBACK) + return refuse_query(resolve_query, "destination is not a readback buffer", type, start, count); + const u64 bytes = u64{count} * sizeof(UINT64); + if ((offset & 7) || offset > desc.Width || bytes > desc.Width - offset) + return refuse_query(resolve_query, "outside the destination buffer", type, start, count); + list->ResolveQueryData(real, static_cast(type), start, count, resource, offset); +} +// Device slot 39, CreateQueryHeap(desc, riid, ppv): forwarded, and the desc kept for the query slots. +HRESULT __stdcall device_create_query_heap(Wrapper* self, const D3D12_QUERY_HEAP_DESC* desc, const GUID* iid, void** out) +{ + const auto hr = static_cast(create_slot(self, reinterpret_cast(desc), + reinterpret_cast(iid), reinterpret_cast(out), + 0, 0, 0, 0, 0)); + if (Wrapper* w = SUCCEEDED(hr) && desc && out ? as_wrapper(*out) : nullptr; w && w->own().kind == query_heap_kind) + w->own().query_heap = *desc; + return hr; +} + // The guest method has independent resource and byte-offset arguments. void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) @@ -3748,7 +3877,7 @@ void build_tables() enable_create(); // CreateFence(initial, flags, riid, ppv) enable_forward(); // GetDeviceRemovedReason tables[device_kind][38] = reinterpret_cast(&device_copyable_footprints); - enable_create(); // CreateQueryHeap(desc, riid, ppv) + tables[device_kind][39] = reinterpret_cast(&device_create_query_heap); // CreateQueryHeap(desc, riid, ppv) enable_forward(); // SetStablePowerState tables[device_kind][41] = reinterpret_cast(&device_create_command_signature); // CreateCommandSignature(desc, root, riid, ppv) enable_forward(); // GetResourceTiling @@ -3799,6 +3928,13 @@ void build_tables() list_typed[47] = reinterpret_cast(&list_index_buffer); list_typed[48] = reinterpret_cast(&list_vertex_buffers); list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast(&list_execute_indirect); + // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): which console methods sit at 28 to 30 is a hypothesis, so the query + // bindings are opt-in. Unset, the slots stay no-ops. + if (wchar_t on[4]{}; GetEnvironmentVariableW(L"X2W_D3D12_QUERY_SLOTS", on, 4) && on[0] == L'1') { + list_typed[28] = reinterpret_cast(&list_begin_query); + list_typed[29] = reinterpret_cast(&list_end_query); + list_typed[30] = reinterpret_cast(&list_resolve_query); + } } tables[device_kind][16] = reinterpret_cast(&device_create_root_signature); diff --git a/tests/startup_list_queries.cpp b/tests/startup_list_queries.cpp new file mode 100644 index 000000000..474bc2f19 --- /dev/null +++ b/tests/startup_list_queries.cpp @@ -0,0 +1,297 @@ +// Occlusion queries recorded on a console command list (slots 28, 29 and 30). +// +// startup_list_queries [default] +// +// The probe sets X2W_D3D12_QUERY_SLOTS=1, the opt-in that binds the three slots, unless "default" is given. +// Through D3D12XboxCreateDevice it creates an occlusion query heap of 8 (device slot 39) and a readback buffer +// in COPY_DEST (device slot 27), fills the buffer with a sentinel, and records on a DIRECT console list: +// +// query 0: BeginQuery / EndQuery (slots 28, 29) around a draw that covers an 8x8 target -> 64 samples +// query 1: BeginQuery / EndQuery around nothing -> 0 samples +// query 2: BeginQuery / EndQuery with the pipeline-statistics type on the occlusion heap -> refused +// query 3: EndQuery without a BeginQuery -> refused +// query 4: BeginQuery / EndQuery with the binary-occlusion type -> forwarded +// queries 5 and 7: BeginQuery / EndQuery; query 6 never begun -> forwarded +// query 2: BeginQuery (occlusion) without an EndQuery -> ended at Close +// ResolveQueryData (slot 30) of queries 0 and 1 (occlusion) to word 0 -> forwarded +// Resolves that must leave their words untouched (refused): query 3 (never begun), queries 5 to 7 (a +// hole at 6), query 4 as occlusion (ended with the other type), queries 1 and 2 (2 still open), a range +// past the heap's count, and one past the buffer's end. +// +// Which console methods sit at slots 28 to 30 is a hypothesis: the probe calls those slots directly, so it +// checks the forwarding, the refusals and the end at Close, not the numbering. +// +// The list is submitted and signalled through the console queue. The buffer, read through the console +// resource's Map, must hold 64 and 0 in its first two words and the sentinel everywhere else, and the D3D12 +// debug layer must store no errors. A refused call that reached the desktop list would add one or make the +// desktop Close fail (an EndQuery without its BeginQuery does: exit code 3). +// +// With "default" the opt-in is not set and the three slots stay no-ops, the behaviour before this change: +// the buffer keeps its sentinel and the probe fails with exit code 1. +// +// Exit codes: 0 pass, 1 wrong query results, 2 usage, 3 setup failure, 4 debug-layer error, 77 no physical adapter. +#include +#include +#include +#include +#include + +#include "desktop_gpu.h" + +#include +#include +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Microsoft::WRL::ComPtr; +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f); +} + +constexpr UINT side = 8; +constexpr std::uint64_t sentinel = 0xa5a5a5a5a5a5a5a5ull; +constexpr UINT heap_count = 8, buffer_words = 12; + +constexpr char shader[] = R"( +float4 vs(uint id : SV_VertexID) : SV_Position +{ + return float4(id == 1 ? 3.0 : -1.0, id == 2 ? -3.0 : 1.0, 0.0, 1.0); +} +float4 ps() : SV_Target { return float4(1, 1, 1, 1); } +)"; + +ComPtr compile(const char* entry, const char* target) +{ + ComPtr code, errors; + const HRESULT hr = D3DCompile(shader, sizeof(shader) - 1, nullptr, nullptr, nullptr, entry, target, 0, 0, &code, &errors); + if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); + check(hr, entry); + return code; +} + +template +ComPtr native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) +{ + // SetPrivateDataInterface unwraps a guest argument before the call reaches the shared desktop device. + constexpr GUID key{0x7c1d52a0, 0x3b4e, 0x4f61, {0x9a, 0x0d, 0x51, 0x2e, 0x86, 0x14, 0xc7, 0x3b}}; + check(guest->SetPrivateDataInterface(key, object), "publish underlying object"); + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); + check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); + check(read, "retrieve underlying object"); + ComPtr result; + check(stored.As(&result), "query underlying object"); + return result; +} + +UINT64 debug_errors(ID3D12Device* device) +{ + ComPtr info; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&info)))) return 0; + UINT64 errors = 0; + for (UINT64 i = 0, n = info->GetNumStoredMessages(); i < n; ++i) { + SIZE_T bytes = 0; + if (FAILED(info->GetMessage(i, nullptr, &bytes))) continue; + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(info->GetMessage(i, message, &bytes))) continue; + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + ++errors; + std::fprintf(stderr, "D3D12 debug message %u: %s\n", static_cast(message->ID), message->pDescription); + } + } + return errors; +} +} // namespace + +int main(int argc, char** argv) try +{ + const bool default_slots = argc == 3 && std::strcmp(argv[2], "default") == 0; + if (argc != 2 && !default_slots) return 2; + const bool warp = std::strcmp(argv[1], "warp") == 0; + if (!warp && std::strcmp(argv[1], "hardware") != 0) return 2; + ComPtr debug; + const HRESULT debug_hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debug)); + if (debug_hr != DXGI_ERROR_SDK_COMPONENT_MISSING) check(debug_hr, "get debug layer"); + if (debug) debug->EnableDebugLayer(); + ComPtr factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "create DXGI factory"); + ComPtr adapter; + if (warp) { + check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)), "find WARP"); + } else { + for (UINT index = 0; factory->EnumAdapters1(index, adapter.ReleaseAndGetAddressOf()) == S_OK; ++index) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) break; + } + if (!adapter) return 77; + } + ComPtr device; + check(D3D12XboxCreateDevice(adapter.Get(), nullptr, IID_PPV_ARGS(&device)), "create desktop device through d3d12_xs"); + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_LIST_NOOP", "1"); + SetEnvironmentVariableA("X2W_D3D12_RENDER", "1"); + SetEnvironmentVariableA("X2W_D3D12_QUERY_SLOTS", default_slots ? nullptr : "1"); + const std::array parameters{}; + ComPtr guest; + check(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), IID_PPV_ARGS(&guest)), "create guest device"); + DXGI_ADAPTER_DESC1 adapter_desc{}; + check(adapter->GetDesc1(&adapter_desc), "get adapter description"); + std::printf("adapter: %ls, debug layer %s\n", adapter_desc.Description, debug ? "enabled" : "unavailable"); + LARGE_INTEGER driver{}; + if (SUCCEEDED(adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver))) + std::printf("driver: %u.%u.%u.%u\n", HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), + LOWORD(driver.LowPart)); + + // Desktop draw state: an empty root signature, a full-target triangle, and an 8x8 target with its view. + const D3D12_ROOT_SIGNATURE_DESC root_desc{0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr serialized; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr), "serialize root"); + ComPtr root; + check(device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&root)), + "create root"); + const auto vs = compile("vs", "vs_5_0"); + const auto ps = compile("ps", "ps_5_0"); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.Get(); + pso_desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + pso_desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = ~0u; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pso_desc.SampleDesc.Count = 1; + ComPtr pso; + check(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso)), "create pipeline"); + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const auto target = resource(device.Get(), target_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + ComPtr rtv_heap; + check(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap)), "create view heap"); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rtv); + + // Console objects: the query heap, the readback buffer, a queue, a fence, an allocator and a list. + const D3D12_QUERY_HEAP_DESC heap_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, heap_count, 0}; + ComPtr heap; + check(guest->CreateQueryHeap(&heap_desc, IID_PPV_ARGS(&heap)), "create guest query heap"); + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, buffer_words * sizeof(std::uint64_t), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + ComPtr results; + check(guest->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&results)), "create guest readback buffer"); + void* mapped = nullptr; + check(results->Map(0, nullptr, &mapped), "map guest readback buffer"); + for (UINT i = 0; i < buffer_words; ++i) static_cast(mapped)[i] = sentinel; + results->Unmap(0, nullptr); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + void* queue = nullptr; + void* fence = nullptr; + void* allocator = nullptr; + void* list = nullptr; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + check(static_cast(invoke(guest.Get(), 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))), + "create guest queue"); + check(static_cast(invoke(guest.Get(), 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))), "create guest fence"); + check(static_cast(invoke(guest.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), + arg(&allocator))), "create guest allocator"); + check(static_cast(invoke(guest.Get(), 73, arg(list_desc), arg(allocator), 0, + arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list))), "create guest list"); + check(static_cast(invoke(list, 139, arg(allocator))), "reset guest list"); + const auto native_list = native_object(device.Get(), guest.Get(), + static_cast(list)); + + // The draw is recorded on the desktop list behind the console one; the queries go through the console slots. + auto* desktop = native_list.Get(); + transition(desktop, target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + desktop->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const D3D12_VIEWPORT viewport{0, 0, side, side, 0, 1}; + const D3D12_RECT scissor{0, 0, side, side}; + desktop->RSSetViewports(1, &viewport); + desktop->RSSetScissorRects(1, &scissor); + desktop->SetGraphicsRootSignature(root.Get()); + desktop->SetPipelineState(pso.Get()); + desktop->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const Word occlusion = D3D12_QUERY_TYPE_OCCLUSION, statistics = D3D12_QUERY_TYPE_PIPELINE_STATISTICS; + invoke(list, 28, arg(heap.Get()), occlusion, 0); + desktop->DrawInstanced(3, 1, 0, 0); + invoke(list, 29, arg(heap.Get()), occlusion, 0); + invoke(list, 28, arg(heap.Get()), occlusion, 1); + invoke(list, 29, arg(heap.Get()), occlusion, 1); + invoke(list, 28, arg(heap.Get()), statistics, 2); // refused: the heap holds occlusion queries + invoke(list, 29, arg(heap.Get()), statistics, 2); // refused + invoke(list, 29, arg(heap.Get()), occlusion, 3); // refused: query 3 was never begun + const Word binary = D3D12_QUERY_TYPE_BINARY_OCCLUSION; + invoke(list, 28, arg(heap.Get()), binary, 4); + invoke(list, 29, arg(heap.Get()), binary, 4); + invoke(list, 28, arg(heap.Get()), occlusion, 5); + invoke(list, 29, arg(heap.Get()), occlusion, 5); + invoke(list, 28, arg(heap.Get()), occlusion, 7); + invoke(list, 29, arg(heap.Get()), occlusion, 7); + invoke(list, 28, arg(heap.Get()), occlusion, 2); // never ended: the stand-in ends it at Close + transition(desktop, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COMMON); + invoke(list, 30, arg(heap.Get()), occlusion, 0, 2, arg(results.Get()), 0); + // Each refused resolve below targets its own words, which must keep the sentinel. + invoke(list, 30, arg(heap.Get()), occlusion, 3, 1, arg(results.Get()), 16); // word 2: query 3 never begun + invoke(list, 30, arg(heap.Get()), occlusion, 5, 3, arg(results.Get()), 24); // words 3-5: hole at query 6 + invoke(list, 30, arg(heap.Get()), occlusion, 4, 1, arg(results.Get()), 48); // word 6: query 4 is binary + invoke(list, 30, arg(heap.Get()), occlusion, 1, 2, arg(results.Get()), 56); // words 7-8: query 2 still open + invoke(list, 30, arg(heap.Get()), occlusion, 7, 2, arg(results.Get()), 72); // words 9-10: past the heap's count + invoke(list, 30, arg(heap.Get()), occlusion, 0, 2, arg(results.Get()), 88); // past the buffer's end + check(static_cast(invoke(list, 9)), "close guest list"); + + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + check(static_cast(invoke(queue, 14, arg(fence), 1)), "signal guest fence"); + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < 1) { + if (GetTickCount64() >= deadline) { + std::fprintf(stderr, "the guest fence did not reach 1\n"); + return 3; + } + Sleep(1); + } + check(device->GetDeviceRemovedReason(), "GPU completion"); + + std::uint64_t observed[buffer_words]{}; + const D3D12_RANGE read{0, sizeof(observed)}; + check(results->Map(0, &read, &mapped), "map guest readback buffer"); + std::memcpy(observed, mapped, sizeof(observed)); + const D3D12_RANGE untouched{0, 0}; + results->Unmap(0, &untouched); + std::uint64_t expected[buffer_words]; + for (auto& word : expected) word = sentinel; + expected[0] = side * side; + expected[1] = 0; + std::printf("samples: query 0 = %llu (expected %llu), query 1 = %llu (expected 0)\n", + static_cast(observed[0]), static_cast(expected[0]), + static_cast(observed[1])); + for (UINT i = 0; i < buffer_words; ++i) { + if (observed[i] == expected[i]) continue; + std::fprintf(stderr, "word %u: got 0x%016llx, expected 0x%016llx\n", i, static_cast(observed[i]), + static_cast(expected[i])); + return 1; + } + if (debug_errors(device.Get())) return 4; + return 0; +} +catch (const std::exception&) { + return 3; +}