diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 8bf2bd38ea..afaa0c2780 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2711,11 +2711,38 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a The access itself is never dropped, so the dependency still covers everything the application named, over a slightly larger scope. -- Render passes: `BeginRenderPass`/`EndRenderPass` map to `vkCmdBeginRendering`/`vkCmdEndRendering` (dynamic - rendering). The `D3D12_RENDER_PASS_BEGINNING_ACCESS`/`ENDING_ACCESS` types give the load/store ops and resolve - targets. Suspending/resuming passes have no direct Vulkan equivalent; split them into two rendering scopes with - the same attachments and `LOAD`/`STORE`. If the game does not use render passes, build a rendering scope per draw - from the bound RTVs/DSV and let explicit `Clear*View` calls do the clears. +- Render passes (D3D-27): the device reports `RenderPassesTier = TIER_0`, and `BeginRenderPass`/`EndRenderPass` are + emulated on the list's own commands, as the D3D12 runtime does for a Tier 0 driver. Draws keep their rendering scope + per draw from the bound RTVs/DSV. `BeginRenderPass` binds the pass's RTVs and DSV as `OMSetRenderTargets` does and + records each `CLEAR` beginning access as a `ClearRenderTargetView` or a `ClearDepthStencilView` (the depth and + stencil planes by their own access, in one clear). `PRESERVE`, `DISCARD`, `NO_ACCESS` and the `PRESERVE_LOCAL_*` + accesses record nothing: a discarded target is undefined, so keeping its contents is valid. `RESOLVE` ending + accesses are copied at `BeginRenderPass` (the application's arrays need not outlive the call) and recorded at + `EndRenderPass` as one `ResolveSubresourceRegion` per subresource parameter, with its checks. A `RESUMING_PASS` + skips its clears and a `SUSPENDING_PASS` its resolves, so they run once, in the first and the last part of the pass. + `ALLOW_UAV_WRITES` needs nothing at Tier 0, and the `BIND_READ_ONLY_*` flags use the DSV as it was created. `Close` + follows Windows WARP, measured by `d3d12_render_pass_test` (the host D3D12 runtime on an RTX 5070 Ti, for the cases + #1062's review probed, gave the same codes): `E_INVALIDARG` after `EndRenderPass` with no pass open, after a second + `EndRenderPass` and after a nested `BeginRenderPass`; `E_FAIL` with a pass left open, with more than eight render + targets, for a pass on a bundle or a compute list, and after a call D3D12 forbids inside a pass: + `OMSetRenderTargets`, `ClearRenderTargetView`, `ClearDepthStencilView`, `CopyResource`, `CopyTextureRegion`, + `CopyBufferRegion`, `DiscardResource`, `ResolveSubresource`, `ResolveSubresourceRegion` and `Dispatch` (not + recorded). A resource barrier inside a pass is allowed. WARP ignores a `CLEAR` with no descriptor and a `RESOLVE` + with no source, and so does the layer; a target count with no array faults inside WARP, and the layer makes the list + invalid. Not measured, so not checked: the other calls D3D12 forbids inside a pass (the UAV clears, `CopyTiles`, + `ExecuteIndirect`, queries). `d3d12_render_pass_test` runs eight cases on the Vulkan-backed device and on WARP + through the D3D12 API and compares the bytes read back and the `Close` results, and checks WARP against the values + written in the test: CLEAR and PRESERVE on two colour targets, also with `ALLOW_UAV_WRITES`; a + `D32_FLOAT_S8X24_UINT` target whose depth plane is cleared with stencil PRESERVEd, then whose stencil is cleared + with depth NO_ACCESS; a 4x MSAA colour target CLEARed and RESOLVEd into a 2 x 2 rectangle at (1, 1) of a larger + target; a 4x MSAA `D32_FLOAT` depth RESOLVE (MIN, named `R32_FLOAT`, skipped on a Vulkan device without MIN depth + resolves); the colour pass suspended in one list and resumed in the next of one `ExecuteCommandLists` (the resumed + part's red CLEAR does not run, and the suspended part's RESOLVE, aimed at (0, 0), leaves no trace); and the 29 + `Close` cases above. On an AMD Radeon RX 6600 (AMD Windows driver 26.6.4, Windows 10 19045) all eight pass, also + with `LEONIDA_VK_VALIDATION=1` (0 errors); on `main` before this change all eight fail, and each of seven targeted + mutations of the emulation fails one. Draws inside a pass are not in the test: they use the same per-draw rendering + scope as after `OMSetRenderTargets`. A Tier 1 path, mapping the accesses to `vkCmdBeginRendering` load/store ops and + resolve attachments, is not needed for correctness and is left out. ### 4.4 Fences, queues and frames in flight @@ -3756,7 +3783,7 @@ M0–M2 do not need the executable. | **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0. **Met with stand-in shaders** by `d3d12_draw_test`: every pixel of two indexed draws and a culled triangle matches, through the proxy, validation clean. With translated game shaders most of them declare bindings, which M2 (pipelines bind set 0) lets through. **M1.5 (D3D-53) met with translator output** by `d3d12_translated_draw_test`: see below | | **M1.5** | The same, with real translator output: hand-written RDNA2 VS+PS, PSO found by FSSM hash, vertex fetch through a V# loaded from the user-data table, a root constant, a table in the arena, the code base | The push-constant, vertex-fetch and code-base contracts on translated code | Met by `d3d12_translated_draw_test`: three draws, every pixel off the triangle's edge exact in a float target, validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. An upload buffer behind a V# is not supported (section 3.3) | | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU). Formats, mips and arrays through a PSO: `d3d12_m2_formats_test` samples an 8×8 BC1 and an 8×8 BC7 texture with 4 mips each and an R8G8B8A8 2D array of 3 slices through the same path (every subresource uploaded at its `GetCopyableFootprints` layout, POINT samplers with `MinLOD = MaxLOD` pinning each level, a view from mip 1, two array views read by `ps_m2_array.asm`); all 12 cases match the CPU with error 0, validation clean on the RTX 4070 Ti SUPER, with no layer change needed | -| **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; before the far rectangle, a single-output probe (`ps_m3_query.asm`) uses the same depth/stencil tests with color, depth and stencil writes disabled, inside `BeginQuery`/`EndQuery(OCCLUSION)`, and `ResolveQueryData` writes its sample count to a readback buffer. The actual far-rectangle draw still writes both render targets with depth/stencil writes enabled. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the single-output probe's occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames). The original version was validation clean (including synchronization validation) on the AMD Radeon 880M and the RTX 5070 Laptop; current probe/isolation results are recorded below. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | +| **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; before the far rectangle, a single-output probe (`ps_m3_query.asm`) uses the same depth/stencil tests with color, depth and stencil writes disabled, inside `BeginQuery`/`EndQuery(OCCLUSION)`, and `ResolveQueryData` writes its sample count to a readback buffer. The actual far-rectangle draw still writes both render targets with depth/stencil writes enabled. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the single-output probe's occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames). The original version was validation clean (including synchronization validation) on the AMD Radeon 880M and the RTX 5070 Laptop; current probe/isolation results are recorded below. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). Render passes (`BeginRenderPass`/`EndRenderPass`, D3D-27) are emulated at Tier 0 and checked against WARP by `d3d12_render_pass_test` (section 4.3), not in this frame test. **Still open for M3:** `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | | **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one); and a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker followed submission order, so a copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error): such a batch is now held on the CPU until a Signal that satisfies its Wait has been submitted, and recorded in dependency order (section 4.4, "Wait before Signal across queues"; `d3d12_queue_handover_test`, every queue-type and submission order, exact against the host runtime). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; buffer SRVs and CBVs as V#s (typed buffer UAVs and UAV counters are done: `d3d12_buffer_uav_test`, section 3.4 "Buffer UAVs"), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | | **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3b334c7133..fbd8163a8c 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2353,6 +2353,14 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_rgb96 PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU or no WARP adapter set_tests_properties(d3d12_typeless_rtv PROPERTIES SKIP_RETURN_CODE 77) + # Render passes (D3D-27): Tier 0 emulation against Windows WARP. + add_executable(d3d12_render_pass_test test/d3d12_render_pass_test.cpp) + target_link_libraries(d3d12_render_pass_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_render_pass_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_render_pass_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_render_pass COMMAND d3d12_render_pass_test) + set_tests_properties(d3d12_render_pass PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU or no WARP adapter + # Depth/stencil ResolveSubresourceRegion against the host runtime and WARP; run explicitly on a Vulkan GPU. add_executable(d3d12_depth_resolve_test test/d3d12_depth_resolve_test.cpp) target_link_libraries(d3d12_depth_resolve_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..5cf79e612b 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -217,8 +217,18 @@ class GraphicsCommandList final HRESULT STDMETHODCALLTYPE Close() override { constexpr auto method = "ID3D12GraphicsCommandList::Close"; if (list_.queries_open()) invalid_ = true; + // A render pass ends in the list that began it; one that continues in a later list ends here too, with + // SUSPENDING_PASS. A pass left open, a call D3D12 forbids inside a pass, and a pass on a list that cannot + // record one make Close E_FAIL rather than E_INVALIDARG, as on Windows WARP and NVIDIA's D3D12 runtime (D3D-27, + // d3d12_render_pass_test). + const bool pass_failed = in_render_pass_ || pass_misuse_; if (!list_.close()) return d3d12_trace::result(method, E_FAIL); stop_recording(); + if (pass_failed) { + in_render_pass_ = false; + invalid_ = true; + return d3d12_trace::result(method, E_FAIL); + } return d3d12_trace::result(method, invalid_ ? E_INVALIDARG : S_OK); } @@ -233,6 +243,8 @@ class GraphicsCommandList final if (!list_.reset()) return d3d12_trace::result(method, E_FAIL); // D3D12 resets only closed lists record_into(command_allocator); invalid_ = false; + in_render_pass_ = pass_suspending_ = pass_misuse_ = false; // here, not in reset_state: ClearState keeps them + pass_resolves_.clear(); calls_.clear(); release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default @@ -366,6 +378,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE Dispatch(UINT x, UINT y, UINT z) override { d3d12_trace::record("ID3D12GraphicsCommandList::Dispatch"); + if (forbidden_in_pass()) return; if (defer([=](GraphicsCommandList& l) { l.record_dispatch(x, y, z); }, true)) return; record_dispatch(x, y, z); } @@ -435,8 +448,15 @@ class GraphicsCommandList final // D3D12 reads render-target and depth descriptors here, so their views are copied now. void STDMETHODCALLTYPE OMSetRenderTargets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override { + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); + bind_targets(count, targets, single_range, depth); + } + + // OMSetRenderTargets' binding, shared with BeginRenderPass. + void bind_targets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range, + const D3D12_CPU_DESCRIPTOR_HANDLE* depth) { render_targets_.fill({}); render_target_count_ = count; draw_views_stale_ = true; @@ -557,6 +577,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE CopyBufferRegion(ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, UINT64 src_offset, UINT64 bytes) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyBufferRegion"); + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); check(list_.copy_buffer({resource_id(dst), dst_offset, resource_id(src), src_offset, bytes})); } @@ -612,6 +633,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE CopyTextureRegion(const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src, const D3D12_BOX* box) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyTextureRegion"); + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!dst || !src) return check(false); leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}}; @@ -621,6 +643,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override { d3d12_trace::record("ID3D12GraphicsCommandList::CopyResource"); + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (dst && dst == src) { // A self-copy on a DEFAULT heap is a no-op, but an UPLOAD/READBACK resource still cannot @@ -637,6 +660,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE ResolveSubresource(ID3D12Resource* dst, UINT dst_subresource, ID3D12Resource* src, UINT src_subresource, DXGI_FORMAT format) override { d3d12_trace::record("ID3D12GraphicsCommandList::ResolveSubresource"); + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); const auto integer_color = [](ID3D12Resource* resource) { if (!resource) return false; @@ -655,7 +679,112 @@ class GraphicsCommandList final ID3D12Resource* src, UINT src_subresource, D3D12_RECT* rect, DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) override { d3d12_trace::record("ID3D12GraphicsCommandList1::ResolveSubresourceRegion"); + if (forbidden_in_pass()) return; if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); + resolve_region(dst, dst_subresource, x, y, src, src_subresource, rect, format, mode); + } + + // ID3D12GraphicsCommandList4 render passes, emulated at RenderPassesTier 0 on the list's own commands (D3D-27, + // docs/d3d12_vulkan.md section 4.3). BeginRenderPass binds the pass's targets as OMSetRenderTargets does and runs + // the CLEAR beginning accesses as ClearRenderTargetView / ClearDepthStencilView (the depth and stencil planes each + // by their own access). PRESERVE, DISCARD, NO_ACCESS and the PRESERVE_LOCAL_* accesses need no command: a + // discarded target's contents are undefined, so keeping them is valid. The RESOLVE ending accesses are copied + // here, since the application's arrays need not outlive the call, and run at EndRenderPass as + // ResolveSubresourceRegion does. A pass that resumes a suspended one skips its clears, and a pass that suspends + // skips its resolves: those belong to the first and the last part of the pass. Direct lists only, one pass at a + // time. As on Windows WARP (d3d12_render_pass_test), a CLEAR with no descriptor and a RESOLVE with no source, + // destination or parameters are skipped without an error, and more than eight targets fail Close with E_FAIL. + void STDMETHODCALLTYPE BeginRenderPass(UINT count, const D3D12_RENDER_PASS_RENDER_TARGET_DESC* targets, + const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* depth, + D3D12_RENDER_PASS_FLAGS flags) override { + d3d12_trace::record("ID3D12GraphicsCommandList4::BeginRenderPass"); + if (list_.closed()) return check(false); + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) { // E_FAIL at Close on a bundle or a compute list + pass_misuse_ = true; + return; + } + if (in_render_pass_) return check(false); // nested: the open pass stays open + // From here the pass is open, even if nothing is recorded, so its EndRenderPass is not a second error. + in_render_pass_ = true; + pass_resolves_.clear(); + pass_suspending_ = flags & D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS; + if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) { + pass_misuse_ = true; + return; + } + if (count && !targets) return check(false); // the D3D12 runtime faults on this one + if (flags & D3D12_RENDER_PASS_FLAG_ALLOW_UAV_WRITES) + note_once("BeginRenderPass: ALLOW_UAV_WRITES needs no command at RenderPassesTier 0"); + if (flags & (D3D12_RENDER_PASS_FLAG_BIND_READ_ONLY_DEPTH | D3D12_RENDER_PASS_FLAG_BIND_READ_ONLY_STENCIL)) + note_once("BeginRenderPass: BIND_READ_ONLY_DEPTH/STENCIL use the DSV as it was created"); + const bool resuming = flags & D3D12_RENDER_PASS_FLAG_RESUMING_PASS; + const auto clears = [&](const D3D12_RENDER_PASS_BEGINNING_ACCESS& access) { + return access.Type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR && !resuming; + }; + const auto resolves = [](const D3D12_RENDER_PASS_ENDING_ACCESS& access) { + return access.Type == D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE; + }; + + std::array handles{}; + for (UINT i = 0; i < count; ++i) handles[i] = targets[i].cpuDescriptor; + const D3D12_CPU_DESCRIPTOR_HANDLE depth_handle = depth ? depth->cpuDescriptor : D3D12_CPU_DESCRIPTOR_HANDLE{}; + bind_targets(count, count ? handles.data() : nullptr, FALSE, depth ? &depth_handle : nullptr); + + for (UINT i = 0; i < count; ++i) { + const auto& target = targets[i]; + if (clears(target.BeginningAccess) && target.cpuDescriptor.ptr) { + const FLOAT* color = target.BeginningAccess.Clear.ClearValue.Color; + check(list_.clear_render_target(*reinterpret_cast(target.cpuDescriptor.ptr), + {color[0], color[1], color[2], color[3]}, {})); + } + if (resolves(target.EndingAccess)) keep_resolve(target.EndingAccess.Resolve); + } + if (!depth) return; + UINT clear_flags = 0; + if (clears(depth->DepthBeginningAccess)) clear_flags |= D3D12_CLEAR_FLAG_DEPTH; + if (clears(depth->StencilBeginningAccess)) clear_flags |= D3D12_CLEAR_FLAG_STENCIL; + if (clear_flags && depth->cpuDescriptor.ptr) { + const auto& depth_value = depth->DepthBeginningAccess.Clear.ClearValue.DepthStencil; + const auto& stencil_value = depth->StencilBeginningAccess.Clear.ClearValue.DepthStencil; + check(list_.clear_depth_stencil(*reinterpret_cast(depth->cpuDescriptor.ptr), + clear_flags, depth_value.Depth, stencil_value.Stencil, {})); + } + if (resolves(depth->DepthEndingAccess)) keep_resolve(depth->DepthEndingAccess.Resolve); + if (resolves(depth->StencilEndingAccess)) keep_resolve(depth->StencilEndingAccess.Resolve); + } + + void STDMETHODCALLTYPE EndRenderPass() override { + d3d12_trace::record("ID3D12GraphicsCommandList4::EndRenderPass"); + if (list_.closed()) return check(false); + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) { // E_FAIL at Close, as BeginRenderPass + pass_misuse_ = true; + return; + } + if (!in_render_pass_) return check(false); + in_render_pass_ = false; + if (!pass_suspending_) { + for (auto& resolve : pass_resolves_) { + for (auto& sub : resolve.subresources) + resolve_region(resolve.dst, sub.DstSubresource, sub.DstX, sub.DstY, resolve.src, + sub.SrcSubresource, &sub.SrcRect, resolve.format, resolve.mode); + } + } + pass_resolves_.clear(); + } + + // D3D12 forbids these calls inside a render pass: OMSetRenderTargets, the RTV/DSV clears, the copies, discards, + // resolves and Dispatch. Each one makes Close E_FAIL there (measured on Windows WARP, and on NVIDIA's D3D12 runtime + // in #1062's review) and is not recorded. + bool forbidden_in_pass() { + if (!in_render_pass_) return false; + pass_misuse_ = true; + return true; + } + + // The checks and the command of ResolveSubresourceRegion, without its trace line (a render pass resolve is + // traced as EndRenderPass). + void resolve_region(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, ID3D12Resource* src, + UINT src_subresource, D3D12_RECT* rect, DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) { leonida::ResolveRegion region{x, y, std::nullopt}; if (mode != D3D12_RESOLVE_MODE_AVERAGE || !color_resolve_format_matches(format, dst, src)) { if (!depth_stencil_resolve_supported(format, dst, dst_subresource, x, y, src, src_subresource, rect, @@ -696,6 +825,7 @@ class GraphicsCommandList final void STDMETHODCALLTYPE ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE view, const FLOAT color[4], UINT count, const D3D12_RECT* rects) override { d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr || !color) return check(false); check(list_.clear_render_target(*reinterpret_cast(view.ptr), @@ -706,6 +836,7 @@ class GraphicsCommandList final FLOAT depth, UINT8 stencil, UINT count, const D3D12_RECT* rects) override { d3d12_trace::record("ID3D12GraphicsCommandList::ClearDepthStencilView"); + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!view.ptr) return check(false); check(list_.clear_depth_stencil(*reinterpret_cast(view.ptr), u(flags), depth, @@ -714,6 +845,7 @@ class GraphicsCommandList final // A null region discards the whole resource. Not allowed in a bundle. void STDMETHODCALLTYPE DiscardResource(ID3D12Resource* resource, const D3D12_DISCARD_REGION* region) override { + if (forbidden_in_pass()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!region) return check(list_.discard({resource_id(resource), 0, 0, false, true})); if (region->NumRects && !region->pRects) return check(false); @@ -1275,6 +1407,31 @@ class GraphicsCommandList final leonida::TargetView depth_{}; std::array blend_factor_{1, 1, 1, 1}; + // The open render pass: its RESOLVE ending accesses, copied at BeginRenderPass, and whether it suspends. + struct PassResolve { + ID3D12Resource* src = nullptr; + ID3D12Resource* dst = nullptr; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + D3D12_RESOLVE_MODE mode = D3D12_RESOLVE_MODE_AVERAGE; + std::vector subresources; + }; + std::vector pass_resolves_; + bool in_render_pass_ = false; + bool pass_suspending_ = false; + // A call D3D12 forbids inside a pass, or a pass on a list that cannot record one: Close returns E_FAIL. + bool pass_misuse_ = false; + + // A RESOLVE with no source, destination or parameters is skipped, as on Windows WARP. + void keep_resolve(const D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS& resolve) { + if (!resolve.pSrcResource || !resolve.pDstResource || + (resolve.SubresourceCount && !resolve.pSubresourceParameters)) + return; + PassResolve kept{resolve.pSrcResource, resolve.pDstResource, resolve.Format, resolve.ResolveMode, {}}; + kept.subresources.assign(resolve.pSubresourceParameters, + resolve.pSubresourceParameters + resolve.SubresourceCount); + pass_resolves_.push_back(std::move(kept)); + } + // The root signatures and pipeline states this recording uses. D3D12 lets an application release them right // after Set*RootSignature / SetPipelineState; the list keeps them until Reset or its own release, so the root // layout it reads and the pipeline ExecuteCommandLists looks up still exist. (Keeping them alive while the GPU diff --git a/runtime/test/d3d12_render_pass_test.cpp b/runtime/test/d3d12_render_pass_test.cpp new file mode 100644 index 0000000000..c57a2c2ca0 --- /dev/null +++ b/runtime/test/d3d12_render_pass_test.cpp @@ -0,0 +1,691 @@ +// ID3D12GraphicsCommandList4 render passes (D3D-27) on the Vulkan-backed list, compared byte for byte with Windows WARP +// through the D3D12 API on both sides: CLEAR and PRESERVE beginning accesses on two render targets (also with +// ALLOW_UAV_WRITES), the depth and stencil planes cleared by their own accesses, an MSAA colour RESOLVE ending access +// into a rectangle of a larger target and a depth one, a pass suspended in one list and resumed in the next, and what +// Close returns in 29 list cases: pass nesting, the calls D3D12 forbids inside a pass, passes on bundles and compute +// lists, and descriptions WARP ignores or refuses. Every case also checks WARP against the values written here, so it +// cannot pass by both sides being wrong. +// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include +#include +#include +#include +#include +#include +#include +#include +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { +template +struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } +}; +struct Event { + HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); + ~Event() { if (handle) CloseHandle(handle); } +}; + +constexpr UINT kSize = 4; // every target is 4 x 4 +constexpr DXGI_FORMAT kColor = DXGI_FORMAT_R8G8B8A8_UNORM; +constexpr DXGI_FORMAT kDepth = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + +// What a case leaves behind: the bytes of every subresource it reads back, and the HRESULTs it records. +struct Result { + std::vector> images; + std::vector results; +}; + +// One queue, fence and readback path per case. `list` is the first list; `second()` makes another one, for the +// suspend/resume case. +struct Context { + ID3D12Device* device = nullptr; + Ref queue; + Ref allocator, allocator2; + Ref list, list2; + Ref fence; + UINT64 fence_value = 0; + std::deque> readbacks; // a deque: Ref is not movable, and the buffers must not move + struct Pending { + ID3D12Resource* readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint; + UINT bytes; + UINT64 size; + }; + std::vector pending; + + bool create(ID3D12Device* d) { + device = d; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + return true; + } + bool second() { + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator2.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator2.p, nullptr, + IID_PPV_ARGS(&list2.p)))); + return true; + } + + bool texture(DXGI_FORMAT format, UINT samples, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state, + Ref& out) { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = desc.Height = kSize; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.Format = format; + desc.SampleDesc.Count = samples; + desc.Flags = flags; + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p)))); + return true; + } + + // A descriptor heap of `count` RTVs or DSVs; handle(i) is its i-th slot. + struct Heap { + Ref heap; + UINT increment = 0; + D3D12_CPU_DESCRIPTOR_HANDLE handle(UINT i) const { + auto h = heap.p->GetCPUDescriptorHandleForHeapStart(); + h.ptr += SIZE_T(i) * increment; + return h; + } + }; + bool heap(D3D12_DESCRIPTOR_HEAP_TYPE type, UINT count, Heap& out) { + const D3D12_DESCRIPTOR_HEAP_DESC desc{type, count, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&out.heap.p)))); + out.increment = device->GetDescriptorHandleIncrementSize(type); + return true; + } + + static void barrier(ID3D12GraphicsCommandList* l, ID3D12Resource* resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = resource; + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = before; + b.Transition.StateAfter = after; + l->ResourceBarrier(1, &b); + } + + // Records a copy of one subresource (already in COPY_SOURCE) to a new readback buffer; finish() reads it. + bool read(ID3D12GraphicsCommandList* l, ID3D12Resource* resource, UINT subresource, UINT bytes) { + const auto desc = resource->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + device->GetCopyableFootprints(&desc, subresource, 1, 0, &footprint, nullptr, nullptr, &total); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_READBACK; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = total; + buffer.Height = buffer.SampleDesc.Count = 1; + buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + readbacks.emplace_back(); + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readbacks.back().p)))); + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = resource; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = subresource; + dst.pResource = readbacks.back().p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = footprint; + l->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + pending.push_back({readbacks.back().p, footprint, bytes, total}); + return true; + } + + // Closes and executes the lists in one ExecuteCommandLists, waits, and appends every pending readback. + bool finish(Result& result, bool both = false) { + CHECK(SUCCEEDED(list->Close())); + if (both) CHECK(SUCCEEDED(list2->Close())); + ID3D12CommandList* lists[] = {list.p, list2.p}; + queue->ExecuteCommandLists(both ? 2 : 1, lists); + CHECK(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + Event event; + CHECK(event.handle); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(fence_value, event.handle))); + CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); + for (const auto& p : pending) { + void* mapped = nullptr; + const D3D12_RANGE range{0, SIZE_T(p.size)}; + CHECK(SUCCEEDED(p.readback->Map(0, &range, &mapped)) && mapped); + std::vector pixels; + for (UINT row = 0; row < p.footprint.Footprint.Height; ++row) { + const auto* start = static_cast(mapped) + row * p.footprint.Footprint.RowPitch; + pixels.insert(pixels.end(), start, start + p.footprint.Footprint.Width * p.bytes); + } + const D3D12_RANGE none{}; + p.readback->Unmap(0, &none); + result.images.push_back(std::move(pixels)); + } + pending.clear(); + return true; + } +}; + +D3D12_RENDER_PASS_BEGINNING_ACCESS begin_access(D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE type, + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN, + std::array color = {}, float depth = 0, UINT8 stencil = 0) { + D3D12_RENDER_PASS_BEGINNING_ACCESS access{}; + access.Type = type; + if (type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR) { + access.Clear.ClearValue.Format = format; + if (format == kDepth || format == DXGI_FORMAT_D32_FLOAT) { + access.Clear.ClearValue.DepthStencil = {depth, stencil}; + } else { + std::memcpy(access.Clear.ClearValue.Color, color.data(), sizeof(float) * 4); + } + } + return access; +} + +D3D12_RENDER_PASS_ENDING_ACCESS end_access(D3D12_RENDER_PASS_ENDING_ACCESS_TYPE type) { + D3D12_RENDER_PASS_ENDING_ACCESS access{}; + access.Type = type; + return access; +} + +constexpr auto kBeginPreserve = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE; +constexpr auto kBeginClear = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR; +constexpr auto kBeginNoAccess = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_NO_ACCESS; +constexpr auto kEndPreserve = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE; +constexpr auto kEndNoAccess = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_NO_ACCESS; +constexpr auto kEndResolve = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE; +constexpr auto kRT = D3D12_RESOURCE_STATE_RENDER_TARGET; +constexpr auto kCopySrc = D3D12_RESOURCE_STATE_COPY_SOURCE; + +// Two colour targets cleared red and blue before the pass; the pass CLEARs the first to green and PRESERVEs the +// second. Expected: green, blue. `flags` is the pass's (ALLOW_UAV_WRITES must change nothing at Tier 0). +bool clear_and_preserve(ID3D12Device* device, D3D12_RENDER_PASS_FLAGS flags, Result& result) { + Context c; + CHECK(c.create(device)); + Ref rt[2]; + for (auto& r : rt) CHECK(c.texture(kColor, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, kRT, r)); + Context::Heap rtv; + CHECK(c.heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, rtv)); + for (UINT i = 0; i < 2; ++i) device->CreateRenderTargetView(rt[i].p, nullptr, rtv.handle(i)); + const FLOAT red[4]{1, 0, 0, 1}, blue[4]{0, 0, 1, 1}; + c.list->ClearRenderTargetView(rtv.handle(0), red, 0, nullptr); + c.list->ClearRenderTargetView(rtv.handle(1), blue, 0, nullptr); + D3D12_RENDER_PASS_RENDER_TARGET_DESC targets[2]{}; + targets[0] = {rtv.handle(0), begin_access(kBeginClear, kColor, {0, 1, 0, 1}), end_access(kEndPreserve)}; + targets[1] = {rtv.handle(1), begin_access(kBeginPreserve), end_access(kEndPreserve)}; + c.list->BeginRenderPass(2, targets, nullptr, flags); + c.list->EndRenderPass(); + for (auto& r : rt) { + Context::barrier(c.list.p, r.p, kRT, kCopySrc); + CHECK(c.read(c.list.p, r.p, 0, 4)); + } + return c.finish(result); +} + +// A D32_FLOAT_S8X24 target cleared to depth 1, stencil 3 before the passes. Pass 1 CLEARs depth to 0.25 and +// PRESERVEs stencil; with `second`, pass 2 leaves depth (NO_ACCESS) and CLEARs stencil to 9. Expected: +// 0.25 / 3 after pass 1, 0.25 / 9 after pass 2. +bool depth_and_stencil_planes(ID3D12Device* device, bool second, Result& result) { + Context c; + CHECK(c.create(device)); + Ref ds; + CHECK(c.texture(kDepth, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE, ds)); + Context::Heap dsv; + CHECK(c.heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, dsv)); + device->CreateDepthStencilView(ds.p, nullptr, dsv.handle(0)); + c.list->ClearDepthStencilView(dsv.handle(0), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 3, 0, + nullptr); + D3D12_RENDER_PASS_DEPTH_STENCIL_DESC pass1{}; + pass1.cpuDescriptor = dsv.handle(0); + pass1.DepthBeginningAccess = begin_access(kBeginClear, kDepth, {}, 0.25f, 0); + pass1.StencilBeginningAccess = begin_access(kBeginPreserve); + pass1.DepthEndingAccess = end_access(kEndPreserve); + pass1.StencilEndingAccess = end_access(kEndPreserve); + c.list->BeginRenderPass(0, nullptr, &pass1, D3D12_RENDER_PASS_FLAG_NONE); + c.list->EndRenderPass(); + if (second) { + D3D12_RENDER_PASS_DEPTH_STENCIL_DESC pass2{}; + pass2.cpuDescriptor = dsv.handle(0); + pass2.DepthBeginningAccess = begin_access(kBeginNoAccess); + pass2.StencilBeginningAccess = begin_access(kBeginClear, kDepth, {}, 0, 9); + pass2.DepthEndingAccess = end_access(kEndNoAccess); + pass2.StencilEndingAccess = end_access(kEndPreserve); + c.list->BeginRenderPass(0, nullptr, &pass2, D3D12_RENDER_PASS_FLAG_NONE); + c.list->EndRenderPass(); + } + Context::barrier(c.list.p, ds.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, kCopySrc); + CHECK(c.read(c.list.p, ds.p, 0, 4)); // the depth plane, R32_FLOAT + CHECK(c.read(c.list.p, ds.p, 1, 1)); // the stencil plane, R8_UINT + return c.finish(result); +} + +// A 4x MSAA colour target CLEARed in the pass and RESOLVEd at its end into the 2 x 2 rectangle at (1, 1) of a +// single-sample target cleared blue before. With `suspend`, the pass is split: it suspends in the first list and +// resumes in the second, whose CLEAR (red) and the first part's RESOLVE are the ones D3D12 does not run. The first +// part's RESOLVE names the rectangle at (0, 0) instead, so running it would show. Expected: the clear colour in the +// rectangle at (1, 1), blue around it. +bool msaa_resolve(ID3D12Device* device, bool suspend, Result& result) { + Context c; + CHECK(c.create(device)); + if (suspend) CHECK(c.second()); + Ref msaa, dst; + CHECK(c.texture(kColor, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, kRT, msaa)); + CHECK(c.texture(kColor, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, kRT, dst)); + Context::Heap rtv; + CHECK(c.heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, rtv)); + device->CreateRenderTargetView(msaa.p, nullptr, rtv.handle(0)); + device->CreateRenderTargetView(dst.p, nullptr, rtv.handle(1)); + const FLOAT blue[4]{0, 0, 1, 1}; + c.list->ClearRenderTargetView(rtv.handle(1), blue, 0, nullptr); + Context::barrier(c.list.p, dst.p, kRT, D3D12_RESOURCE_STATE_RESOLVE_DEST); + + D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS sub{0, 0, 1, 1, {0, 0, 2, 2}}; + D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS corner{0, 0, 0, 0, {0, 0, 2, 2}}; + const auto pass = [&](ID3D12GraphicsCommandList4* l, std::array color, D3D12_RENDER_PASS_FLAGS flags, + D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS* where) { + D3D12_RENDER_PASS_RENDER_TARGET_DESC target{}; + target.cpuDescriptor = rtv.handle(0); + target.BeginningAccess = begin_access(kBeginClear, kColor, color); + target.EndingAccess = end_access(kEndResolve); + auto& resolve = target.EndingAccess.Resolve; + resolve.pSrcResource = msaa.p; + resolve.pDstResource = dst.p; + resolve.SubresourceCount = 1; + resolve.pSubresourceParameters = where; + resolve.Format = kColor; + resolve.ResolveMode = D3D12_RESOLVE_MODE_AVERAGE; + resolve.PreserveResolveSource = FALSE; + l->BeginRenderPass(1, &target, nullptr, flags); + l->EndRenderPass(); + }; + // 0.2 / 0.4 / 0.6 / 0.8 are exact enough in UNORM8 that every sample averages to the same byte. + ID3D12GraphicsCommandList4* last = c.list.p; + if (suspend) { + pass(c.list.p, {0.2f, 0.4f, 0.6f, 0.8f}, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS, &corner); + pass(c.list2.p, {1, 0, 0, 1}, D3D12_RENDER_PASS_FLAG_RESUMING_PASS, &sub); + last = c.list2.p; + } else { + pass(c.list.p, {0.2f, 0.4f, 0.6f, 0.8f}, D3D12_RENDER_PASS_FLAG_NONE, &sub); + } + Context::barrier(last, dst.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, kCopySrc); + CHECK(c.read(last, dst.p, 0, 4)); + return c.finish(result, suspend); +} + +// A 4x MSAA D32_FLOAT target whose depth the pass CLEARs to 0.25 and RESOLVEs at its end (MIN, named R32_FLOAT: +// WARP removes the device for a D32_FLOAT resolve format, see d3d12_depth_resolve_test) into a single-sample target +// cleared to 1 before. Expected: 0.25 everywhere. +bool depth_resolve(ID3D12Device* device, Result& result) { + Context c; + CHECK(c.create(device)); + constexpr auto d32 = DXGI_FORMAT_D32_FLOAT; + constexpr auto depth_write = D3D12_RESOURCE_STATE_DEPTH_WRITE; + Ref msaa, dst; + CHECK(c.texture(d32, 4, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, depth_write, msaa)); + CHECK(c.texture(d32, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, depth_write, dst)); + Context::Heap dsv; + CHECK(c.heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, dsv)); + device->CreateDepthStencilView(msaa.p, nullptr, dsv.handle(0)); + device->CreateDepthStencilView(dst.p, nullptr, dsv.handle(1)); + c.list->ClearDepthStencilView(dsv.handle(1), D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + Context::barrier(c.list.p, dst.p, depth_write, D3D12_RESOURCE_STATE_RESOLVE_DEST); + D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS sub{0, 0, 0, 0, {0, 0, LONG(kSize), LONG(kSize)}}; + D3D12_RENDER_PASS_DEPTH_STENCIL_DESC pass{}; + pass.cpuDescriptor = dsv.handle(0); + pass.DepthBeginningAccess = begin_access(kBeginClear, d32, {}, 0.25f, 0); + pass.StencilBeginningAccess = begin_access(kBeginNoAccess); + pass.DepthEndingAccess = end_access(kEndResolve); + auto& resolve = pass.DepthEndingAccess.Resolve; + resolve.pSrcResource = msaa.p; + resolve.pDstResource = dst.p; + resolve.SubresourceCount = 1; + resolve.pSubresourceParameters = ⊂ + resolve.Format = DXGI_FORMAT_R32_FLOAT; + resolve.ResolveMode = D3D12_RESOLVE_MODE_MIN; + resolve.PreserveResolveSource = FALSE; + pass.StencilEndingAccess = end_access(kEndNoAccess); + c.list->BeginRenderPass(0, nullptr, &pass, D3D12_RENDER_PASS_FLAG_NONE); + c.list->EndRenderPass(); + Context::barrier(c.list.p, dst.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, kCopySrc); + CHECK(c.read(c.list.p, dst.p, 0, 4)); + return c.finish(result); +} + +// What Close returns, each case on a list of its own: pass nesting and order, suspend and resume, the calls D3D12 +// forbids inside a pass, and passes on lists that cannot record one. The names are printed on a mismatch. +const char* const kListCases[] = { + "EndRenderPass without a pass", "a pass left open", "a nested BeginRenderPass", "a valid pass", + "EndRenderPass twice", "a SUSPENDING pass", "a RESUMING pass", "a pass with no targets", + "ResourceBarrier in a pass", "OMSetRenderTargets in a pass", "ClearRenderTargetView in a pass", + "ClearDepthStencilView in a pass", "CopyResource in a pass", "CopyTextureRegion in a pass", + "CopyBufferRegion in a pass", "DiscardResource in a pass", "ResolveSubresource in a pass", + "ResolveSubresourceRegion in a pass", "Dispatch in a pass", "a pass on a bundle", "a pass on a compute list", + "EndRenderPass on a bundle", "EndRenderPass on a compute list", "BeginRenderPass on a bundle", + "BeginRenderPass on a compute list", "a CLEAR with a null RTV", "a depth CLEAR with a null DSV", + "a RESOLVE with no source", "nine render targets", +}; + +bool list_errors(ID3D12Device* device, Result& result) { + Context c; + CHECK(c.create(device)); + Ref rt, rt2, msaa, single, ds, buffer, buffer2; + CHECK(c.texture(kColor, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, kRT, rt)); + CHECK(c.texture(kColor, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_DEST, rt2)); + CHECK(c.texture(kColor, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE, msaa)); + CHECK(c.texture(kColor, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_DEST, single)); + CHECK(c.texture(kDepth, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE, ds)); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.SampleDesc.Count = 1; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer.p)))); + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer2.p)))); + Context::Heap rtv, dsv; + CHECK(c.heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, rtv)); + CHECK(c.heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, dsv)); + device->CreateRenderTargetView(rt.p, nullptr, rtv.handle(0)); + device->CreateDepthStencilView(ds.p, nullptr, dsv.handle(0)); + D3D12_RENDER_PASS_RENDER_TARGET_DESC target{rtv.handle(0), begin_access(kBeginPreserve), end_access(kEndPreserve)}; + const auto begin = [&](ID3D12GraphicsCommandList4* l, D3D12_RENDER_PASS_FLAGS flags) { + l->BeginRenderPass(1, &target, nullptr, flags); + }; + constexpr auto none = D3D12_RENDER_PASS_FLAG_NONE; + // Records `body` on a new list of `type` and appends what its Close returns. + const auto close_after = [&](D3D12_COMMAND_LIST_TYPE type, auto&& body) { + Ref allocator; + Ref list; + CHECK(SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); + body(list.p); + result.results.push_back(list->Close()); + return true; + }; + constexpr auto direct = D3D12_COMMAND_LIST_TYPE_DIRECT; + const auto in_pass = [&](auto&& call) { + return close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + begin(l, none); + call(l); + l->EndRenderPass(); + }); + }; + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { l->EndRenderPass(); })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { begin(l, none); })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + begin(l, none); + begin(l, none); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + begin(l, none); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + begin(l, none); + l->EndRenderPass(); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + begin(l, D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + begin(l, D3D12_RENDER_PASS_FLAG_RESUMING_PASS); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + l->BeginRenderPass(0, nullptr, nullptr, none); + l->EndRenderPass(); + })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { + Context::barrier(l, rt.p, kRT, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + Context::barrier(l, rt.p, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, kRT); + })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { + const auto handle = rtv.handle(0); + l->OMSetRenderTargets(1, &handle, FALSE, nullptr); + })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { + const FLOAT color[4]{0, 0, 0, 1}; + l->ClearRenderTargetView(rtv.handle(0), color, 0, nullptr); + })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { + l->ClearDepthStencilView(dsv.handle(0), D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { l->CopyResource(rt2.p, rt.p); })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { + D3D12_TEXTURE_COPY_LOCATION dst{}, src{}; + dst.pResource = rt2.p; + src.pResource = rt.p; + dst.Type = src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + l->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { l->CopyBufferRegion(buffer2.p, 0, buffer.p, 0, 16); })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { l->DiscardResource(rt.p, nullptr); })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { l->ResolveSubresource(single.p, 0, msaa.p, 0, kColor); })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { + l->ResolveSubresourceRegion(single.p, 0, 0, 0, msaa.p, 0, nullptr, kColor, D3D12_RESOLVE_MODE_AVERAGE); + })); + CHECK(in_pass([&](ID3D12GraphicsCommandList4* l) { l->Dispatch(1, 1, 1); })); + CHECK(close_after(D3D12_COMMAND_LIST_TYPE_BUNDLE, [&](ID3D12GraphicsCommandList4* l) { + begin(l, none); + l->EndRenderPass(); + })); + CHECK(close_after(D3D12_COMMAND_LIST_TYPE_COMPUTE, [&](ID3D12GraphicsCommandList4* l) { + begin(l, none); + l->EndRenderPass(); + })); + CHECK(close_after(D3D12_COMMAND_LIST_TYPE_BUNDLE, [&](ID3D12GraphicsCommandList4* l) { l->EndRenderPass(); })); + CHECK(close_after(D3D12_COMMAND_LIST_TYPE_COMPUTE, [&](ID3D12GraphicsCommandList4* l) { l->EndRenderPass(); })); + CHECK(close_after(D3D12_COMMAND_LIST_TYPE_BUNDLE, [&](ID3D12GraphicsCommandList4* l) { begin(l, none); })); + CHECK(close_after(D3D12_COMMAND_LIST_TYPE_COMPUTE, [&](ID3D12GraphicsCommandList4* l) { begin(l, none); })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + D3D12_RENDER_PASS_RENDER_TARGET_DESC null_target{{}, begin_access(kBeginClear, kColor, {0, 1, 0, 1}), + end_access(kEndPreserve)}; + l->BeginRenderPass(1, &null_target, nullptr, none); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + D3D12_RENDER_PASS_DEPTH_STENCIL_DESC null_depth{}; + null_depth.DepthBeginningAccess = begin_access(kBeginClear, kDepth, {}, 0.5f, 0); + null_depth.StencilBeginningAccess = begin_access(kBeginNoAccess); + null_depth.DepthEndingAccess = end_access(kEndPreserve); + null_depth.StencilEndingAccess = end_access(kEndNoAccess); + l->BeginRenderPass(0, nullptr, &null_depth, none); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS sub{0, 0, 0, 0, {0, 0, 1, 1}}; + D3D12_RENDER_PASS_RENDER_TARGET_DESC resolving{rtv.handle(0), begin_access(kBeginPreserve), + end_access(kEndResolve)}; + resolving.EndingAccess.Resolve = {nullptr, single.p, 1, &sub, kColor, D3D12_RESOLVE_MODE_AVERAGE, FALSE}; + l->BeginRenderPass(1, &resolving, nullptr, none); + l->EndRenderPass(); + })); + CHECK(close_after(direct, [&](ID3D12GraphicsCommandList4* l) { + D3D12_RENDER_PASS_RENDER_TARGET_DESC nine[9]; + for (auto& t : nine) t = target; + l->BeginRenderPass(9, nine, nullptr, none); + l->EndRenderPass(); + })); + return true; +} + +std::string hex(const std::vector& bytes) { + std::string out; + char buffer[4]; + for (unsigned char b : bytes) { + std::snprintf(buffer, sizeof(buffer), "%02x", b); + out += buffer; + } + return out; +} + +std::vector repeat(std::initializer_list pixel, UINT count) { + std::vector out; + for (UINT i = 0; i < count; ++i) out.insert(out.end(), pixel); + return out; +} + +std::vector depth_bytes(float value) { + std::vector out(kSize * kSize * 4); + for (UINT i = 0; i < kSize * kSize; ++i) std::memcpy(out.data() + i * 4, &value, 4); + return out; +} + +// The blue 4 x 4 target with the 2 x 2 rectangle at (1, 1) in `inside`. +std::vector resolved(std::initializer_list inside) { + std::vector out; + for (UINT y = 0; y < kSize; ++y) { + for (UINT x = 0; x < kSize; ++x) { + const bool in = x >= 1 && x < 3 && y >= 1 && y < 3; + if (in) out.insert(out.end(), inside); + else out.insert(out.end(), {0, 0, 255, 255}); + } + } + return out; +} +} // namespace + +int main() { + vktest::Device vk; + const auto device_status = vk.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + const unsigned errors_before = vk.validation_errors(); + int failures = 0; + { + Ref ours, host; + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; + Ref factory; + Ref warp; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || + FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || + FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { + std::puts("WARP reference unavailable: differential test skipped"); + return 77; + } + D3D12_FEATURE_DATA_D3D12_OPTIONS5 options5{}; + if (SUCCEEDED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &options5, sizeof(options5))) && + options5.RenderPassesTier != D3D12_RENDER_PASS_TIER_0) { + std::fprintf(stderr, "RenderPassesTier is %d, this emulation is Tier 0\n", int(options5.RenderPassesTier)); + ++failures; + } + + using Case = bool (*)(ID3D12Device*, Result&); + struct Named { + const char* name; + Case run; + std::vector> expected; // the bytes WARP must also give + std::vector expected_results = {}; // the Close results WARP must also give + bool skip = false; // the Vulkan device cannot replay the case + }; + // The depth RESOLVE uses MIN, which Vulkan makes optional (SAMPLE_ZERO is the one every device has). + VkPhysicalDeviceDepthStencilResolveProperties resolve{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve}; + vk.instance_fn("vkGetPhysicalDeviceProperties2")(vk.physical, &properties); + const bool depth_min = resolve.supportedDepthResolveModes & VK_RESOLVE_MODE_MIN_BIT; + constexpr HRESULT s_ok = S_OK, arg = E_INVALIDARG, fail = E_FAIL; + const std::vector list_results = { + arg, fail, arg, s_ok, arg, s_ok, s_ok, s_ok, s_ok, // nesting, order, suspend/resume, barrier + fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, // forbidden inside a pass + fail, fail, fail, fail, fail, fail, // bundles and compute lists + s_ok, s_ok, // CLEAR with a null descriptor + s_ok, fail, // no RESOLVE source, nine targets + }; + const auto green = repeat({0, 255, 0, 255}, kSize * kSize), blue = repeat({0, 0, 255, 255}, kSize * kSize); + const auto resolve_colour = resolved({51, 102, 153, 204}); + const Named cases[] = { + {"clear_and_preserve", + [](ID3D12Device* d, Result& r) { return clear_and_preserve(d, D3D12_RENDER_PASS_FLAG_NONE, r); }, + {green, blue}}, + {"clear_and_preserve_allow_uav_writes", + [](ID3D12Device* d, Result& r) { + return clear_and_preserve(d, D3D12_RENDER_PASS_FLAG_ALLOW_UAV_WRITES, r); + }, + {green, blue}}, + {"depth_clear_stencil_preserve", + [](ID3D12Device* d, Result& r) { return depth_and_stencil_planes(d, false, r); }, + {depth_bytes(0.25f), repeat({3}, kSize * kSize)}}, + {"stencil_clear_depth_no_access", + [](ID3D12Device* d, Result& r) { return depth_and_stencil_planes(d, true, r); }, + {depth_bytes(0.25f), repeat({9}, kSize * kSize)}}, + {"msaa_resolve_region", [](ID3D12Device* d, Result& r) { return msaa_resolve(d, false, r); }, + {resolve_colour}}, + {"suspend_resume", [](ID3D12Device* d, Result& r) { return msaa_resolve(d, true, r); }, {resolve_colour}}, + {"depth_resolve_min", depth_resolve, {depth_bytes(0.25f)}, {}, !depth_min}, + {"list_errors", list_errors, {}, list_results}, + }; + for (const auto& item : cases) { + if (item.skip) { + std::printf("SKIP %s (the Vulkan device has no MIN depth resolve)\n", item.name); + continue; + } + Result from_host, from_ours; + if (!item.run(host.p, from_host)) { + std::fprintf(stderr, "%s: the WARP run failed\n", item.name); + ++failures; + continue; + } + if (!item.run(ours.p, from_ours)) { + std::fprintf(stderr, "%s: the Vulkan-backed run failed\n", item.name); + ++failures; + continue; + } + bool ok = from_host.images == from_ours.images && from_host.results == from_ours.results; + if (from_host.images != item.expected || from_host.results != item.expected_results) { + std::fprintf(stderr, "%s: WARP differs from the expected values, so the case does not test what it " + "says\n", item.name); + ok = false; + } + for (size_t i = 0; !ok && i < from_host.images.size() && i < from_ours.images.size(); ++i) { + if (from_host.images[i] == from_ours.images[i]) continue; + std::fprintf(stderr, "%s image %zu:\n WARP %s\n ours %s\n", item.name, i, + hex(from_host.images[i]).c_str(), hex(from_ours.images[i]).c_str()); + } + for (size_t i = 0; !ok && i < from_host.results.size(); ++i) { + const HRESULT want = i < item.expected_results.size() ? item.expected_results[i] : S_OK; + const HRESULT ours_result = i < from_ours.results.size() ? from_ours.results[i] : S_OK; + if (from_host.results[i] == want && ours_result == want) continue; + std::fprintf(stderr, "%s, %s: expected 0x%08lx, WARP 0x%08lx, ours 0x%08lx\n", item.name, + i < std::size(kListCases) ? kListCases[i] : "?", static_cast(want), + static_cast(from_host.results[i]), static_cast(ours_result)); + } + std::printf("%s %s\n", ok ? "PASS" : "FAIL", item.name); + if (!ok) ++failures; + } + } + const unsigned errors = vk.validation_errors() - errors_before; + if (errors) { + std::fprintf(stderr, "%u Vulkan validation errors\n", errors); + ++failures; + } + std::printf("%s\n", failures ? "render pass test FAILED" : "render pass test passed"); + return failures ? 1 : 0; +}