Skip to content
18 changes: 18 additions & 0 deletions debian/README.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions debian/changelog
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ruis-render-directx (1.0.0-1) unstable; urgency=medium

* initial version.

-- Ivan Gagis <igagis@gmail.com> Sat, 29 Nov 2026 01:00:00 +0200
198 changes: 124 additions & 74 deletions src/ruis/render/directx/context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <cstring>
#include <stdexcept>
#include <utility>
#include <vector>

#include <utki/windows.hpp>

Expand Down Expand Up @@ -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};
}()
),
Expand Down Expand Up @@ -182,7 +189,7 @@ void context::create_swapchain()
IDXGISwapChain1* sc = nullptr;
check_hresult(
dxgi_factory->CreateSwapChainForHwnd(
reinterpret_cast<IUnknown*>(this->device),
reinterpret_cast<IUnknown*>(this->queue),
this->surface_ref.get().get_hwnd(),
&desc,
nullptr,
Expand Down Expand Up @@ -348,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");
Expand All @@ -367,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;
}
Expand All @@ -393,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]),
Expand Down Expand Up @@ -585,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<const texture_2d&>(*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:
Expand All @@ -602,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;
}
Expand All @@ -635,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");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make a comment here that vs_5_1 is chosen because not all drivers support 6_0?

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<D3D12_INPUT_ELEMENT_DESC>{
{.SemanticName = "POSITION",
Expand All @@ -653,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
}
);
Expand Down Expand Up @@ -696,17 +700,24 @@ 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(), 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,
.FrontCounterClockwise = FALSE,
.CullMode = D3D12_CULL_MODE_BACK,
.FrontCounterClockwise = TRUE,
.DepthBias = 0,
.DepthBiasClamp = 0.0f,
.SlopeScaledDepthBias = 0.0f,
Expand All @@ -721,20 +732,52 @@ 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<DXGI_FORMAT>(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;
}

// 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) {
#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 at all: treat triangle fan as
// unsupported (the check is conservative)
this->triangle_fan_supported_cache = false;
#endif
this->triangle_fan_supported_checked = true;
}
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()) {
throw std::runtime_error("Unsupported: triangle_fan primitive topology");
}
}

ID3D12PipelineState* context::get_or_create_pipeline(
shader_kind kind, //
bool textured,
Expand All @@ -748,7 +791,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);
Expand Down Expand Up @@ -776,30 +820,34 @@ 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<const vertex_buffer&>(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<D3D12_VERTEX_BUFFER_VIEW> 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<const vertex_buffer&>(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
// 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<const index_buffer&>(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)
Expand Down Expand Up @@ -843,11 +891,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<const index_buffer&>(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);
}
}
}

Expand Down Expand Up @@ -875,7 +925,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,
Expand All @@ -892,7 +942,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,
Expand Down Expand Up @@ -941,7 +991,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<uint8_t> pixels(row_pitch * h);
std::vector<uint8_t> pixels(SIZE_T(row_pitch * h));
{
const auto pitch = row_pitch;
D3D12_RANGE read_range{0, SIZE_T(pitch * h)};
Expand All @@ -950,7 +1000,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende
auto* dst = pixels.data();
auto* src = static_cast<const uint8_t*>(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;
}
Expand Down
Loading
Loading