diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0652c6c875..7742515aa9 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -169,7 +169,7 @@ The command-list surface maps to the IR as follows: | `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | | `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | | `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | +| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology. The console's rectangle list (17, PSO topology type 19) and quad list (19) are drawn as triangles, see *Console rectangle and quad lists* below | | `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | | `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | | `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | @@ -2109,6 +2109,17 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +### Console rectangle and quad lists + +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern + `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance + order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still + read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking + vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type + is the ordinary triangle type. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f317958f12..9f153ff5ef 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2383,6 +2383,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_rect_list_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) + set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) @@ -3216,6 +3225,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) + target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_quad_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_quad_list COMMAND replay_quad_list_test) # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index a6911d0f4e..8dd16932ff 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18,6 +18,7 @@ #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" @@ -65,7 +66,10 @@ namespace { constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; +constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read +constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; +constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the @@ -3058,7 +3062,8 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) + .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); @@ -3455,8 +3460,18 @@ class PipelineState final log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); return E_NOTIMPL; } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); + // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds + // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of + // the application's own. + // Decode the ABI field as bits. The console's value is outside the PC enum's range. + const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); + const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; + if (rect_list && (geometry || !device_.info.features.geometryShader)) { + log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); + return geometry ? E_INVALIDARG : E_NOTIMPL; + } + if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; @@ -3635,6 +3650,26 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + std::string why; + const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", + vs_stage.entry->name.c_str(), why.c_str()); + return E_NOTIMPL; + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -3709,12 +3744,13 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored @@ -3736,7 +3772,7 @@ class PipelineState final return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return E_NOTIMPL; } @@ -5442,7 +5478,13 @@ class Device final return false; } arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read + std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read + auto* indices = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { + const std::uint32_t base = i / kQuadIndicesPerQuad * 4; + std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, + [base](std::uint32_t index) { return base + index; }); + } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); @@ -5453,7 +5495,8 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + state_.context->set_zero_page(arena.buffer, 0, kZeroPage); + state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); return true; } diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..e90173095d --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,268 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners and the hardware makes the fourth, a + b - p (p the right-angle corner, a and b its +// neighbours), for the position and for every interpolant, after the vertex stage. Which vertex is p is not fixed: +// the retail boot's full-screen rectangle has it at the second vertex. The stage picks the vertex opposite the longest +// screen-space edge, and the first vertex on a tie. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in +// its backlog); no code is taken from it. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws and emits the parallelogram as the two triangles (p, a, f) and (p, f, b), with the winding of +// (v1, v2, v3). Both start at p, so a flat input (taken from a triangle's first vertex) is p's over the whole +// rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. +// +// The edges are measured in normalized device coordinates, not pixels (the stage does not know the viewport). For the +// usual axis-aligned rectangle that is exact; a rotated rectangle drawn into a very non-square viewport can pick a +// different corner than the pixel-space right angle. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_fmul = 133, op_fdiv = 136, + op_type_bool = 20, op_composite_construct = 80, op_composite_extract = 81, op_logical_and = 167, + op_logical_not = 168, op_select = 169, op_ford_greater_equal = 190, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + // Known limit: every vec4 float output gets the plain a + b - p corner. The translator can export an attribute + // as the register's raw bits with two packed f16 halves (only the pixel shader knows, through per_vertex in + // tools/rdna2spirv.py), and nothing on the vertex side tells those apart, so such an output would get a wrong + // fourth corner. Fixing it needs the pixel shader's words here and a per-channel marker from the translator. + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), + c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(), t_bool = id(), t_bool4 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_type_bool, {t_bool}); + emit(globals, op_type_vector, {t_bool4, t_bool, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three vertices as drawn, loaded first. + struct Corners { std::uint32_t v[4]; }; // v[0] the right-angle corner, v[1], v[2] its neighbours, v[3] the fourth + std::vector corners; + std::vector> loaded; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + std::array three{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + three[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, three[k], ptr}); + } + loaded.push_back(three); + } + // Which vertex is the right angle: the one opposite the longest edge, measured on screen (position.xy / position.w; + // a right triangle's longest edge is its hypotenuse). Ties go to the first vertex, which keeps the plain + // "v1 is the corner" order for every rectangle whose right angle is there. A triangle that is not a right + // triangle gets the same rule, so the choice is at least consistent. + std::uint32_t screen[3][2]; + for (int k = 0; k < 3; ++k) { + const std::uint32_t x = id(), y = id(), w = id(); + emit(body, op_composite_extract, {t_float, x, loaded[0][k], 0}); + emit(body, op_composite_extract, {t_float, y, loaded[0][k], 1}); + emit(body, op_composite_extract, {t_float, w, loaded[0][k], 3}); + screen[k][0] = id(); + screen[k][1] = id(); + emit(body, op_fdiv, {t_float, screen[k][0], x, w}); + emit(body, op_fdiv, {t_float, screen[k][1], y, w}); + } + const auto squared_edge = [&](int a, int b) { + const std::uint32_t dx = id(), dy = id(), xx = id(), yy = id(), sum = id(); + emit(body, op_fsub, {t_float, dx, screen[a][0], screen[b][0]}); + emit(body, op_fsub, {t_float, dy, screen[a][1], screen[b][1]}); + emit(body, op_fmul, {t_float, xx, dx, dx}); + emit(body, op_fmul, {t_float, yy, dy, dy}); + emit(body, op_fadd, {t_float, sum, xx, yy}); + return sum; + }; + const std::uint32_t e01 = squared_edge(0, 1), e02 = squared_edge(0, 2), e12 = squared_edge(1, 2); + const std::uint32_t g12_01 = id(), g12_02 = id(), at_first = id(), g02_01 = id(), not_first = id(), at_second = id(); + emit(body, op_ford_greater_equal, {t_bool, g12_01, e12, e01}); + emit(body, op_ford_greater_equal, {t_bool, g12_02, e12, e02}); + emit(body, op_logical_and, {t_bool, at_first, g12_01, g12_02}); // the edge opposite v1 is longest: v1 is the corner + emit(body, op_ford_greater_equal, {t_bool, g02_01, e02, e01}); + emit(body, op_logical_not, {t_bool, not_first, at_first}); + emit(body, op_logical_and, {t_bool, at_second, not_first, g02_01}); // else the edge opposite v2: v2; else v3 + const std::uint32_t first4 = id(), second4 = id(); + emit(body, op_composite_construct, {t_bool4, first4, at_first, at_first, at_first, at_first}); + emit(body, op_composite_construct, {t_bool4, second4, at_second, at_second, at_second, at_second}); + // The corner p, its neighbours a = next and b = the one after (the same cyclic order as v1 v2 v3, so the winding + // is the drawn triangle's), and the fourth corner a + b - p, for the position and for every interpolant alike. + for (const auto& three : loaded) { + Corners c{}; + const auto pick = [&](std::uint32_t first, std::uint32_t second, std::uint32_t third) { + const std::uint32_t inner = id(), outer = id(); + emit(body, op_select, {t_v4, inner, second4, second, third}); + emit(body, op_select, {t_v4, outer, first4, first, inner}); + return outer; + }; + c.v[0] = pick(three[0], three[1], three[2]); + c.v[1] = pick(three[1], three[2], three[0]); + c.v[2] = pick(three[2], three[0], three[1]); + const std::uint32_t sum = id(), diff = id(); + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); + c.v[3] = diff; + corners.push_back(c); + } + // Two triangles, (p, a, f) and (p, f, b): the diagonal is p to f, so both start at p and a flat input + // (which Vulkan takes from a triangle's first vertex) is p's over the whole rectangle. The attributes are + // affine over the parallelogram, so the split does not change any interpolated value. + const int triangles[2][3] = {{0, 1, 3}, {0, 3, 2}}; + for (const auto& triangle : triangles) { + for (int k : triangle) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + } + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {2}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 6}); // OutputVertices 6 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe89..02fdad1a09 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1268,6 +1268,14 @@ class VulkanContext { replay_.zero_size = size; } + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). + void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { + std::unique_lock lock(resource_mutex_); + replay_.quad_indices = buffer; + replay_.quad_indices_offset = offset; + replay_.quad_index_count = count; + } + // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..f9dfb6b030 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -32,6 +32,7 @@ #include "command_list.h" #include "depth24.h" +#include "rect_list_geometry.h" #include "uav_clear.h" #include @@ -43,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -869,6 +871,10 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; + // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad. + VkBuffer quad_indices = VK_NULL_HANDLE; + VkDeviceSize quad_indices_offset = 0; + std::uint32_t quad_index_count = 0; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. std::functionzero_step_slots & (1u << slot)) ? 0 : view.stride; } + // A non-indexed quad list is drawn from the shared triangle index buffer (emit). + if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; @@ -2227,6 +2236,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; + // emit() overrides non-indexed quads to a triangle list backed by the shared indices. + case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -4190,7 +4203,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); vk.set_primitive_topology(command_buffer, topology); const bool restart = draw->indexed && detail::strip_topology(topology) && ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || @@ -4207,6 +4221,28 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } else if (draw->topology == topology_quad_list) { + if (draw->indexed) { + // Indexed quads still read their vertices from the application's index buffer, one fan per quad. + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, + draw->base_vertex, draw->first_instance); + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp new file mode 100644 index 0000000000..a6d4d25b85 --- /dev/null +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -0,0 +1,421 @@ +// The console's rectangle and quad lists drawn through the D3D12-on-Vulkan layer (src/rect_list_geometry.h). +// +// Built like d3d12_translated_draw_test.cpp, from the same translated vs_m15 / ps_m15 (the VS fetches its vertices +// through a V#; the PS multiplies the colour by (0.5, 2, 1, 1) and adds the bias, 0 here), so the shaders are real +// translator output found by the SHA-256 of their FSSM programs. +// frame 1, rectangle list: PSO topology type 19, IASetPrimitiveTopology(17), DrawInstanced(3). The three corners +// v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth +// corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane +// through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frames 3 to 5, rectangle lists whose right angle is at the second vertex, at the third vertex, and a triangle with +// no right angle at all. The layer takes the right-angle corner as the vertex opposite the longest screen edge, so +// the first two must cover all 64x64 pixels on the colour plane too (the retail boot's full-screen draw has its +// right angle at the second vertex); the third only has to draw something and not fail. +// frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners +// in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. +// Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 +// runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M15_DIR +#error "LEONIDA_TEST_M15_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_m15.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY rect_list = D3D_PRIMITIVE_TOPOLOGY(17), quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +const std::uint32_t rect_type_value = 19; // not an enumerator of D3D12_PRIMITIVE_TOPOLOGY_TYPE + +std::array make_vsharp(std::uint64_t base, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = 32; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +Vertex vertex(float x, float y, const float* c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_m15.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_m15.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() == 0x110); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. + const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; + const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + const Vertex vertices[20] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2), + // vertices 11..13: right angle at the second vertex; 14..16: at the third; 17..19: none + vertex(-1, 1, ca), vertex(1, 1, cb), vertex(1, -1, cc), + vertex(-1, 1, ca), vertex(1, -1, cb), vertex(-1, -1, cc), + vertex(-1, 1, ca), vertex(0.5f, 0.75f, cb), vertex(-0.25f, -1, cc)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 640); + const Vertex* const corner_cases[2] = {&vertices[11], &vertices[14]}; + + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent), + second_pixels(target_extent * target_extent), third_pixels(target_extent * target_extent), + skew_pixels(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; // geometryShader: the rectangle stage needs it + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref rect_pso, quad_pso; + std::memcpy(&pso_desc.PrimitiveTopologyType, &rect_type_value, sizeof(rect_type_value)); // 19: rectangles + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&rect_pso.p)))); + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&quad_pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + + // V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners, slots 2 to 4 + // the three more rectangles. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000); + const std::array vsharps[5] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8), + make_vsharp(buffer_va + 11 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 14 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 17 * sizeof(Vertex), 3)}; + for (unsigned i = 0; i < 5; ++i) + std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, rect_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + + const auto render_frame = [&](UINT64 frame, ID3D12PipelineState* pso, D3D_PRIMITIVE_TOPOLOGY topology, + unsigned vsharp_slot, UINT vertex_count, std::vector& out) -> int { + if (frame > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } else { + list->SetPipelineState(pso); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(topology); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {0, 0, 0, 0}; // no offset, no bias + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(vsharp_slot) * step}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + list->DrawInstanced(vertex_count, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, frame))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(frame, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); + EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + EXPECT(render_frame(3, rect_pso.p, rect_list, 2, 3, second_pixels) == 0); + EXPECT(render_frame(4, rect_pso.p, rect_list, 3, 3, third_pixels) == 0); + EXPECT(render_frame(5, rect_pso.p, rect_list, 4, 3, skew_pixels) == 0); + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + rect_pso.reset(); + quad_pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // Rectangle: the plane through the three corner colours, at each pixel centre, through the PS's scale. + const float scale[4] = {0.5f, 2.0f, 1.0f, 1.0f}; + unsigned covered = 0, off = 0; + float worst = 0.0f; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + const Pixel& got = rect_pixels[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + worst = std::fmax(worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + covered += pixel_ok; + if (!pixel_ok && off++ < 8) + std::fprintf(stderr, "rect pixel (%u, %u): got %g,%g,%g,%g\n", col, row, got[0], got[1], got[2], got[3]); + } + } + // The four quadrant centres on their own, so a wrong fourth corner is named by quadrant. + const char* names[4] = {"top left", "top right", "bottom left", "bottom right"}; + for (int quadrant = 0; quadrant < 4; ++quadrant) { + const UINT col = (quadrant & 1 ? 48 : 16), row = (quadrant & 2 ? 48 : 16); + const Pixel& got = rect_pixels[row * target_extent + col]; + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + if (!(std::fabs(got[c] - want) <= 2e-5f)) { + std::fprintf(stderr, "rect %s quadrant: channel %d got %g want %g\n", names[quadrant], c, got[c], want); + return 1; + } + } + } + EXPECT(covered == target_extent * target_extent); + + // Right angle at the second and at the third vertex: the plane through the three drawn corners, everywhere. + const std::vector* const corner_pixels[2] = {&second_pixels, &third_pixels}; + const char* const corner_names[2] = {"second", "third"}; + unsigned corner_covered[2] = {0, 0}; + float corner_worst = 0.0f; + for (int which = 0; which < 2; ++which) { + const Vertex* t = corner_cases[which]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const Pixel& got = (*corner_pixels[which])[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (t[0].color[c] + s * (t[1].color[c] - t[0].color[c]) + + r * (t[2].color[c] - t[0].color[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + corner_worst = std::fmax(corner_worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + corner_covered[which] += pixel_ok; + } + } + if (corner_covered[which] != target_extent * target_extent) { + std::fprintf(stderr, "rect list with the right angle at the %s vertex: %u of %u pixels on the plane\n", + corner_names[which], corner_covered[which], target_extent * target_extent); + return 1; + } + } + // Not a right triangle: any consistent corner is fine, but every corner choice makes a parallelogram that holds the + // drawn triangle, so each pixel well inside the triangle must be drawn (not the clear colour). + const Pixel clear_pixel = {0.5f, 0.125f, 0.25f, 0.5f}; + unsigned skew_drawn = 0, skew_inside = 0, skew_missing = 0; + { + const Vertex* t = &vertices[17]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const bool drawn = std::memcmp(&skew_pixels[row * target_extent + col], &clear_pixel, sizeof(Pixel)) != 0; + skew_drawn += drawn; + if (s > 0.02f && r > 0.02f && s + r < 0.98f) { + ++skew_inside; + skew_missing += !drawn; + } + } + } + } + EXPECT(skew_inside > 1000 && skew_missing == 0); + + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. + const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; + const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; + const Pixel bottom_right = {q2[0] * scale[0], q2[1] * scale[1], q2[2], q2[3]}; + unsigned quad_wrong = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const bool top = row < target_extent / 2, left = col < target_extent / 2; + const Pixel& want = top && left ? top_left : (!top && !left ? bottom_right : clear_color); + const Pixel& got = quad_pixels[row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) continue; + if (quad_wrong++ < 8) + std::fprintf(stderr, "quad pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!quad_wrong); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; right angle at " + "the second vertex %u and at the third %u of %u (worst error %g); no right angle: %u pixels drawn; " + "quad list: %u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), corner_covered[0], corner_covered[1], + target_extent * target_extent, double(corner_worst), skew_drawn, + target_extent * target_extent - quad_wrong, target_extent * target_extent); + return 0; +} diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp new file mode 100644 index 0000000000..15b0c7e781 --- /dev/null +++ b/runtime/test/replay_quad_list_test.cpp @@ -0,0 +1,110 @@ +// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans +// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +#include "../src/vulkan_replay.h" + +#include +#include +#include + +namespace { +using namespace leonida; + +struct DrawCall { + VkPrimitiveTopology topology; + VkBuffer buffer; + VkDeviceSize offset; + VkIndexType index_type; + std::uint32_t count, instances, first_index; + std::int32_t base_vertex; + std::uint32_t first_instance; + bool operator==(const DrawCall&) const = default; +}; + +DrawCall recorded{}; +std::vector calls; + +bool check(bool condition, const char* description) { + if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); + return condition; +} +} + +int main() { + using namespace leonida; + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, + std::uint32_t, const void*) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + recorded.buffer = buffer; + recorded.offset = offset; + recorded.index_type = type; + }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + recorded.count = count; + recorded.instances = instances; + recorded.first_index = first; + recorded.base_vertex = base; + recorded.first_instance = first_instance; + calls.push_back(recorded); + }; + + vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices_offset = 64; + vk.quad_index_count = 12; + const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + + GraphicsPipeline graphics{}; + const auto collect = [&](const Draw& draw) { + calls.clear(); + CommandList list; + if (!list.draw(draw) || !list.close()) return false; + PreparedList prepared; + prepared.list = &list; + prepared.commands.resize(1); + prepared.commands[0].draw = 0; + auto& entry = prepared.draws.emplace_back(); + entry.graphics = &graphics; + entry.index_buffer = app_buffer; + entry.index_offset = 32; + emit(prepared, VK_NULL_HANDLE, vk); + return true; + }; + + Draw draw{}; + draw.pipeline = 1; + draw.topology = topology_quad_list; + draw.count = 8; + draw.instances = 2; + draw.first = 13; + draw.first_instance = 7; + + const DrawCall triangles{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, vk.quad_indices, 64, VK_INDEX_TYPE_UINT32, + 12, 2, 0, 13, 7}; + bool ok = check(collect(draw) && calls == std::vector{triangles}, + "non-indexed quads use one triangle-list draw and preserve draw bases"); + draw.count = 13; + ok &= check(collect(draw) && calls == std::vector{triangles}, + "a draw is limited to whole quads in the generated index buffer"); + draw.count = 3; + ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + + draw.indexed = true; + draw.count = 8; + draw.first = 5; + draw.base_vertex = -2; + const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; + const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; + ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, + "indexed quads use the application's index buffer and base vertex"); + return ok ? 0 : 1; +}