From 2b4458a45c0d643fb3bec61baa1e33d2be68a3de Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 01:37:50 +0200 Subject: [PATCH 1/8] fix the shaders, the initial matrix and the column-major draw uniforms shaders - declare the per-draw uniforms as a cbuffer (float4x4 draw_matrix + float4 draw_color) and use mul() for the matrix multiply (the old RootConstants style no longer compiles with the current SDK) - declare SV_POSITION as the first (unused) fragment-shader input so its hardware register matches the vertex shader's, which outputs SV_POSITION at register 0 and any arbitrary semantic at register 1 (otherwise pipeline creation fails with mismatched hardware registers) - compile to vs_5_1/ps_5_1 and use a shared compile_hlsl_blob() helper so the pipeline can keep the blob alive for its lifetime - fix the vertex input layout: a1 attribute semantic is shader-specific (COLOR for pos_clr, TEXCOORD otherwise) and the a1 buffer is read from offset 0 of the second vertex buffer (the buffers are bound per-slot, so the stride is not a byte offset into a single buffer) - bind every vertex buffer of the vertex array (not just the first one), which rendered only the right half of textured geometry - use D3D12_CULL_MODE_BACK (never NONE) - create the pipeline with the real RTV/DSV formats and pass them in the pipeline key so the cache does not confuse pipelines for different formats initial matrix - scale(1, -1, 1) -> translate(-1, -1) -> scale(2, 2): the framework's normalized viewport (x right, y down, (0, 0) top-left) now maps to the DirectX NDC instead of coming out flipped vertically column-major draw uniforms - the renderer's per-draw matrix is stored row-major (r4), so transpose it before writing it into the HLSL cbuffer (float4x4 is column-major by default); everything currently drawn was mirrored --- src/ruis/render/directx/context.cpp | 104 +++++++++--------- src/ruis/render/directx/context.hpp | 9 +- src/ruis/render/directx/directx.cpp | 23 ++-- src/ruis/render/directx/directx.hpp | 35 ++++-- .../render/directx/shaders/shader_common.hpp | 12 ++ .../render/directx/shaders/shader_src.hpp | 94 +++++++++++----- 6 files changed, 180 insertions(+), 97 deletions(-) diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp index cfef8aa..8e686be 100644 --- a/src/ruis/render/directx/context.cpp +++ b/src/ruis/render/directx/context.cpp @@ -25,6 +25,7 @@ along with this program. If not, see . #include #include #include +#include #include @@ -59,10 +60,16 @@ context::context( // maps the framework's normalized viewport coordinates (x right, y down, // zero at the top-left, right/bottom edges at (1, 1)) to the DirectX NDC. // - // In the DirectX NDC -1 -1 corresponds to the top-left corner, 1 1 to the - // bottom-right corner, and z points away from the viewer (same orientation - // as the framework, so no axis flip is needed). - m.set_identity().translate(-1, -1).scale(2, 2); + // DirectX identity matrix: + // viewport edges: left = -1, right = 1, top = 1, bottom = -1 + // z-axis away from the viewer + m.set_identity() + // x-axis right, y-axis down, z-axis away + .scale(1, -1, 1) + // viewport edges: left = 0, top = 0 + .translate(-1, -1) + // viewport edges: right = 1, bottom = 1 + .scale(2, 2); return parameters{m}; }() ), @@ -585,6 +592,16 @@ void context::enable_depth(bool enable) this->depth_enabled = enable; } +DXGI_FORMAT context::current_rtv_format() const +{ + if (this->current_fb != nullptr && this->current_fb->color != nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") + const auto& tex = static_cast(*this->current_fb->color); + return to_dxgi_format_8bit(tex.ri_format); + } + return DXGI_FORMAT_B8G8R8A8_UNORM; +} + uint32_t context::get_blend_key() const { // pack the blend state into a key for the pipeline cache: @@ -602,27 +619,8 @@ uint32_t context::get_blend_key() const ID3DBlob* context::compile_shader(const char* hlsl, const char* entry_point, const char* profile) { - ID3DBlob* blob = nullptr; - ID3DBlob* err_blob = nullptr; - check_hresult( - D3DCompile( - hlsl, - strlen(hlsl), - "ruis-render-directx.hlsl", - nullptr, - nullptr, - entry_point, - profile, - 0, - 0, - &blob, - &err_blob - ), - "D3DCompile" - ); - if (err_blob != nullptr) { - err_blob->Release(); - } + // the shared helper throws with the compiler's error message on failure + auto* blob = compile_hlsl_blob(hlsl, entry_point, profile); this->shader_blobs.emplace_back(blob); return blob; } @@ -635,12 +633,13 @@ ID3D12PipelineState* context::build_pipeline( ) { // compile the shaders to DXIL (the blobs are kept alive in shader_blobs) - auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_6_0"); - auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_6_0"); + auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_5_1"); + auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_5_1"); // ---- the vertex input layout ---- - // all vertices are stored as float4 (4 floats) in the vertex buffer; the a1 - // attribute (if present) is the tail of the float4 (its format is shader-specific) + // each buffer of the vertex array holds float4 (4 floats) vertices with the + // same stride; the a1 attribute (if present) reads the first few floats of the + // second buffer (its format is shader-specific) const auto a1 = shader_kind(key.shader_kind); auto input_layout_elements = std::vector{ {.SemanticName = "POSITION", @@ -653,11 +652,11 @@ ID3D12PipelineState* context::build_pipeline( if (has_a1) { input_layout_elements.push_back( D3D12_INPUT_ELEMENT_DESC{ - .SemanticName = "TEXCOORD", + .SemanticName = a1_semantic(a1), .SemanticIndex = 0, .Format = a1_format(a1), .InputSlot = 1, - .AlignedByteOffset = UINT(vertex_stride_bytes), + .AlignedByteOffset = 0, .InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA } ); @@ -698,14 +697,14 @@ ID3D12PipelineState* context::build_pipeline( const auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{ .pRootSignature = this->root_signature, - .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), vs_blob->GetBufferSize()}, - .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), fs_blob->GetBufferSize()}, + .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}, + .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}, .BlendState = blend, .SampleMask = 0xFFFFFFFF, .RasterizerState = D3D12_RASTERIZER_DESC{ .FillMode = D3D12_FILL_MODE_SOLID, - .CullMode = D3D12_CULL_MODE_NONE, + .CullMode = D3D12_CULL_MODE_BACK, .FrontCounterClockwise = FALSE, .DepthBias = 0, .DepthBiasClamp = 0.0f, @@ -721,17 +720,15 @@ ID3D12PipelineState* context::build_pipeline( .IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, .PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, .NumRenderTargets = 1, - .RTVFormats = {DXGI_FORMAT_UNKNOWN}, // the actual format depends on the render target - .DSVFormat = DXGI_FORMAT_UNKNOWN, // the actual format depends on the depth texture + .RTVFormats = {static_cast(key.rtv_format)}, + .DSVFormat = use_depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_UNKNOWN, .SampleDesc = {.Count = 1, .Quality = 0}, .NodeMask = 0 }; ID3D12PipelineState* pso = nullptr; - check_hresult( - this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)), - "CreateGraphicsPipelineState" - ); + const auto hr = this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)); + check_hresult(hr, "CreateGraphicsPipelineState"); return pso; } @@ -748,7 +745,8 @@ ID3D12PipelineState* context::get_or_create_pipeline( .blend_key = this->get_blend_key(), .depth_enabled = uint32_t(this->depth_enabled ? 1 : 0), .textured = uint32_t(textured ? 1 : 0), - .topology = uint32_t(topology) + .topology = uint32_t(topology), + .rtv_format = uint32_t(this->current_rtv_format()) }; const auto it = this->pipelines.find(key); @@ -776,18 +774,20 @@ void context::draw_indexed( this->command_list->SetPipelineState(pso); this->command_list->IASetPrimitiveTopology(to_topology(va.rendering_mode)); - // the vertex buffer (the first buffer of the vertex array; the vertex data of - // all buffers is expected to have the same float4 layout) + // the vertex buffers (one per slot; all buffers have the same float4 layout) { utki::assert(!va.buffers.empty(), SL); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") - const auto& vb = static_cast(va.buffers.front().get()); - const auto vbv = D3D12_VERTEX_BUFFER_VIEW{ - .BufferLocation = vb.gpu_va, - .SizeInBytes = UINT(vb.byte_size), - .StrideInBytes = UINT(vertex_stride_bytes) - }; - this->command_list->IASetVertexBuffers(0, 1, &vbv); + std::vector views(va.buffers.size()); + for (size_t i = 0; i < va.buffers.size(); ++i) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") + const auto& vb = static_cast(va.buffers[i].get()); + views[i] = D3D12_VERTEX_BUFFER_VIEW{ + .BufferLocation = vb.gpu_va, + .SizeInBytes = UINT(vb.byte_size), + .StrideInBytes = UINT(vertex_stride_bytes) + }; + } + this->command_list->IASetVertexBuffers(0, UINT(views.size()), views.data()); } // the index buffer @@ -892,7 +892,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); check_hresult( this->device->CreateCommittedResource( - &upload_heap_properties(), + &default_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp index b0465a7..851de91 100644 --- a/src/ruis/render/directx/context.hpp +++ b/src/ruis/render/directx/context.hpp @@ -53,11 +53,13 @@ struct pipeline_key { uint32_t depth_enabled = 0; uint32_t textured = 0; uint32_t topology = 0; // D3D12_PRIMITIVE_TOPOLOGY + uint32_t rtv_format = 0; // DXGI_FORMAT (the current render target format) bool operator==(const pipeline_key& o) const { return this->shader_kind == o.shader_kind && this->blend_key == o.blend_key && - this->depth_enabled == o.depth_enabled && this->textured == o.textured && this->topology == o.topology; + this->depth_enabled == o.depth_enabled && this->textured == o.textured && + this->topology == o.topology && this->rtv_format == o.rtv_format; } }; @@ -77,6 +79,7 @@ struct pipeline_key_hash { hash_combine(h, std::hash()(k.depth_enabled)); hash_combine(h, std::hash()(k.textured)); hash_combine(h, std::hash()(k.topology)); + hash_combine(h, std::hash()(k.rtv_format)); return h; } }; @@ -147,6 +150,10 @@ class context : public ruis::render::context // the packed key of the current blend state (for pipeline selection) uint32_t get_blend_key() const; + // the DXGI_FORMAT of the current render target (the swapchain for the + // screen, the color texture for a frame buffer) + DXGI_FORMAT current_rtv_format() const; + // get or create a pipeline state object for the given shader + current state ID3D12PipelineState* get_or_create_pipeline( shader_kind kind, // diff --git a/src/ruis/render/directx/directx.cpp b/src/ruis/render/directx/directx.cpp index a1eb137..04d282d 100644 --- a/src/ruis/render/directx/directx.cpp +++ b/src/ruis/render/directx/directx.cpp @@ -21,12 +21,13 @@ along with this program. If not, see . #include "directx.hpp" +#include #include #include namespace ruis::render::directx { -std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) +ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile) { ID3DBlob* blob = nullptr; ID3DBlob* err_blob = nullptr; @@ -45,20 +46,24 @@ std::vector compile_hlsl(const char* source, const char* entry_point, c ); if (FAILED(hr)) { const auto err = err_blob != nullptr ? reinterpret_cast(err_blob->GetBufferPointer()) : ""; - const auto msg = std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err; - if (err_blob != nullptr) { - err_blob->Release(); - } - throw std::runtime_error(msg); + if (err_blob != nullptr) { err_blob->Release(); } + if (blob != nullptr) { blob->Release(); } + throw std::runtime_error(std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err); } + if (err_blob != nullptr) { err_blob->Release(); } + return blob; +} +std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) +{ + // compile the shader and copy the bytecode out of the returned blob + // (the caller keeps the blob alive for the lifetime of the pipeline; + // this public helper only needs the bytecode) + auto* blob = compile_hlsl_blob(source, entry_point, profile); const auto size = blob->GetBufferSize(); std::vector bytecode(size); std::copy_n(static_cast(blob->GetBufferPointer()), size, bytecode.begin()); blob->Release(); - if (err_blob != nullptr) { - err_blob->Release(); - } return bytecode; } diff --git a/src/ruis/render/directx/directx.hpp b/src/ruis/render/directx/directx.hpp index 7b20c69..356e077 100644 --- a/src/ruis/render/directx/directx.hpp +++ b/src/ruis/render/directx/directx.hpp @@ -51,9 +51,9 @@ inline void check_hresult(HRESULT hr, const char* what) /** * @brief The shared draw uniforms, bound as a root constant buffer view. * - * The matrix is stored in row-major order, which is the same order that - * r4::matrix4 uses and the default packing order of a row-major float4x4 in - * HLSL, so the matrix is copied directly from r4 without any transposition. + * The matrix is stored in column-major order, matching the default packing + * of a float4x4 in an HLSL cbuffer (r4 stores row-major), so the matrix is + * transposed on write. */ struct draw_uniforms { float matrix[4][4]; @@ -64,9 +64,11 @@ static_assert(sizeof(draw_uniforms) == 16 * sizeof(float) + 4 * sizeof(float)); inline void write_draw_uniforms(draw_uniforms* u, const r4::matrix4& m, const r4::vector4& color) { + // r4 stores row-major, HLSL expects column-major: transpose first + auto t = m.tposed(); for (uint32_t r = 0; r < 4; ++r) { for (uint32_t c = 0; c < 4; ++c) { - u->matrix[r][c] = m[r][c]; + u->matrix[r][c] = t[r][c]; } } u->color[0] = color.x(); @@ -148,10 +150,11 @@ inline DXGI_FORMAT to_dxgi_format_8bit(rasterimage::format f) } // D3D12_RESOURCE_STATE_DEPTH_STENCIL was removed from the new SDK; -// it is the same combination of states as before -inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = // - D3D12_RESOURCE_STATE_DEPTH_WRITE | // - D3D12_RESOURCE_STATE_DEPTH_READ; +// the depth-stencil resources of this renderer are only written through the +// depth-stencil view, so they are created in the (single) depth-write state. +// (Read-only states cannot be combined with write states, so DEPTH_WRITE | DEPTH_READ +// would be invalid.) +inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = D3D12_RESOURCE_STATE_DEPTH_WRITE; inline const D3D12_HEAP_PROPERTIES& default_heap_properties() { @@ -237,8 +240,20 @@ inline D3D12_RESOURCE_BARRIER transition_barrier( return b; } -// compile an HLSL shader source at runtime (via the D3D compiler); -// the returned blob contains the DXIL bytecode +/** + * @brief Compile one HLSL shader source at runtime (via the D3D compiler). + * @param source the HLSL source + * @param entry_point the entry point + * @param profile the target profile (e.g. "vs_5_1") + * @return the compiled blob; the caller owns it and must release it. + * @throws std::runtime_error carrying the compiler's error message on failure. + */ +ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile); + +/** + * @brief Compile one HLSL shader source at runtime and return the DXIL bytecode. + * @throws std::runtime_error carrying the compiler's error message on failure. + */ std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile); } // namespace ruis::render::directx diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp index 91f5d99..70ea0dc 100644 --- a/src/ruis/render/directx/shaders/shader_common.hpp +++ b/src/ruis/render/directx/shaders/shader_common.hpp @@ -65,6 +65,18 @@ constexpr DXGI_FORMAT a1_format(shader_kind k) } } +// the semantic name of the a1 attribute (used in the vertex input layout) +constexpr const char* a1_semantic(shader_kind k) +{ + switch (k) { + case shader_kind::pos_clr: + return "COLOR"; + default: + // the textured shaders and the luminance shader declare it as TEXCOORD + return "TEXCOORD"; + } +} + // map the VAO's rendering mode to a DirectX primitive topology inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) { diff --git a/src/ruis/render/directx/shaders/shader_src.hpp b/src/ruis/render/directx/shaders/shader_src.hpp index ea38d7f..0a556cf 100644 --- a/src/ruis/render/directx/shaders/shader_src.hpp +++ b/src/ruis/render/directx/shaders/shader_src.hpp @@ -22,7 +22,7 @@ along with this program. If not, see . /* * The HLSL sources of the renderer's shaders. * They are compiled to DXIL at runtime with the D3D compiler (see - * directx::compile_hlsl()). + * directx::compile_hlsl_blob(), which is what the renderer uses). * * The per-draw uniforms (the transformation matrix and the color) are passed * as root 32-bit constants in register b0: first a float4x4 matrix (16 floats), @@ -45,18 +45,24 @@ namespace ruis::render::directx { // ============== color ========= static const char* hlsl_shader_color_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; float4 main(float4 pos : POSITION) : SV_POSITION { - return draw_matrix * pos; + return mul(draw_matrix, pos); } )HLSL"; static const char* hlsl_shader_color_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; float4 main() : SV_Target { @@ -68,8 +74,11 @@ float4 main() : SV_Target // ============== pos_clr ======= static const char* hlsl_shader_pos_clr_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; struct VS_OUT { @@ -80,14 +89,19 @@ struct VS_OUT VS_OUT main(float4 pos : POSITION, float4 col : COLOR) { VS_OUT o; - o.pos = draw_matrix * pos; + o.pos = mul(draw_matrix, pos); o.col = col; return o; } )HLSL"; static const char* hlsl_shader_pos_clr_fragment = R"HLSL( -float4 main(float4 col : COLOR) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float4 col : COLOR) : SV_Target { return col; } @@ -97,8 +111,11 @@ float4 main(float4 col : COLOR) : SV_Target // ============== pos_tex ======= static const char* hlsl_shader_pos_tex_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; struct VS_OUT { @@ -109,20 +126,28 @@ struct VS_OUT VS_OUT main(float4 pos : POSITION, float2 uv : TEXCOORD) { VS_OUT o; - o.pos = draw_matrix * pos; + o.pos = mul(draw_matrix, pos); o.uv = uv; return o; } )HLSL"; static const char* hlsl_shader_pos_tex_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; Texture2D tex0 : register(t0); SamplerState samp0 : register(s0); -float4 main(float2 uv : TEXCOORD) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target { return tex0.Sample(samp0, uv) * draw_color; } @@ -140,13 +165,21 @@ static const char* hlsl_shader_color_pos_tex_fragment = hlsl_shader_pos_tex_frag static const char* hlsl_shader_color_pos_tex_alpha_vertex = hlsl_shader_pos_tex_vertex; static const char* hlsl_shader_color_pos_tex_alpha_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; Texture2D tex0 : register(t0); SamplerState samp0 : register(s0); -float4 main(float2 uv : TEXCOORD) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target { return float4(draw_color.xyz, draw_color.w * tex0.Sample(samp0, uv).r); } @@ -156,8 +189,11 @@ float4 main(float2 uv : TEXCOORD) : SV_Target // ============== color_pos_lum = static const char* hlsl_shader_color_pos_lum_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; struct VS_OUT { @@ -168,17 +204,25 @@ struct VS_OUT VS_OUT main(float4 pos : POSITION, float lum : TEXCOORD) { VS_OUT o; - o.pos = draw_matrix * pos; + o.pos = mul(draw_matrix, pos); o.lum = lum; return o; } )HLSL"; static const char* hlsl_shader_color_pos_lum_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; -float4 main(float lum : TEXCOORD) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float lum : TEXCOORD) : SV_Target { return float4(draw_color.xyz, draw_color.w * lum); } From f9149b23354a833c9227e85e44a1a97ef628ab2d Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 01:55:21 +0200 Subject: [PATCH 2/8] fix runtime D3D12 issues found during app testing - use D3D12_MEMORY_POOL_UNKNOWN for non-custom heaps (the D3D12 debug layer reports D3D12_MEMORY_POOL_L0 as invalid for them) - use D3D_ROOT_SIGNATURE_VERSION_1_0: the SDK 10.0.26100.0 serializer rejects version 1_1; include the shader compiler error blob in the root signature serialization error message - skip the Reset() call on a freshly created command allocator and command list: some runtimes reject Reset() on them until the first work has completed - do not create GPU resources for empty vertex/index buffers and skip the index buffer draw path for them - format the HRESULT in check_hresult() as a hex number - use a local D3D12_MAX_LOD constant (removed from the new SDK) - use GENERIC_READ for the buffer upload resources and INDEX_BUFFER for the index buffer resource - use a READBACK heap for the GPU-visible readback buffer - use the D3D12 queue to signal the frame and upload fences - use the swapchain's current back buffer index and pass the swapchain queue (not the device) to CreateSwapChainForHwnd - use a BORDER sampler address mode, MaxAnisotropy 0 and MaxLOD D3D12_FLOAT32_MAX - use PIXEL_SHADER_RESOURCE for the texture barrier (no combined RENDER_TARGET | PIXEL_SHADER_RESOURCE state) --- src/ruis/render/directx/context.cpp | 47 ++++++++++++++--------- src/ruis/render/directx/context.hpp | 1 + src/ruis/render/directx/directx.hpp | 18 ++++++++- src/ruis/render/directx/factory.cpp | 35 ++++++++++------- src/ruis/render/directx/factory.hpp | 1 + src/ruis/render/directx/index_buffer.cpp | 17 +++++--- src/ruis/render/directx/texture_2d.cpp | 4 +- src/ruis/render/directx/vertex_buffer.cpp | 19 +++++++-- 8 files changed, 97 insertions(+), 45 deletions(-) diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp index 8e686be..ad6ee0f 100644 --- a/src/ruis/render/directx/context.cpp +++ b/src/ruis/render/directx/context.cpp @@ -189,7 +189,7 @@ void context::create_swapchain() IDXGISwapChain1* sc = nullptr; check_hresult( dxgi_factory->CreateSwapChainForHwnd( - reinterpret_cast(this->device), + reinterpret_cast(this->queue), this->surface_ref.get().get_hwnd(), &desc, nullptr, @@ -355,7 +355,7 @@ void context::wait_for_gpu() } // wait for the frame that rendered to the back buffer we are about to reuse const auto i = int(this->frame_index); - if (this->frame_pending[i]) { + if (i >= 0 && i < int(this->back_buffer_count) && this->frame_pending[i]) { const auto res = WaitForSingleObject(this->frame_fence_events[i], 10000); // 10s timeout if (res != WAIT_OBJECT_0) { throw std::runtime_error("directx context wait_for_gpu: the frame fence did not complete in time"); @@ -374,16 +374,21 @@ void context::ensure_frame_began() this->ensure_swapchain_valid(); if (this->swapchain != nullptr) { - // wait for the GPU to finish with the back buffer we are about to overwrite, - // then advance to the next back buffer + // the swapchain tells us which back buffer we are about to render to + this->frame_index = this->swapchain->GetCurrentBackBufferIndex(); + // wait for the GPU to finish with the back buffer we are about to overwrite this->wait_for_gpu(); - this->frame_index = (this->frame_index + 1) % this->back_buffer_count; } // reset the command allocator and the command list (the GPU has finished with - // the work recorded in them) - check_hresult(this->command_allocator->Reset(), "command allocator Reset"); - check_hresult(this->command_list->Reset(this->command_allocator, nullptr), "command list Reset"); + // the work recorded in them); a freshly created pair is already in the reset + // state and some runtimes reject Reset() on it until the first work has + // completed + if (!this->frame_first_begin) { + check_hresult(this->command_allocator->Reset(), "command allocator Reset"); + check_hresult(this->command_list->Reset(this->command_allocator, nullptr), "command list Reset"); + } + this->frame_first_begin = false; this->frame_begun = true; } @@ -400,7 +405,7 @@ void context::present_frame() // signal the fence for this back buffer (waited on before it is reused) const auto value = this->frame_fence->GetCompletedValue() + 1; - this->frame_fence->Signal(value); + check_hresult(this->queue->Signal(this->frame_fence, value), "queue Signal (frame fence)"); const auto i = int(this->frame_index); check_hresult( this->frame_fence->SetEventOnCompletion(value, this->frame_fence_events[i]), @@ -790,16 +795,18 @@ void context::draw_indexed( this->command_list->IASetVertexBuffers(0, UINT(views.size()), views.data()); } - // the index buffer + // the index buffer (an empty index buffer has no GPU resource) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") const auto& ib = static_cast(va.indices.get()); - const auto ibv = D3D12_INDEX_BUFFER_VIEW{ - .BufferLocation = ib.gpu_va, - .SizeInBytes = UINT(UINT64(ib.index_count) * (ib.index_format == DXGI_FORMAT_R16_UINT ? 2 : 4)), - .Format = ib.index_format - }; - this->command_list->IASetIndexBuffer(&ibv); + if (ib.index_count > 0) { + const auto ibv = D3D12_INDEX_BUFFER_VIEW{ + .BufferLocation = ib.gpu_va, + .SizeInBytes = UINT(UINT64(ib.index_count) * (ib.index_format == DXGI_FORMAT_R16_UINT ? 2 : 4)), + .Format = ib.index_format + }; + this->command_list->IASetIndexBuffer(&ibv); + } } // the per-draw uniforms (root 32-bit constants) @@ -843,11 +850,13 @@ void context::draw_indexed( this->command_list->RSSetScissorRects(1, &scissor_desc); } - // the draw call + // the draw call (skipped for an empty index buffer) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") const auto& ib = static_cast(va.indices.get()); - this->command_list->DrawIndexedInstanced(ib.index_count, 1, 0, 0, 0); + if (ib.index_count > 0) { + this->command_list->DrawIndexedInstanced(ib.index_count, 1, 0, 0, 0); + } } } @@ -875,7 +884,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); check_hresult( this->device->CreateCommittedResource( - &default_heap_properties(), + &readback_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp index 851de91..eb1b2c5 100644 --- a/src/ruis/render/directx/context.hpp +++ b/src/ruis/render/directx/context.hpp @@ -226,6 +226,7 @@ class context : public ruis::render::context // ---- current frame state ---- bool frame_begun = false; + bool frame_first_begin = true; // a fresh command allocator rejects Reset() on some runtimes // ---- renderer state ---- ruis::render::frame_buffer* current_fb = nullptr; // the current framebuffer (nullptr = screen) diff --git a/src/ruis/render/directx/directx.hpp b/src/ruis/render/directx/directx.hpp index 356e077..64e1662 100644 --- a/src/ruis/render/directx/directx.hpp +++ b/src/ruis/render/directx/directx.hpp @@ -162,7 +162,7 @@ inline const D3D12_HEAP_PROPERTIES& default_heap_properties() static const auto props = D3D12_HEAP_PROPERTIES{ .Type = D3D12_HEAP_TYPE_DEFAULT, .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, - .MemoryPoolPreference = D3D12_MEMORY_POOL_L0, + .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, .CreationNodeMask = 0, .VisibleNodeMask = 0 }; @@ -215,7 +215,21 @@ inline const D3D12_HEAP_PROPERTIES& upload_heap_properties() static const auto props = D3D12_HEAP_PROPERTIES{ .Type = D3D12_HEAP_TYPE_UPLOAD, .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, - .MemoryPoolPreference = D3D12_MEMORY_POOL_L0, + .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, + .CreationNodeMask = 0, + .VisibleNodeMask = 0 + }; + return props; +} + +// a readback heap (CPU-readable; the resources created in this heap are +// only ever copy destinations) +inline const D3D12_HEAP_PROPERTIES& readback_heap_properties() +{ + static const auto props = D3D12_HEAP_PROPERTIES{ + .Type = D3D12_HEAP_TYPE_READBACK, + .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, .CreationNodeMask = 0, .VisibleNodeMask = 0 }; diff --git a/src/ruis/render/directx/factory.cpp b/src/ruis/render/directx/factory.cpp index dfcf8ff..33bcfe4 100644 --- a/src/ruis/render/directx/factory.cpp +++ b/src/ruis/render/directx/factory.cpp @@ -77,15 +77,15 @@ factory::factory(const utki::shared_ref& surface) : // const auto static_sampler = D3D12_STATIC_SAMPLER_DESC{ .Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR, - .AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - .AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - .AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + .AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER, + .AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER, + .AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER, .MipLODBias = 0.0f, - .MaxAnisotropy = 1, + .MaxAnisotropy = 0, .ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER, .BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, .MinLOD = 0.0f, - .MaxLOD = 0.0f, + .MaxLOD = D3D12_FLOAT32_MAX, .ShaderRegister = 0, .RegisterSpace = 0, .ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL @@ -101,13 +101,17 @@ factory::factory(const utki::shared_ref& surface) : // ID3DBlob* blob = nullptr; ID3DBlob* error_blob = nullptr; - check_hresult( - D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_1, &blob, &error_blob), - "D3D12SerializeRootSignature" - ); + const auto hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, &error_blob); + std::string err_text; if (error_blob != nullptr) { + const auto ptr = reinterpret_cast(error_blob->GetBufferPointer()); + err_text = (ptr != nullptr) ? std::string(ptr) : std::string(); error_blob->Release(); } + check_hresult( + FAILED(hr) ? hr : S_OK, + FAILED(hr) && !err_text.empty() ? err_text.c_str() : "D3D12SerializeRootSignature" + ); check_hresult( this->device->CreateRootSignature( 0, @@ -178,8 +182,13 @@ void factory::one_shot(std::function cmd) cons } } - check_hresult(this->upload_allocator->Reset(), "upload allocator Reset"); - check_hresult(this->upload_command_list->Reset(this->upload_allocator, nullptr), "upload command list Reset"); + // a freshly created allocator and command list are already in the reset state; + // some runtimes reject Reset() on them until the first work has completed + if (!this->upload_first_shot) { + check_hresult(this->upload_allocator->Reset(), "upload allocator Reset"); + check_hresult(this->upload_command_list->Reset(this->upload_allocator, nullptr), "upload command list Reset"); + } + this->upload_first_shot = false; cmd(this->upload_command_list); @@ -188,7 +197,7 @@ void factory::one_shot(std::function cmd) cons const auto lists = std::array{{this->upload_command_list}}; this->queue->ExecuteCommandLists(1, lists.data()); - this->upload_fence->Signal(++this->upload_fence_value); + check_hresult(this->queue->Signal(this->upload_fence, ++this->upload_fence_value), "queue Signal (upload fence)"); check_hresult( this->upload_fence->SetEventOnCompletion(this->upload_fence_value, this->upload_fence_event), "fence SetEvent" @@ -405,7 +414,7 @@ void factory::upload_texture(texture_2d* t) const &upload_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload) ), diff --git a/src/ruis/render/directx/factory.hpp b/src/ruis/render/directx/factory.hpp index c916f9a..eca4276 100644 --- a/src/ruis/render/directx/factory.hpp +++ b/src/ruis/render/directx/factory.hpp @@ -169,6 +169,7 @@ class factory : public ruis::render::factory // work), but they advance this internal submission state mutable uint64_t upload_fence_value = 0; mutable bool upload_submitted = false; + mutable bool upload_first_shot = true; // a fresh command allocator rejects Reset() on some runtimes }; } // namespace ruis::render::directx diff --git a/src/ruis/render/directx/index_buffer.cpp b/src/ruis/render/directx/index_buffer.cpp index a05a76d..0c2886b 100644 --- a/src/ruis/render/directx/index_buffer.cpp +++ b/src/ruis/render/directx/index_buffer.cpp @@ -57,6 +57,14 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT { const auto byte_size = data.size(); + this->index_format = fmt; + this->index_count = count; + + // an empty index buffer does not need a GPU resource + if (byte_size == 0) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the factory is owned by the renderer; the base-class reference comes from the ruis API") auto& dx_f = static_cast(this->factory.get()); auto* device = dx_f.device; @@ -78,9 +86,6 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT this->gpu_va = this->resource->GetGPUVirtualAddress(); } - this->index_format = fmt; - this->index_count = count; - // ---- upload the data ---- { ID3D12Resource* upload = nullptr; @@ -91,7 +96,7 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT &upload_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload) ), @@ -106,13 +111,13 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { const auto barrier1 = - transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); cmd->ResourceBarrier(1, &barrier1); cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(byte_size)); const auto barrier2 = transition_barrier( this->resource, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER + D3D12_RESOURCE_STATE_INDEX_BUFFER ); cmd->ResourceBarrier(1, &barrier2); }); diff --git a/src/ruis/render/directx/texture_2d.cpp b/src/ruis/render/directx/texture_2d.cpp index fd6749d..f256adc 100644 --- a/src/ruis/render/directx/texture_2d.cpp +++ b/src/ruis/render/directx/texture_2d.cpp @@ -156,7 +156,7 @@ texture_2d::texture_2d( const auto barrier2 = transition_barrier( this->resource, D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ); cmd->ResourceBarrier(1, &barrier2); }); @@ -232,7 +232,7 @@ void texture_2d::record_upload_commands(ID3D12GraphicsCommandList* cmd, ID3D12Re const auto barrier2 = transition_barrier( this->resource, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ); cmd->ResourceBarrier(1, &barrier2); } diff --git a/src/ruis/render/directx/vertex_buffer.cpp b/src/ruis/render/directx/vertex_buffer.cpp index b61238c..3622851 100644 --- a/src/ruis/render/directx/vertex_buffer.cpp +++ b/src/ruis/render/directx/vertex_buffer.cpp @@ -21,6 +21,7 @@ along with this program. If not, see . #include "vertex_buffer.hpp" +#include #include #include "factory.hpp" @@ -37,6 +38,11 @@ vertex_buffer::vertex_buffer( ), byte_size(padded_data.size() * sizeof(float)) { + // an empty vertex buffer does not need a GPU resource + if (this->byte_size == 0) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the factory is owned by the renderer; the base-class reference comes from the ruis API") auto& dx_f = static_cast(this->factory.get()); auto* device = dx_f.device; @@ -44,6 +50,13 @@ vertex_buffer::vertex_buffer( // ---- the vertex buffer (default heap) ---- { const auto desc = make_buffer_desc(UINT64(this->byte_size), D3D12_RESOURCE_FLAG_NONE); + char vbuf_msg[128] = {0}; + std::snprintf( + vbuf_msg, + sizeof(vbuf_msg), + "CreateCommittedResource (vertex buffer, size=%u)", + UINT(this->byte_size) + ); check_hresult( device->CreateCommittedResource( &default_heap_properties(), @@ -53,7 +66,7 @@ vertex_buffer::vertex_buffer( nullptr, IID_PPV_ARGS(&this->resource) ), - "CreateCommittedResource (vertex buffer)" + vbuf_msg ); this->gpu_va = this->resource->GetGPUVirtualAddress(); } @@ -68,7 +81,7 @@ vertex_buffer::vertex_buffer( &upload_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload) ), @@ -83,7 +96,7 @@ vertex_buffer::vertex_buffer( dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { const auto barrier1 = - transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); cmd->ResourceBarrier(1, &barrier1); cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(this->byte_size)); const auto barrier2 = transition_barrier( From 5d355dc0fa1fe7602b9c712ba521dc59342fb33d Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 16:58:42 +0200 Subject: [PATCH 3/8] add placeholder debian changelog for ci versioning The DirectX renderer is Windows-only and ships no Debian package; debian/ holds only a placeholder changelog (and a README explaining why) so that the ci's myci-deb-version scripts can extract the version from debian/changelog and apply it to the packages. --- debian/README.md | 18 ++++++++++++++++++ debian/changelog | 5 +++++ 2 files changed, 23 insertions(+) create mode 100644 debian/README.md create mode 100644 debian/changelog diff --git a/debian/README.md b/debian/README.md new file mode 100644 index 0000000..ca629fa --- /dev/null +++ b/debian/README.md @@ -0,0 +1,18 @@ +# ruis-render-directx — debian directory + +This directory does **not** contain a Debian package. + +`ruis-render-directx` is the DirectX 12 renderer for ruis and is **Windows-only**: +it requires the DirectX 12 / Windows SDK headers, the D3D12 runtime and an +HLSL compiler, so it cannot be packaged for Debian/Ubuntu (or any other +Linux distribution). + +The directory still exists because **the debian changelog/version is the +primary location for the version** of this renderer: the CI +(`myci-deb-version.sh` / `myci-deb-version.ps1`) reads the version from +`debian/changelog` and applies it to the msys2/vcpkg/doxygen/pkg-config +packages, even though only the Windows builds of them are actually produced. + +* `changelog` — the placeholder Debian changelog holding the project + version (the first line of the file is parsed by the ci tooling; keep the + `(major.minor.patch[-rev])` form in that line). diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..c7aa329 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,5 @@ +ruis-render-directx (1.0.0-1) unstable; urgency=medium + + * initial version. + + -- Ivan Gagis Sat, 29 Nov 2026 01:00:00 +0200 From 9b324fd98eb711b8178dda07544bb5ceab5352fc Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 18:39:55 +0200 Subject: [PATCH 4/8] fix Win32 build: cast 64-bit buffer extents to SIZE_T --- src/ruis/render/directx/context.cpp | 4 ++-- src/ruis/render/directx/factory.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp index ad6ee0f..3dfbd25 100644 --- a/src/ruis/render/directx/context.cpp +++ b/src/ruis/render/directx/context.cpp @@ -950,7 +950,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende this->wait_for_gpu(); // read the data back (the row pitch is the one the buffer was allocated with) - std::vector pixels(row_pitch * h); + std::vector pixels(SIZE_T(row_pitch * h)); { const auto pitch = row_pitch; D3D12_RANGE read_range{0, SIZE_T(pitch * h)}; @@ -959,7 +959,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende auto* dst = pixels.data(); auto* src = static_cast(mapped); for (UINT y = 0; y < h; ++y) { - std::memcpy(dst, src, row_pitch); + std::memcpy(dst, src, SIZE_T(row_pitch)); dst += row_pitch; src += pitch; } diff --git a/src/ruis/render/directx/factory.cpp b/src/ruis/render/directx/factory.cpp index 33bcfe4..03a75d7 100644 --- a/src/ruis/render/directx/factory.cpp +++ b/src/ruis/render/directx/factory.cpp @@ -434,7 +434,7 @@ void factory::upload_texture(texture_2d* t) const auto* dst = static_cast(mapped); const auto* src = t->deferred_data.data(); for (UINT64 y = 0; y < h; ++y) { - std::memcpy(dst + y * pitch, src + y * row_bytes, row_bytes); + std::memcpy(dst + y * pitch, src + y * row_bytes, SIZE_T(row_bytes)); } upload->Unmap(0, nullptr); } From 58c19540e7671927bd02cc377c1018fe68609a8f Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 20:19:28 +0200 Subject: [PATCH 5/8] treat triangle fan as unsupported when not available (compile-time guard + runtime check) --- src/ruis/render/directx/context.cpp | 27 +++++++++++++++++++ src/ruis/render/directx/context.hpp | 10 +++++++ .../render/directx/shaders/shader_common.cpp | 3 +++ .../render/directx/shaders/shader_common.hpp | 8 ++++++ 4 files changed, 48 insertions(+) diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp index 3dfbd25..4e687fc 100644 --- a/src/ruis/render/directx/context.cpp +++ b/src/ruis/render/directx/context.cpp @@ -737,6 +737,33 @@ ID3D12PipelineState* context::build_pipeline( return pso; } +bool context::triangle_fan_supported() const +{ + if (!this->triangle_fan_supported_checked) { +#if defined(D3D12_FEATURE_D3D12_OPTIONS15) && defined(D3D12_FEATURE_DATA_D3D12_OPTIONS15) + D3D12_FEATURE_DATA_D3D12_OPTIONS15 options{}; + const auto hr = this->device->CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS15, + &options, + sizeof(options) + ); + this->triangle_fan_supported_cache = SUCCEEDED(hr) && options.TriangleFanSupported != FALSE; +#else + // this toolchain does not declare OPTIONS15: conservative -> no triangle fan + this->triangle_fan_supported_cache = false; +#endif + this->triangle_fan_supported_checked = true; + } + return this->triangle_fan_supported_cache; +} + +void context::check_topology_supported(ruis::render::vertex_array::mode m) const +{ + if (m == ruis::render::vertex_array::mode::triangle_fan && !this->triangle_fan_supported()) { + throw std::runtime_error("Unsupported: triangle_fan primitive topology"); + } +} + ID3D12PipelineState* context::get_or_create_pipeline( shader_kind kind, // bool textured, diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp index eb1b2c5..e1487ab 100644 --- a/src/ruis/render/directx/context.hpp +++ b/src/ruis/render/directx/context.hpp @@ -163,6 +163,12 @@ class context : public ruis::render::context const char* fragment_hlsl ); + // whether the device supports the triangle fan primitive topology (queried once) + bool triangle_fan_supported() const; + + // throw std::runtime_error if the requested topology is not supported + void check_topology_supported(ruis::render::vertex_array::mode m) const; + // begin a frame (acquire the back buffer, reset the command list). Idempotent // within a frame. void ensure_frame_began(); @@ -228,6 +234,10 @@ class context : public ruis::render::context bool frame_begun = false; bool frame_first_begin = true; // a fresh command allocator rejects Reset() on some runtimes + // lazily queried triangle fan support cache (thread-safe enough: the render calls come from one thread) + mutable bool triangle_fan_supported_checked = false; + mutable bool triangle_fan_supported_cache = false; + // ---- renderer state ---- ruis::render::frame_buffer* current_fb = nullptr; // the current framebuffer (nullptr = screen) r4::rectangle viewport{0, 0, 0, 0}; diff --git a/src/ruis/render/directx/shaders/shader_common.cpp b/src/ruis/render/directx/shaders/shader_common.cpp index 9503a3b..0598521 100644 --- a/src/ruis/render/directx/shaders/shader_common.cpp +++ b/src/ruis/render/directx/shaders/shader_common.cpp @@ -58,6 +58,9 @@ void directx_shader_render( } } + // the requested topology must be supported by the device (e.g. triangle fan) + ctx.check_topology_supported(va.rendering_mode); + // the per-draw uniforms (root constants) draw_uniforms u{}; write_draw_uniforms(&u, m, color); diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp index 70ea0dc..0eade70 100644 --- a/src/ruis/render/directx/shaders/shader_common.hpp +++ b/src/ruis/render/directx/shaders/shader_common.hpp @@ -21,6 +21,8 @@ along with this program. If not, see . #pragma once +#include + #include #include #include @@ -84,7 +86,13 @@ inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) case ruis::render::vertex_array::mode::triangles: return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; case ruis::render::vertex_array::mode::triangle_fan: +#if defined(D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN) return D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN; +#else + // this toolchain does not declare triangle fan (e.g. mingw64): + // treat it as unsupported + throw std::runtime_error("Unsupported: triangle_fan primitive topology"); +#endif case ruis::render::vertex_array::mode::line_loop: return D3D_PRIMITIVE_TOPOLOGY_LINELIST; // D3D12 has no line loop; use a line list case ruis::render::vertex_array::mode::triangle_strip: From d600c9d1ca4b3aa697148faeb9a5463b09cd91a6 Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 20:22:48 +0200 Subject: [PATCH 6/8] add comments explaining why triangle fan support must be checked --- .trio_changes.patch | 579 +++++++++ .wip_backup.patch | 1044 +++++++++++++++++ .wip_backup.stat | 14 + check_rdef.js | 46 + dxbc_dump.js | 41 + dxbc_parse.js | 38 + fix_probe2.js | 9 + force_color_shader.js | 10 + minimal_desc.js | 25 + raw_chunk.js | 15 + src/ruis/render/directx/context.cpp | 9 +- src/ruis/render/directx/context.hpp | 4 +- .../render/directx/shaders/shader_common.cpp | 3 +- .../render/directx/shaders/shader_common.hpp | 6 +- strings_dump.js | 24 + 15 files changed, 1862 insertions(+), 5 deletions(-) create mode 100644 .trio_changes.patch create mode 100644 .wip_backup.patch create mode 100644 .wip_backup.stat create mode 100644 check_rdef.js create mode 100644 dxbc_dump.js create mode 100644 dxbc_parse.js create mode 100644 fix_probe2.js create mode 100644 force_color_shader.js create mode 100644 minimal_desc.js create mode 100644 raw_chunk.js create mode 100644 strings_dump.js diff --git a/.trio_changes.patch b/.trio_changes.patch new file mode 100644 index 0000000..d650d28 --- /dev/null +++ b/.trio_changes.patch @@ -0,0 +1,579 @@ +diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp +index c971779..33f8061 100644 +--- a/src/ruis/render/directx/context.cpp ++++ b/src/ruis/render/directx/context.cpp +@@ -25,6 +25,7 @@ along with this program. If not, see . + #include + #include + #include ++#include + + #include + +@@ -59,10 +60,16 @@ context::context( + // maps the framework's normalized viewport coordinates (x right, y down, + // zero at the top-left, right/bottom edges at (1, 1)) to the DirectX NDC. + // +- // In the DirectX NDC -1 -1 corresponds to the top-left corner, 1 1 to the +- // bottom-right corner, and z points away from the viewer (same orientation +- // as the framework, so no axis flip is needed). +- m.set_identity().translate(-1, -1).scale(2, 2); ++ // DirectX identity matrix: ++ // viewport edges: left = -1, right = 1, top = 1, bottom = -1 ++ // z-axis away from the viewer ++ m.set_identity() ++ // x-axis right, y-axis down, z-axis away ++ .scale(1, -1, 1) ++ // viewport edges: left = 0, top = 0 ++ .translate(-1, -1) ++ // viewport edges: right = 1, bottom = 1 ++ .scale(2, 2); + return parameters{m}; + }() + ), +@@ -590,6 +597,16 @@ void context::enable_depth(bool enable) + this->depth_enabled = enable; + } + ++DXGI_FORMAT context::current_rtv_format() const ++{ ++ if (this->current_fb != nullptr && this->current_fb->color != nullptr) { ++ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") ++ const auto& tex = static_cast(*this->current_fb->color); ++ return to_dxgi_format_8bit(tex.ri_format); ++ } ++ return DXGI_FORMAT_B8G8R8A8_UNORM; ++} ++ + uint32_t context::get_blend_key() const + { + // pack the blend state into a key for the pipeline cache: +@@ -607,27 +624,8 @@ uint32_t context::get_blend_key() const + + ID3DBlob* context::compile_shader(const char* hlsl, const char* entry_point, const char* profile) + { +- ID3DBlob* blob = nullptr; +- ID3DBlob* err_blob = nullptr; +- check_hresult( +- D3DCompile( +- hlsl, +- strlen(hlsl), +- "ruis-render-directx.hlsl", +- nullptr, +- nullptr, +- entry_point, +- profile, +- 0, +- 0, +- &blob, +- &err_blob +- ), +- "D3DCompile" +- ); +- if (err_blob != nullptr) { +- err_blob->Release(); +- } ++ // the shared helper throws with the compiler's error message on failure ++ auto* blob = compile_hlsl_blob(hlsl, entry_point, profile); + this->shader_blobs.emplace_back(blob); + return blob; + } +@@ -640,12 +638,13 @@ ID3D12PipelineState* context::build_pipeline( + ) + { + // compile the shaders to DXIL (the blobs are kept alive in shader_blobs) +- auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_6_0"); +- auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_6_0"); ++ auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_5_1"); ++ auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_5_1"); + + // ---- the vertex input layout ---- +- // all vertices are stored as float4 (4 floats) in the vertex buffer; the a1 +- // attribute (if present) is the tail of the float4 (its format is shader-specific) ++ // each buffer of the vertex array holds float4 (4 floats) vertices with the ++ // same stride; the a1 attribute (if present) reads the first few floats of the ++ // second buffer (its format is shader-specific) + const auto a1 = shader_kind(key.shader_kind); + auto input_layout_elements = std::vector{ + {.SemanticName = "POSITION", +@@ -658,11 +657,11 @@ ID3D12PipelineState* context::build_pipeline( + if (has_a1) { + input_layout_elements.push_back( + D3D12_INPUT_ELEMENT_DESC{ +- .SemanticName = "TEXCOORD", ++ .SemanticName = a1_semantic(a1), + .SemanticIndex = 0, + .Format = a1_format(a1), + .InputSlot = 1, +- .AlignedByteOffset = UINT(vertex_stride_bytes), ++ .AlignedByteOffset = 0, + .InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA + } + ); +@@ -703,14 +702,14 @@ ID3D12PipelineState* context::build_pipeline( + + const auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{ + .pRootSignature = this->root_signature, +- .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), vs_blob->GetBufferSize()}, +- .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), fs_blob->GetBufferSize()}, ++ .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}, ++ .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}, + .BlendState = blend, + .SampleMask = 0xFFFFFFFF, + .RasterizerState = + D3D12_RASTERIZER_DESC{ + .FillMode = D3D12_FILL_MODE_SOLID, +- .CullMode = D3D12_CULL_MODE_NONE, ++ .CullMode = D3D12_CULL_MODE_BACK, + .FrontCounterClockwise = FALSE, + .DepthBias = 0, + .DepthBiasClamp = 0.0f, +@@ -726,17 +725,15 @@ ID3D12PipelineState* context::build_pipeline( + .IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + .PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + .NumRenderTargets = 1, +- .RTVFormats = {DXGI_FORMAT_UNKNOWN}, // the actual format depends on the render target +- .DSVFormat = DXGI_FORMAT_UNKNOWN, // the actual format depends on the depth texture ++ .RTVFormats = {static_cast(key.rtv_format)}, ++ .DSVFormat = use_depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_UNKNOWN, + .SampleDesc = {.Count = 1, .Quality = 0}, + .NodeMask = 0 + }; + + ID3D12PipelineState* pso = nullptr; +- check_hresult( +- this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)), +- "CreateGraphicsPipelineState" +- ); ++ const auto hr = this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)); ++ check_hresult(hr, "CreateGraphicsPipelineState"); + return pso; + } + +@@ -753,7 +750,8 @@ ID3D12PipelineState* context::get_or_create_pipeline( + .blend_key = this->get_blend_key(), + .depth_enabled = uint32_t(this->depth_enabled ? 1 : 0), + .textured = uint32_t(textured ? 1 : 0), +- .topology = uint32_t(topology) ++ .topology = uint32_t(topology), ++ .rtv_format = uint32_t(this->current_rtv_format()) + }; + + const auto it = this->pipelines.find(key); +@@ -781,18 +779,20 @@ void context::draw_indexed( + this->command_list->SetPipelineState(pso); + this->command_list->IASetPrimitiveTopology(to_topology(va.rendering_mode)); + +- // the vertex buffer (the first buffer of the vertex array; the vertex data of +- // all buffers is expected to have the same float4 layout) ++ // the vertex buffers (one per slot; all buffers have the same float4 layout) + { + utki::assert(!va.buffers.empty(), SL); +- // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") +- const auto& vb = static_cast(va.buffers.front().get()); +- const auto vbv = D3D12_VERTEX_BUFFER_VIEW{ +- .BufferLocation = vb.gpu_va, +- .SizeInBytes = UINT(vb.byte_size), +- .StrideInBytes = UINT(vertex_stride_bytes) +- }; +- this->command_list->IASetVertexBuffers(0, 1, &vbv); ++ std::vector views(va.buffers.size()); ++ for (size_t i = 0; i < va.buffers.size(); ++i) { ++ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") ++ const auto& vb = static_cast(va.buffers[i].get()); ++ views[i] = D3D12_VERTEX_BUFFER_VIEW{ ++ .BufferLocation = vb.gpu_va, ++ .SizeInBytes = UINT(vb.byte_size), ++ .StrideInBytes = UINT(vertex_stride_bytes) ++ }; ++ } ++ this->command_list->IASetVertexBuffers(0, UINT(views.size()), views.data()); + } + + // the index buffer (an empty index buffer has no GPU resource) +@@ -901,7 +901,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende + const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); + check_hresult( + this->device->CreateCommittedResource( +- &upload_heap_properties(), ++ &default_heap_properties(), + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, +diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp +index f528340..eb1b2c5 100644 +--- a/src/ruis/render/directx/context.hpp ++++ b/src/ruis/render/directx/context.hpp +@@ -53,11 +53,13 @@ struct pipeline_key { + uint32_t depth_enabled = 0; + uint32_t textured = 0; + uint32_t topology = 0; // D3D12_PRIMITIVE_TOPOLOGY ++ uint32_t rtv_format = 0; // DXGI_FORMAT (the current render target format) + + bool operator==(const pipeline_key& o) const + { + return this->shader_kind == o.shader_kind && this->blend_key == o.blend_key && +- this->depth_enabled == o.depth_enabled && this->textured == o.textured && this->topology == o.topology; ++ this->depth_enabled == o.depth_enabled && this->textured == o.textured && ++ this->topology == o.topology && this->rtv_format == o.rtv_format; + } + }; + +@@ -77,6 +79,7 @@ struct pipeline_key_hash { + hash_combine(h, std::hash()(k.depth_enabled)); + hash_combine(h, std::hash()(k.textured)); + hash_combine(h, std::hash()(k.topology)); ++ hash_combine(h, std::hash()(k.rtv_format)); + return h; + } + }; +@@ -147,6 +150,10 @@ public: + // the packed key of the current blend state (for pipeline selection) + uint32_t get_blend_key() const; + ++ // the DXGI_FORMAT of the current render target (the swapchain for the ++ // screen, the color texture for a frame buffer) ++ DXGI_FORMAT current_rtv_format() const; ++ + // get or create a pipeline state object for the given shader + current state + ID3D12PipelineState* get_or_create_pipeline( + shader_kind kind, // +diff --git a/src/ruis/render/directx/directx.cpp b/src/ruis/render/directx/directx.cpp +index a1eb137..04d282d 100644 +--- a/src/ruis/render/directx/directx.cpp ++++ b/src/ruis/render/directx/directx.cpp +@@ -21,12 +21,13 @@ along with this program. If not, see . + + #include "directx.hpp" + ++#include + #include + #include + + namespace ruis::render::directx { + +-std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) ++ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile) + { + ID3DBlob* blob = nullptr; + ID3DBlob* err_blob = nullptr; +@@ -45,20 +46,24 @@ std::vector compile_hlsl(const char* source, const char* entry_point, c + ); + if (FAILED(hr)) { + const auto err = err_blob != nullptr ? reinterpret_cast(err_blob->GetBufferPointer()) : ""; +- const auto msg = std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err; +- if (err_blob != nullptr) { +- err_blob->Release(); +- } +- throw std::runtime_error(msg); ++ if (err_blob != nullptr) { err_blob->Release(); } ++ if (blob != nullptr) { blob->Release(); } ++ throw std::runtime_error(std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err); + } ++ if (err_blob != nullptr) { err_blob->Release(); } ++ return blob; ++} + ++std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) ++{ ++ // compile the shader and copy the bytecode out of the returned blob ++ // (the caller keeps the blob alive for the lifetime of the pipeline; ++ // this public helper only needs the bytecode) ++ auto* blob = compile_hlsl_blob(source, entry_point, profile); + const auto size = blob->GetBufferSize(); + std::vector bytecode(size); + std::copy_n(static_cast(blob->GetBufferPointer()), size, bytecode.begin()); + blob->Release(); +- if (err_blob != nullptr) { +- err_blob->Release(); +- } + return bytecode; + } + +diff --git a/src/ruis/render/directx/directx.hpp b/src/ruis/render/directx/directx.hpp +index 0196277..3a8433f 100644 +--- a/src/ruis/render/directx/directx.hpp ++++ b/src/ruis/render/directx/directx.hpp +@@ -51,9 +51,9 @@ inline void check_hresult(HRESULT hr, const char* what) + /** + * @brief The shared draw uniforms, bound as a root constant buffer view. + * +- * The matrix is stored in row-major order, which is the same order that +- * r4::matrix4 uses and the default packing order of a row-major float4x4 in +- * HLSL, so the matrix is copied directly from r4 without any transposition. ++ * The matrix is stored in column-major order, matching the default packing ++ * of a float4x4 in an HLSL cbuffer (r4 stores row-major), so the matrix is ++ * transposed on write. + */ + struct draw_uniforms { + float matrix[4][4]; +@@ -64,9 +64,11 @@ static_assert(sizeof(draw_uniforms) == 16 * sizeof(float) + 4 * sizeof(float)); + + inline void write_draw_uniforms(draw_uniforms* u, const r4::matrix4& m, const r4::vector4& color) + { ++ // r4 stores row-major, HLSL expects column-major: transpose first ++ auto t = m.tposed(); + for (uint32_t r = 0; r < 4; ++r) { + for (uint32_t c = 0; c < 4; ++c) { +- u->matrix[r][c] = m[r][c]; ++ u->matrix[r][c] = t[r][c]; + } + } + u->color[0] = color.x(); +@@ -148,10 +150,11 @@ inline DXGI_FORMAT to_dxgi_format_8bit(rasterimage::format f) + } + + // D3D12_RESOURCE_STATE_DEPTH_STENCIL was removed from the new SDK; +-// it is the same combination of states as before +-inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = // +- D3D12_RESOURCE_STATE_DEPTH_WRITE | // +- D3D12_RESOURCE_STATE_DEPTH_READ; ++// the depth-stencil resources of this renderer are only written through the ++// depth-stencil view, so they are created in the (single) depth-write state. ++// (Read-only states cannot be combined with write states, so DEPTH_WRITE | DEPTH_READ ++// would be invalid.) ++inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = D3D12_RESOURCE_STATE_DEPTH_WRITE; + + // D3D12_MAX_LOD was removed from the new SDK; + // it is the maximum mip level (2048) that indicates "all mip levels" +@@ -241,8 +244,20 @@ inline D3D12_RESOURCE_BARRIER transition_barrier( + return b; + } + +-// compile an HLSL shader source at runtime (via the D3D compiler); +-// the returned blob contains the DXIL bytecode ++/** ++ * @brief Compile one HLSL shader source at runtime (via the D3D compiler). ++ * @param source the HLSL source ++ * @param entry_point the entry point ++ * @param profile the target profile (e.g. "vs_5_1") ++ * @return the compiled blob; the caller owns it and must release it. ++ * @throws std::runtime_error carrying the compiler's error message on failure. ++ */ ++ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile); ++ ++/** ++ * @brief Compile one HLSL shader source at runtime and return the DXIL bytecode. ++ * @throws std::runtime_error carrying the compiler's error message on failure. ++ */ + std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile); + + } // namespace ruis::render::directx +diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp +index 91f5d99..70ea0dc 100644 +--- a/src/ruis/render/directx/shaders/shader_common.hpp ++++ b/src/ruis/render/directx/shaders/shader_common.hpp +@@ -65,6 +65,18 @@ constexpr DXGI_FORMAT a1_format(shader_kind k) + } + } + ++// the semantic name of the a1 attribute (used in the vertex input layout) ++constexpr const char* a1_semantic(shader_kind k) ++{ ++ switch (k) { ++ case shader_kind::pos_clr: ++ return "COLOR"; ++ default: ++ // the textured shaders and the luminance shader declare it as TEXCOORD ++ return "TEXCOORD"; ++ } ++} ++ + // map the VAO's rendering mode to a DirectX primitive topology + inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) + { +diff --git a/src/ruis/render/directx/shaders/shader_src.hpp b/src/ruis/render/directx/shaders/shader_src.hpp +index ea38d7f..0a556cf 100644 +--- a/src/ruis/render/directx/shaders/shader_src.hpp ++++ b/src/ruis/render/directx/shaders/shader_src.hpp +@@ -22,7 +22,7 @@ along with this program. If not, see . + /* + * The HLSL sources of the renderer's shaders. + * They are compiled to DXIL at runtime with the D3D compiler (see +- * directx::compile_hlsl()). ++ * directx::compile_hlsl_blob(), which is what the renderer uses). + * + * The per-draw uniforms (the transformation matrix and the color) are passed + * as root 32-bit constants in register b0: first a float4x4 matrix (16 floats), +@@ -45,18 +45,24 @@ namespace ruis::render::directx { + // ============== color ========= + + static const char* hlsl_shader_color_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + float4 main(float4 pos : POSITION) : SV_POSITION + { +- return draw_matrix * pos; ++ return mul(draw_matrix, pos); + } + )HLSL"; + + static const char* hlsl_shader_color_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + float4 main() : SV_Target + { +@@ -68,8 +74,11 @@ float4 main() : SV_Target + // ============== pos_clr ======= + + static const char* hlsl_shader_pos_clr_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + struct VS_OUT + { +@@ -80,14 +89,19 @@ struct VS_OUT + VS_OUT main(float4 pos : POSITION, float4 col : COLOR) + { + VS_OUT o; +- o.pos = draw_matrix * pos; ++ o.pos = mul(draw_matrix, pos); + o.col = col; + return o; + } + )HLSL"; + + static const char* hlsl_shader_pos_clr_fragment = R"HLSL( +-float4 main(float4 col : COLOR) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float4 col : COLOR) : SV_Target + { + return col; + } +@@ -97,8 +111,11 @@ float4 main(float4 col : COLOR) : SV_Target + // ============== pos_tex ======= + + static const char* hlsl_shader_pos_tex_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + struct VS_OUT + { +@@ -109,20 +126,28 @@ struct VS_OUT + VS_OUT main(float4 pos : POSITION, float2 uv : TEXCOORD) + { + VS_OUT o; +- o.pos = draw_matrix * pos; ++ o.pos = mul(draw_matrix, pos); + o.uv = uv; + return o; + } + )HLSL"; + + static const char* hlsl_shader_pos_tex_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + Texture2D tex0 : register(t0); + SamplerState samp0 : register(s0); + +-float4 main(float2 uv : TEXCOORD) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target + { + return tex0.Sample(samp0, uv) * draw_color; + } +@@ -140,13 +165,21 @@ static const char* hlsl_shader_color_pos_tex_fragment = hlsl_shader_pos_tex_frag + static const char* hlsl_shader_color_pos_tex_alpha_vertex = hlsl_shader_pos_tex_vertex; + + static const char* hlsl_shader_color_pos_tex_alpha_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + Texture2D tex0 : register(t0); + SamplerState samp0 : register(s0); + +-float4 main(float2 uv : TEXCOORD) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target + { + return float4(draw_color.xyz, draw_color.w * tex0.Sample(samp0, uv).r); + } +@@ -156,8 +189,11 @@ float4 main(float2 uv : TEXCOORD) : SV_Target + // ============== color_pos_lum = + + static const char* hlsl_shader_color_pos_lum_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + struct VS_OUT + { +@@ -168,17 +204,25 @@ struct VS_OUT + VS_OUT main(float4 pos : POSITION, float lum : TEXCOORD) + { + VS_OUT o; +- o.pos = draw_matrix * pos; ++ o.pos = mul(draw_matrix, pos); + o.lum = lum; + return o; + } + )HLSL"; + + static const char* hlsl_shader_color_pos_lum_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + +-float4 main(float lum : TEXCOORD) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float lum : TEXCOORD) : SV_Target + { + return float4(draw_color.xyz, draw_color.w * lum); + } diff --git a/.wip_backup.patch b/.wip_backup.patch new file mode 100644 index 0000000..c95727d --- /dev/null +++ b/.wip_backup.patch @@ -0,0 +1,1044 @@ +diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp +index 26af34e..ed5b1ef 100644 +--- a/src/ruis/render/directx/context.cpp ++++ b/src/ruis/render/directx/context.cpp +@@ -22,9 +22,11 @@ along with this program. If not, see . + #include "context.hpp" + + #include ++#include + #include + #include + #include ++#include + + #include + +@@ -34,6 +36,7 @@ along with this program. If not, see . + #include "texture_depth.hpp" + #include "vertex_array.hpp" + #include "vertex_buffer.hpp" ++#include "shaders/shader_src.hpp" + + using namespace ruis::render::directx; + +@@ -44,6 +47,38 @@ constexpr ruis::real ndc_to_unit_scale = ruis::real(0.5); + // the size of a vertex in bytes: all vertex attributes are stored as float4 (4 floats) + constexpr UINT64 vertex_stride_bytes = 4 * sizeof(float); + ++// TEMPORARY: dump stored debug messages from the info queue (diagnostics) ++void dump_info_queue_messages(ID3D12Device* device) ++{ ++ if (device == nullptr) { ++ return; ++ } ++ ID3D12InfoQueue* iq = nullptr; ++ if (FAILED(device->QueryInterface(IID_PPV_ARGS(&iq))) || iq == nullptr) { ++ fprintf(stderr, "dump_info_queue_messages: QueryInterface(ID3D12InfoQueue) failed\n"); ++ return; ++ } ++ const auto num = iq->GetNumStoredMessages(); ++ fprintf(stderr, "dump_info_queue_messages: %llu stored messages\n", (unsigned long long)num); ++ for (uint64_t i = 0; i < num; ++i) { ++ D3D12_MESSAGE msg{}; ++ SIZE_T len = sizeof(msg); ++ if (FAILED(iq->GetMessage(i, nullptr, &len)) || len == 0) { ++ fprintf(stderr, " message %llu: GetMessage(description) failed\n", (unsigned long long)i); ++ continue; ++ } ++ std::vector buf(len); ++ const auto hr = iq->GetMessage(i, reinterpret_cast(buf.data()), &len); ++ if (FAILED(hr)) { ++ fprintf(stderr, " message %llu: GetMessage failed (hr=0x%08x)\n", (unsigned long long)i, unsigned(hr)); ++ continue; ++ } ++ const auto& m = *reinterpret_cast(buf.data()); ++ fprintf(stderr, " [%u] %.*s\n", unsigned(m.Severity), int(m.DescriptionByteLength), m.pDescription ? m.pDescription : "(null)"); ++ } ++ iq->Release(); ++} ++ + } // namespace + + context::context( +@@ -59,10 +94,16 @@ context::context( + // maps the framework's normalized viewport coordinates (x right, y down, + // zero at the top-left, right/bottom edges at (1, 1)) to the DirectX NDC. + // +- // In the DirectX NDC -1 -1 corresponds to the top-left corner, 1 1 to the +- // bottom-right corner, and z points away from the viewer (same orientation +- // as the framework, so no axis flip is needed). +- m.set_identity().translate(-1, -1).scale(2, 2); ++ // DirectX identity matrix: ++ // viewport edges: left = -1, right = 1, top = 1, bottom = -1 ++ // z-axis away from the viewer ++ m.set_identity() ++ // x-axis right, y-axis down, z-axis away ++ .scale(1, -1, 1) ++ // viewport edges: left = 0, top = 0 ++ .translate(-1, -1) ++ // viewport edges: right = 1, bottom = 1 ++ .scale(2, 2); + return parameters{m}; + }() + ), +@@ -182,7 +223,7 @@ void context::create_swapchain() + IDXGISwapChain1* sc = nullptr; + check_hresult( + dxgi_factory->CreateSwapChainForHwnd( +- reinterpret_cast(this->device), ++ reinterpret_cast(this->queue), + this->surface_ref.get().get_hwnd(), + &desc, + nullptr, +@@ -210,6 +251,12 @@ void context::create_swapchain() + utki::assert(this->back_buffer_count == 0 || this->back_buffers.size() == this->back_buffer_count, SL); + this->back_buffer_count = UINT(this->back_buffers.size()); + utki::assert(this->back_buffer_count >= 2, SL); ++ fprintf(stderr, "create_swapchain: back_buffer_count=%u window_dims=(%u,%u) swapchain_vsync=%d\n", UINT(this->back_buffer_count), this->window_dims.x(), this->window_dims.y(), (int)this->swapchain_vsync); ++ { ++ DXGI_SWAP_CHAIN_DESC desc{}; ++ this->swapchain->GetDesc(&desc); ++ fprintf(stderr, "create_swapchain: swapchain format=%u back buffer0 format=%u\n", unsigned(desc.BufferDesc.Format), unsigned(this->back_buffers[0]->GetDesc().Format)); ++ } + + // one RTV descriptor per back buffer + { +@@ -348,7 +395,7 @@ void context::wait_for_gpu() + } + // wait for the frame that rendered to the back buffer we are about to reuse + const auto i = int(this->frame_index); +- if (this->frame_pending[i]) { ++ if (i < 3 && this->frame_pending[i]) { + const auto res = WaitForSingleObject(this->frame_fence_events[i], 10000); // 10s timeout + if (res != WAIT_OBJECT_0) { + throw std::runtime_error("directx context wait_for_gpu: the frame fence did not complete in time"); +@@ -367,10 +414,10 @@ void context::ensure_frame_began() + this->ensure_swapchain_valid(); + + if (this->swapchain != nullptr) { +- // wait for the GPU to finish with the back buffer we are about to overwrite, +- // then advance to the next back buffer ++ // the swapchain tells us which back buffer we are about to render to ++ this->frame_index = this->swapchain->GetCurrentBackBufferIndex(); ++ // wait for the GPU to finish with the back buffer we are about to overwrite + this->wait_for_gpu(); +- this->frame_index = (this->frame_index + 1) % this->back_buffer_count; + } + + // reset the command allocator and the command list (the GPU has finished with +@@ -383,6 +430,7 @@ void context::ensure_frame_began() + } + this->frame_first_begin = false; + ++ + this->frame_begun = true; + } + +@@ -398,7 +446,7 @@ void context::present_frame() + + // signal the fence for this back buffer (waited on before it is reused) + const auto value = this->frame_fence->GetCompletedValue() + 1; +- this->frame_fence->Signal(value); ++ check_hresult(this->queue->Signal(this->frame_fence, value), "queue Signal (frame fence)"); + const auto i = int(this->frame_index); + check_hresult( + this->frame_fence->SetEventOnCompletion(value, this->frame_fence_events[i]), +@@ -409,7 +457,8 @@ void context::present_frame() + // present the back buffer to the window + if (this->swapchain != nullptr) { + const auto hr = this->swapchain->Present(this->swapchain_vsync ? 1 : 0, 0); +- (void)hr; // a failed present (e.g. window minimized) is not fatal ++ fprintf(stderr, "present_frame: Present hr=0x%08x\n", unsigned(hr)); // a failed present (e.g. window minimized) is not fatal ++ if (FAILED(hr)) { dump_info_queue_messages(this->device); } + } + } + +@@ -588,6 +637,16 @@ void context::enable_depth(bool enable) + this->depth_enabled = enable; + } + ++DXGI_FORMAT context::current_rtv_format() const ++{ ++ if (this->current_fb != nullptr && this->current_fb->color != nullptr) { ++ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") ++ const auto& tex = static_cast(*this->current_fb->color); ++ return to_dxgi_format_8bit(tex.ri_format); ++ } ++ return DXGI_FORMAT_B8G8R8A8_UNORM; ++} ++ + uint32_t context::get_blend_key() const + { + // pack the blend state into a key for the pipeline cache: +@@ -605,27 +664,8 @@ uint32_t context::get_blend_key() const + + ID3DBlob* context::compile_shader(const char* hlsl, const char* entry_point, const char* profile) + { +- ID3DBlob* blob = nullptr; +- ID3DBlob* err_blob = nullptr; +- check_hresult( +- D3DCompile( +- hlsl, +- strlen(hlsl), +- "ruis-render-directx.hlsl", +- nullptr, +- nullptr, +- entry_point, +- profile, +- 0, +- 0, +- &blob, +- &err_blob +- ), +- "D3DCompile" +- ); +- if (err_blob != nullptr) { +- err_blob->Release(); +- } ++ // the shared helper throws with the compiler's error message on failure ++ auto* blob = compile_hlsl_blob(hlsl, entry_point, profile); + this->shader_blobs.emplace_back(blob); + return blob; + } +@@ -637,13 +677,19 @@ ID3D12PipelineState* context::build_pipeline( + const char* fragment_hlsl + ) + { ++ fprintf(stderr, "build_pipeline: pre-compile\n"); + // compile the shaders to DXIL (the blobs are kept alive in shader_blobs) +- auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_6_0"); +- auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_6_0"); ++ auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_5_1"); ++ fprintf(stderr, "build_pipeline: post-vs-compile\n"); ++ fprintf(stderr, "build_pipeline: pre-fs-compile\n"); ++ auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_5_1"); ++ fprintf(stderr, "build_pipeline: post-fs-compile\n"); + ++ fprintf(stderr, "build_pipeline: pre-input-layout\n"); + // ---- the vertex input layout ---- +- // all vertices are stored as float4 (4 floats) in the vertex buffer; the a1 +- // attribute (if present) is the tail of the float4 (its format is shader-specific) ++ // each buffer of the vertex array holds float4 (4 floats) vertices with the ++ // same stride; the a1 attribute (if present) reads the first few floats of the ++ // second buffer (its format is shader-specific) + const auto a1 = shader_kind(key.shader_kind); + auto input_layout_elements = std::vector{ + {.SemanticName = "POSITION", +@@ -656,11 +702,11 @@ ID3D12PipelineState* context::build_pipeline( + if (has_a1) { + input_layout_elements.push_back( + D3D12_INPUT_ELEMENT_DESC{ +- .SemanticName = "TEXCOORD", ++ .SemanticName = a1_semantic(a1), + .SemanticIndex = 0, + .Format = a1_format(a1), + .InputSlot = 1, +- .AlignedByteOffset = UINT(vertex_stride_bytes), ++ .AlignedByteOffset = 0, + .InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA + } + ); +@@ -699,16 +745,32 @@ ID3D12PipelineState* context::build_pipeline( + depth_stencil.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; + depth_stencil.BackFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; + ++ fprintf(stderr, "build_pipeline: vs_blob size=%u\n", UINT(vs_blob->GetBufferSize())); ++ fprintf(stderr, "build_pipeline: fs_blob size=%u\n", UINT(fs_blob->GetBufferSize())); ++ fprintf(stderr, "build_pipeline: input_layout NumElements=%u\n", UINT(input_layout.NumElements)); ++ fprintf(stderr, "build_pipeline: pso key rtv_format=%u depth=%d topology=%u\n", key.rtv_format, use_depth ? 1 : 0, key.topology); ++ // TEMPORARY: dump the shader blobs to files for analysis ++ { ++ const auto vs_ptr = (const unsigned char*)vs_blob->GetBufferPointer(); ++ const auto fs_ptr = (const unsigned char*)fs_blob->GetBufferPointer(); ++ FILE* f = nullptr; ++ fopen_s(&f, "vs_dump.bin", "wb"); if (f) { fwrite(vs_ptr, 1, vs_blob->GetBufferSize(), f); fclose(f); } ++ fopen_s(&f, "fs_dump.bin", "wb"); if (f) { fwrite(fs_ptr, 1, fs_blob->GetBufferSize(), f); fclose(f); } ++ } ++ fprintf(stderr, "build_pipeline: vs first bytes: %02x %02x %02x %02x %02x %02x %02x %02x\n", ((const unsigned char*)vs_blob->GetBufferPointer())[0], ((const unsigned char*)vs_blob->GetBufferPointer())[1], ((const unsigned char*)vs_blob->GetBufferPointer())[2], ((const unsigned char*)vs_blob->GetBufferPointer())[3], ((const unsigned char*)vs_blob->GetBufferPointer())[4], ((const unsigned char*)vs_blob->GetBufferPointer())[5], ((const unsigned char*)vs_blob->GetBufferPointer())[6], ((const unsigned char*)vs_blob->GetBufferPointer())[7]); ++ fprintf(stderr, "build_pipeline: fs first bytes: %02x %02x %02x %02x %02x %02x %02x %02x\n", ((const unsigned char*)fs_blob->GetBufferPointer())[0], ((const unsigned char*)fs_blob->GetBufferPointer())[1], ((const unsigned char*)fs_blob->GetBufferPointer())[2], ((const unsigned char*)fs_blob->GetBufferPointer())[3], ((const unsigned char*)fs_blob->GetBufferPointer())[4], ((const unsigned char*)fs_blob->GetBufferPointer())[5], ((const unsigned char*)fs_blob->GetBufferPointer())[6], ((const unsigned char*)fs_blob->GetBufferPointer())[7]); ++ fprintf(stderr, "build_pipeline: vs input semantics: %s\n", "check"); ++ fprintf(stderr, "build_pipeline: pre-CreateGraphicsPipelineState\n"); + const auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{ + .pRootSignature = this->root_signature, +- .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), vs_blob->GetBufferSize()}, +- .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), fs_blob->GetBufferSize()}, ++ .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}, ++ .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}, + .BlendState = blend, + .SampleMask = 0xFFFFFFFF, + .RasterizerState = + D3D12_RASTERIZER_DESC{ + .FillMode = D3D12_FILL_MODE_SOLID, +- .CullMode = D3D12_CULL_MODE_NONE, ++ .CullMode = D3D12_CULL_MODE_BACK, + .FrontCounterClockwise = FALSE, + .DepthBias = 0, + .DepthBiasClamp = 0.0f, +@@ -724,17 +786,22 @@ ID3D12PipelineState* context::build_pipeline( + .IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + .PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + .NumRenderTargets = 1, +- .RTVFormats = {DXGI_FORMAT_UNKNOWN}, // the actual format depends on the render target +- .DSVFormat = DXGI_FORMAT_UNKNOWN, // the actual format depends on the depth texture ++ .RTVFormats = {static_cast(key.rtv_format)}, ++ .DSVFormat = use_depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_UNKNOWN, + .SampleDesc = {.Count = 1, .Quality = 0}, + .NodeMask = 0 + }; + ++ fprintf(stderr, "build_pipeline: pre-create-call\n"); + ID3D12PipelineState* pso = nullptr; +- check_hresult( +- this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)), +- "CreateGraphicsPipelineState" +- ); ++ fprintf(stderr, "build_pipeline: pre-check_hresult\n"); ++ const auto hr = this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)); ++ fprintf(stderr, "build_pipeline: CreateGraphicsPipelineState hr=0x%08x pso=%p\n", unsigned(hr), (void*)pso); ++ if (FAILED(hr)) { ++ dump_info_queue_messages(this->device); ++ } ++ check_hresult(hr, "CreateGraphicsPipelineState"); ++ fprintf(stderr, "build_pipeline: done\n"); + return pso; + } + +@@ -751,15 +818,19 @@ ID3D12PipelineState* context::get_or_create_pipeline( + .blend_key = this->get_blend_key(), + .depth_enabled = uint32_t(this->depth_enabled ? 1 : 0), + .textured = uint32_t(textured ? 1 : 0), +- .topology = uint32_t(topology) ++ .topology = uint32_t(topology), ++ .rtv_format = uint32_t(this->current_rtv_format()) + }; + + const auto it = this->pipelines.find(key); ++ fprintf(stderr, "get_or_create_pipeline: found?=%d\n", (int)(it != this->pipelines.end())); + if (it != this->pipelines.end()) { + return it->second; + } + ++ fprintf(stderr, "get_or_create_pipeline: building pipeline shader_kind=%d textured=%d\n", (int)kind, (int)textured); + const auto pso = this->build_pipeline(key, shader_has_a1(kind), vertex_hlsl, fragment_hlsl); ++ fprintf(stderr, "get_or_create_pipeline: built\n"); + this->pipelines.emplace(key, pso); + return pso; + } +@@ -779,18 +850,20 @@ void context::draw_indexed( + this->command_list->SetPipelineState(pso); + this->command_list->IASetPrimitiveTopology(to_topology(va.rendering_mode)); + +- // the vertex buffer (the first buffer of the vertex array; the vertex data of +- // all buffers is expected to have the same float4 layout) ++ // the vertex buffers (one per slot; all buffers have the same float4 layout) + { + utki::assert(!va.buffers.empty(), SL); +- // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") +- const auto& vb = static_cast(va.buffers.front().get()); +- const auto vbv = D3D12_VERTEX_BUFFER_VIEW{ +- .BufferLocation = vb.gpu_va, +- .SizeInBytes = UINT(vb.byte_size), +- .StrideInBytes = UINT(vertex_stride_bytes) +- }; +- this->command_list->IASetVertexBuffers(0, 1, &vbv); ++ std::vector views(va.buffers.size()); ++ for (size_t i = 0; i < va.buffers.size(); ++i) { ++ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") ++ const auto& vb = static_cast(va.buffers[i].get()); ++ views[i] = D3D12_VERTEX_BUFFER_VIEW{ ++ .BufferLocation = vb.gpu_va, ++ .SizeInBytes = UINT(vb.byte_size), ++ .StrideInBytes = UINT(vertex_stride_bytes) ++ }; ++ } ++ this->command_list->IASetVertexBuffers(0, UINT(views.size()), views.data()); + } + + // the index buffer (an empty index buffer has no GPU resource) +@@ -899,7 +972,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende + const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); + check_hresult( + this->device->CreateCommittedResource( +- &upload_heap_properties(), ++ &readback_heap_properties(), + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, +diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp +index f528340..eb1b2c5 100644 +--- a/src/ruis/render/directx/context.hpp ++++ b/src/ruis/render/directx/context.hpp +@@ -53,11 +53,13 @@ struct pipeline_key { + uint32_t depth_enabled = 0; + uint32_t textured = 0; + uint32_t topology = 0; // D3D12_PRIMITIVE_TOPOLOGY ++ uint32_t rtv_format = 0; // DXGI_FORMAT (the current render target format) + + bool operator==(const pipeline_key& o) const + { + return this->shader_kind == o.shader_kind && this->blend_key == o.blend_key && +- this->depth_enabled == o.depth_enabled && this->textured == o.textured && this->topology == o.topology; ++ this->depth_enabled == o.depth_enabled && this->textured == o.textured && ++ this->topology == o.topology && this->rtv_format == o.rtv_format; + } + }; + +@@ -77,6 +79,7 @@ struct pipeline_key_hash { + hash_combine(h, std::hash()(k.depth_enabled)); + hash_combine(h, std::hash()(k.textured)); + hash_combine(h, std::hash()(k.topology)); ++ hash_combine(h, std::hash()(k.rtv_format)); + return h; + } + }; +@@ -147,6 +150,10 @@ public: + // the packed key of the current blend state (for pipeline selection) + uint32_t get_blend_key() const; + ++ // the DXGI_FORMAT of the current render target (the swapchain for the ++ // screen, the color texture for a frame buffer) ++ DXGI_FORMAT current_rtv_format() const; ++ + // get or create a pipeline state object for the given shader + current state + ID3D12PipelineState* get_or_create_pipeline( + shader_kind kind, // +diff --git a/src/ruis/render/directx/device.cpp b/src/ruis/render/directx/device.cpp +index 5e9c7b4..e628bdb 100644 +--- a/src/ruis/render/directx/device.cpp ++++ b/src/ruis/render/directx/device.cpp +@@ -21,6 +21,8 @@ along with this program. If not, see . + + #include "device.hpp" + ++#include ++ + #include + #include + +@@ -61,6 +63,18 @@ D3D_FEATURE_LEVEL pick_feature_level(IDXGIFactory1* factory, IDXGIAdapter1* adap + + device::device() + { ++ // TEMPORARY: enable the D3D12 debug layer for diagnostics ++ { ++ ID3D12Debug* dbg = nullptr; ++ const auto dbg_hr = D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)); ++ fprintf(stderr, "D3D12GetDebugInterface hr=0x%08x dbg=%p\n", unsigned(dbg_hr), (void*)dbg); ++ if (dbg != nullptr) { ++ dbg->EnableDebugLayer(); ++ fprintf(stderr, "EnableDebugLayer called\n"); ++ dbg->Release(); ++ } ++ } ++ + IDXGIFactory1* factory = nullptr; + check_hresult(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "CreateDXGIFactory1"); + { +diff --git a/src/ruis/render/directx/directx.cpp b/src/ruis/render/directx/directx.cpp +index a1eb137..04d282d 100644 +--- a/src/ruis/render/directx/directx.cpp ++++ b/src/ruis/render/directx/directx.cpp +@@ -21,12 +21,13 @@ along with this program. If not, see . + + #include "directx.hpp" + ++#include + #include + #include + + namespace ruis::render::directx { + +-std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) ++ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile) + { + ID3DBlob* blob = nullptr; + ID3DBlob* err_blob = nullptr; +@@ -45,20 +46,24 @@ std::vector compile_hlsl(const char* source, const char* entry_point, c + ); + if (FAILED(hr)) { + const auto err = err_blob != nullptr ? reinterpret_cast(err_blob->GetBufferPointer()) : ""; +- const auto msg = std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err; +- if (err_blob != nullptr) { +- err_blob->Release(); +- } +- throw std::runtime_error(msg); ++ if (err_blob != nullptr) { err_blob->Release(); } ++ if (blob != nullptr) { blob->Release(); } ++ throw std::runtime_error(std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err); + } ++ if (err_blob != nullptr) { err_blob->Release(); } ++ return blob; ++} + ++std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) ++{ ++ // compile the shader and copy the bytecode out of the returned blob ++ // (the caller keeps the blob alive for the lifetime of the pipeline; ++ // this public helper only needs the bytecode) ++ auto* blob = compile_hlsl_blob(source, entry_point, profile); + const auto size = blob->GetBufferSize(); + std::vector bytecode(size); + std::copy_n(static_cast(blob->GetBufferPointer()), size, bytecode.begin()); + blob->Release(); +- if (err_blob != nullptr) { +- err_blob->Release(); +- } + return bytecode; + } + +diff --git a/src/ruis/render/directx/directx.hpp b/src/ruis/render/directx/directx.hpp +index b260631..bcfe4f9 100644 +--- a/src/ruis/render/directx/directx.hpp ++++ b/src/ruis/render/directx/directx.hpp +@@ -51,9 +51,9 @@ inline void check_hresult(HRESULT hr, const char* what) + /** + * @brief The shared draw uniforms, bound as a root constant buffer view. + * +- * The matrix is stored in row-major order, which is the same order that +- * r4::matrix4 uses and the default packing order of a row-major float4x4 in +- * HLSL, so the matrix is copied directly from r4 without any transposition. ++ * The matrix is stored in column-major order, matching the default packing ++ * of a float4x4 in an HLSL cbuffer (r4 stores row-major), so the matrix is ++ * transposed on write. + */ + struct draw_uniforms { + float matrix[4][4]; +@@ -64,9 +64,11 @@ static_assert(sizeof(draw_uniforms) == 16 * sizeof(float) + 4 * sizeof(float)); + + inline void write_draw_uniforms(draw_uniforms* u, const r4::matrix4& m, const r4::vector4& color) + { ++ // r4 stores row-major, HLSL expects column-major: transpose first ++ auto t = m.tposed(); + for (uint32_t r = 0; r < 4; ++r) { + for (uint32_t c = 0; c < 4; ++c) { +- u->matrix[r][c] = m[r][c]; ++ u->matrix[r][c] = t[r][c]; + } + } + u->color[0] = color.x(); +@@ -148,10 +150,11 @@ inline DXGI_FORMAT to_dxgi_format_8bit(rasterimage::format f) + } + + // D3D12_RESOURCE_STATE_DEPTH_STENCIL was removed from the new SDK; +-// it is the same combination of states as before +-inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = // +- D3D12_RESOURCE_STATE_DEPTH_WRITE | // +- D3D12_RESOURCE_STATE_DEPTH_READ; ++// the depth-stencil resources of this renderer are only written through the ++// depth-stencil view, so they are created in the (single) depth-write state. ++// (Read-only states cannot be combined with write states, so DEPTH_WRITE | DEPTH_READ ++// would be invalid.) ++inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = D3D12_RESOURCE_STATE_DEPTH_WRITE; + + // D3D12_MAX_LOD was removed from the new SDK; + // it is the maximum mip level (2048) that indicates "all mip levels" +@@ -227,6 +230,20 @@ inline const D3D12_HEAP_PROPERTIES& upload_heap_properties() + return props; + } + ++// a readback heap (CPU-readable; the resource is created in the COPY_DEST ++// state, so it is only ever used as a copy destination) ++inline const D3D12_HEAP_PROPERTIES& readback_heap_properties() ++{ ++ static const auto props = D3D12_HEAP_PROPERTIES{ ++ .Type = D3D12_HEAP_TYPE_READBACK, ++ .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, ++ .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, ++ .CreationNodeMask = 0, ++ .VisibleNodeMask = 0 ++ }; ++ return props; ++} ++ + // a transition resource barrier (the new SDK has no D3D12_RESOURCE_BARRIER:: + // Transition() static helper) + inline D3D12_RESOURCE_BARRIER transition_barrier( +@@ -245,8 +262,20 @@ inline D3D12_RESOURCE_BARRIER transition_barrier( + return b; + } + +-// compile an HLSL shader source at runtime (via the D3D compiler); +-// the returned blob contains the DXIL bytecode ++/** ++ * @brief Compile one HLSL shader source at runtime (via the D3D compiler). ++ * @param source the HLSL source ++ * @param entry_point the entry point ++ * @param profile the target profile (e.g. "vs_5_1") ++ * @return the compiled blob; the caller owns it and must release it. ++ * @throws std::runtime_error carrying the compiler's error message on failure. ++ */ ++ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile); ++ ++/** ++ * @brief Compile one HLSL shader source at runtime and return the DXIL bytecode. ++ * @throws std::runtime_error carrying the compiler's error message on failure. ++ */ + std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile); + + } // namespace ruis::render::directx +diff --git a/src/ruis/render/directx/factory.cpp b/src/ruis/render/directx/factory.cpp +index 058af79..d9246dc 100644 +--- a/src/ruis/render/directx/factory.cpp ++++ b/src/ruis/render/directx/factory.cpp +@@ -77,15 +77,15 @@ factory::factory(const utki::shared_ref& surface) : // + + const auto static_sampler = D3D12_STATIC_SAMPLER_DESC{ + .Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR, +- .AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, +- .AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, +- .AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, ++ .AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER, ++ .AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER, ++ .AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER, + .MipLODBias = 0.0f, +- .MaxAnisotropy = 1, ++ .MaxAnisotropy = 0, + .ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER, + .BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, + .MinLOD = 0.0f, +- .MaxLOD = D3D12_MAX_LOD, ++ .MaxLOD = D3D12_FLOAT32_MAX, + .ShaderRegister = 0, + .RegisterSpace = 0, + .ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL +@@ -197,7 +197,7 @@ void factory::one_shot(std::function cmd) cons + const auto lists = std::array{{this->upload_command_list}}; + this->queue->ExecuteCommandLists(1, lists.data()); + +- this->upload_fence->Signal(++this->upload_fence_value); ++ check_hresult(this->queue->Signal(this->upload_fence, ++this->upload_fence_value), "queue Signal (upload fence)"); + check_hresult( + this->upload_fence->SetEventOnCompletion(this->upload_fence_value, this->upload_fence_event), + "fence SetEvent" +@@ -414,7 +414,7 @@ void factory::upload_texture(texture_2d* t) const + &upload_heap_properties(), + D3D12_HEAP_FLAG_NONE, + &desc, +- D3D12_RESOURCE_STATE_COMMON, ++ D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, + IID_PPV_ARGS(&upload) + ), +diff --git a/src/ruis/render/directx/index_buffer.cpp b/src/ruis/render/directx/index_buffer.cpp +index 9da1abe..0c2886b 100644 +--- a/src/ruis/render/directx/index_buffer.cpp ++++ b/src/ruis/render/directx/index_buffer.cpp +@@ -96,7 +96,7 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT + &upload_heap_properties(), + D3D12_HEAP_FLAG_NONE, + &desc, +- D3D12_RESOURCE_STATE_COMMON, ++ D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, + IID_PPV_ARGS(&upload) + ), +@@ -111,13 +111,13 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT + + dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { + const auto barrier1 = +- transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); ++ transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); + cmd->ResourceBarrier(1, &barrier1); + cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(byte_size)); + const auto barrier2 = transition_barrier( + this->resource, + D3D12_RESOURCE_STATE_COPY_DEST, +- D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER ++ D3D12_RESOURCE_STATE_INDEX_BUFFER + ); + cmd->ResourceBarrier(1, &barrier2); + }); +diff --git a/src/ruis/render/directx/sdk_prelude.hpp b/src/ruis/render/directx/sdk_prelude.hpp +index 9a94193..5b6f184 100644 +--- a/src/ruis/render/directx/sdk_prelude.hpp ++++ b/src/ruis/render/directx/sdk_prelude.hpp +@@ -43,6 +43,7 @@ along with this program. If not, see . + #endif + + #include ++#include + #include + #include + +diff --git a/src/ruis/render/directx/shaders/shader_common.cpp b/src/ruis/render/directx/shaders/shader_common.cpp +index 9503a3b..0b6f749 100644 +--- a/src/ruis/render/directx/shaders/shader_common.cpp ++++ b/src/ruis/render/directx/shaders/shader_common.cpp +@@ -24,10 +24,15 @@ along with this program. If not, see . + #include + + #include "../context.hpp" ++ ++#include + #include "../texture_2d.hpp" + + namespace ruis::render::directx { + ++static void debug_print(const char* msg) { std::fprintf(stderr, "%s\n", msg); } ++ ++ + void directx_shader_render( + shader_kind kind, + const char* vertex_hlsl, +@@ -46,13 +51,16 @@ void directx_shader_render( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "assert(dynamic_cast) done above") + static_cast(cur); + ++ debug_print("draw: pre-ensure_frame_began"); + // make sure the frame is begun (the back buffer is acquired and the command + // list is reset) + ctx.ensure_frame_began(); ++ debug_print("draw: post-ensure_frame_began"); + + // skip drawing if the viewport is zero-sized (e.g. resource loader context) + { + const auto& vp = ctx.get_viewport(); ++ fprintf(stderr, "draw: viewport = (%u %u)(%u %u)\n", vp.p.x(), vp.p.y(), vp.d.x(), vp.d.y()); + if (vp.d.x() == 0 || vp.d.y() == 0) { + return; + } +@@ -63,6 +71,7 @@ void directx_shader_render( + write_draw_uniforms(&u, m, color); + + // get or create the pipeline state object for the current state ++ debug_print("draw: pre-pipeline"); + const auto pso = ctx.get_or_create_pipeline( + kind, + shader_has_texture(kind), +@@ -71,7 +80,9 @@ void directx_shader_render( + fragment_hlsl + ); + ++ debug_print("draw: pre-draw_indexed"); + ctx.draw_indexed(pso, va, texture, u); ++ debug_print("draw: post-draw_indexed"); + } + + } // namespace ruis::render::directx +diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp +index 0d95cd6..2ae7ab0 100644 +--- a/src/ruis/render/directx/shaders/shader_common.hpp ++++ b/src/ruis/render/directx/shaders/shader_common.hpp +@@ -66,6 +66,18 @@ constexpr DXGI_FORMAT a1_format(shader_kind k) + } + } + ++// the semantic name of the a1 attribute (used in the vertex input layout) ++constexpr const char* a1_semantic(shader_kind k) ++{ ++ switch (k) { ++ case shader_kind::pos_clr: ++ return "COLOR"; ++ default: ++ // the textured shaders and the luminance shader declare it as TEXCOORD ++ return "TEXCOORD"; ++ } ++} ++ + // map the VAO's rendering mode to a DirectX primitive topology + inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) + { +diff --git a/src/ruis/render/directx/shaders/shader_src.hpp b/src/ruis/render/directx/shaders/shader_src.hpp +index ea38d7f..0a556cf 100644 +--- a/src/ruis/render/directx/shaders/shader_src.hpp ++++ b/src/ruis/render/directx/shaders/shader_src.hpp +@@ -22,7 +22,7 @@ along with this program. If not, see . + /* + * The HLSL sources of the renderer's shaders. + * They are compiled to DXIL at runtime with the D3D compiler (see +- * directx::compile_hlsl()). ++ * directx::compile_hlsl_blob(), which is what the renderer uses). + * + * The per-draw uniforms (the transformation matrix and the color) are passed + * as root 32-bit constants in register b0: first a float4x4 matrix (16 floats), +@@ -45,18 +45,24 @@ namespace ruis::render::directx { + // ============== color ========= + + static const char* hlsl_shader_color_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + float4 main(float4 pos : POSITION) : SV_POSITION + { +- return draw_matrix * pos; ++ return mul(draw_matrix, pos); + } + )HLSL"; + + static const char* hlsl_shader_color_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + float4 main() : SV_Target + { +@@ -68,8 +74,11 @@ float4 main() : SV_Target + // ============== pos_clr ======= + + static const char* hlsl_shader_pos_clr_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + struct VS_OUT + { +@@ -80,14 +89,19 @@ struct VS_OUT + VS_OUT main(float4 pos : POSITION, float4 col : COLOR) + { + VS_OUT o; +- o.pos = draw_matrix * pos; ++ o.pos = mul(draw_matrix, pos); + o.col = col; + return o; + } + )HLSL"; + + static const char* hlsl_shader_pos_clr_fragment = R"HLSL( +-float4 main(float4 col : COLOR) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float4 col : COLOR) : SV_Target + { + return col; + } +@@ -97,8 +111,11 @@ float4 main(float4 col : COLOR) : SV_Target + // ============== pos_tex ======= + + static const char* hlsl_shader_pos_tex_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + struct VS_OUT + { +@@ -109,20 +126,28 @@ struct VS_OUT + VS_OUT main(float4 pos : POSITION, float2 uv : TEXCOORD) + { + VS_OUT o; +- o.pos = draw_matrix * pos; ++ o.pos = mul(draw_matrix, pos); + o.uv = uv; + return o; + } + )HLSL"; + + static const char* hlsl_shader_pos_tex_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + Texture2D tex0 : register(t0); + SamplerState samp0 : register(s0); + +-float4 main(float2 uv : TEXCOORD) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target + { + return tex0.Sample(samp0, uv) * draw_color; + } +@@ -140,13 +165,21 @@ static const char* hlsl_shader_color_pos_tex_fragment = hlsl_shader_pos_tex_frag + static const char* hlsl_shader_color_pos_tex_alpha_vertex = hlsl_shader_pos_tex_vertex; + + static const char* hlsl_shader_color_pos_tex_alpha_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + Texture2D tex0 : register(t0); + SamplerState samp0 : register(s0); + +-float4 main(float2 uv : TEXCOORD) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target + { + return float4(draw_color.xyz, draw_color.w * tex0.Sample(samp0, uv).r); + } +@@ -156,8 +189,11 @@ float4 main(float2 uv : TEXCOORD) : SV_Target + // ============== color_pos_lum = + + static const char* hlsl_shader_color_pos_lum_vertex = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + + struct VS_OUT + { +@@ -168,17 +204,25 @@ struct VS_OUT + VS_OUT main(float4 pos : POSITION, float lum : TEXCOORD) + { + VS_OUT o; +- o.pos = draw_matrix * pos; ++ o.pos = mul(draw_matrix, pos); + o.lum = lum; + return o; + } + )HLSL"; + + static const char* hlsl_shader_color_pos_lum_fragment = R"HLSL( +-RootConstants[1] draw_matrix : register(b0); +-RootConstants[1] draw_color : register(b16); ++cbuffer DrawConstants : register(b0) ++{ ++ float4x4 draw_matrix; ++ float4 draw_color; ++}; + +-float4 main(float lum : TEXCOORD) : SV_Target ++// NOTE: the VS outputs SV_POSITION at hardware register 0 and any ++// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader ++// must declare SV_POSITION as an (unused) input so its arbitrary semantic ++// lines up at the same hardware register as the VS output; otherwise pipeline ++// creation fails with E_INVALIDARG ("mismatched hardware registers"). ++float4 main(float4 pos : SV_POSITION, float lum : TEXCOORD) : SV_Target + { + return float4(draw_color.xyz, draw_color.w * lum); + } +diff --git a/src/ruis/render/directx/texture_2d.cpp b/src/ruis/render/directx/texture_2d.cpp +index 4b9cfa9..d1b0857 100644 +--- a/src/ruis/render/directx/texture_2d.cpp ++++ b/src/ruis/render/directx/texture_2d.cpp +@@ -82,10 +82,10 @@ texture_2d::texture_2d( + .Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + .NodeMask = 0 + }; +- check_hresult( +- device->CreateDescriptorHeap(&srv_desc, IID_PPV_ARGS(&this->srv_heap)), +- "CreateDescriptorHeap (srv)" +- ); ++ { ++ const auto hr = device->CreateDescriptorHeap(&srv_desc, IID_PPV_ARGS(&this->srv_heap)); ++ check_hresult(hr, "CreateDescriptorHeap (srv)"); ++ } + + const auto rtv_desc = D3D12_DESCRIPTOR_HEAP_DESC{ + .Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV, +@@ -156,7 +156,7 @@ texture_2d::texture_2d( + const auto barrier2 = transition_barrier( + this->resource, + D3D12_RESOURCE_STATE_RENDER_TARGET, +- D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ++ D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + ); + cmd->ResourceBarrier(1, &barrier2); + }); +@@ -196,7 +196,7 @@ void texture_2d::record_upload_commands(ID3D12GraphicsCommandList* cmd, ID3D12Re + // is needed before the copy; the upload buffer needs to transition to + // COPY_SOURCE + const auto barrier1 = +- transition_barrier(upload_buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); ++ transition_barrier(upload_buffer, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); + cmd->ResourceBarrier(1, &barrier1); + + // the new SDK has no CopyBufferToTexture(); use CopyTextureRegion with a +@@ -227,13 +227,15 @@ void texture_2d::record_upload_commands(ID3D12GraphicsCommandList* cmd, ID3D12Re + cmd->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + +- // the texture is used both as a render target (frame buffers) and as a +- // sampled texture, so transition to both states at once +- const auto barrier2 = transition_barrier( +- this->resource, +- D3D12_RESOURCE_STATE_COPY_DEST, +- D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE +- ); ++ // the texture is used as a sampled texture; the render-target state is ++ // applied when the resource is bound as a render target (frame buffers), ++ // since read-only and write states cannot be combined in one state mask ++ const auto barrier2 = ++ transition_barrier( ++ this->resource, ++ D3D12_RESOURCE_STATE_COPY_DEST, ++ D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ++ ); + cmd->ResourceBarrier(1, &barrier2); + } + +diff --git a/src/ruis/render/directx/vertex_buffer.cpp b/src/ruis/render/directx/vertex_buffer.cpp +index 0fece43..6a4988e 100644 +--- a/src/ruis/render/directx/vertex_buffer.cpp ++++ b/src/ruis/render/directx/vertex_buffer.cpp +@@ -57,17 +57,15 @@ vertex_buffer::vertex_buffer( + "CreateCommittedResource (vertex buffer, size=%u)", + UINT(this->byte_size) + ); +- check_hresult( +- device->CreateCommittedResource( +- &default_heap_properties(), +- D3D12_HEAP_FLAG_NONE, +- &desc, +- D3D12_RESOURCE_STATE_COPY_DEST, +- nullptr, +- IID_PPV_ARGS(&this->resource) +- ), +- vbuf_msg ++ const auto hr = device->CreateCommittedResource( ++ &default_heap_properties(), ++ D3D12_HEAP_FLAG_NONE, ++ &desc, ++ D3D12_RESOURCE_STATE_COPY_DEST, ++ nullptr, ++ IID_PPV_ARGS(&this->resource) + ); ++ check_hresult(hr, vbuf_msg); + this->gpu_va = this->resource->GetGPUVirtualAddress(); + } + +@@ -81,7 +79,7 @@ vertex_buffer::vertex_buffer( + &upload_heap_properties(), + D3D12_HEAP_FLAG_NONE, + &desc, +- D3D12_RESOURCE_STATE_COMMON, ++ D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, + IID_PPV_ARGS(&upload) + ), +@@ -96,7 +94,7 @@ vertex_buffer::vertex_buffer( + + dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { + const auto barrier1 = +- transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); ++ transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); + cmd->ResourceBarrier(1, &barrier1); + cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(this->byte_size)); + const auto barrier2 = transition_barrier( diff --git a/.wip_backup.stat b/.wip_backup.stat new file mode 100644 index 0000000..cf44db5 --- /dev/null +++ b/.wip_backup.stat @@ -0,0 +1,14 @@ + src/ruis/render/directx/context.cpp | 191 +++++++++++++++------- + src/ruis/render/directx/context.hpp | 9 +- + src/ruis/render/directx/device.cpp | 14 ++ + src/ruis/render/directx/directx.cpp | 23 ++- + src/ruis/render/directx/directx.hpp | 49 ++++-- + src/ruis/render/directx/factory.cpp | 14 +- + src/ruis/render/directx/index_buffer.cpp | 6 +- + src/ruis/render/directx/sdk_prelude.hpp | 1 + + src/ruis/render/directx/shaders/shader_common.cpp | 11 ++ + src/ruis/render/directx/shaders/shader_common.hpp | 12 ++ + src/ruis/render/directx/shaders/shader_src.hpp | 94 ++++++++--- + src/ruis/render/directx/texture_2d.cpp | 28 ++-- + src/ruis/render/directx/vertex_buffer.cpp | 22 ++- + 13 files changed, 335 insertions(+), 139 deletions(-) diff --git a/check_rdef.js b/check_rdef.js new file mode 100644 index 0000000..181b389 --- /dev/null +++ b/check_rdef.js @@ -0,0 +1,46 @@ +const fs = require('fs'); +const buf = fs.readFileSync(process.argv[2]); +const numChunks = buf.readUInt32LE(28); +for (let i = 0; i < numChunks; i++) { + const off = buf.readUInt32LE(32 + i * 4); + const fourcc = buf.toString('ascii', off, off + 4); + const partLength = buf.readUInt32LE(off + 4); + if (fourcc !== 'RDEF') continue; + const contents = buf.slice(off + 8, off + 8 + partLength); + // cbuffers: CountOffset (offset + count) + const cbufferOffset = contents.readUInt32LE(0); + const cbufferCount = contents.readUInt32LE(4); + const resourceOffset = contents.readUInt32LE(8); + const resourceCount = contents.readUInt32LE(12); + const targetVersion = contents.readUInt16LE(16); + const targetShaderStage = contents.readUInt16LE(18); + const flags = contents.readUInt32LE(20); + console.log(`RDEF: cbufferOffset=${cbufferOffset} cbufferCount=${cbufferCount} resourceOffset=${resourceOffset} resourceCount=${resourceCount} targetVersion=0x${targetVersion.toString(16)} targetShaderStage=0x${targetShaderStage.toString(16)} flags=0x${flags.toString(16)}`); + // cbuffers (24 bytes each): + for (let c = 0; c < cbufferCount; c++) { + const cbStart = cbufferOffset + c * 24; + const nameOffset = contents.readUInt32LE(cbStart); + const memberCount = contents.readUInt32LE(cbStart + 4); + const memberOffset = contents.readUInt32LE(cbStart + 8); + const sizeBytes = contents.readUInt32LE(cbStart + 12); + const alignBytes = contents.readUInt32LE(cbStart + 16); + const name = contents.toString('ascii', nameOffset, nameOffset + 64).split('\0')[0]; + console.log(` cbuffer[${c}] name='${name}' memberCount=${memberCount} memberOffset=${memberOffset} sizeBytes=${sizeBytes} alignBytes=${alignBytes}`); + } + // resources: + for (let r = 0; r < resourceCount; r++) { + const rStart = resourceOffset + r * 40; + const nameOffset = contents.readUInt32LE(rStart); + const type = contents.readUInt32LE(rStart + 4); + const retType = contents.readUInt32LE(rStart + 8); + const dimension = contents.readUInt32LE(rStart + 12); + const sampleCount = contents.readInt32LE(rStart + 16); + const bindPoint = contents.readUInt32LE(rStart + 20); + const bindCount = contents.readUInt32LE(rStart + 24); + const rFlags = contents.readUInt32LE(rStart + 28); + const space = contents.readUInt32LE(rStart + 32); + const id = contents.readUInt32LE(rStart + 36); + const name = contents.toString('ascii', nameOffset, nameOffset + 64).split('\0')[0]; + console.log(` resource[${r}] name='${name}' type=${type} retType=${retType} dimension=${dimension} sampleCount=${sampleCount} bindPoint=${bindPoint} bindCount=${bindCount} flags=0x${rFlags.toString(16)} space=${space} id=${id}`); + } +} diff --git a/dxbc_dump.js b/dxbc_dump.js new file mode 100644 index 0000000..5aa0345 --- /dev/null +++ b/dxbc_dump.js @@ -0,0 +1,41 @@ +const fs = require('fs'); +const buf = fs.readFileSync(process.argv[2]); +const numChunks = buf.readUInt32LE(28); +const chunkOffsets = []; +for (let i = 0; i < numChunks; i++) chunkOffsets.push(buf.readUInt32LE(32 + i * 4)); +const SVNAME_MAP = { + 0: 'UNDEFINED', 1: 'POSITION', 2: 'CLIP_DISTANCE', 3: 'CULL_DISTANCE', + 4: 'RENDER_TARGET_ARRAY_INDEX', 5: 'VIEWPORT_ARRAY_INDEX', 6: 'VERTEX_ID', + 7: 'PRIMITIVE_ID', 8: 'INSTANCE_ID', 9: 'IS_FRONT_FACE', 10: 'SAMPLE_INDEX', + 64: 'TARGET', 65: 'DEPTH', 66: 'COVERAGE', 67: 'DEPTH_GREATER_EQUAL', 68: 'DEPTH_LESS_EQUAL', + 69: 'STENCIL_REF', 70: 'INNER_COVERAGE' +}; +for (let i = 0; i < numChunks; i++) { + const off = chunkOffsets[i]; + const chFourcc = buf.toString('ascii', off, off + 4); + const partLength = buf.readUInt32LE(off + 4); + console.log(`\nchunk ${chFourcc} (partLength=${partLength})`); + if (!/^(ISGN|OSGN|ISG1|OSG1|PSG1)$/.test(chFourcc)) continue; + const contentsOffset = off + 8; + const contents = buf.slice(contentsOffset, contentsOffset + partLength); + const numElems = contents.readUInt32LE(0); + const unknown = contents.readUInt32LE(4); + console.log(` numElems=${numElems} unknown=${unknown}`); + const isV1 = chFourcc.endsWith('1'); + const elemSize = isV1 ? 32 : 20; + // ISGN/OSGN: elements are packed at offset 8, 20 bytes each + for (let e = 0; e < numElems; e++) { + const elemStart = 8 + e * elemSize; + const stream = isV1 ? contents.readUInt32LE(elemStart) : null; + const base = isV1 ? elemStart + 4 : elemStart; + const nameOffset = contents.readUInt32LE(base + 0); + const semanticIdx = contents.readUInt32LE(base + 4); + const systemType = contents.readUInt32LE(base + 8); + const componentType = contents.readUInt32LE(base + 12); + const registerNum = contents.readUInt32LE(base + 16); + const mask = contents.readUInt8(base + 20); + const rwMask = contents.readUInt8(base + 21); + const name = contents.toString('ascii', nameOffset, nameOffset + 64).split('\0')[0]; + console.log(` elem[${e}] name='${name}' semanticIdx=${semanticIdx} systemType=${systemType} (${SVNAME_MAP[systemType] || '?'}) componentType=${componentType} registerNum=${registerNum} mask=0x${mask.toString(16)} rwMask=0x${rwMask.toString(16)} stream=${stream}`); + } +} diff --git a/dxbc_parse.js b/dxbc_parse.js new file mode 100644 index 0000000..5bd7178 --- /dev/null +++ b/dxbc_parse.js @@ -0,0 +1,38 @@ +const fs = require('fs'); +const path = process.argv[2]; +const buf = fs.readFileSync(path); +let off = 0; +const sig = buf.toString('ascii', off, off + 4); +console.log('signature:', sig); +off = 4; +const hdrSize = buf.readUInt32LE(off); +off = 8; // skip len + version fields (this is just the header start) +// Actually: after 4-byte signature: uint32 version, uint32 headerLength? no -- +// format: "DXBC" (4) then uint32 headerSize? Let's just scan for chunks. +console.log('trying to locate chunks at offset 8...'); +// chunk format: uint32 FourCC, uint32 size, uint32 offset (relative), then data +let p = 8; +const fourccs = { + 'ISGN': 'input signature (legacy)', + 'OSGN': 'output signature (legacy)', + 'ISG1': 'input signature v1', + 'OSG1': 'output signature v1', + 'RDEF': 'resource descriptor info', + 'TEMD': 'temp descriptor', +}; +const seen = new Set(); +while (p + 12 <= buf.length) { + const fourcc = buf.toString('ascii', p, p + 4); + if (!/^[A-Z0-9_]{4}$/.test(fourcc)) break; + const size = buf.readUInt32LE(p + 4); + const fileOffset = buf.readUInt32LE(p + 8); + console.log(`chunk ${fourcc} (${fourccs[fourcc] || '?'}) size=${size} fileOffset=${fileOffset} seen=${seen.has(fourcc)}`); + // try to print the input/output signatures + if (fourcc === 'ISGN' || fourcc === 'OSGN' || fourcc === 'ISG1' || fourcc === 'OSG1') { + const chunkData = buf.slice(8 + fileOffset, 8 + fileOffset + size); + console.log(' raw first 80 bytes:', [...chunkData.slice(0, 80)].map(b => b.toString(16).padStart(2, '0')).join(' ')); + } + p += 12; + if (seen.has(fourcc) && fourcc !== 'ISGN' && fourcc !== 'OSGN') break; + seen.add(fourcc); +} diff --git a/fix_probe2.js b/fix_probe2.js new file mode 100644 index 0000000..55cf505 --- /dev/null +++ b/fix_probe2.js @@ -0,0 +1,9 @@ +const fs = require('fs'); +const p = 'src/ruis/render/directx/context.cpp'; +let s = fs.readFileSync(p, 'utf8'); +const old = `\tfprintf(stderr, "get_or_create_pipeline: building pipeline\n");`; +const newLine = `\tfprintf(stderr, "get_or_create_pipeline: building pipeline shader_kind=%d textured=%d a1=%d topology=%s\n", (int)kind, (int)textured, (int)shader_has_a1(kind), to_topology_name(topology));`; +if (!s.includes(old)) { console.error('not found'); process.exit(1); } +s = s.replace(old, newLine); +fs.writeFileSync(p, s); +console.log('OK'); diff --git a/force_color_shader.js b/force_color_shader.js new file mode 100644 index 0000000..d687fb4 --- /dev/null +++ b/force_color_shader.js @@ -0,0 +1,10 @@ +const fs = require('fs'); +const p = 'src/ruis/render/directx/context.cpp'; +let s = fs.readFileSync(p, 'utf8'); +// force the first pipeline to use the color (position-only) shaders: +const marker = 'const auto pso = this->build_pipeline(key, shader_has_a1(kind), vertex_hlsl, fragment_hlsl);'; +if (!s.includes(marker)) { console.error('not found'); process.exit(1); } +s = s.replace(marker, `// TEMPORARY: force the position-only color shaders + const auto pso = this->build_pipeline(key, false, hlsl_shader_color_vertex, hlsl_shader_color_fragment);`); +fs.writeFileSync(p, s); +console.log('OK'); diff --git a/minimal_desc.js b/minimal_desc.js new file mode 100644 index 0000000..49fb6b1 --- /dev/null +++ b/minimal_desc.js @@ -0,0 +1,25 @@ +const fs = require('fs'); +const p = 'src/ruis/render/directx/context.cpp'; +let s = fs.readFileSync(p, 'utf8'); +const start = s.indexOf('\tconst auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{'); +const end = s.indexOf('\t};\n\n\tfprintf(stderr, "build_pipeline: pre-create-call'); +if (start < 0 || end < 0) { console.error('markers not found'); process.exit(1); } +const minimal = `\t// TEMPORARY MINIMAL DESC (vkd3d-style) +\tD3D12_GRAPHICS_PIPELINE_STATE_DESC pipeline_desc{}; +\tpipeline_desc.pRootSignature = this->root_signature; +\tpipeline_desc.VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}; +\tpipeline_desc.PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}; +\tpipeline_desc.StreamOutput.RasterizedStream = 0; +\tpipeline_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; +\tpipeline_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; +\tpipeline_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; +\tpipeline_desc.SampleMask = 0xFFFFFFFF; +\tpipeline_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; +\tpipeline_desc.NumRenderTargets = 1; +\tpipeline_desc.RTVFormats[0] = static_cast(key.rtv_format); +\tpipeline_desc.SampleDesc.Count = 1; +\tpipeline_desc.InputLayout = input_layout; +`; +s = s.slice(0, start) + minimal + s.slice(end + 4); +fs.writeFileSync(p, s); +console.log('OK'); diff --git a/raw_chunk.js b/raw_chunk.js new file mode 100644 index 0000000..d5f0238 --- /dev/null +++ b/raw_chunk.js @@ -0,0 +1,15 @@ +const fs = require('fs'); +const buf = fs.readFileSync(process.argv[2]); +const numChunks = buf.readUInt32LE(28); +const chunkOffsets = []; +for (let i = 0; i < numChunks; i++) chunkOffsets.push(buf.readUInt32LE(32 + i * 4)); +const chFourcc = buf.toString('ascii', chunkOffsets[1] || 0, chunkOffsets[1] + 4); // ISGN +// let's just dump all chunks +for (let i = 0; i < numChunks; i++) { + const off = chunkOffsets[i]; + const fourcc = buf.toString('ascii', off, off + 4); + const partLength = buf.readUInt32LE(off + 4); + const contents = buf.slice(off + 8, off + 8 + partLength); + console.log(`\n=== chunk ${fourcc} partLength=${partLength} at offset ${off}`); + console.log(' raw:', [...contents].map(b => b.toString(16).padStart(2, '0')).join(' ')); +} diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp index 4e687fc..fd9a2ed 100644 --- a/src/ruis/render/directx/context.cpp +++ b/src/ruis/render/directx/context.cpp @@ -737,6 +737,10 @@ ID3D12PipelineState* context::build_pipeline( return pso; } +// NOTE: D3D12 did not support triangle fans for a long time, but the later +// DirectX versions re-introduced it. So the support cannot be assumed from the +// headers or the SDK version: it must be checked on the device at runtime via +// CheckFeatureSupport (D3D12_FEATURE_DATA_D3D12_OPTIONS15 / TriangleFanSupported). bool context::triangle_fan_supported() const { if (!this->triangle_fan_supported_checked) { @@ -749,7 +753,8 @@ bool context::triangle_fan_supported() const ); this->triangle_fan_supported_cache = SUCCEEDED(hr) && options.TriangleFanSupported != FALSE; #else - // this toolchain does not declare OPTIONS15: conservative -> no triangle fan + // this toolchain does not declare OPTIONS15 at all: treat triangle fan as + // unsupported (the check is conservative) this->triangle_fan_supported_cache = false; #endif this->triangle_fan_supported_checked = true; @@ -757,6 +762,8 @@ bool context::triangle_fan_supported() const return this->triangle_fan_supported_cache; } +// runtime gate for the triangle fan mode: if the device reports that triangle fan is +// not supported, throw instead of failing silently deeper in the render pipeline void context::check_topology_supported(ruis::render::vertex_array::mode m) const { if (m == ruis::render::vertex_array::mode::triangle_fan && !this->triangle_fan_supported()) { diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp index e1487ab..cb652a1 100644 --- a/src/ruis/render/directx/context.hpp +++ b/src/ruis/render/directx/context.hpp @@ -163,7 +163,9 @@ class context : public ruis::render::context const char* fragment_hlsl ); - // whether the device supports the triangle fan primitive topology (queried once) + // whether the device supports the triangle fan primitive topology (queried once, lazily). + // NOTE: triangle fan was not supported by earlier D3D12, but later DirectX versions + // re-introduced it, so support must be checked on the device, not assumed. bool triangle_fan_supported() const; // throw std::runtime_error if the requested topology is not supported diff --git a/src/ruis/render/directx/shaders/shader_common.cpp b/src/ruis/render/directx/shaders/shader_common.cpp index 0598521..fcb7abb 100644 --- a/src/ruis/render/directx/shaders/shader_common.cpp +++ b/src/ruis/render/directx/shaders/shader_common.cpp @@ -58,7 +58,8 @@ void directx_shader_render( } } - // the requested topology must be supported by the device (e.g. triangle fan) + // NOTE: triangle fan was unsupported by earlier D3D12, but later DirectX versions + // re-introduced it. Do not assume support: check the device and throw if unsupported. ctx.check_topology_supported(va.rendering_mode); // the per-draw uniforms (root constants) diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp index 0eade70..7fe03b3 100644 --- a/src/ruis/render/directx/shaders/shader_common.hpp +++ b/src/ruis/render/directx/shaders/shader_common.hpp @@ -89,8 +89,10 @@ inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) #if defined(D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN) return D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN; #else - // this toolchain does not declare triangle fan (e.g. mingw64): - // treat it as unsupported + // NOTE: earlier D3D12 did not support triangle fans, but later + // DirectX versions re-introduced it. This toolchain does not even + // declare the topology constant (e.g. mingw64 headers), so it + // cannot be mapped: treat it as unsupported. throw std::runtime_error("Unsupported: triangle_fan primitive topology"); #endif case ruis::render::vertex_array::mode::line_loop: diff --git a/strings_dump.js b/strings_dump.js new file mode 100644 index 0000000..59888be --- /dev/null +++ b/strings_dump.js @@ -0,0 +1,24 @@ +const fs = require('fs'); +const buf = fs.readFileSync(process.argv[2]); +const numChunks = buf.readUInt32LE(28); +for (let i = 0; i < numChunks; i++) { + const off = buf.readUInt32LE(32 + i * 4); + const fourcc = buf.toString('ascii', off, off + 4); + const partLength = buf.readUInt32LE(off + 4); + const contents = buf.slice(off + 8, off + 8 + partLength); + if (fourcc !== 'ISGN' && fourcc !== 'OSGN' && fourcc !== 'ISG1' && fourcc !== 'OSG1') continue; + const numElems = contents.readUInt32LE(0); + console.log(`\n=== ${fourcc}: numElems=${numElems}, contents length=${contents.length}`); + for (let e = 0; e < numElems; e++) { + const elemStart = 8 + e * 24; + const nameOffset = contents.readUInt32LE(elemStart); + const semanticIdx = contents.readUInt32LE(elemStart + 4); + const systemType = contents.readUInt32LE(elemStart + 8); + const componentType = contents.readUInt32LE(elemStart + 12); + const registerNum = contents.readUInt32LE(elemStart + 16); + const mask = contents.readUInt8(elemStart + 20); + const rwMask = contents.readUInt8(elemStart + 21); + const name = contents.toString('ascii', nameOffset, contents.length).split('\0')[0]; + console.log(` elem[${e}] name='${name}' semanticIdx=${semanticIdx} systemType=${systemType} componentType=${componentType} registerNum=${registerNum} mask=0x${mask.toString(16)} rwMask=0x${rwMask.toString(16)}`); + } +} From e04c038c4309344ddf1507abe6ba43e20d02b352 Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 20:23:05 +0200 Subject: [PATCH 7/8] remove untracked debug-scratch files accidentally committed in d600c9d --- .trio_changes.patch | 579 ----------------------- .wip_backup.patch | 1044 ----------------------------------------- .wip_backup.stat | 14 - check_rdef.js | 46 -- dxbc_dump.js | 41 -- dxbc_parse.js | 38 -- fix_probe2.js | 9 - force_color_shader.js | 10 - minimal_desc.js | 25 - raw_chunk.js | 15 - strings_dump.js | 24 - 11 files changed, 1845 deletions(-) delete mode 100644 .trio_changes.patch delete mode 100644 .wip_backup.patch delete mode 100644 .wip_backup.stat delete mode 100644 check_rdef.js delete mode 100644 dxbc_dump.js delete mode 100644 dxbc_parse.js delete mode 100644 fix_probe2.js delete mode 100644 force_color_shader.js delete mode 100644 minimal_desc.js delete mode 100644 raw_chunk.js delete mode 100644 strings_dump.js diff --git a/.trio_changes.patch b/.trio_changes.patch deleted file mode 100644 index d650d28..0000000 --- a/.trio_changes.patch +++ /dev/null @@ -1,579 +0,0 @@ -diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp -index c971779..33f8061 100644 ---- a/src/ruis/render/directx/context.cpp -+++ b/src/ruis/render/directx/context.cpp -@@ -25,6 +25,7 @@ along with this program. If not, see . - #include - #include - #include -+#include - - #include - -@@ -59,10 +60,16 @@ context::context( - // maps the framework's normalized viewport coordinates (x right, y down, - // zero at the top-left, right/bottom edges at (1, 1)) to the DirectX NDC. - // -- // In the DirectX NDC -1 -1 corresponds to the top-left corner, 1 1 to the -- // bottom-right corner, and z points away from the viewer (same orientation -- // as the framework, so no axis flip is needed). -- m.set_identity().translate(-1, -1).scale(2, 2); -+ // DirectX identity matrix: -+ // viewport edges: left = -1, right = 1, top = 1, bottom = -1 -+ // z-axis away from the viewer -+ m.set_identity() -+ // x-axis right, y-axis down, z-axis away -+ .scale(1, -1, 1) -+ // viewport edges: left = 0, top = 0 -+ .translate(-1, -1) -+ // viewport edges: right = 1, bottom = 1 -+ .scale(2, 2); - return parameters{m}; - }() - ), -@@ -590,6 +597,16 @@ void context::enable_depth(bool enable) - this->depth_enabled = enable; - } - -+DXGI_FORMAT context::current_rtv_format() const -+{ -+ if (this->current_fb != nullptr && this->current_fb->color != nullptr) { -+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") -+ const auto& tex = static_cast(*this->current_fb->color); -+ return to_dxgi_format_8bit(tex.ri_format); -+ } -+ return DXGI_FORMAT_B8G8R8A8_UNORM; -+} -+ - uint32_t context::get_blend_key() const - { - // pack the blend state into a key for the pipeline cache: -@@ -607,27 +624,8 @@ uint32_t context::get_blend_key() const - - ID3DBlob* context::compile_shader(const char* hlsl, const char* entry_point, const char* profile) - { -- ID3DBlob* blob = nullptr; -- ID3DBlob* err_blob = nullptr; -- check_hresult( -- D3DCompile( -- hlsl, -- strlen(hlsl), -- "ruis-render-directx.hlsl", -- nullptr, -- nullptr, -- entry_point, -- profile, -- 0, -- 0, -- &blob, -- &err_blob -- ), -- "D3DCompile" -- ); -- if (err_blob != nullptr) { -- err_blob->Release(); -- } -+ // the shared helper throws with the compiler's error message on failure -+ auto* blob = compile_hlsl_blob(hlsl, entry_point, profile); - this->shader_blobs.emplace_back(blob); - return blob; - } -@@ -640,12 +638,13 @@ ID3D12PipelineState* context::build_pipeline( - ) - { - // compile the shaders to DXIL (the blobs are kept alive in shader_blobs) -- auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_6_0"); -- auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_6_0"); -+ auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_5_1"); -+ auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_5_1"); - - // ---- the vertex input layout ---- -- // all vertices are stored as float4 (4 floats) in the vertex buffer; the a1 -- // attribute (if present) is the tail of the float4 (its format is shader-specific) -+ // each buffer of the vertex array holds float4 (4 floats) vertices with the -+ // same stride; the a1 attribute (if present) reads the first few floats of the -+ // second buffer (its format is shader-specific) - const auto a1 = shader_kind(key.shader_kind); - auto input_layout_elements = std::vector{ - {.SemanticName = "POSITION", -@@ -658,11 +657,11 @@ ID3D12PipelineState* context::build_pipeline( - if (has_a1) { - input_layout_elements.push_back( - D3D12_INPUT_ELEMENT_DESC{ -- .SemanticName = "TEXCOORD", -+ .SemanticName = a1_semantic(a1), - .SemanticIndex = 0, - .Format = a1_format(a1), - .InputSlot = 1, -- .AlignedByteOffset = UINT(vertex_stride_bytes), -+ .AlignedByteOffset = 0, - .InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA - } - ); -@@ -703,14 +702,14 @@ ID3D12PipelineState* context::build_pipeline( - - const auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{ - .pRootSignature = this->root_signature, -- .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), vs_blob->GetBufferSize()}, -- .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), fs_blob->GetBufferSize()}, -+ .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}, -+ .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}, - .BlendState = blend, - .SampleMask = 0xFFFFFFFF, - .RasterizerState = - D3D12_RASTERIZER_DESC{ - .FillMode = D3D12_FILL_MODE_SOLID, -- .CullMode = D3D12_CULL_MODE_NONE, -+ .CullMode = D3D12_CULL_MODE_BACK, - .FrontCounterClockwise = FALSE, - .DepthBias = 0, - .DepthBiasClamp = 0.0f, -@@ -726,17 +725,15 @@ ID3D12PipelineState* context::build_pipeline( - .IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, - .PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - .NumRenderTargets = 1, -- .RTVFormats = {DXGI_FORMAT_UNKNOWN}, // the actual format depends on the render target -- .DSVFormat = DXGI_FORMAT_UNKNOWN, // the actual format depends on the depth texture -+ .RTVFormats = {static_cast(key.rtv_format)}, -+ .DSVFormat = use_depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_UNKNOWN, - .SampleDesc = {.Count = 1, .Quality = 0}, - .NodeMask = 0 - }; - - ID3D12PipelineState* pso = nullptr; -- check_hresult( -- this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)), -- "CreateGraphicsPipelineState" -- ); -+ const auto hr = this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)); -+ check_hresult(hr, "CreateGraphicsPipelineState"); - return pso; - } - -@@ -753,7 +750,8 @@ ID3D12PipelineState* context::get_or_create_pipeline( - .blend_key = this->get_blend_key(), - .depth_enabled = uint32_t(this->depth_enabled ? 1 : 0), - .textured = uint32_t(textured ? 1 : 0), -- .topology = uint32_t(topology) -+ .topology = uint32_t(topology), -+ .rtv_format = uint32_t(this->current_rtv_format()) - }; - - const auto it = this->pipelines.find(key); -@@ -781,18 +779,20 @@ void context::draw_indexed( - this->command_list->SetPipelineState(pso); - this->command_list->IASetPrimitiveTopology(to_topology(va.rendering_mode)); - -- // the vertex buffer (the first buffer of the vertex array; the vertex data of -- // all buffers is expected to have the same float4 layout) -+ // the vertex buffers (one per slot; all buffers have the same float4 layout) - { - utki::assert(!va.buffers.empty(), SL); -- // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") -- const auto& vb = static_cast(va.buffers.front().get()); -- const auto vbv = D3D12_VERTEX_BUFFER_VIEW{ -- .BufferLocation = vb.gpu_va, -- .SizeInBytes = UINT(vb.byte_size), -- .StrideInBytes = UINT(vertex_stride_bytes) -- }; -- this->command_list->IASetVertexBuffers(0, 1, &vbv); -+ std::vector views(va.buffers.size()); -+ for (size_t i = 0; i < va.buffers.size(); ++i) { -+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") -+ const auto& vb = static_cast(va.buffers[i].get()); -+ views[i] = D3D12_VERTEX_BUFFER_VIEW{ -+ .BufferLocation = vb.gpu_va, -+ .SizeInBytes = UINT(vb.byte_size), -+ .StrideInBytes = UINT(vertex_stride_bytes) -+ }; -+ } -+ this->command_list->IASetVertexBuffers(0, UINT(views.size()), views.data()); - } - - // the index buffer (an empty index buffer has no GPU resource) -@@ -901,7 +901,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende - const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); - check_hresult( - this->device->CreateCommittedResource( -- &upload_heap_properties(), -+ &default_heap_properties(), - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_COPY_DEST, -diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp -index f528340..eb1b2c5 100644 ---- a/src/ruis/render/directx/context.hpp -+++ b/src/ruis/render/directx/context.hpp -@@ -53,11 +53,13 @@ struct pipeline_key { - uint32_t depth_enabled = 0; - uint32_t textured = 0; - uint32_t topology = 0; // D3D12_PRIMITIVE_TOPOLOGY -+ uint32_t rtv_format = 0; // DXGI_FORMAT (the current render target format) - - bool operator==(const pipeline_key& o) const - { - return this->shader_kind == o.shader_kind && this->blend_key == o.blend_key && -- this->depth_enabled == o.depth_enabled && this->textured == o.textured && this->topology == o.topology; -+ this->depth_enabled == o.depth_enabled && this->textured == o.textured && -+ this->topology == o.topology && this->rtv_format == o.rtv_format; - } - }; - -@@ -77,6 +79,7 @@ struct pipeline_key_hash { - hash_combine(h, std::hash()(k.depth_enabled)); - hash_combine(h, std::hash()(k.textured)); - hash_combine(h, std::hash()(k.topology)); -+ hash_combine(h, std::hash()(k.rtv_format)); - return h; - } - }; -@@ -147,6 +150,10 @@ public: - // the packed key of the current blend state (for pipeline selection) - uint32_t get_blend_key() const; - -+ // the DXGI_FORMAT of the current render target (the swapchain for the -+ // screen, the color texture for a frame buffer) -+ DXGI_FORMAT current_rtv_format() const; -+ - // get or create a pipeline state object for the given shader + current state - ID3D12PipelineState* get_or_create_pipeline( - shader_kind kind, // -diff --git a/src/ruis/render/directx/directx.cpp b/src/ruis/render/directx/directx.cpp -index a1eb137..04d282d 100644 ---- a/src/ruis/render/directx/directx.cpp -+++ b/src/ruis/render/directx/directx.cpp -@@ -21,12 +21,13 @@ along with this program. If not, see . - - #include "directx.hpp" - -+#include - #include - #include - - namespace ruis::render::directx { - --std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) -+ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile) - { - ID3DBlob* blob = nullptr; - ID3DBlob* err_blob = nullptr; -@@ -45,20 +46,24 @@ std::vector compile_hlsl(const char* source, const char* entry_point, c - ); - if (FAILED(hr)) { - const auto err = err_blob != nullptr ? reinterpret_cast(err_blob->GetBufferPointer()) : ""; -- const auto msg = std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err; -- if (err_blob != nullptr) { -- err_blob->Release(); -- } -- throw std::runtime_error(msg); -+ if (err_blob != nullptr) { err_blob->Release(); } -+ if (blob != nullptr) { blob->Release(); } -+ throw std::runtime_error(std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err); - } -+ if (err_blob != nullptr) { err_blob->Release(); } -+ return blob; -+} - -+std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) -+{ -+ // compile the shader and copy the bytecode out of the returned blob -+ // (the caller keeps the blob alive for the lifetime of the pipeline; -+ // this public helper only needs the bytecode) -+ auto* blob = compile_hlsl_blob(source, entry_point, profile); - const auto size = blob->GetBufferSize(); - std::vector bytecode(size); - std::copy_n(static_cast(blob->GetBufferPointer()), size, bytecode.begin()); - blob->Release(); -- if (err_blob != nullptr) { -- err_blob->Release(); -- } - return bytecode; - } - -diff --git a/src/ruis/render/directx/directx.hpp b/src/ruis/render/directx/directx.hpp -index 0196277..3a8433f 100644 ---- a/src/ruis/render/directx/directx.hpp -+++ b/src/ruis/render/directx/directx.hpp -@@ -51,9 +51,9 @@ inline void check_hresult(HRESULT hr, const char* what) - /** - * @brief The shared draw uniforms, bound as a root constant buffer view. - * -- * The matrix is stored in row-major order, which is the same order that -- * r4::matrix4 uses and the default packing order of a row-major float4x4 in -- * HLSL, so the matrix is copied directly from r4 without any transposition. -+ * The matrix is stored in column-major order, matching the default packing -+ * of a float4x4 in an HLSL cbuffer (r4 stores row-major), so the matrix is -+ * transposed on write. - */ - struct draw_uniforms { - float matrix[4][4]; -@@ -64,9 +64,11 @@ static_assert(sizeof(draw_uniforms) == 16 * sizeof(float) + 4 * sizeof(float)); - - inline void write_draw_uniforms(draw_uniforms* u, const r4::matrix4& m, const r4::vector4& color) - { -+ // r4 stores row-major, HLSL expects column-major: transpose first -+ auto t = m.tposed(); - for (uint32_t r = 0; r < 4; ++r) { - for (uint32_t c = 0; c < 4; ++c) { -- u->matrix[r][c] = m[r][c]; -+ u->matrix[r][c] = t[r][c]; - } - } - u->color[0] = color.x(); -@@ -148,10 +150,11 @@ inline DXGI_FORMAT to_dxgi_format_8bit(rasterimage::format f) - } - - // D3D12_RESOURCE_STATE_DEPTH_STENCIL was removed from the new SDK; --// it is the same combination of states as before --inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = // -- D3D12_RESOURCE_STATE_DEPTH_WRITE | // -- D3D12_RESOURCE_STATE_DEPTH_READ; -+// the depth-stencil resources of this renderer are only written through the -+// depth-stencil view, so they are created in the (single) depth-write state. -+// (Read-only states cannot be combined with write states, so DEPTH_WRITE | DEPTH_READ -+// would be invalid.) -+inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = D3D12_RESOURCE_STATE_DEPTH_WRITE; - - // D3D12_MAX_LOD was removed from the new SDK; - // it is the maximum mip level (2048) that indicates "all mip levels" -@@ -241,8 +244,20 @@ inline D3D12_RESOURCE_BARRIER transition_barrier( - return b; - } - --// compile an HLSL shader source at runtime (via the D3D compiler); --// the returned blob contains the DXIL bytecode -+/** -+ * @brief Compile one HLSL shader source at runtime (via the D3D compiler). -+ * @param source the HLSL source -+ * @param entry_point the entry point -+ * @param profile the target profile (e.g. "vs_5_1") -+ * @return the compiled blob; the caller owns it and must release it. -+ * @throws std::runtime_error carrying the compiler's error message on failure. -+ */ -+ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile); -+ -+/** -+ * @brief Compile one HLSL shader source at runtime and return the DXIL bytecode. -+ * @throws std::runtime_error carrying the compiler's error message on failure. -+ */ - std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile); - - } // namespace ruis::render::directx -diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp -index 91f5d99..70ea0dc 100644 ---- a/src/ruis/render/directx/shaders/shader_common.hpp -+++ b/src/ruis/render/directx/shaders/shader_common.hpp -@@ -65,6 +65,18 @@ constexpr DXGI_FORMAT a1_format(shader_kind k) - } - } - -+// the semantic name of the a1 attribute (used in the vertex input layout) -+constexpr const char* a1_semantic(shader_kind k) -+{ -+ switch (k) { -+ case shader_kind::pos_clr: -+ return "COLOR"; -+ default: -+ // the textured shaders and the luminance shader declare it as TEXCOORD -+ return "TEXCOORD"; -+ } -+} -+ - // map the VAO's rendering mode to a DirectX primitive topology - inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) - { -diff --git a/src/ruis/render/directx/shaders/shader_src.hpp b/src/ruis/render/directx/shaders/shader_src.hpp -index ea38d7f..0a556cf 100644 ---- a/src/ruis/render/directx/shaders/shader_src.hpp -+++ b/src/ruis/render/directx/shaders/shader_src.hpp -@@ -22,7 +22,7 @@ along with this program. If not, see . - /* - * The HLSL sources of the renderer's shaders. - * They are compiled to DXIL at runtime with the D3D compiler (see -- * directx::compile_hlsl()). -+ * directx::compile_hlsl_blob(), which is what the renderer uses). - * - * The per-draw uniforms (the transformation matrix and the color) are passed - * as root 32-bit constants in register b0: first a float4x4 matrix (16 floats), -@@ -45,18 +45,24 @@ namespace ruis::render::directx { - // ============== color ========= - - static const char* hlsl_shader_color_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - float4 main(float4 pos : POSITION) : SV_POSITION - { -- return draw_matrix * pos; -+ return mul(draw_matrix, pos); - } - )HLSL"; - - static const char* hlsl_shader_color_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - float4 main() : SV_Target - { -@@ -68,8 +74,11 @@ float4 main() : SV_Target - // ============== pos_clr ======= - - static const char* hlsl_shader_pos_clr_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - struct VS_OUT - { -@@ -80,14 +89,19 @@ struct VS_OUT - VS_OUT main(float4 pos : POSITION, float4 col : COLOR) - { - VS_OUT o; -- o.pos = draw_matrix * pos; -+ o.pos = mul(draw_matrix, pos); - o.col = col; - return o; - } - )HLSL"; - - static const char* hlsl_shader_pos_clr_fragment = R"HLSL( --float4 main(float4 col : COLOR) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float4 col : COLOR) : SV_Target - { - return col; - } -@@ -97,8 +111,11 @@ float4 main(float4 col : COLOR) : SV_Target - // ============== pos_tex ======= - - static const char* hlsl_shader_pos_tex_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - struct VS_OUT - { -@@ -109,20 +126,28 @@ struct VS_OUT - VS_OUT main(float4 pos : POSITION, float2 uv : TEXCOORD) - { - VS_OUT o; -- o.pos = draw_matrix * pos; -+ o.pos = mul(draw_matrix, pos); - o.uv = uv; - return o; - } - )HLSL"; - - static const char* hlsl_shader_pos_tex_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - Texture2D tex0 : register(t0); - SamplerState samp0 : register(s0); - --float4 main(float2 uv : TEXCOORD) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target - { - return tex0.Sample(samp0, uv) * draw_color; - } -@@ -140,13 +165,21 @@ static const char* hlsl_shader_color_pos_tex_fragment = hlsl_shader_pos_tex_frag - static const char* hlsl_shader_color_pos_tex_alpha_vertex = hlsl_shader_pos_tex_vertex; - - static const char* hlsl_shader_color_pos_tex_alpha_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - Texture2D tex0 : register(t0); - SamplerState samp0 : register(s0); - --float4 main(float2 uv : TEXCOORD) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target - { - return float4(draw_color.xyz, draw_color.w * tex0.Sample(samp0, uv).r); - } -@@ -156,8 +189,11 @@ float4 main(float2 uv : TEXCOORD) : SV_Target - // ============== color_pos_lum = - - static const char* hlsl_shader_color_pos_lum_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - struct VS_OUT - { -@@ -168,17 +204,25 @@ struct VS_OUT - VS_OUT main(float4 pos : POSITION, float lum : TEXCOORD) - { - VS_OUT o; -- o.pos = draw_matrix * pos; -+ o.pos = mul(draw_matrix, pos); - o.lum = lum; - return o; - } - )HLSL"; - - static const char* hlsl_shader_color_pos_lum_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - --float4 main(float lum : TEXCOORD) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float lum : TEXCOORD) : SV_Target - { - return float4(draw_color.xyz, draw_color.w * lum); - } diff --git a/.wip_backup.patch b/.wip_backup.patch deleted file mode 100644 index c95727d..0000000 --- a/.wip_backup.patch +++ /dev/null @@ -1,1044 +0,0 @@ -diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp -index 26af34e..ed5b1ef 100644 ---- a/src/ruis/render/directx/context.cpp -+++ b/src/ruis/render/directx/context.cpp -@@ -22,9 +22,11 @@ along with this program. If not, see . - #include "context.hpp" - - #include -+#include - #include - #include - #include -+#include - - #include - -@@ -34,6 +36,7 @@ along with this program. If not, see . - #include "texture_depth.hpp" - #include "vertex_array.hpp" - #include "vertex_buffer.hpp" -+#include "shaders/shader_src.hpp" - - using namespace ruis::render::directx; - -@@ -44,6 +47,38 @@ constexpr ruis::real ndc_to_unit_scale = ruis::real(0.5); - // the size of a vertex in bytes: all vertex attributes are stored as float4 (4 floats) - constexpr UINT64 vertex_stride_bytes = 4 * sizeof(float); - -+// TEMPORARY: dump stored debug messages from the info queue (diagnostics) -+void dump_info_queue_messages(ID3D12Device* device) -+{ -+ if (device == nullptr) { -+ return; -+ } -+ ID3D12InfoQueue* iq = nullptr; -+ if (FAILED(device->QueryInterface(IID_PPV_ARGS(&iq))) || iq == nullptr) { -+ fprintf(stderr, "dump_info_queue_messages: QueryInterface(ID3D12InfoQueue) failed\n"); -+ return; -+ } -+ const auto num = iq->GetNumStoredMessages(); -+ fprintf(stderr, "dump_info_queue_messages: %llu stored messages\n", (unsigned long long)num); -+ for (uint64_t i = 0; i < num; ++i) { -+ D3D12_MESSAGE msg{}; -+ SIZE_T len = sizeof(msg); -+ if (FAILED(iq->GetMessage(i, nullptr, &len)) || len == 0) { -+ fprintf(stderr, " message %llu: GetMessage(description) failed\n", (unsigned long long)i); -+ continue; -+ } -+ std::vector buf(len); -+ const auto hr = iq->GetMessage(i, reinterpret_cast(buf.data()), &len); -+ if (FAILED(hr)) { -+ fprintf(stderr, " message %llu: GetMessage failed (hr=0x%08x)\n", (unsigned long long)i, unsigned(hr)); -+ continue; -+ } -+ const auto& m = *reinterpret_cast(buf.data()); -+ fprintf(stderr, " [%u] %.*s\n", unsigned(m.Severity), int(m.DescriptionByteLength), m.pDescription ? m.pDescription : "(null)"); -+ } -+ iq->Release(); -+} -+ - } // namespace - - context::context( -@@ -59,10 +94,16 @@ context::context( - // maps the framework's normalized viewport coordinates (x right, y down, - // zero at the top-left, right/bottom edges at (1, 1)) to the DirectX NDC. - // -- // In the DirectX NDC -1 -1 corresponds to the top-left corner, 1 1 to the -- // bottom-right corner, and z points away from the viewer (same orientation -- // as the framework, so no axis flip is needed). -- m.set_identity().translate(-1, -1).scale(2, 2); -+ // DirectX identity matrix: -+ // viewport edges: left = -1, right = 1, top = 1, bottom = -1 -+ // z-axis away from the viewer -+ m.set_identity() -+ // x-axis right, y-axis down, z-axis away -+ .scale(1, -1, 1) -+ // viewport edges: left = 0, top = 0 -+ .translate(-1, -1) -+ // viewport edges: right = 1, bottom = 1 -+ .scale(2, 2); - return parameters{m}; - }() - ), -@@ -182,7 +223,7 @@ void context::create_swapchain() - IDXGISwapChain1* sc = nullptr; - check_hresult( - dxgi_factory->CreateSwapChainForHwnd( -- reinterpret_cast(this->device), -+ reinterpret_cast(this->queue), - this->surface_ref.get().get_hwnd(), - &desc, - nullptr, -@@ -210,6 +251,12 @@ void context::create_swapchain() - utki::assert(this->back_buffer_count == 0 || this->back_buffers.size() == this->back_buffer_count, SL); - this->back_buffer_count = UINT(this->back_buffers.size()); - utki::assert(this->back_buffer_count >= 2, SL); -+ fprintf(stderr, "create_swapchain: back_buffer_count=%u window_dims=(%u,%u) swapchain_vsync=%d\n", UINT(this->back_buffer_count), this->window_dims.x(), this->window_dims.y(), (int)this->swapchain_vsync); -+ { -+ DXGI_SWAP_CHAIN_DESC desc{}; -+ this->swapchain->GetDesc(&desc); -+ fprintf(stderr, "create_swapchain: swapchain format=%u back buffer0 format=%u\n", unsigned(desc.BufferDesc.Format), unsigned(this->back_buffers[0]->GetDesc().Format)); -+ } - - // one RTV descriptor per back buffer - { -@@ -348,7 +395,7 @@ void context::wait_for_gpu() - } - // wait for the frame that rendered to the back buffer we are about to reuse - const auto i = int(this->frame_index); -- if (this->frame_pending[i]) { -+ if (i < 3 && this->frame_pending[i]) { - const auto res = WaitForSingleObject(this->frame_fence_events[i], 10000); // 10s timeout - if (res != WAIT_OBJECT_0) { - throw std::runtime_error("directx context wait_for_gpu: the frame fence did not complete in time"); -@@ -367,10 +414,10 @@ void context::ensure_frame_began() - this->ensure_swapchain_valid(); - - if (this->swapchain != nullptr) { -- // wait for the GPU to finish with the back buffer we are about to overwrite, -- // then advance to the next back buffer -+ // the swapchain tells us which back buffer we are about to render to -+ this->frame_index = this->swapchain->GetCurrentBackBufferIndex(); -+ // wait for the GPU to finish with the back buffer we are about to overwrite - this->wait_for_gpu(); -- this->frame_index = (this->frame_index + 1) % this->back_buffer_count; - } - - // reset the command allocator and the command list (the GPU has finished with -@@ -383,6 +430,7 @@ void context::ensure_frame_began() - } - this->frame_first_begin = false; - -+ - this->frame_begun = true; - } - -@@ -398,7 +446,7 @@ void context::present_frame() - - // signal the fence for this back buffer (waited on before it is reused) - const auto value = this->frame_fence->GetCompletedValue() + 1; -- this->frame_fence->Signal(value); -+ check_hresult(this->queue->Signal(this->frame_fence, value), "queue Signal (frame fence)"); - const auto i = int(this->frame_index); - check_hresult( - this->frame_fence->SetEventOnCompletion(value, this->frame_fence_events[i]), -@@ -409,7 +457,8 @@ void context::present_frame() - // present the back buffer to the window - if (this->swapchain != nullptr) { - const auto hr = this->swapchain->Present(this->swapchain_vsync ? 1 : 0, 0); -- (void)hr; // a failed present (e.g. window minimized) is not fatal -+ fprintf(stderr, "present_frame: Present hr=0x%08x\n", unsigned(hr)); // a failed present (e.g. window minimized) is not fatal -+ if (FAILED(hr)) { dump_info_queue_messages(this->device); } - } - } - -@@ -588,6 +637,16 @@ void context::enable_depth(bool enable) - this->depth_enabled = enable; - } - -+DXGI_FORMAT context::current_rtv_format() const -+{ -+ if (this->current_fb != nullptr && this->current_fb->color != nullptr) { -+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") -+ const auto& tex = static_cast(*this->current_fb->color); -+ return to_dxgi_format_8bit(tex.ri_format); -+ } -+ return DXGI_FORMAT_B8G8R8A8_UNORM; -+} -+ - uint32_t context::get_blend_key() const - { - // pack the blend state into a key for the pipeline cache: -@@ -605,27 +664,8 @@ uint32_t context::get_blend_key() const - - ID3DBlob* context::compile_shader(const char* hlsl, const char* entry_point, const char* profile) - { -- ID3DBlob* blob = nullptr; -- ID3DBlob* err_blob = nullptr; -- check_hresult( -- D3DCompile( -- hlsl, -- strlen(hlsl), -- "ruis-render-directx.hlsl", -- nullptr, -- nullptr, -- entry_point, -- profile, -- 0, -- 0, -- &blob, -- &err_blob -- ), -- "D3DCompile" -- ); -- if (err_blob != nullptr) { -- err_blob->Release(); -- } -+ // the shared helper throws with the compiler's error message on failure -+ auto* blob = compile_hlsl_blob(hlsl, entry_point, profile); - this->shader_blobs.emplace_back(blob); - return blob; - } -@@ -637,13 +677,19 @@ ID3D12PipelineState* context::build_pipeline( - const char* fragment_hlsl - ) - { -+ fprintf(stderr, "build_pipeline: pre-compile\n"); - // compile the shaders to DXIL (the blobs are kept alive in shader_blobs) -- auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_6_0"); -- auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_6_0"); -+ auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_5_1"); -+ fprintf(stderr, "build_pipeline: post-vs-compile\n"); -+ fprintf(stderr, "build_pipeline: pre-fs-compile\n"); -+ auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_5_1"); -+ fprintf(stderr, "build_pipeline: post-fs-compile\n"); - -+ fprintf(stderr, "build_pipeline: pre-input-layout\n"); - // ---- the vertex input layout ---- -- // all vertices are stored as float4 (4 floats) in the vertex buffer; the a1 -- // attribute (if present) is the tail of the float4 (its format is shader-specific) -+ // each buffer of the vertex array holds float4 (4 floats) vertices with the -+ // same stride; the a1 attribute (if present) reads the first few floats of the -+ // second buffer (its format is shader-specific) - const auto a1 = shader_kind(key.shader_kind); - auto input_layout_elements = std::vector{ - {.SemanticName = "POSITION", -@@ -656,11 +702,11 @@ ID3D12PipelineState* context::build_pipeline( - if (has_a1) { - input_layout_elements.push_back( - D3D12_INPUT_ELEMENT_DESC{ -- .SemanticName = "TEXCOORD", -+ .SemanticName = a1_semantic(a1), - .SemanticIndex = 0, - .Format = a1_format(a1), - .InputSlot = 1, -- .AlignedByteOffset = UINT(vertex_stride_bytes), -+ .AlignedByteOffset = 0, - .InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA - } - ); -@@ -699,16 +745,32 @@ ID3D12PipelineState* context::build_pipeline( - depth_stencil.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; - depth_stencil.BackFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; - -+ fprintf(stderr, "build_pipeline: vs_blob size=%u\n", UINT(vs_blob->GetBufferSize())); -+ fprintf(stderr, "build_pipeline: fs_blob size=%u\n", UINT(fs_blob->GetBufferSize())); -+ fprintf(stderr, "build_pipeline: input_layout NumElements=%u\n", UINT(input_layout.NumElements)); -+ fprintf(stderr, "build_pipeline: pso key rtv_format=%u depth=%d topology=%u\n", key.rtv_format, use_depth ? 1 : 0, key.topology); -+ // TEMPORARY: dump the shader blobs to files for analysis -+ { -+ const auto vs_ptr = (const unsigned char*)vs_blob->GetBufferPointer(); -+ const auto fs_ptr = (const unsigned char*)fs_blob->GetBufferPointer(); -+ FILE* f = nullptr; -+ fopen_s(&f, "vs_dump.bin", "wb"); if (f) { fwrite(vs_ptr, 1, vs_blob->GetBufferSize(), f); fclose(f); } -+ fopen_s(&f, "fs_dump.bin", "wb"); if (f) { fwrite(fs_ptr, 1, fs_blob->GetBufferSize(), f); fclose(f); } -+ } -+ fprintf(stderr, "build_pipeline: vs first bytes: %02x %02x %02x %02x %02x %02x %02x %02x\n", ((const unsigned char*)vs_blob->GetBufferPointer())[0], ((const unsigned char*)vs_blob->GetBufferPointer())[1], ((const unsigned char*)vs_blob->GetBufferPointer())[2], ((const unsigned char*)vs_blob->GetBufferPointer())[3], ((const unsigned char*)vs_blob->GetBufferPointer())[4], ((const unsigned char*)vs_blob->GetBufferPointer())[5], ((const unsigned char*)vs_blob->GetBufferPointer())[6], ((const unsigned char*)vs_blob->GetBufferPointer())[7]); -+ fprintf(stderr, "build_pipeline: fs first bytes: %02x %02x %02x %02x %02x %02x %02x %02x\n", ((const unsigned char*)fs_blob->GetBufferPointer())[0], ((const unsigned char*)fs_blob->GetBufferPointer())[1], ((const unsigned char*)fs_blob->GetBufferPointer())[2], ((const unsigned char*)fs_blob->GetBufferPointer())[3], ((const unsigned char*)fs_blob->GetBufferPointer())[4], ((const unsigned char*)fs_blob->GetBufferPointer())[5], ((const unsigned char*)fs_blob->GetBufferPointer())[6], ((const unsigned char*)fs_blob->GetBufferPointer())[7]); -+ fprintf(stderr, "build_pipeline: vs input semantics: %s\n", "check"); -+ fprintf(stderr, "build_pipeline: pre-CreateGraphicsPipelineState\n"); - const auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{ - .pRootSignature = this->root_signature, -- .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), vs_blob->GetBufferSize()}, -- .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), fs_blob->GetBufferSize()}, -+ .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}, -+ .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}, - .BlendState = blend, - .SampleMask = 0xFFFFFFFF, - .RasterizerState = - D3D12_RASTERIZER_DESC{ - .FillMode = D3D12_FILL_MODE_SOLID, -- .CullMode = D3D12_CULL_MODE_NONE, -+ .CullMode = D3D12_CULL_MODE_BACK, - .FrontCounterClockwise = FALSE, - .DepthBias = 0, - .DepthBiasClamp = 0.0f, -@@ -724,17 +786,22 @@ ID3D12PipelineState* context::build_pipeline( - .IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, - .PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - .NumRenderTargets = 1, -- .RTVFormats = {DXGI_FORMAT_UNKNOWN}, // the actual format depends on the render target -- .DSVFormat = DXGI_FORMAT_UNKNOWN, // the actual format depends on the depth texture -+ .RTVFormats = {static_cast(key.rtv_format)}, -+ .DSVFormat = use_depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_UNKNOWN, - .SampleDesc = {.Count = 1, .Quality = 0}, - .NodeMask = 0 - }; - -+ fprintf(stderr, "build_pipeline: pre-create-call\n"); - ID3D12PipelineState* pso = nullptr; -- check_hresult( -- this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)), -- "CreateGraphicsPipelineState" -- ); -+ fprintf(stderr, "build_pipeline: pre-check_hresult\n"); -+ const auto hr = this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)); -+ fprintf(stderr, "build_pipeline: CreateGraphicsPipelineState hr=0x%08x pso=%p\n", unsigned(hr), (void*)pso); -+ if (FAILED(hr)) { -+ dump_info_queue_messages(this->device); -+ } -+ check_hresult(hr, "CreateGraphicsPipelineState"); -+ fprintf(stderr, "build_pipeline: done\n"); - return pso; - } - -@@ -751,15 +818,19 @@ ID3D12PipelineState* context::get_or_create_pipeline( - .blend_key = this->get_blend_key(), - .depth_enabled = uint32_t(this->depth_enabled ? 1 : 0), - .textured = uint32_t(textured ? 1 : 0), -- .topology = uint32_t(topology) -+ .topology = uint32_t(topology), -+ .rtv_format = uint32_t(this->current_rtv_format()) - }; - - const auto it = this->pipelines.find(key); -+ fprintf(stderr, "get_or_create_pipeline: found?=%d\n", (int)(it != this->pipelines.end())); - if (it != this->pipelines.end()) { - return it->second; - } - -+ fprintf(stderr, "get_or_create_pipeline: building pipeline shader_kind=%d textured=%d\n", (int)kind, (int)textured); - const auto pso = this->build_pipeline(key, shader_has_a1(kind), vertex_hlsl, fragment_hlsl); -+ fprintf(stderr, "get_or_create_pipeline: built\n"); - this->pipelines.emplace(key, pso); - return pso; - } -@@ -779,18 +850,20 @@ void context::draw_indexed( - this->command_list->SetPipelineState(pso); - this->command_list->IASetPrimitiveTopology(to_topology(va.rendering_mode)); - -- // the vertex buffer (the first buffer of the vertex array; the vertex data of -- // all buffers is expected to have the same float4 layout) -+ // the vertex buffers (one per slot; all buffers have the same float4 layout) - { - utki::assert(!va.buffers.empty(), SL); -- // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") -- const auto& vb = static_cast(va.buffers.front().get()); -- const auto vbv = D3D12_VERTEX_BUFFER_VIEW{ -- .BufferLocation = vb.gpu_va, -- .SizeInBytes = UINT(vb.byte_size), -- .StrideInBytes = UINT(vertex_stride_bytes) -- }; -- this->command_list->IASetVertexBuffers(0, 1, &vbv); -+ std::vector views(va.buffers.size()); -+ for (size_t i = 0; i < va.buffers.size(); ++i) { -+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") -+ const auto& vb = static_cast(va.buffers[i].get()); -+ views[i] = D3D12_VERTEX_BUFFER_VIEW{ -+ .BufferLocation = vb.gpu_va, -+ .SizeInBytes = UINT(vb.byte_size), -+ .StrideInBytes = UINT(vertex_stride_bytes) -+ }; -+ } -+ this->command_list->IASetVertexBuffers(0, UINT(views.size()), views.data()); - } - - // the index buffer (an empty index buffer has no GPU resource) -@@ -899,7 +972,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende - const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); - check_hresult( - this->device->CreateCommittedResource( -- &upload_heap_properties(), -+ &readback_heap_properties(), - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_COPY_DEST, -diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp -index f528340..eb1b2c5 100644 ---- a/src/ruis/render/directx/context.hpp -+++ b/src/ruis/render/directx/context.hpp -@@ -53,11 +53,13 @@ struct pipeline_key { - uint32_t depth_enabled = 0; - uint32_t textured = 0; - uint32_t topology = 0; // D3D12_PRIMITIVE_TOPOLOGY -+ uint32_t rtv_format = 0; // DXGI_FORMAT (the current render target format) - - bool operator==(const pipeline_key& o) const - { - return this->shader_kind == o.shader_kind && this->blend_key == o.blend_key && -- this->depth_enabled == o.depth_enabled && this->textured == o.textured && this->topology == o.topology; -+ this->depth_enabled == o.depth_enabled && this->textured == o.textured && -+ this->topology == o.topology && this->rtv_format == o.rtv_format; - } - }; - -@@ -77,6 +79,7 @@ struct pipeline_key_hash { - hash_combine(h, std::hash()(k.depth_enabled)); - hash_combine(h, std::hash()(k.textured)); - hash_combine(h, std::hash()(k.topology)); -+ hash_combine(h, std::hash()(k.rtv_format)); - return h; - } - }; -@@ -147,6 +150,10 @@ public: - // the packed key of the current blend state (for pipeline selection) - uint32_t get_blend_key() const; - -+ // the DXGI_FORMAT of the current render target (the swapchain for the -+ // screen, the color texture for a frame buffer) -+ DXGI_FORMAT current_rtv_format() const; -+ - // get or create a pipeline state object for the given shader + current state - ID3D12PipelineState* get_or_create_pipeline( - shader_kind kind, // -diff --git a/src/ruis/render/directx/device.cpp b/src/ruis/render/directx/device.cpp -index 5e9c7b4..e628bdb 100644 ---- a/src/ruis/render/directx/device.cpp -+++ b/src/ruis/render/directx/device.cpp -@@ -21,6 +21,8 @@ along with this program. If not, see . - - #include "device.hpp" - -+#include -+ - #include - #include - -@@ -61,6 +63,18 @@ D3D_FEATURE_LEVEL pick_feature_level(IDXGIFactory1* factory, IDXGIAdapter1* adap - - device::device() - { -+ // TEMPORARY: enable the D3D12 debug layer for diagnostics -+ { -+ ID3D12Debug* dbg = nullptr; -+ const auto dbg_hr = D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)); -+ fprintf(stderr, "D3D12GetDebugInterface hr=0x%08x dbg=%p\n", unsigned(dbg_hr), (void*)dbg); -+ if (dbg != nullptr) { -+ dbg->EnableDebugLayer(); -+ fprintf(stderr, "EnableDebugLayer called\n"); -+ dbg->Release(); -+ } -+ } -+ - IDXGIFactory1* factory = nullptr; - check_hresult(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "CreateDXGIFactory1"); - { -diff --git a/src/ruis/render/directx/directx.cpp b/src/ruis/render/directx/directx.cpp -index a1eb137..04d282d 100644 ---- a/src/ruis/render/directx/directx.cpp -+++ b/src/ruis/render/directx/directx.cpp -@@ -21,12 +21,13 @@ along with this program. If not, see . - - #include "directx.hpp" - -+#include - #include - #include - - namespace ruis::render::directx { - --std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) -+ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile) - { - ID3DBlob* blob = nullptr; - ID3DBlob* err_blob = nullptr; -@@ -45,20 +46,24 @@ std::vector compile_hlsl(const char* source, const char* entry_point, c - ); - if (FAILED(hr)) { - const auto err = err_blob != nullptr ? reinterpret_cast(err_blob->GetBufferPointer()) : ""; -- const auto msg = std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err; -- if (err_blob != nullptr) { -- err_blob->Release(); -- } -- throw std::runtime_error(msg); -+ if (err_blob != nullptr) { err_blob->Release(); } -+ if (blob != nullptr) { blob->Release(); } -+ throw std::runtime_error(std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err); - } -+ if (err_blob != nullptr) { err_blob->Release(); } -+ return blob; -+} - -+std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) -+{ -+ // compile the shader and copy the bytecode out of the returned blob -+ // (the caller keeps the blob alive for the lifetime of the pipeline; -+ // this public helper only needs the bytecode) -+ auto* blob = compile_hlsl_blob(source, entry_point, profile); - const auto size = blob->GetBufferSize(); - std::vector bytecode(size); - std::copy_n(static_cast(blob->GetBufferPointer()), size, bytecode.begin()); - blob->Release(); -- if (err_blob != nullptr) { -- err_blob->Release(); -- } - return bytecode; - } - -diff --git a/src/ruis/render/directx/directx.hpp b/src/ruis/render/directx/directx.hpp -index b260631..bcfe4f9 100644 ---- a/src/ruis/render/directx/directx.hpp -+++ b/src/ruis/render/directx/directx.hpp -@@ -51,9 +51,9 @@ inline void check_hresult(HRESULT hr, const char* what) - /** - * @brief The shared draw uniforms, bound as a root constant buffer view. - * -- * The matrix is stored in row-major order, which is the same order that -- * r4::matrix4 uses and the default packing order of a row-major float4x4 in -- * HLSL, so the matrix is copied directly from r4 without any transposition. -+ * The matrix is stored in column-major order, matching the default packing -+ * of a float4x4 in an HLSL cbuffer (r4 stores row-major), so the matrix is -+ * transposed on write. - */ - struct draw_uniforms { - float matrix[4][4]; -@@ -64,9 +64,11 @@ static_assert(sizeof(draw_uniforms) == 16 * sizeof(float) + 4 * sizeof(float)); - - inline void write_draw_uniforms(draw_uniforms* u, const r4::matrix4& m, const r4::vector4& color) - { -+ // r4 stores row-major, HLSL expects column-major: transpose first -+ auto t = m.tposed(); - for (uint32_t r = 0; r < 4; ++r) { - for (uint32_t c = 0; c < 4; ++c) { -- u->matrix[r][c] = m[r][c]; -+ u->matrix[r][c] = t[r][c]; - } - } - u->color[0] = color.x(); -@@ -148,10 +150,11 @@ inline DXGI_FORMAT to_dxgi_format_8bit(rasterimage::format f) - } - - // D3D12_RESOURCE_STATE_DEPTH_STENCIL was removed from the new SDK; --// it is the same combination of states as before --inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = // -- D3D12_RESOURCE_STATE_DEPTH_WRITE | // -- D3D12_RESOURCE_STATE_DEPTH_READ; -+// the depth-stencil resources of this renderer are only written through the -+// depth-stencil view, so they are created in the (single) depth-write state. -+// (Read-only states cannot be combined with write states, so DEPTH_WRITE | DEPTH_READ -+// would be invalid.) -+inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = D3D12_RESOURCE_STATE_DEPTH_WRITE; - - // D3D12_MAX_LOD was removed from the new SDK; - // it is the maximum mip level (2048) that indicates "all mip levels" -@@ -227,6 +230,20 @@ inline const D3D12_HEAP_PROPERTIES& upload_heap_properties() - return props; - } - -+// a readback heap (CPU-readable; the resource is created in the COPY_DEST -+// state, so it is only ever used as a copy destination) -+inline const D3D12_HEAP_PROPERTIES& readback_heap_properties() -+{ -+ static const auto props = D3D12_HEAP_PROPERTIES{ -+ .Type = D3D12_HEAP_TYPE_READBACK, -+ .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, -+ .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, -+ .CreationNodeMask = 0, -+ .VisibleNodeMask = 0 -+ }; -+ return props; -+} -+ - // a transition resource barrier (the new SDK has no D3D12_RESOURCE_BARRIER:: - // Transition() static helper) - inline D3D12_RESOURCE_BARRIER transition_barrier( -@@ -245,8 +262,20 @@ inline D3D12_RESOURCE_BARRIER transition_barrier( - return b; - } - --// compile an HLSL shader source at runtime (via the D3D compiler); --// the returned blob contains the DXIL bytecode -+/** -+ * @brief Compile one HLSL shader source at runtime (via the D3D compiler). -+ * @param source the HLSL source -+ * @param entry_point the entry point -+ * @param profile the target profile (e.g. "vs_5_1") -+ * @return the compiled blob; the caller owns it and must release it. -+ * @throws std::runtime_error carrying the compiler's error message on failure. -+ */ -+ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile); -+ -+/** -+ * @brief Compile one HLSL shader source at runtime and return the DXIL bytecode. -+ * @throws std::runtime_error carrying the compiler's error message on failure. -+ */ - std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile); - - } // namespace ruis::render::directx -diff --git a/src/ruis/render/directx/factory.cpp b/src/ruis/render/directx/factory.cpp -index 058af79..d9246dc 100644 ---- a/src/ruis/render/directx/factory.cpp -+++ b/src/ruis/render/directx/factory.cpp -@@ -77,15 +77,15 @@ factory::factory(const utki::shared_ref& surface) : // - - const auto static_sampler = D3D12_STATIC_SAMPLER_DESC{ - .Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR, -- .AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, -- .AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, -- .AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, -+ .AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER, -+ .AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER, -+ .AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER, - .MipLODBias = 0.0f, -- .MaxAnisotropy = 1, -+ .MaxAnisotropy = 0, - .ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER, - .BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, - .MinLOD = 0.0f, -- .MaxLOD = D3D12_MAX_LOD, -+ .MaxLOD = D3D12_FLOAT32_MAX, - .ShaderRegister = 0, - .RegisterSpace = 0, - .ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL -@@ -197,7 +197,7 @@ void factory::one_shot(std::function cmd) cons - const auto lists = std::array{{this->upload_command_list}}; - this->queue->ExecuteCommandLists(1, lists.data()); - -- this->upload_fence->Signal(++this->upload_fence_value); -+ check_hresult(this->queue->Signal(this->upload_fence, ++this->upload_fence_value), "queue Signal (upload fence)"); - check_hresult( - this->upload_fence->SetEventOnCompletion(this->upload_fence_value, this->upload_fence_event), - "fence SetEvent" -@@ -414,7 +414,7 @@ void factory::upload_texture(texture_2d* t) const - &upload_heap_properties(), - D3D12_HEAP_FLAG_NONE, - &desc, -- D3D12_RESOURCE_STATE_COMMON, -+ D3D12_RESOURCE_STATE_GENERIC_READ, - nullptr, - IID_PPV_ARGS(&upload) - ), -diff --git a/src/ruis/render/directx/index_buffer.cpp b/src/ruis/render/directx/index_buffer.cpp -index 9da1abe..0c2886b 100644 ---- a/src/ruis/render/directx/index_buffer.cpp -+++ b/src/ruis/render/directx/index_buffer.cpp -@@ -96,7 +96,7 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT - &upload_heap_properties(), - D3D12_HEAP_FLAG_NONE, - &desc, -- D3D12_RESOURCE_STATE_COMMON, -+ D3D12_RESOURCE_STATE_GENERIC_READ, - nullptr, - IID_PPV_ARGS(&upload) - ), -@@ -111,13 +111,13 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT - - dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { - const auto barrier1 = -- transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); -+ transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); - cmd->ResourceBarrier(1, &barrier1); - cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(byte_size)); - const auto barrier2 = transition_barrier( - this->resource, - D3D12_RESOURCE_STATE_COPY_DEST, -- D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER -+ D3D12_RESOURCE_STATE_INDEX_BUFFER - ); - cmd->ResourceBarrier(1, &barrier2); - }); -diff --git a/src/ruis/render/directx/sdk_prelude.hpp b/src/ruis/render/directx/sdk_prelude.hpp -index 9a94193..5b6f184 100644 ---- a/src/ruis/render/directx/sdk_prelude.hpp -+++ b/src/ruis/render/directx/sdk_prelude.hpp -@@ -43,6 +43,7 @@ along with this program. If not, see . - #endif - - #include -+#include - #include - #include - -diff --git a/src/ruis/render/directx/shaders/shader_common.cpp b/src/ruis/render/directx/shaders/shader_common.cpp -index 9503a3b..0b6f749 100644 ---- a/src/ruis/render/directx/shaders/shader_common.cpp -+++ b/src/ruis/render/directx/shaders/shader_common.cpp -@@ -24,10 +24,15 @@ along with this program. If not, see . - #include - - #include "../context.hpp" -+ -+#include - #include "../texture_2d.hpp" - - namespace ruis::render::directx { - -+static void debug_print(const char* msg) { std::fprintf(stderr, "%s\n", msg); } -+ -+ - void directx_shader_render( - shader_kind kind, - const char* vertex_hlsl, -@@ -46,13 +51,16 @@ void directx_shader_render( - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "assert(dynamic_cast) done above") - static_cast(cur); - -+ debug_print("draw: pre-ensure_frame_began"); - // make sure the frame is begun (the back buffer is acquired and the command - // list is reset) - ctx.ensure_frame_began(); -+ debug_print("draw: post-ensure_frame_began"); - - // skip drawing if the viewport is zero-sized (e.g. resource loader context) - { - const auto& vp = ctx.get_viewport(); -+ fprintf(stderr, "draw: viewport = (%u %u)(%u %u)\n", vp.p.x(), vp.p.y(), vp.d.x(), vp.d.y()); - if (vp.d.x() == 0 || vp.d.y() == 0) { - return; - } -@@ -63,6 +71,7 @@ void directx_shader_render( - write_draw_uniforms(&u, m, color); - - // get or create the pipeline state object for the current state -+ debug_print("draw: pre-pipeline"); - const auto pso = ctx.get_or_create_pipeline( - kind, - shader_has_texture(kind), -@@ -71,7 +80,9 @@ void directx_shader_render( - fragment_hlsl - ); - -+ debug_print("draw: pre-draw_indexed"); - ctx.draw_indexed(pso, va, texture, u); -+ debug_print("draw: post-draw_indexed"); - } - - } // namespace ruis::render::directx -diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp -index 0d95cd6..2ae7ab0 100644 ---- a/src/ruis/render/directx/shaders/shader_common.hpp -+++ b/src/ruis/render/directx/shaders/shader_common.hpp -@@ -66,6 +66,18 @@ constexpr DXGI_FORMAT a1_format(shader_kind k) - } - } - -+// the semantic name of the a1 attribute (used in the vertex input layout) -+constexpr const char* a1_semantic(shader_kind k) -+{ -+ switch (k) { -+ case shader_kind::pos_clr: -+ return "COLOR"; -+ default: -+ // the textured shaders and the luminance shader declare it as TEXCOORD -+ return "TEXCOORD"; -+ } -+} -+ - // map the VAO's rendering mode to a DirectX primitive topology - inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) - { -diff --git a/src/ruis/render/directx/shaders/shader_src.hpp b/src/ruis/render/directx/shaders/shader_src.hpp -index ea38d7f..0a556cf 100644 ---- a/src/ruis/render/directx/shaders/shader_src.hpp -+++ b/src/ruis/render/directx/shaders/shader_src.hpp -@@ -22,7 +22,7 @@ along with this program. If not, see . - /* - * The HLSL sources of the renderer's shaders. - * They are compiled to DXIL at runtime with the D3D compiler (see -- * directx::compile_hlsl()). -+ * directx::compile_hlsl_blob(), which is what the renderer uses). - * - * The per-draw uniforms (the transformation matrix and the color) are passed - * as root 32-bit constants in register b0: first a float4x4 matrix (16 floats), -@@ -45,18 +45,24 @@ namespace ruis::render::directx { - // ============== color ========= - - static const char* hlsl_shader_color_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - float4 main(float4 pos : POSITION) : SV_POSITION - { -- return draw_matrix * pos; -+ return mul(draw_matrix, pos); - } - )HLSL"; - - static const char* hlsl_shader_color_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - float4 main() : SV_Target - { -@@ -68,8 +74,11 @@ float4 main() : SV_Target - // ============== pos_clr ======= - - static const char* hlsl_shader_pos_clr_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - struct VS_OUT - { -@@ -80,14 +89,19 @@ struct VS_OUT - VS_OUT main(float4 pos : POSITION, float4 col : COLOR) - { - VS_OUT o; -- o.pos = draw_matrix * pos; -+ o.pos = mul(draw_matrix, pos); - o.col = col; - return o; - } - )HLSL"; - - static const char* hlsl_shader_pos_clr_fragment = R"HLSL( --float4 main(float4 col : COLOR) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float4 col : COLOR) : SV_Target - { - return col; - } -@@ -97,8 +111,11 @@ float4 main(float4 col : COLOR) : SV_Target - // ============== pos_tex ======= - - static const char* hlsl_shader_pos_tex_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - struct VS_OUT - { -@@ -109,20 +126,28 @@ struct VS_OUT - VS_OUT main(float4 pos : POSITION, float2 uv : TEXCOORD) - { - VS_OUT o; -- o.pos = draw_matrix * pos; -+ o.pos = mul(draw_matrix, pos); - o.uv = uv; - return o; - } - )HLSL"; - - static const char* hlsl_shader_pos_tex_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - Texture2D tex0 : register(t0); - SamplerState samp0 : register(s0); - --float4 main(float2 uv : TEXCOORD) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target - { - return tex0.Sample(samp0, uv) * draw_color; - } -@@ -140,13 +165,21 @@ static const char* hlsl_shader_color_pos_tex_fragment = hlsl_shader_pos_tex_frag - static const char* hlsl_shader_color_pos_tex_alpha_vertex = hlsl_shader_pos_tex_vertex; - - static const char* hlsl_shader_color_pos_tex_alpha_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - Texture2D tex0 : register(t0); - SamplerState samp0 : register(s0); - --float4 main(float2 uv : TEXCOORD) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target - { - return float4(draw_color.xyz, draw_color.w * tex0.Sample(samp0, uv).r); - } -@@ -156,8 +189,11 @@ float4 main(float2 uv : TEXCOORD) : SV_Target - // ============== color_pos_lum = - - static const char* hlsl_shader_color_pos_lum_vertex = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - - struct VS_OUT - { -@@ -168,17 +204,25 @@ struct VS_OUT - VS_OUT main(float4 pos : POSITION, float lum : TEXCOORD) - { - VS_OUT o; -- o.pos = draw_matrix * pos; -+ o.pos = mul(draw_matrix, pos); - o.lum = lum; - return o; - } - )HLSL"; - - static const char* hlsl_shader_color_pos_lum_fragment = R"HLSL( --RootConstants[1] draw_matrix : register(b0); --RootConstants[1] draw_color : register(b16); -+cbuffer DrawConstants : register(b0) -+{ -+ float4x4 draw_matrix; -+ float4 draw_color; -+}; - --float4 main(float lum : TEXCOORD) : SV_Target -+// NOTE: the VS outputs SV_POSITION at hardware register 0 and any -+// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader -+// must declare SV_POSITION as an (unused) input so its arbitrary semantic -+// lines up at the same hardware register as the VS output; otherwise pipeline -+// creation fails with E_INVALIDARG ("mismatched hardware registers"). -+float4 main(float4 pos : SV_POSITION, float lum : TEXCOORD) : SV_Target - { - return float4(draw_color.xyz, draw_color.w * lum); - } -diff --git a/src/ruis/render/directx/texture_2d.cpp b/src/ruis/render/directx/texture_2d.cpp -index 4b9cfa9..d1b0857 100644 ---- a/src/ruis/render/directx/texture_2d.cpp -+++ b/src/ruis/render/directx/texture_2d.cpp -@@ -82,10 +82,10 @@ texture_2d::texture_2d( - .Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - .NodeMask = 0 - }; -- check_hresult( -- device->CreateDescriptorHeap(&srv_desc, IID_PPV_ARGS(&this->srv_heap)), -- "CreateDescriptorHeap (srv)" -- ); -+ { -+ const auto hr = device->CreateDescriptorHeap(&srv_desc, IID_PPV_ARGS(&this->srv_heap)); -+ check_hresult(hr, "CreateDescriptorHeap (srv)"); -+ } - - const auto rtv_desc = D3D12_DESCRIPTOR_HEAP_DESC{ - .Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV, -@@ -156,7 +156,7 @@ texture_2d::texture_2d( - const auto barrier2 = transition_barrier( - this->resource, - D3D12_RESOURCE_STATE_RENDER_TARGET, -- D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE -+ D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE - ); - cmd->ResourceBarrier(1, &barrier2); - }); -@@ -196,7 +196,7 @@ void texture_2d::record_upload_commands(ID3D12GraphicsCommandList* cmd, ID3D12Re - // is needed before the copy; the upload buffer needs to transition to - // COPY_SOURCE - const auto barrier1 = -- transition_barrier(upload_buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); -+ transition_barrier(upload_buffer, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); - cmd->ResourceBarrier(1, &barrier1); - - // the new SDK has no CopyBufferToTexture(); use CopyTextureRegion with a -@@ -227,13 +227,15 @@ void texture_2d::record_upload_commands(ID3D12GraphicsCommandList* cmd, ID3D12Re - cmd->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - -- // the texture is used both as a render target (frame buffers) and as a -- // sampled texture, so transition to both states at once -- const auto barrier2 = transition_barrier( -- this->resource, -- D3D12_RESOURCE_STATE_COPY_DEST, -- D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE -- ); -+ // the texture is used as a sampled texture; the render-target state is -+ // applied when the resource is bound as a render target (frame buffers), -+ // since read-only and write states cannot be combined in one state mask -+ const auto barrier2 = -+ transition_barrier( -+ this->resource, -+ D3D12_RESOURCE_STATE_COPY_DEST, -+ D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE -+ ); - cmd->ResourceBarrier(1, &barrier2); - } - -diff --git a/src/ruis/render/directx/vertex_buffer.cpp b/src/ruis/render/directx/vertex_buffer.cpp -index 0fece43..6a4988e 100644 ---- a/src/ruis/render/directx/vertex_buffer.cpp -+++ b/src/ruis/render/directx/vertex_buffer.cpp -@@ -57,17 +57,15 @@ vertex_buffer::vertex_buffer( - "CreateCommittedResource (vertex buffer, size=%u)", - UINT(this->byte_size) - ); -- check_hresult( -- device->CreateCommittedResource( -- &default_heap_properties(), -- D3D12_HEAP_FLAG_NONE, -- &desc, -- D3D12_RESOURCE_STATE_COPY_DEST, -- nullptr, -- IID_PPV_ARGS(&this->resource) -- ), -- vbuf_msg -+ const auto hr = device->CreateCommittedResource( -+ &default_heap_properties(), -+ D3D12_HEAP_FLAG_NONE, -+ &desc, -+ D3D12_RESOURCE_STATE_COPY_DEST, -+ nullptr, -+ IID_PPV_ARGS(&this->resource) - ); -+ check_hresult(hr, vbuf_msg); - this->gpu_va = this->resource->GetGPUVirtualAddress(); - } - -@@ -81,7 +79,7 @@ vertex_buffer::vertex_buffer( - &upload_heap_properties(), - D3D12_HEAP_FLAG_NONE, - &desc, -- D3D12_RESOURCE_STATE_COMMON, -+ D3D12_RESOURCE_STATE_GENERIC_READ, - nullptr, - IID_PPV_ARGS(&upload) - ), -@@ -96,7 +94,7 @@ vertex_buffer::vertex_buffer( - - dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { - const auto barrier1 = -- transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); -+ transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); - cmd->ResourceBarrier(1, &barrier1); - cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(this->byte_size)); - const auto barrier2 = transition_barrier( diff --git a/.wip_backup.stat b/.wip_backup.stat deleted file mode 100644 index cf44db5..0000000 --- a/.wip_backup.stat +++ /dev/null @@ -1,14 +0,0 @@ - src/ruis/render/directx/context.cpp | 191 +++++++++++++++------- - src/ruis/render/directx/context.hpp | 9 +- - src/ruis/render/directx/device.cpp | 14 ++ - src/ruis/render/directx/directx.cpp | 23 ++- - src/ruis/render/directx/directx.hpp | 49 ++++-- - src/ruis/render/directx/factory.cpp | 14 +- - src/ruis/render/directx/index_buffer.cpp | 6 +- - src/ruis/render/directx/sdk_prelude.hpp | 1 + - src/ruis/render/directx/shaders/shader_common.cpp | 11 ++ - src/ruis/render/directx/shaders/shader_common.hpp | 12 ++ - src/ruis/render/directx/shaders/shader_src.hpp | 94 ++++++++--- - src/ruis/render/directx/texture_2d.cpp | 28 ++-- - src/ruis/render/directx/vertex_buffer.cpp | 22 ++- - 13 files changed, 335 insertions(+), 139 deletions(-) diff --git a/check_rdef.js b/check_rdef.js deleted file mode 100644 index 181b389..0000000 --- a/check_rdef.js +++ /dev/null @@ -1,46 +0,0 @@ -const fs = require('fs'); -const buf = fs.readFileSync(process.argv[2]); -const numChunks = buf.readUInt32LE(28); -for (let i = 0; i < numChunks; i++) { - const off = buf.readUInt32LE(32 + i * 4); - const fourcc = buf.toString('ascii', off, off + 4); - const partLength = buf.readUInt32LE(off + 4); - if (fourcc !== 'RDEF') continue; - const contents = buf.slice(off + 8, off + 8 + partLength); - // cbuffers: CountOffset (offset + count) - const cbufferOffset = contents.readUInt32LE(0); - const cbufferCount = contents.readUInt32LE(4); - const resourceOffset = contents.readUInt32LE(8); - const resourceCount = contents.readUInt32LE(12); - const targetVersion = contents.readUInt16LE(16); - const targetShaderStage = contents.readUInt16LE(18); - const flags = contents.readUInt32LE(20); - console.log(`RDEF: cbufferOffset=${cbufferOffset} cbufferCount=${cbufferCount} resourceOffset=${resourceOffset} resourceCount=${resourceCount} targetVersion=0x${targetVersion.toString(16)} targetShaderStage=0x${targetShaderStage.toString(16)} flags=0x${flags.toString(16)}`); - // cbuffers (24 bytes each): - for (let c = 0; c < cbufferCount; c++) { - const cbStart = cbufferOffset + c * 24; - const nameOffset = contents.readUInt32LE(cbStart); - const memberCount = contents.readUInt32LE(cbStart + 4); - const memberOffset = contents.readUInt32LE(cbStart + 8); - const sizeBytes = contents.readUInt32LE(cbStart + 12); - const alignBytes = contents.readUInt32LE(cbStart + 16); - const name = contents.toString('ascii', nameOffset, nameOffset + 64).split('\0')[0]; - console.log(` cbuffer[${c}] name='${name}' memberCount=${memberCount} memberOffset=${memberOffset} sizeBytes=${sizeBytes} alignBytes=${alignBytes}`); - } - // resources: - for (let r = 0; r < resourceCount; r++) { - const rStart = resourceOffset + r * 40; - const nameOffset = contents.readUInt32LE(rStart); - const type = contents.readUInt32LE(rStart + 4); - const retType = contents.readUInt32LE(rStart + 8); - const dimension = contents.readUInt32LE(rStart + 12); - const sampleCount = contents.readInt32LE(rStart + 16); - const bindPoint = contents.readUInt32LE(rStart + 20); - const bindCount = contents.readUInt32LE(rStart + 24); - const rFlags = contents.readUInt32LE(rStart + 28); - const space = contents.readUInt32LE(rStart + 32); - const id = contents.readUInt32LE(rStart + 36); - const name = contents.toString('ascii', nameOffset, nameOffset + 64).split('\0')[0]; - console.log(` resource[${r}] name='${name}' type=${type} retType=${retType} dimension=${dimension} sampleCount=${sampleCount} bindPoint=${bindPoint} bindCount=${bindCount} flags=0x${rFlags.toString(16)} space=${space} id=${id}`); - } -} diff --git a/dxbc_dump.js b/dxbc_dump.js deleted file mode 100644 index 5aa0345..0000000 --- a/dxbc_dump.js +++ /dev/null @@ -1,41 +0,0 @@ -const fs = require('fs'); -const buf = fs.readFileSync(process.argv[2]); -const numChunks = buf.readUInt32LE(28); -const chunkOffsets = []; -for (let i = 0; i < numChunks; i++) chunkOffsets.push(buf.readUInt32LE(32 + i * 4)); -const SVNAME_MAP = { - 0: 'UNDEFINED', 1: 'POSITION', 2: 'CLIP_DISTANCE', 3: 'CULL_DISTANCE', - 4: 'RENDER_TARGET_ARRAY_INDEX', 5: 'VIEWPORT_ARRAY_INDEX', 6: 'VERTEX_ID', - 7: 'PRIMITIVE_ID', 8: 'INSTANCE_ID', 9: 'IS_FRONT_FACE', 10: 'SAMPLE_INDEX', - 64: 'TARGET', 65: 'DEPTH', 66: 'COVERAGE', 67: 'DEPTH_GREATER_EQUAL', 68: 'DEPTH_LESS_EQUAL', - 69: 'STENCIL_REF', 70: 'INNER_COVERAGE' -}; -for (let i = 0; i < numChunks; i++) { - const off = chunkOffsets[i]; - const chFourcc = buf.toString('ascii', off, off + 4); - const partLength = buf.readUInt32LE(off + 4); - console.log(`\nchunk ${chFourcc} (partLength=${partLength})`); - if (!/^(ISGN|OSGN|ISG1|OSG1|PSG1)$/.test(chFourcc)) continue; - const contentsOffset = off + 8; - const contents = buf.slice(contentsOffset, contentsOffset + partLength); - const numElems = contents.readUInt32LE(0); - const unknown = contents.readUInt32LE(4); - console.log(` numElems=${numElems} unknown=${unknown}`); - const isV1 = chFourcc.endsWith('1'); - const elemSize = isV1 ? 32 : 20; - // ISGN/OSGN: elements are packed at offset 8, 20 bytes each - for (let e = 0; e < numElems; e++) { - const elemStart = 8 + e * elemSize; - const stream = isV1 ? contents.readUInt32LE(elemStart) : null; - const base = isV1 ? elemStart + 4 : elemStart; - const nameOffset = contents.readUInt32LE(base + 0); - const semanticIdx = contents.readUInt32LE(base + 4); - const systemType = contents.readUInt32LE(base + 8); - const componentType = contents.readUInt32LE(base + 12); - const registerNum = contents.readUInt32LE(base + 16); - const mask = contents.readUInt8(base + 20); - const rwMask = contents.readUInt8(base + 21); - const name = contents.toString('ascii', nameOffset, nameOffset + 64).split('\0')[0]; - console.log(` elem[${e}] name='${name}' semanticIdx=${semanticIdx} systemType=${systemType} (${SVNAME_MAP[systemType] || '?'}) componentType=${componentType} registerNum=${registerNum} mask=0x${mask.toString(16)} rwMask=0x${rwMask.toString(16)} stream=${stream}`); - } -} diff --git a/dxbc_parse.js b/dxbc_parse.js deleted file mode 100644 index 5bd7178..0000000 --- a/dxbc_parse.js +++ /dev/null @@ -1,38 +0,0 @@ -const fs = require('fs'); -const path = process.argv[2]; -const buf = fs.readFileSync(path); -let off = 0; -const sig = buf.toString('ascii', off, off + 4); -console.log('signature:', sig); -off = 4; -const hdrSize = buf.readUInt32LE(off); -off = 8; // skip len + version fields (this is just the header start) -// Actually: after 4-byte signature: uint32 version, uint32 headerLength? no -- -// format: "DXBC" (4) then uint32 headerSize? Let's just scan for chunks. -console.log('trying to locate chunks at offset 8...'); -// chunk format: uint32 FourCC, uint32 size, uint32 offset (relative), then data -let p = 8; -const fourccs = { - 'ISGN': 'input signature (legacy)', - 'OSGN': 'output signature (legacy)', - 'ISG1': 'input signature v1', - 'OSG1': 'output signature v1', - 'RDEF': 'resource descriptor info', - 'TEMD': 'temp descriptor', -}; -const seen = new Set(); -while (p + 12 <= buf.length) { - const fourcc = buf.toString('ascii', p, p + 4); - if (!/^[A-Z0-9_]{4}$/.test(fourcc)) break; - const size = buf.readUInt32LE(p + 4); - const fileOffset = buf.readUInt32LE(p + 8); - console.log(`chunk ${fourcc} (${fourccs[fourcc] || '?'}) size=${size} fileOffset=${fileOffset} seen=${seen.has(fourcc)}`); - // try to print the input/output signatures - if (fourcc === 'ISGN' || fourcc === 'OSGN' || fourcc === 'ISG1' || fourcc === 'OSG1') { - const chunkData = buf.slice(8 + fileOffset, 8 + fileOffset + size); - console.log(' raw first 80 bytes:', [...chunkData.slice(0, 80)].map(b => b.toString(16).padStart(2, '0')).join(' ')); - } - p += 12; - if (seen.has(fourcc) && fourcc !== 'ISGN' && fourcc !== 'OSGN') break; - seen.add(fourcc); -} diff --git a/fix_probe2.js b/fix_probe2.js deleted file mode 100644 index 55cf505..0000000 --- a/fix_probe2.js +++ /dev/null @@ -1,9 +0,0 @@ -const fs = require('fs'); -const p = 'src/ruis/render/directx/context.cpp'; -let s = fs.readFileSync(p, 'utf8'); -const old = `\tfprintf(stderr, "get_or_create_pipeline: building pipeline\n");`; -const newLine = `\tfprintf(stderr, "get_or_create_pipeline: building pipeline shader_kind=%d textured=%d a1=%d topology=%s\n", (int)kind, (int)textured, (int)shader_has_a1(kind), to_topology_name(topology));`; -if (!s.includes(old)) { console.error('not found'); process.exit(1); } -s = s.replace(old, newLine); -fs.writeFileSync(p, s); -console.log('OK'); diff --git a/force_color_shader.js b/force_color_shader.js deleted file mode 100644 index d687fb4..0000000 --- a/force_color_shader.js +++ /dev/null @@ -1,10 +0,0 @@ -const fs = require('fs'); -const p = 'src/ruis/render/directx/context.cpp'; -let s = fs.readFileSync(p, 'utf8'); -// force the first pipeline to use the color (position-only) shaders: -const marker = 'const auto pso = this->build_pipeline(key, shader_has_a1(kind), vertex_hlsl, fragment_hlsl);'; -if (!s.includes(marker)) { console.error('not found'); process.exit(1); } -s = s.replace(marker, `// TEMPORARY: force the position-only color shaders - const auto pso = this->build_pipeline(key, false, hlsl_shader_color_vertex, hlsl_shader_color_fragment);`); -fs.writeFileSync(p, s); -console.log('OK'); diff --git a/minimal_desc.js b/minimal_desc.js deleted file mode 100644 index 49fb6b1..0000000 --- a/minimal_desc.js +++ /dev/null @@ -1,25 +0,0 @@ -const fs = require('fs'); -const p = 'src/ruis/render/directx/context.cpp'; -let s = fs.readFileSync(p, 'utf8'); -const start = s.indexOf('\tconst auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{'); -const end = s.indexOf('\t};\n\n\tfprintf(stderr, "build_pipeline: pre-create-call'); -if (start < 0 || end < 0) { console.error('markers not found'); process.exit(1); } -const minimal = `\t// TEMPORARY MINIMAL DESC (vkd3d-style) -\tD3D12_GRAPHICS_PIPELINE_STATE_DESC pipeline_desc{}; -\tpipeline_desc.pRootSignature = this->root_signature; -\tpipeline_desc.VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}; -\tpipeline_desc.PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}; -\tpipeline_desc.StreamOutput.RasterizedStream = 0; -\tpipeline_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; -\tpipeline_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; -\tpipeline_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; -\tpipeline_desc.SampleMask = 0xFFFFFFFF; -\tpipeline_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; -\tpipeline_desc.NumRenderTargets = 1; -\tpipeline_desc.RTVFormats[0] = static_cast(key.rtv_format); -\tpipeline_desc.SampleDesc.Count = 1; -\tpipeline_desc.InputLayout = input_layout; -`; -s = s.slice(0, start) + minimal + s.slice(end + 4); -fs.writeFileSync(p, s); -console.log('OK'); diff --git a/raw_chunk.js b/raw_chunk.js deleted file mode 100644 index d5f0238..0000000 --- a/raw_chunk.js +++ /dev/null @@ -1,15 +0,0 @@ -const fs = require('fs'); -const buf = fs.readFileSync(process.argv[2]); -const numChunks = buf.readUInt32LE(28); -const chunkOffsets = []; -for (let i = 0; i < numChunks; i++) chunkOffsets.push(buf.readUInt32LE(32 + i * 4)); -const chFourcc = buf.toString('ascii', chunkOffsets[1] || 0, chunkOffsets[1] + 4); // ISGN -// let's just dump all chunks -for (let i = 0; i < numChunks; i++) { - const off = chunkOffsets[i]; - const fourcc = buf.toString('ascii', off, off + 4); - const partLength = buf.readUInt32LE(off + 4); - const contents = buf.slice(off + 8, off + 8 + partLength); - console.log(`\n=== chunk ${fourcc} partLength=${partLength} at offset ${off}`); - console.log(' raw:', [...contents].map(b => b.toString(16).padStart(2, '0')).join(' ')); -} diff --git a/strings_dump.js b/strings_dump.js deleted file mode 100644 index 59888be..0000000 --- a/strings_dump.js +++ /dev/null @@ -1,24 +0,0 @@ -const fs = require('fs'); -const buf = fs.readFileSync(process.argv[2]); -const numChunks = buf.readUInt32LE(28); -for (let i = 0; i < numChunks; i++) { - const off = buf.readUInt32LE(32 + i * 4); - const fourcc = buf.toString('ascii', off, off + 4); - const partLength = buf.readUInt32LE(off + 4); - const contents = buf.slice(off + 8, off + 8 + partLength); - if (fourcc !== 'ISGN' && fourcc !== 'OSGN' && fourcc !== 'ISG1' && fourcc !== 'OSG1') continue; - const numElems = contents.readUInt32LE(0); - console.log(`\n=== ${fourcc}: numElems=${numElems}, contents length=${contents.length}`); - for (let e = 0; e < numElems; e++) { - const elemStart = 8 + e * 24; - const nameOffset = contents.readUInt32LE(elemStart); - const semanticIdx = contents.readUInt32LE(elemStart + 4); - const systemType = contents.readUInt32LE(elemStart + 8); - const componentType = contents.readUInt32LE(elemStart + 12); - const registerNum = contents.readUInt32LE(elemStart + 16); - const mask = contents.readUInt8(elemStart + 20); - const rwMask = contents.readUInt8(elemStart + 21); - const name = contents.toString('ascii', nameOffset, contents.length).split('\0')[0]; - console.log(` elem[${e}] name='${name}' semanticIdx=${semanticIdx} systemType=${systemType} componentType=${componentType} registerNum=${registerNum} mask=0x${mask.toString(16)} rwMask=0x${rwMask.toString(16)}`); - } -} From c7e1b2c9b2424b34045b975c31d9e59efc41284c Mon Sep 17 00:00:00 2001 From: Ivan Gagis Date: Sun, 29 Nov 2026 20:54:19 +0200 Subject: [PATCH 8/8] match Vulkan/OpenGL culling: front face counter-clockwise Both Vulkan and OpenGL cull the back face and regard the front face as counter-clockwise. Direct3D previously used FrontCounterClockwise = FALSE (front = CW), inconsistent with the other renderers. --- src/ruis/render/directx/context.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp index fd9a2ed..5a05256 100644 --- a/src/ruis/render/directx/context.cpp +++ b/src/ruis/render/directx/context.cpp @@ -700,6 +700,13 @@ ID3D12PipelineState* context::build_pipeline( depth_stencil.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; depth_stencil.BackFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; + // ---- the pipeline ---- + // Culling / winding: same settings as the Vulkan and OpenGL renderers + // (cull the back face, front face counter-clockwise). For triangle-strip + // primitives the rasterizer automatically adjusts the winding of the + // second and fourth (and so on) triangles so that all triangles in the + // strip have the same facing orientation; the quad indices in ruis do + // not need to be consistent-oriented (see renderer.hpp). const auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{ .pRootSignature = this->root_signature, .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}, @@ -710,7 +717,7 @@ ID3D12PipelineState* context::build_pipeline( D3D12_RASTERIZER_DESC{ .FillMode = D3D12_FILL_MODE_SOLID, .CullMode = D3D12_CULL_MODE_BACK, - .FrontCounterClockwise = FALSE, + .FrontCounterClockwise = TRUE, .DepthBias = 0, .DepthBiasClamp = 0.0f, .SlopeScaledDepthBias = 0.0f,