Debian Codegraph @

Sources/nCine/Graphics/RHI/D3D11/D3D11Device.cpp

raw
1 #include "D3D11Device.h"
2 #include "D3D11ShaderProgram.h"
3 #include "D3D11RenderTarget.h"
4 #include "D3D11Texture.h"
5 #include "D3D11BufferObject.h"
6
7 #include <cstdint>
8 #include <cstring>
9 #include <string>
10
11 // The Windows / Direct3D 11 headers are pulled in only by this translation unit
12 #include <d3d11.h>
13 #include <dxgi.h>
14 // IDXGIFactory2 / DXGI_SWAP_CHAIN_DESC1 / CreateSwapChainForCoreWindow (the UWP flip-model swap chain).
15 // dxgi1_2.h extends dxgi.h and is available on both desktop and UWP, so it is included unconditionally.
16 #include <dxgi1_2.h>
17 #include <d3dcompiler.h>
18
19 #include <Asserts.h>
20
21 #include "../../../Base/HashFunctions.h"
22
23 namespace nCine::RHI::D3D11
24 {
25 namespace
26 {
27 template<class T>
28 void SafeRelease(T*& p)
29 {
30 if (p != nullptr) {
31 p->Release();
32 p = nullptr;
33 }
34 }
35
36 // Flip-blit shader used at present: a fullscreen triangle (SV_VertexID) that samples the intermediate present
37 // texture with a vertically flipped V. Every draw is rendered GL-bottom-up (clip-space Y flipped in the
38 // projection, see BindConstantBuffers) into the present texture; this final flip turns that bottom-up
39 // composite into the upright top-down image the DXGI back-buffer scans out.
40 const char* kPresentVs =
41 "struct VOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };\n"
42 "VOut VSMain(uint id : SV_VertexID) {\n"
43 " VOut o;\n"
44 " float2 t = float2((id << 1) & 2, id & 2);\n"
45 " o.pos = float4(t.x * 2.0 - 1.0, 1.0 - t.y * 2.0, 0.0, 1.0);\n"
46 " o.uv = float2(t.x, 1.0 - t.y);\n" // flip V
47 " return o;\n"
48 "}\n";
49 const char* kPresentPs =
50 "Texture2D tex : register(t0);\n"
51 "SamplerState smp : register(s0);\n"
52 "float4 PSMain(float4 pos : SV_Position, float2 uv : TEXCOORD0) : SV_Target {\n"
53 " return tex.Sample(smp, uv);\n"
54 "}\n";
55
56 // Builds a normal (top-down) D3D11 viewport for a target. The GL<->D3D vertical orientation is handled
57 // entirely by flipping clip-space Y in the projection matrix (see BindConstantBuffers) plus the single
58 // flip-blit at present - a negative-height viewport, the usual GL-on-D3D trick, is silently ignored by the
59 // D3D11 runtime here (its sign has no effect), so the viewport is always kept positive.
60 D3D11_VIEWPORT MakeViewport(const Recti& rect)
61 {
62 D3D11_VIEWPORT vp;
63 vp.TopLeftX = static_cast<float>(rect.X);
64 vp.TopLeftY = static_cast<float>(rect.Y);
65 vp.Width = static_cast<float>(rect.W);
66 vp.Height = static_cast<float>(rect.H);
67 vp.MinDepth = 0.0f;
68 vp.MaxDepth = 1.0f;
69 return vp;
70 }
71
72 // Cursor into the constant-buffer pool, reset at the start of each draw's cbuffer build so every
73 // simultaneously-bound cbuffer gets a distinct backing buffer (aliasing them would make the second
74 // WRITE_DISCARD Map discard the first slot's data)
75 std::uint32_t s_cbufferCursor = 0;
76
77 D3D11_PRIMITIVE_TOPOLOGY MapPrimitive(PrimitiveType primitive)
78 {
79 switch (primitive) {
80 case PrimitiveType::Points: return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
81 case PrimitiveType::Lines: return D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
82 case PrimitiveType::LineStrip:
83 case PrimitiveType::LineLoop: return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
84 case PrimitiveType::Triangles: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
85 case PrimitiveType::TriangleStrip:
86 case PrimitiveType::TriangleFan: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
87 default: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
88 }
89 }
90
91 // Compact 0..14 code for a blend factor, so four of them pack into a small collision-free cache key
92 // (the raw enum values are GL constants up to 0x8004 and would not fit into bit fields)
93 std::uint32_t BlendCode(nCine::BlendingFactor factor)
94 {
95 switch (factor) {
96 case nCine::BlendingFactor::Zero: return 0;
97 case nCine::BlendingFactor::One: return 1;
98 case nCine::BlendingFactor::SrcColor: return 2;
99 case nCine::BlendingFactor::OneMinusSrcColor: return 3;
100 case nCine::BlendingFactor::SrcAlpha: return 4;
101 case nCine::BlendingFactor::OneMinusSrcAlpha: return 5;
102 case nCine::BlendingFactor::DstAlpha: return 6;
103 case nCine::BlendingFactor::OneMinusDstAlpha: return 7;
104 case nCine::BlendingFactor::DstColor: return 8;
105 case nCine::BlendingFactor::OneMinusDstColor: return 9;
106 case nCine::BlendingFactor::SrcAlphaSaturate: return 10;
107 case nCine::BlendingFactor::ConstantColor: return 11;
108 case nCine::BlendingFactor::OneMinusConstantColor: return 12;
109 case nCine::BlendingFactor::ConstantAlpha: return 13;
110 case nCine::BlendingFactor::OneMinusConstantAlpha: return 14;
111 default: return 1;
112 }
113 }
114
115 D3D11_BLEND MapBlend(nCine::BlendingFactor factor, bool alpha)
116 {
117 switch (factor) {
118 case nCine::BlendingFactor::Zero: return D3D11_BLEND_ZERO;
119 case nCine::BlendingFactor::One: return D3D11_BLEND_ONE;
120 case nCine::BlendingFactor::SrcColor: return alpha ? D3D11_BLEND_SRC_ALPHA : D3D11_BLEND_SRC_COLOR;
121 case nCine::BlendingFactor::OneMinusSrcColor: return alpha ? D3D11_BLEND_INV_SRC_ALPHA : D3D11_BLEND_INV_SRC_COLOR;
122 case nCine::BlendingFactor::SrcAlpha: return D3D11_BLEND_SRC_ALPHA;
123 case nCine::BlendingFactor::OneMinusSrcAlpha: return D3D11_BLEND_INV_SRC_ALPHA;
124 case nCine::BlendingFactor::DstAlpha: return D3D11_BLEND_DEST_ALPHA;
125 case nCine::BlendingFactor::OneMinusDstAlpha: return D3D11_BLEND_INV_DEST_ALPHA;
126 case nCine::BlendingFactor::DstColor: return alpha ? D3D11_BLEND_DEST_ALPHA : D3D11_BLEND_DEST_COLOR;
127 case nCine::BlendingFactor::OneMinusDstColor: return alpha ? D3D11_BLEND_INV_DEST_ALPHA : D3D11_BLEND_INV_DEST_COLOR;
128 case nCine::BlendingFactor::SrcAlphaSaturate: return D3D11_BLEND_SRC_ALPHA_SAT;
129 case nCine::BlendingFactor::ConstantColor:
130 case nCine::BlendingFactor::ConstantAlpha: return D3D11_BLEND_BLEND_FACTOR;
131 case nCine::BlendingFactor::OneMinusConstantColor:
132 case nCine::BlendingFactor::OneMinusConstantAlpha: return D3D11_BLEND_INV_BLEND_FACTOR;
133 default: return D3D11_BLEND_ONE;
134 }
135 }
136 }
137
138 // -- Static state --
139
140 D3D11Device::BlendingState D3D11Device::_blending;
141 D3D11Device::DepthTestState D3D11Device::_depthTest;
142 D3D11Device::CullFaceState D3D11Device::_cullFace;
143 D3D11Device::ScissorState D3D11Device::_scissor;
144 Recti D3D11Device::_viewport(0, 0, 0, 0);
145 Colorf D3D11Device::_clearColor(0.0f, 0.0f, 0.0f, 0.0f);
146
147 D3D11ShaderProgram* D3D11Device::_currentProgram = nullptr;
148 const D3D11Texture* D3D11Device::_boundTextures[MaxTextureUnits] = {};
149 D3D11Device::UniformRange D3D11Device::_boundUniformRanges[MaxUniformBindings] = {};
150 D3D11RenderTarget* D3D11Device::_currentRenderTarget = nullptr;
151
152 ID3D11Device* D3D11Device::_device = nullptr;
153 ID3D11DeviceContext* D3D11Device::_context = nullptr;
154 IDXGISwapChain* D3D11Device::_swapchain = nullptr;
155 ID3D11RenderTargetView* D3D11Device::_backbufferRtv = nullptr;
156 bool D3D11Device::_vsync = true;
157 std::uint32_t D3D11Device::_swapchainFlags = 0;
158 std::int32_t D3D11Device::_backbufferWidth = 0;
159 std::int32_t D3D11Device::_backbufferHeight = 0;
160 std::int32_t D3D11Device::_maxTextureDimension = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
161 ID3D11Texture2D* D3D11Device::_presentTexture = nullptr;
162 ID3D11RenderTargetView* D3D11Device::_presentRtv = nullptr;
163 ID3D11ShaderResourceView* D3D11Device::_presentSrv = nullptr;
164 ID3D11VertexShader* D3D11Device::_presentVs = nullptr;
165 ID3D11PixelShader* D3D11Device::_presentPs = nullptr;
166 ID3D11SamplerState* D3D11Device::_presentSampler = nullptr;
167 ID3D11RenderTargetView* D3D11Device::_secondaryTargetRtv = nullptr;
168 std::int32_t D3D11Device::_secondaryTargetHeight = 0;
169
170 SmallVector<D3D11Device::PooledCBuffer, 0> D3D11Device::_cbufferPool;
171 SmallVector<std::uint8_t, 0> D3D11Device::_cbufferStaging;
172 SmallVector<D3D11Device::BlendStateEntry, 8> D3D11Device::_blendStates;
173 SmallVector<D3D11Device::RasterStateEntry, 8> D3D11Device::_rasterStates;
174 ID3D11DepthStencilState* D3D11Device::_depthDisabledState = nullptr;
175
176 ID3D11BlendState* D3D11Device::_lastBlendState = nullptr;
177 ID3D11RasterizerState* D3D11Device::_lastRasterState = nullptr;
178 bool D3D11Device::_depthStateApplied = false;
179 ID3D11VertexShader* D3D11Device::_lastVs = nullptr;
180 ID3D11PixelShader* D3D11Device::_lastPs = nullptr;
181 std::uint32_t D3D11Device::_lastTopology = 0;
182 ID3D11RenderTargetView* D3D11Device::_lastRtvs[D3D11Device::MaxRenderTargets] = {};
183 std::uint32_t D3D11Device::_lastRtvCount = 0;
184 bool D3D11Device::_lastRtvValid = false;
185 Recti D3D11Device::_lastViewport(0, 0, 0, 0);
186 bool D3D11Device::_lastViewportValid = false;
187 D3D11Device::CachedRect D3D11Device::_lastScissorRect;
188 bool D3D11Device::_lastScissorValid = false;
189 ID3D11ShaderResourceView* D3D11Device::_lastSrvs[2][D3D11Device::MaxTextureUnits] = {};
190 ID3D11SamplerState* D3D11Device::_lastSamplers[2][D3D11Device::MaxTextureUnits] = {};
191 bool D3D11Device::_srvShadowValid = false;
192
193 void D3D11Device::InvalidateCachedState()
194 {
195 _lastBlendState = nullptr;
196 _lastRasterState = nullptr;
197 _depthStateApplied = false;
198 _lastVs = nullptr;
199 _lastPs = nullptr;
200 _lastTopology = 0;
201 std::memset(_lastRtvs, 0, sizeof(_lastRtvs));
202 _lastRtvCount = 0;
203 _lastRtvValid = false;
204 _lastViewportValid = false;
205 _lastScissorValid = false;
206 std::memset(_lastSrvs, 0, sizeof(_lastSrvs));
207 std::memset(_lastSamplers, 0, sizeof(_lastSamplers));
208 _srvShadowValid = false;
209 }
210
211 // -- Pipeline state (recorded) --
212
213 void D3D11Device::SetBlendingEnabled(bool enabled) { _blending.Enabled = enabled; }
214
215 void D3D11Device::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha)
216 {
217 _blending.SrcRgb = srcRgb;
218 _blending.DstRgb = dstRgb;
219 _blending.SrcAlpha = srcAlpha;
220 _blending.DstAlpha = dstAlpha;
221 }
222
223 D3D11Device::BlendingState D3D11Device::GetBlendingState() { return _blending; }
224 void D3D11Device::SetBlendingState(const BlendingState& state) { _blending = state; }
225
226 void D3D11Device::SetDepthTestEnabled(bool enabled) { _depthTest.TestEnabled = enabled; }
227 void D3D11Device::SetDepthMaskEnabled(bool enabled) { _depthTest.MaskEnabled = enabled; }
228 D3D11Device::DepthTestState D3D11Device::GetDepthTestState() { return _depthTest; }
229 void D3D11Device::SetDepthTestState(const DepthTestState& state) { _depthTest = state; }
230
231 void D3D11Device::SetCullFaceEnabled(bool enabled) { _cullFace.Enabled = enabled; }
232 D3D11Device::CullFaceState D3D11Device::GetCullFaceState() { return _cullFace; }
233 void D3D11Device::SetCullFaceState(const CullFaceState& state) { _cullFace = state; }
234
235 D3D11Device::ScissorState D3D11Device::GetScissorState() { return _scissor; }
236 void D3D11Device::SetScissorState(const ScissorState& state) { _scissor = state; }
237 void D3D11Device::SetScissor(const Recti& rect) { _scissor.Enabled = true; _scissor.Rect = rect; }
238 void D3D11Device::SetScissorTestEnabled(bool enabled) { _scissor.Enabled = enabled; }
239
240 Recti D3D11Device::GetViewport() { return _viewport; }
241
242 void D3D11Device::SetViewport(const Recti& rect)
243 {
244 _viewport = rect;
245 if (_context != nullptr) {
246 D3D11_VIEWPORT vp = MakeViewport(rect);
247 _context->RSSetViewports(1, &vp);
248 _lastViewport = rect;
249 _lastViewportValid = true;
250 }
251 }
252
253 void D3D11Device::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height)
254 {
255 _viewport = Recti(x, y, width, height);
256 }
257
258 Colorf D3D11Device::GetClearColor() { return _clearColor; }
259 void D3D11Device::SetClearColor(const Colorf& color) { _clearColor = color; }
260
261 void D3D11Device::Clear(ClearFlags flags)
262 {
263 if (_context == nullptr) {
264 return;
265 }
266 if ((flags & ClearFlags::Color) != ClearFlags::None) {
267 const float c[4] = { _clearColor.R, _clearColor.G, _clearColor.B, _clearColor.A };
268 if (_currentRenderTarget != nullptr) {
269 // The clear covers every bound color attachment (the contiguous attached run, bounded by the
270 // draw-buffer count), matching glClear's semantics of clearing all enabled draw buffers
271 ID3D11RenderTargetView* rtvs[D3D11RenderTarget::MaxColorAttachments];
272 const std::uint32_t numRtvs = _currentRenderTarget->GetRTVs(rtvs);
273 for (std::uint32_t i = 0; i < numRtvs; i++) {
274 _context->ClearRenderTargetView(rtvs[i], c);
275 }
276 } else {
277 ID3D11RenderTargetView* screenRtv = ScreenRtv();
278 if (screenRtv != nullptr) {
279 _context->ClearRenderTargetView(screenRtv, c);
280 }
281 }
282 }
283 }
284
285 void D3D11Device::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
286 {
287 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices), false, IndexFormat::UInt16, 0, 1, 0);
288 }
289
290 void D3D11Device::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances)
291 {
292 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices), false, IndexFormat::UInt16, 0, numInstances, 0);
293 }
294
295 void D3D11Device::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
296 {
297 DrawCommon(primitive, 0, numIndices, true, indexFormat, indexOffset, 1, baseVertex);
298 }
299
300 void D3D11Device::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
301 {
302 DrawCommon(primitive, 0, numIndices, true, indexFormat, indexOffset, numInstances, baseVertex);
303 }
304
305 void D3D11Device::DrawCommon(PrimitiveType primitive, std::int32_t firstVertex, std::uint32_t count,
306 bool indexed, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
307 {
308 D3D11ShaderProgram* prog = _currentProgram;
309 if (_context == nullptr || prog == nullptr || prog->GetVertexShader() == nullptr || count == 0) {
310 return;
311 }
312
313 BindCurrentRenderTarget();
314
315 // The viewport is always positive/top-down; the GL<->D3D vertical flip is applied uniformly in the vertex
316 // transform (projection matrix Y negated in BindConstantBuffers), which flips every draw to every target
317 // consistently - so back-buffer geometry and off-screen render targets stay in agreement with no present-flip.
318 if (!_lastViewportValid || _lastViewport != _viewport) {
319 D3D11_VIEWPORT vp = MakeViewport(_viewport);
320 _context->RSSetViewports(1, &vp);
321 _lastViewport = _viewport;
322 _lastViewportValid = true;
323 }
324
325 // SV_VertexID shaders (sprites, background, the fullscreen post-processing chain) need no vertex buffer;
326 // attribute-based shaders (mesh sprites, tilemap) bind the input layout + vertex/index buffers built
327 // from the reflected attributes and the vertex format the pipeline defined.
328 if (prog->HasVertexAttributes()) {
329 ID3D11InputLayout* layout = prog->GetInputLayout();
330 const D3D11BufferObject* vbo = prog->GetBoundVbo();
331 const std::uint32_t stride = prog->GetVertexStride();
332 ID3D11Buffer* vb = (vbo != nullptr ? vbo->GetD3DBuffer() : nullptr);
333 if (layout == nullptr || vb == nullptr || stride == 0) {
334 return;
335 }
336 UINT strideU = stride;
337 UINT vbOffset = 0;
338 _context->IASetInputLayout(layout);
339 _context->IASetVertexBuffers(0, 1, &vb, &strideU, &vbOffset);
340 if (indexed) {
341 const D3D11BufferObject* ibo = prog->GetBoundIbo();
342 ID3D11Buffer* ib = (ibo != nullptr ? ibo->GetD3DBuffer() : nullptr);
343 if (ib == nullptr) {
344 return;
345 }
346 _context->IASetIndexBuffer(ib, indexFormat == IndexFormat::UInt32 ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT, 0);
347 }
348 } else {
349 _context->IASetInputLayout(nullptr);
350 }
351
352 const D3D11_PRIMITIVE_TOPOLOGY topology = MapPrimitive(primitive);
353 if (_lastTopology != std::uint32_t(topology)) {
354 _context->IASetPrimitiveTopology(topology);
355 _lastTopology = std::uint32_t(topology);
356 }
357 if (_lastVs != prog->GetVertexShader()) {
358 _lastVs = prog->GetVertexShader();
359 _context->VSSetShader(_lastVs, nullptr, 0);
360 }
361 if (_lastPs != prog->GetPixelShader()) {
362 _lastPs = prog->GetPixelShader();
363 _context->PSSetShader(_lastPs, nullptr, 0);
364 }
365 BindConstantBuffers();
366 BindTextures();
367 ApplyRenderState();
368
369 const UINT indexSize = (indexFormat == IndexFormat::UInt32 ? 4u : 2u);
370 if (indexed) {
371 if (numInstances > 1) {
372 _context->DrawIndexedInstanced(count, std::uint32_t(numInstances), static_cast<UINT>(indexOffset / indexSize), baseVertex, 0);
373 } else {
374 _context->DrawIndexed(count, static_cast<UINT>(indexOffset / indexSize), baseVertex);
375 }
376 } else if (numInstances > 1) {
377 _context->DrawInstanced(count, std::uint32_t(numInstances), std::uint32_t(firstVertex), 0);
378 } else {
379 _context->Draw(count, std::uint32_t(firstVertex));
380 }
381 }
382
383 ID3D11RenderTargetView* D3D11Device::ScreenRtv()
384 {
385 // "Screen" is the intermediate present texture (flip-blitted into the back-buffer at present time), or the
386 // back-buffer itself if that texture is missing - unless drawing is currently redirected into a secondary
387 // swap chain, whose back-buffer then stands in for the screen target
388 if (_secondaryTargetRtv != nullptr) {
389 return _secondaryTargetRtv;
390 }
391 return (_presentRtv != nullptr ? _presentRtv : _backbufferRtv);
392 }
393
394 void D3D11Device::BindCurrentRenderTarget()
395 {
396 static_assert(MaxRenderTargets == D3D11RenderTarget::MaxColorAttachments,
397 "The device's RTV shadow must span every color attachment a render target can hold");
398
399 // "Screen" (no render target bound) is directed into the intermediate present texture; PresentFrame()
400 // flip-blits it into the real back-buffer (the single GL bottom-up -> D3D top-down scan-out correction).
401 // Falls back to the back-buffer if the present texture is absent. An off-screen render target binds
402 // every color attachment it has enabled for drawing (the contiguous attached run, bounded by
403 // SetDrawBuffers - the glDrawBuffers equivalent).
404 ID3D11RenderTargetView* rtvs[MaxRenderTargets] = {};
405 std::uint32_t numRtvs;
406 if (_currentRenderTarget != nullptr) {
407 numRtvs = _currentRenderTarget->GetRTVs(rtvs);
408 if (numRtvs == 0) {
409 // Attachment 0 unusable: keep the historical behavior of explicitly binding a null target
410 numRtvs = 1;
411 }
412 } else {
413 rtvs[0] = ScreenRtv();
414 numRtvs = 1;
415 }
416 if (_lastRtvValid && _lastRtvCount == numRtvs &&
417 std::memcmp(_lastRtvs, rtvs, numRtvs * sizeof(ID3D11RenderTargetView*)) == 0) {
418 return;
419 }
420
421 // Read/write hazard guard: if a texture becoming a render target attachment is still bound as an SRV
422 // from an earlier pass, unbind it explicitly. Without this the runtime silently nulls the SRV slot at
423 // draw time, which would desync the SRV shadow cache (it would still believe the SRV is bound and skip
424 // a later rebind). Covers every bound color attachment, not just attachment 0.
425 if (_currentRenderTarget != nullptr) {
426 ID3D11ShaderResourceView* nullSrv = nullptr;
427 for (std::uint32_t a = 0; a < numRtvs; a++) {
428 const D3D11Texture* rtTex = _currentRenderTarget->GetColorTexture(a);
429 ID3D11ShaderResourceView* rtSrv = (rtTex != nullptr ? rtTex->GetSRV() : nullptr);
430 if (rtSrv == nullptr) {
431 continue;
432 }
433 for (std::uint32_t u = 0; u < MaxTextureUnits; u++) {
434 if (_lastSrvs[0][u] == rtSrv) {
435 _context->PSSetShaderResources(u, 1, &nullSrv);
436 _lastSrvs[0][u] = nullptr;
437 }
438 if (_lastSrvs[1][u] == rtSrv) {
439 _context->VSSetShaderResources(u, 1, &nullSrv);
440 _lastSrvs[1][u] = nullptr;
441 }
442 }
443 }
444 }
445
446 _context->OMSetRenderTargets(numRtvs, rtvs, nullptr);
447 std::memcpy(_lastRtvs, rtvs, sizeof(_lastRtvs));
448 _lastRtvCount = numRtvs;
449 _lastRtvValid = true;
450 }
451
452 std::uint32_t D3D11Device::AcquireConstantBuffer(std::uint32_t size)
453 {
454 std::uint32_t size16 = (size + 15u) & ~15u;
455 if (size16 == 0) {
456 size16 = 16;
457 }
458 if (s_cbufferCursor >= _cbufferPool.size()) {
459 _cbufferPool.push_back(PooledCBuffer{});
460 }
461 PooledCBuffer& entry = _cbufferPool[s_cbufferCursor];
462 if (entry.Buffer == nullptr || entry.Size < size16) {
463 SafeRelease(entry.Buffer);
464 D3D11_BUFFER_DESC desc = {};
465 desc.ByteWidth = size16;
466 desc.Usage = D3D11_USAGE_DYNAMIC;
467 desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
468 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
469 if (FAILED(_device->CreateBuffer(&desc, nullptr, &entry.Buffer))) {
470 entry.Buffer = nullptr;
471 }
472 entry.Size = size16;
473 entry.ContentSize = 0; // fresh buffer: its previous contents are gone, so the skip cache is stale
474 }
475 return s_cbufferCursor++;
476 }
477
478 void D3D11Device::BindConstantBuffers()
479 {
480 D3D11ShaderProgram* prog = _currentProgram;
481 s_cbufferCursor = 0;
482
483 auto buildAndBind = [&](const CBufferSlotList& slots, bool vertexStage) {
484 for (const D3D11CBufferSlot& slot : slots) {
485 std::uint32_t uploadSize = slot.ByteSize;
486 // Assemble the exact bytes to upload into one contiguous span (`srcBytes`), so they can be
487 // hashed against the pool buffer's current contents and copied in a single memcpy.
488 const std::uint8_t* srcBytes = nullptr;
489 if (slot.IsGlobals) {
490 // Loose uniforms are scattered across the program's resolved-value pointers, so gather them
491 // (plus the projection Y-flip) into the reusable staging buffer first.
492 if (_cbufferStaging.size() < uploadSize) {
493 _cbufferStaging.resize(uploadSize);
494 }
495 std::uint8_t* dst = _cbufferStaging.data();
496 std::memset(dst, 0, uploadSize);
497 for (const D3D11CBufferSlot::GlobalVar& gv : slot.Globals) {
498 const std::uint8_t* src = prog->ResolveUniform(gv.Name.c_str());
499 if (src != nullptr && gv.Offset + gv.Size <= uploadSize) {
500 std::memcpy(dst + gv.Offset, src, gv.Size);
501 // Orientation fix: the engine renders in the OpenGL convention, which is upside down on
502 // D3D's top-down back-buffer and render targets (a negative-height viewport, the usual
503 // remedy, is ignored by the D3D11 runtime here). Instead flip clip-space Y for every draw
504 // by negating the projection matrix's second row (indices 1,5,9,13 of the column-major
505 // mat4). Applied uniformly to every shader (all use uProjectionMatrix; ImGui uses
506 // uGuiProjection), this renders every target bottom-up exactly like GL, keeping the scene
507 // composite and direct-drawn HUD consistent; PresentFrame() flip-blits once for D3D scan-out.
508 // The exception is a secondary swap chain (an ImGui platform window): it is presented
509 // directly, with no flip-blit to undo the flip, so it is drawn top-down as D3D expects.
510 if (_secondaryTargetHeight == 0 && gv.Size >= 64 && (gv.Name == "uProjectionMatrix" || gv.Name == "uGuiProjection")) {
511 float* m = reinterpret_cast<float*>(dst + gv.Offset);
512 m[1] = -m[1];
513 m[5] = -m[5];
514 m[9] = -m[9];
515 m[13] = -m[13];
516 }
517 }
518 }
519 srcBytes = dst;
520 } else {
521 if (slot.BlockIndex < 0 || slot.BlockIndex >= std::int32_t(MaxUniformBindings)) {
522 continue;
523 }
524 const std::uint8_t* blockData = _boundUniformRanges[slot.BlockIndex].Data;
525 const std::uint32_t blockSize = _boundUniformRanges[slot.BlockIndex].Size;
526 if (blockData != nullptr) {
527 // A uniform block is bound with exactly the bytes the shader reads (valid instances), so a
528 // buffer sized to the uploaded range is enough and avoids allocating the full declared cbuffer
529 if (blockSize > 0 && blockSize < uploadSize) {
530 uploadSize = blockSize;
531 }
532 srcBytes = blockData;
533 } else {
534 if (_cbufferStaging.size() < uploadSize) {
535 _cbufferStaging.resize(uploadSize);
536 }
537 std::memset(_cbufferStaging.data(), 0, uploadSize);
538 srcBytes = _cbufferStaging.data();
539 }
540 }
541
542 const std::uint32_t poolIndex = AcquireConstantBuffer(uploadSize);
543 PooledCBuffer& entry = _cbufferPool[poolIndex];
544 ID3D11Buffer* cb = entry.Buffer;
545 if (cb == nullptr) {
546 continue;
547 }
548
549 // Skip the Map/Unmap (a driver buffer-rename each draw) when this pool buffer already holds
550 // exactly these bytes. AcquireConstantBuffer() clears ContentSize when it (re)creates the buffer,
551 // so a stale slot never matches. The per-draw cursor keeps simultaneously-bound cbuffers in
552 // distinct slots, so a skip only ever re-binds a buffer that genuinely still holds this data.
553 const std::uint64_t hash = static_cast<std::uint64_t>(xxHash3(reinterpret_cast<const char*>(srcBytes), uploadSize));
554 if (entry.ContentSize != uploadSize || entry.ContentHash != hash) {
555 D3D11_MAPPED_SUBRESOURCE mapped;
556 if (FAILED(_context->Map(cb, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
557 continue;
558 }
559 std::memcpy(mapped.pData, srcBytes, uploadSize);
560 _context->Unmap(cb, 0);
561 entry.ContentHash = hash;
562 entry.ContentSize = uploadSize;
563 }
564
565 if (vertexStage) {
566 _context->VSSetConstantBuffers(slot.Register, 1, &cb);
567 } else {
568 _context->PSSetConstantBuffers(slot.Register, 1, &cb);
569 }
570 }
571 };
572
573 buildAndBind(prog->GetVsCBuffers(), true);
574 buildAndBind(prog->GetPsCBuffers(), false);
575 }
576
577 void D3D11Device::BindTextures()
578 {
579 // Only touch the slots the current program's stages actually read (from bytecode reflection), and skip
580 // the call when the slot already holds this SRV/sampler. The read/write hazard guard: a texture that is
581 // any color attachment of the current render target is never bound as an SRV (the runtime would silently
582 // null it, desyncing the shadow); it re-binds naturally on the first draw after the target changes.
583 const D3D11ShaderProgram* prog = _currentProgram;
584 const std::uint32_t psMask = prog->GetPsTextureMask();
585 const std::uint32_t vsMask = prog->GetVsTextureMask();
586 const D3D11Texture* rtTexs[D3D11RenderTarget::MaxColorAttachments];
587 std::uint32_t numRtTexs = 0;
588 if (_currentRenderTarget != nullptr) {
589 std::uint32_t boundCount = _currentRenderTarget->GetAttachedCount();
590 const std::uint32_t numDrawBuffers = _currentRenderTarget->GetNumDrawBuffers();
591 if (numDrawBuffers > 0 && numDrawBuffers < boundCount) {
592 boundCount = numDrawBuffers;
593 }
594 for (std::uint32_t a = 0; a < boundCount; a++) {
595 const D3D11Texture* rtTex = _currentRenderTarget->GetColorTexture(a);
596 if (rtTex != nullptr) {
597 rtTexs[numRtTexs++] = rtTex;
598 }
599 }
600 }
601 const bool force = !_srvShadowValid;
602
603 std::uint32_t mask = psMask | vsMask;
604 for (std::uint32_t u = 0; u < MaxTextureUnits; u++) {
605 if ((mask & (1u << u)) == 0 && !force) {
606 continue;
607 }
608 const D3D11Texture* tex = _boundTextures[u];
609 for (std::uint32_t a = 0; a < numRtTexs; a++) {
610 if (tex == rtTexs[a]) {
611 tex = nullptr;
612 break;
613 }
614 }
615 ID3D11ShaderResourceView* srv = (tex != nullptr ? tex->GetSRV() : nullptr);
616 ID3D11SamplerState* samp = (tex != nullptr ? tex->GetSampler() : nullptr);
617 if (force || _lastSrvs[0][u] != srv) {
618 _context->PSSetShaderResources(u, 1, &srv);
619 _lastSrvs[0][u] = srv;
620 }
621 if (force || _lastSamplers[0][u] != samp) {
622 _context->PSSetSamplers(u, 1, &samp);
623 _lastSamplers[0][u] = samp;
624 }
625 if (force || _lastSrvs[1][u] != srv) {
626 _context->VSSetShaderResources(u, 1, &srv);
627 _lastSrvs[1][u] = srv;
628 }
629 if (force || _lastSamplers[1][u] != samp) {
630 _context->VSSetSamplers(u, 1, &samp);
631 _lastSamplers[1][u] = samp;
632 }
633 }
634 _srvShadowValid = true;
635 }
636
637 void D3D11Device::ApplyRenderState()
638 {
639 // Blend state (keyed on enabled + the four factors)
640 {
641 std::uint64_t key = (_blending.Enabled ? 1u : 0u);
642 key |= std::uint64_t(BlendCode(_blending.SrcRgb)) << 1;
643 key |= std::uint64_t(BlendCode(_blending.DstRgb)) << 5;
644 key |= std::uint64_t(BlendCode(_blending.SrcAlpha)) << 9;
645 key |= std::uint64_t(BlendCode(_blending.DstAlpha)) << 13;
646 ID3D11BlendState* state = nullptr;
647 for (const BlendStateEntry& e : _blendStates) {
648 if (e.Key == key) {
649 state = e.State;
650 break;
651 }
652 }
653 if (state == nullptr) {
654 // The engine has a single blend state for all attachments (glBlendFunc applies to every draw
655 // buffer), so IndependentBlendEnable stays FALSE (zero-init): D3D11 then applies the
656 // RenderTarget[0] description to every simultaneously bound render target, which is exactly
657 // the GL contract - no per-attachment replication needed.
658 D3D11_BLEND_DESC desc = {};
659 desc.RenderTarget[0].BlendEnable = _blending.Enabled ? TRUE : FALSE;
660 desc.RenderTarget[0].SrcBlend = MapBlend(_blending.SrcRgb, false);
661 desc.RenderTarget[0].DestBlend = MapBlend(_blending.DstRgb, false);
662 desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
663 desc.RenderTarget[0].SrcBlendAlpha = MapBlend(_blending.SrcAlpha, true);
664 desc.RenderTarget[0].DestBlendAlpha = MapBlend(_blending.DstAlpha, true);
665 desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
666 desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
667 if (SUCCEEDED(_device->CreateBlendState(&desc, &state))) {
668 _blendStates.push_back({ key, state });
669 }
670 }
671 if (state != _lastBlendState || state == nullptr) {
672 const float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
673 _context->OMSetBlendState(state, blendFactor, 0xFFFFFFFF);
674 _lastBlendState = state;
675 }
676 }
677
678 // Depth-stencil: the renderer is 2D and no depth buffer is attached, so depth is always disabled
679 if (_depthDisabledState == nullptr) {
680 D3D11_DEPTH_STENCIL_DESC desc = {};
681 desc.DepthEnable = FALSE;
682 desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
683 desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
684 desc.StencilEnable = FALSE;
685 _device->CreateDepthStencilState(&desc, &_depthDisabledState);
686 _depthStateApplied = false;
687 }
688 if (!_depthStateApplied) {
689 _context->OMSetDepthStencilState(_depthDisabledState, 0);
690 _depthStateApplied = true;
691 }
692
693 // Rasterizer (keyed on cull enabled + mode + scissor enabled)
694 {
695 std::uint32_t key = (_cullFace.Enabled ? 1u : 0u) | (std::uint32_t(_cullFace.Mode) << 1) | (_scissor.Enabled ? 0x10000u : 0u);
696 ID3D11RasterizerState* state = nullptr;
697 for (const RasterStateEntry& e : _rasterStates) {
698 if (e.Key == key) {
699 state = e.State;
700 break;
701 }
702 }
703 if (state == nullptr) {
704 D3D11_RASTERIZER_DESC desc = {};
705 desc.FillMode = D3D11_FILL_SOLID;
706 if (!_cullFace.Enabled) {
707 desc.CullMode = D3D11_CULL_NONE;
708 } else {
709 desc.CullMode = (_cullFace.Mode == CullFaceMode::Front ? D3D11_CULL_FRONT : D3D11_CULL_BACK);
710 }
711 desc.FrontCounterClockwise = TRUE; // GL default winding
712 // A command's layer is turned into a clip-space Z spanning the camera's near..far planes, which are
713 // GL's [-1,1] - so the upper half of the 16-bit layer range lands on a negative Z. D3D clips against
714 // [0,w] (unlike GL's [-w,w]), which would silently discard every draw on a layer above ~32767 (the
715 // splitscreen HUD overlay composite, for one). Skipping Z from the clip test keeps the whole layer
716 // range renderable; there is nothing to lose, the renderer is 2D and never attaches a depth buffer
717 // (see the always-disabled depth-stencil state above). Mirrors the Vulkan backend's depth clamp.
718 desc.DepthClipEnable = FALSE;
719 desc.ScissorEnable = _scissor.Enabled ? TRUE : FALSE;
720 if (SUCCEEDED(_device->CreateRasterizerState(&desc, &state))) {
721 _rasterStates.push_back({ key, state });
722 }
723 }
724 if (state != _lastRasterState || state == nullptr) {
725 _context->RSSetState(state);
726 _lastRasterState = state;
727 }
728 }
729
730 // Scissor rectangle. The engine specifies it in GL window space (bottom-left origin), and every draw is
731 // rasterized bottom-up because clip-space Y is flipped in the projection (see BindConstantBuffers), so
732 // virtually every surface drawn into stores its rows bottom-up: off-screen render targets and equally the
733 // intermediate present texture the "screen" path is redirected to. A GL Y therefore maps straight to a
734 // D3D row index (top = glY) - the correction is PresentFrame()'s flip-blit. The real back-buffer is
735 // top-down but is never scissored into (that blit runs with the default rasterizer state, which has
736 // scissoring disabled); a secondary swap chain, drawn top-down because it skips the flip-blit, is not.
737 if (_scissor.Enabled) {
738 const Recti& r = _scissor.Rect;
739 // The one top-down surface is a secondary swap chain's back-buffer (see _secondaryTargetHeight), whose
740 // rows therefore need the standard flip against the target height
741 std::int32_t top = r.Y;
742 if (_secondaryTargetHeight > 0) {
743 top = _secondaryTargetHeight - (r.Y + r.H);
744 }
745 D3D11_RECT sr;
746 // A rectangle may reach outside the target (an ImGui window dragged past the left/top edge gives
747 // negative coordinates); D3D11 rejects negative scissor bounds outright, which would leave the
748 // previous rectangle in effect, so clamp instead - oversized bounds the rasterizer handles itself
749 sr.left = (r.X > 0 ? r.X : 0);
750 sr.top = (top > 0 ? top : 0);
751 sr.right = (r.X + r.W > sr.left ? r.X + r.W : sr.left);
752 sr.bottom = (top + r.H > sr.top ? top + r.H : sr.top);
753 if (!_lastScissorValid || _lastScissorRect.L != sr.left || _lastScissorRect.T != sr.top ||
754 _lastScissorRect.R != sr.right || _lastScissorRect.B != sr.bottom) {
755 _context->RSSetScissorRects(1, &sr);
756 _lastScissorRect = { sr.left, sr.top, sr.right, sr.bottom };
757 _lastScissorValid = true;
758 }
759 }
760 }
761
762 FenceHandle D3D11Device::InsertFence() { return nullptr; }
763 void D3D11Device::DeleteFence(FenceHandle& fence) { fence = nullptr; }
764 bool D3D11Device::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs)
765 {
766 static_cast<void>(fence);
767 static_cast<void>(timeoutNs);
768 return true;
769 }
770
771 void D3D11Device::SetupInitialState()
772 {
773 _blending = BlendingState{};
774 _depthTest = DepthTestState{};
775 _cullFace = CullFaceState{};
776 _scissor = ScissorState{};
777 }
778
779 // -- Backend extensions (recorders) --
780
781 void D3D11Device::BindProgram(D3D11ShaderProgram* program) { _currentProgram = program; }
782 D3D11ShaderProgram* D3D11Device::CurrentProgram() { return _currentProgram; }
783
784 void D3D11Device::BindTexture(std::uint32_t unit, const D3D11Texture* texture)
785 {
786 if (unit < MaxTextureUnits) {
787 _boundTextures[unit] = texture;
788 }
789 }
790
791 void D3D11Device::UnbindTexture(const D3D11Texture* texture)
792 {
793 // Called from ~D3D11Texture so a destroyed texture never lingers as a dangling pointer in the bound-texture
794 // tracking (a later draw would then dereference freed memory in BindTextures - crashed during level changes
795 // in splitscreen). Clear every unit it may be bound to. Only touches the static array (no D3D calls), so it
796 // is safe at any time including shutdown. Mirrors GLTexture's destructor.
797 for (std::uint32_t unit = 0; unit < MaxTextureUnits; unit++) {
798 if (_boundTextures[unit] == texture) {
799 _boundTextures[unit] = nullptr;
800 }
801 }
802 // Scrub the last-bound SRV/sampler shadows too (the views are released right after this call, and a new
803 // texture recycling the same pointer would otherwise be mistaken for still-bound and its bind skipped).
804 // Peek* returns the existing objects without lazily creating them (this runs from the destructor).
805 if (texture != nullptr) {
806 ID3D11ShaderResourceView* srv = texture->PeekSRV();
807 ID3D11SamplerState* samp = texture->PeekSampler();
808 for (std::uint32_t stage = 0; stage < 2; stage++) {
809 for (std::uint32_t unit = 0; unit < MaxTextureUnits; unit++) {
810 if (srv != nullptr && _lastSrvs[stage][unit] == srv) {
811 _lastSrvs[stage][unit] = nullptr;
812 _srvShadowValid = false;
813 }
814 if (samp != nullptr && _lastSamplers[stage][unit] == samp) {
815 _lastSamplers[stage][unit] = nullptr;
816 _srvShadowValid = false;
817 }
818 }
819 }
820 }
821 }
822
823 const D3D11Texture* D3D11Device::GetBoundTexture(std::uint32_t unit)
824 {
825 return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr);
826 }
827
828 void D3D11Device::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size)
829 {
830 if (index < MaxUniformBindings) {
831 _boundUniformRanges[index].Data = data;
832 _boundUniformRanges[index].Size = size;
833 }
834 }
835
836 void D3D11Device::SetRenderTarget(D3D11RenderTarget* renderTarget)
837 {
838 _currentRenderTarget = renderTarget;
839 if (_context != nullptr) {
840 BindCurrentRenderTarget();
841 }
842 }
843
844 void D3D11Device::UnbindRenderTarget(const D3D11RenderTarget* renderTarget)
845 {
846 // Called from ~D3D11RenderTarget so a destroyed render target can't dangle as _currentRenderTarget (a later
847 // Clear/scissor/draw dereferences it). Reverts to the screen (nullptr); the pipeline binds a fresh target
848 // before drawing to it. Only touches the static pointer (no D3D calls), so it is safe at any time.
849 if (_currentRenderTarget == renderTarget) {
850 _currentRenderTarget = nullptr;
851 }
852 // The RTVs are released with the target; forget them so a recycled pointer can't match the shadow
853 std::memset(_lastRtvs, 0, sizeof(_lastRtvs));
854 _lastRtvCount = 0;
855 _lastRtvValid = false;
856 }
857
858 void D3D11Device::OnRtvReleased(const ID3D11RenderTargetView* rtv)
859 {
860 // Called by D3D11RenderTarget whenever it releases one of its views (attachment change, lazy rebuild,
861 // destruction). If the dying view is part of the last-bound shadow, forget the whole set so a new RTV
862 // recycling the same pointer can't be mistaken for still bound (the next draw re-issues the bind).
863 // Only touches the static shadow (no D3D calls), so it is safe at any time including shutdown.
864 if (_lastRtvValid && rtv != nullptr) {
865 for (std::uint32_t i = 0; i < _lastRtvCount; i++) {
866 if (_lastRtvs[i] == rtv) {
867 std::memset(_lastRtvs, 0, sizeof(_lastRtvs));
868 _lastRtvCount = 0;
869 _lastRtvValid = false;
870 break;
871 }
872 }
873 }
874 }
875
876 void D3D11Device::OnProgramDestroyed(const D3D11ShaderProgram* program)
877 {
878 if (_currentProgram == program) {
879 _currentProgram = nullptr;
880 }
881 if (program != nullptr) {
882 if (_lastVs != nullptr && _lastVs == program->GetVertexShader()) {
883 _lastVs = nullptr;
884 }
885 if (_lastPs != nullptr && _lastPs == program->GetPixelShader()) {
886 _lastPs = nullptr;
887 }
888 }
889 }
890
891 // -- Direct3D 11 device / swap-chain lifecycle --
892
893 #if defined(D3D11_MRT_PROBE)
894 namespace
895 {
896 // Synthetic multi-render-target self-test, compiled only when D3D11_MRT_PROBE is defined (no runtime
897 // cost otherwise, mirrors the Vulkan backend's VULKAN_MRT_PROBE). Run once at device creation: attaches
898 // two color textures to one render target, binds both through a single OMSetRenderTargets (the regular
899 // BindCurrentRenderTarget path), verifies the multi-attachment device Clear() covers both, then clears
900 // attachment 0 red and attachment 1 green through their per-attachment RTVs, reads both back through
901 // the regular staging readback and logs PASS/FAIL. Exercises per-attachment RTV creation, the
902 // contiguous multi-attachment bind, multi-attachment clears and the readback path.
903 void RunMrtProbe()
904 {
905 constexpr std::int32_t Size = 4;
906 D3D11Texture tex0(TextureTarget::Texture2D);
907 D3D11Texture tex1(TextureTarget::Texture2D);
908 tex0.TexStorage2D(1, PixelFormat::RGBA8, Size, Size);
909 tex1.TexStorage2D(1, PixelFormat::RGBA8, Size, Size);
910
911 D3D11RenderTarget rt;
912 rt.AttachColorTexture(tex0, 0);
913 rt.AttachColorTexture(tex1, 1);
914 rt.SetDrawBuffers(2);
915 rt.BindDraw(); // one bind covering both attachments (OMSetRenderTargets count 2)
916
917 // Multi-attachment Clear(): both attachments must come out blue from the single call
918 const Colorf previousClearColor = D3D11Device::GetClearColor();
919 D3D11Device::SetClearColor(Colorf(0.0f, 0.0f, 1.0f, 1.0f));
920 D3D11Device::Clear(ClearFlags::Color);
921 D3D11Device::SetClearColor(previousClearColor);
922
923 std::uint8_t px0[Size * Size * 4] = {};
924 std::uint8_t px1[Size * Size * 4] = {};
925 tex0.GetTexImage(0, PixelFormat::RGBA8, false, px0);
926 tex1.GetTexImage(0, PixelFormat::RGBA8, false, px1);
927 bool clearOk = true;
928 for (std::int32_t i = 0; i < Size * Size; i++) {
929 clearOk = clearOk && (px0[i * 4 + 0] == 0 && px0[i * 4 + 1] == 0 && px0[i * 4 + 2] == 255 && px0[i * 4 + 3] == 255);
930 clearOk = clearOk && (px1[i * 4 + 0] == 0 && px1[i * 4 + 1] == 0 && px1[i * 4 + 2] == 255 && px1[i * 4 + 3] == 255);
931 }
932
933 // Distinct per-attachment clears through the lazily created per-attachment RTVs
934 ID3D11DeviceContext* context = D3D11Device::GetD3DContext();
935 ID3D11RenderTargetView* rtv0 = rt.GetRTV(0);
936 ID3D11RenderTargetView* rtv1 = rt.GetRTV(1);
937 if (context == nullptr || rtv0 == nullptr || rtv1 == nullptr) {
938 LOGE("MRT probe FAILED: context={}, rtv0={}, rtv1={}", reinterpret_cast<std::uint64_t>(context),
939 reinterpret_cast<std::uint64_t>(rtv0), reinterpret_cast<std::uint64_t>(rtv1));
940 rt.UnbindDraw();
941 return;
942 }
943 const float red[4] = { 1.0f, 0.0f, 0.0f, 1.0f };
944 const float green[4] = { 0.0f, 1.0f, 0.0f, 1.0f };
945 context->ClearRenderTargetView(rtv0, red);
946 context->ClearRenderTargetView(rtv1, green);
947
948 tex0.GetTexImage(0, PixelFormat::RGBA8, false, px0);
949 tex1.GetTexImage(0, PixelFormat::RGBA8, false, px1);
950 bool ok0 = true, ok1 = true;
951 for (std::int32_t i = 0; i < Size * Size; i++) {
952 ok0 = ok0 && (px0[i * 4 + 0] == 255 && px0[i * 4 + 1] == 0 && px0[i * 4 + 2] == 0 && px0[i * 4 + 3] == 255);
953 ok1 = ok1 && (px1[i * 4 + 0] == 0 && px1[i * 4 + 1] == 255 && px1[i * 4 + 2] == 0 && px1[i * 4 + 3] == 255);
954 }
955 rt.UnbindDraw();
956
957 if (clearOk && ok0 && ok1) {
958 LOGI("MRT probe PASSED: multi-attachment Clear() OK, attachment 0 = red, attachment 1 = green (2-attachment bind / per-attachment RTVs / clears / readback verified)");
959 } else {
960 LOGE("MRT probe FAILED: multi-clear {}, attachment 0 {} (got {},{},{},{}), attachment 1 {} (got {},{},{},{})",
961 clearOk ? "OK" : "WRONG", ok0 ? "OK" : "WRONG", px0[0], px0[1], px0[2], px0[3],
962 ok1 ? "OK" : "WRONG", px1[0], px1[1], px1[2], px1[3]);
963 }
964 }
965 }
966 #endif
967
968 bool D3D11Device::CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync)
969 {
970 _vsync = vsync;
971 _swapchainFlags = 0; // negotiated below on the desktop path; the UWP CoreWindow chain carries no flags
972
973 if (width <= 0) width = 1;
974 if (height <= 0) height = 1;
975
976 const D3D_FEATURE_LEVEL requestedLevels[] = {
977 D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0
978 };
979 const UINT numRequestedLevels = static_cast<UINT>(sizeof(requestedLevels) / sizeof(requestedLevels[0]));
980 D3D_FEATURE_LEVEL obtainedLevel = D3D_FEATURE_LEVEL_11_0;
981
982 // Presentation model of the swap chain, reported in the one summary trace at the end. The UWP CoreWindow
983 // chain below is unconditionally a two-buffer flip-model one with no tearing flag; the desktop path
984 // negotiates its model and overwrites these.
985 const char* swapchainModel = "flip";
986 std::uint32_t swapchainBuffers = 2;
987 bool swapchainTearing = false;
988
989 #if defined(DEATH_TARGET_WINDOWS_RT)
990 // -- UWP (Windows Store / Xbox) path --
991 // UWP has no HWND: the window is a CoreWindow (passed here as an opaque IUnknown*). Create the device
992 // first, then a *flip-model* swap chain bound to the CoreWindow via IDXGIFactory2::CreateSwapChainForCoreWindow.
993 // UWP forbids the desktop bitblt DXGI_SWAP_EFFECT_DISCARD swap chain, so a flip-model swap chain
994 // (FLIP_SEQUENTIAL, BufferCount 2) is mandatory. D3D11_CREATE_DEVICE_BGRA_SUPPORT keeps it interoperable
995 // with Direct2D/DirectWrite and matches the ANGLE/UWP configuration.
996 const UINT createFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
997 HRESULT hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createFlags,
998 requestedLevels, numRequestedLevels, D3D11_SDK_VERSION, &_device, &obtainedLevel, &_context);
999 if (FAILED(hr)) {
1000 LOGW("D3D11CreateDevice (hardware) failed (0x{:.8x}), falling back to WARP", static_cast<std::uint32_t>(hr));
1001 hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createFlags,
1002 requestedLevels, numRequestedLevels, D3D11_SDK_VERSION, &_device, &obtainedLevel, &_context);
1003 }
1004 if (FAILED(hr)) {
1005 LOGE("D3D11CreateDevice failed: 0x{:.8x}", static_cast<std::uint32_t>(hr));
1006 DestroySwapchain();
1007 return false;
1008 }
1009
1010 // Fetch the DXGI factory that owns the device's adapter (needed for CreateSwapChainForCoreWindow)
1011 IDXGIDevice1* dxgiDevice = nullptr;
1012 hr = _device->QueryInterface(__uuidof(IDXGIDevice1), reinterpret_cast<void**>(&dxgiDevice));
1013 if (FAILED(hr) || dxgiDevice == nullptr) {
1014 LOGE("Failed to query IDXGIDevice1 from the Direct3D 11 device: 0x{:.8x}", static_cast<std::uint32_t>(hr));
1015 DestroySwapchain();
1016 return false;
1017 }
1018 // Cap the number of queued frames to reduce latency (Windows Store certification recommendation)
1019 dxgiDevice->SetMaximumFrameLatency(1);
1020
1021 IDXGIAdapter* adapter = nullptr;
1022 IDXGIFactory2* factory = nullptr;
1023 if (SUCCEEDED(dxgiDevice->GetAdapter(&adapter)) && adapter != nullptr) {
1024 adapter->GetParent(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(&factory));
1025 }
1026 SafeRelease(adapter);
1027 SafeRelease(dxgiDevice);
1028 if (factory == nullptr) {
1029 LOGE("Failed to obtain the DXGI factory for the CoreWindow swap chain");
1030 DestroySwapchain();
1031 return false;
1032 }
1033
1034 DXGI_SWAP_CHAIN_DESC1 sd = {};
1035 sd.Width = static_cast<UINT>(width);
1036 sd.Height = static_cast<UINT>(height);
1037 sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1038 sd.Stereo = FALSE;
1039 sd.SampleDesc.Count = 1;
1040 sd.SampleDesc.Quality = 0;
1041 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
1042 sd.BufferCount = 2; // flip-model requires at least two buffers
1043 sd.Scaling = DXGI_SCALING_STRETCH;
1044 sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // flip-model (bitblt DISCARD is illegal on UWP)
1045 sd.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
1046 sd.Flags = 0;
1047
1048 IDXGISwapChain1* swapchain1 = nullptr;
1049 hr = factory->CreateSwapChainForCoreWindow(_device, reinterpret_cast<IUnknown*>(windowHandle), &sd, nullptr, &swapchain1);
1050 SafeRelease(factory);
1051 if (FAILED(hr) || swapchain1 == nullptr) {
1052 LOGE("IDXGIFactory2::CreateSwapChainForCoreWindow() failed: 0x{:.8x}", static_cast<std::uint32_t>(hr));
1053 DestroySwapchain();
1054 return false;
1055 }
1056 _swapchain = swapchain1; // IDXGISwapChain1 derives from IDXGISwapChain
1057 #else
1058 // -- Desktop (SDL2 HWND) path: a windowed swap chain created from the native HWND --
1059 // The *flip model* is preferred over the legacy bitblt one: its buffers can be handed straight to the
1060 // display (DirectFlip) when the window covers the whole output, which is what makes a borderless
1061 // fullscreen window actually cover the taskbar instead of being composited under it - a bitblt swap
1062 // chain always goes through the compositor, so the (topmost) taskbar stays painted on top. It is also
1063 // the lower-latency, lower-power path Microsoft recommends for every new app. The presentation model is
1064 // negotiated downwards, most capable first, because each step needs a newer Windows/DXGI than the last:
1065 // flip + tearing (an uncapped, tearing present with vsync off - the legacy model's behavior, which the
1066 // flip model otherwise replaces with a vblank-paced discard), then plain flip, then legacy bitblt.
1067 auto createDeviceAndSwapchain = [&](D3D_DRIVER_TYPE driverType, DXGI_SWAP_EFFECT swapEffect, UINT flags) -> HRESULT {
1068 // A failed attempt may have handed back some of the objects; start from a clean slate every time
1069 SafeRelease(_swapchain);
1070 SafeRelease(_context);
1071 SafeRelease(_device);
1072 _swapchainFlags = flags;
1073
1074 DXGI_SWAP_CHAIN_DESC sd = {};
1075 // The flip model requires at least two buffers (and forbids multisampling, which is unused here)
1076 sd.BufferCount = (swapEffect == DXGI_SWAP_EFFECT_DISCARD ? 1 : 2);
1077 sd.BufferDesc.Width = static_cast<UINT>(width);
1078 sd.BufferDesc.Height = static_cast<UINT>(height);
1079 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1080 sd.BufferDesc.RefreshRate.Numerator = 0;
1081 sd.BufferDesc.RefreshRate.Denominator = 1;
1082 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
1083 sd.OutputWindow = reinterpret_cast<HWND>(windowHandle);
1084 sd.SampleDesc.Count = 1;
1085 sd.SampleDesc.Quality = 0;
1086 sd.Windowed = TRUE;
1087 sd.SwapEffect = swapEffect;
1088 sd.Flags = flags;
1089
1090 return D3D11CreateDeviceAndSwapChain(nullptr, driverType, nullptr, 0,
1091 requestedLevels, numRequestedLevels, D3D11_SDK_VERSION,
1092 &sd, &_swapchain, &_device, &obtainedLevel, &_context);
1093 };
1094 auto negotiateSwapchain = [&](D3D_DRIVER_TYPE driverType) -> HRESULT {
1095 HRESULT result = createDeviceAndSwapchain(driverType, DXGI_SWAP_EFFECT_FLIP_DISCARD, DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING);
1096 if (FAILED(result)) {
1097 result = createDeviceAndSwapchain(driverType, DXGI_SWAP_EFFECT_FLIP_DISCARD, 0);
1098 }
1099 if (FAILED(result)) {
1100 result = createDeviceAndSwapchain(driverType, DXGI_SWAP_EFFECT_DISCARD, 0);
1101 }
1102 return result;
1103 };
1104
1105 HRESULT hr = negotiateSwapchain(D3D_DRIVER_TYPE_HARDWARE);
1106 if (FAILED(hr)) {
1107 LOGW("D3D11CreateDeviceAndSwapChain (hardware) failed (0x{:.8x}), falling back to WARP", static_cast<std::uint32_t>(hr));
1108 hr = negotiateSwapchain(D3D_DRIVER_TYPE_WARP);
1109 }
1110
1111 if (FAILED(hr)) {
1112 LOGE("D3D11CreateDeviceAndSwapChain failed: 0x{:.8x}", static_cast<std::uint32_t>(hr));
1113 DestroySwapchain();
1114 return false;
1115 }
1116
1117 {
1118 // Remember the negotiated model for the summary trace below - it is worth knowing when a presentation
1119 // problem is reported (a bitblt chain cannot cover the taskbar in borderless fullscreen, nor tear)
1120 DXGI_SWAP_CHAIN_DESC obtained = {};
1121 if (SUCCEEDED(_swapchain->GetDesc(&obtained))) {
1122 swapchainModel = (obtained.SwapEffect == DXGI_SWAP_EFFECT_DISCARD || obtained.SwapEffect == DXGI_SWAP_EFFECT_SEQUENTIAL ? "bitblt" : "flip");
1123 swapchainBuffers = static_cast<std::uint32_t>(obtained.BufferCount);
1124 }
1125 swapchainTearing = ((_swapchainFlags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0);
1126 }
1127
1128 // DXGI hooks the output window and turns Alt+Enter into its own exclusive-fullscreen toggle. The game
1129 // drives fullscreen itself (F11 / Alt+Enter -> a borderless window sized to the display, through SDL),
1130 // so both handlers would react to the same keystroke and leave the window and the swap chain
1131 // disagreeing about the fullscreen state. Opt out and leave SDL as the only authority.
1132 {
1133 IDXGIFactory* factory = nullptr;
1134 if (SUCCEEDED(_swapchain->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory))) && factory != nullptr) {
1135 factory->MakeWindowAssociation(reinterpret_cast<HWND>(windowHandle), DXGI_MWA_NO_ALT_ENTER);
1136 SafeRelease(factory);
1137 }
1138 }
1139 #endif
1140
1141 // The real texture-dimension limit of the obtained feature level: D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION
1142 // (16384) on 11_x, 8192 (the D3D10_REQ_ equivalent) on the 10.x fallback levels
1143 _maxTextureDimension = (obtainedLevel >= D3D_FEATURE_LEVEL_11_0 ? D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION : 8192);
1144
1145 if (!CreateBackbufferRtv()) {
1146 DestroySwapchain();
1147 return false;
1148 }
1149
1150 _backbufferWidth = width;
1151 _backbufferHeight = height;
1152 CreatePresentResources(width, height);
1153
1154 SetViewport(Recti(0, 0, width, height));
1155
1156 LOGI("Direct3D 11 device created (feature level {}.{}), {}x{} {}-model swap chain ({} buffers, tearing {})",
1157 (static_cast<int>(obtainedLevel) >> 12) & 0xF, (static_cast<int>(obtainedLevel) >> 8) & 0xF, width, height,
1158 swapchainModel, swapchainBuffers, swapchainTearing ? "allowed" : "unavailable");
1159
1160 #if defined(D3D11_MRT_PROBE)
1161 RunMrtProbe();
1162 #endif
1163 return true;
1164 }
1165
1166 bool D3D11Device::CreateBackbufferRtv()
1167 {
1168 if (_device == nullptr || _swapchain == nullptr) {
1169 return false;
1170 }
1171
1172 ID3D11Texture2D* backBuffer = nullptr;
1173 HRESULT hr = _swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer));
1174 if (FAILED(hr) || backBuffer == nullptr) {
1175 LOGE("IDXGISwapChain::GetBuffer() failed: 0x{:.8x}", static_cast<std::uint32_t>(hr));
1176 return false;
1177 }
1178
1179 hr = _device->CreateRenderTargetView(backBuffer, nullptr, &_backbufferRtv);
1180 backBuffer->Release();
1181 if (FAILED(hr)) {
1182 LOGE("ID3D11Device::CreateRenderTargetView() failed: 0x{:.8x}", static_cast<std::uint32_t>(hr));
1183 return false;
1184 }
1185
1186 _context->OMSetRenderTargets(1, &_backbufferRtv, nullptr);
1187 InvalidateCachedState();
1188 return true;
1189 }
1190
1191 void D3D11Device::ResizeSwapchain(std::int32_t width, std::int32_t height)
1192 {
1193 if (_swapchain == nullptr || _context == nullptr || width <= 0 || height <= 0) {
1194 return;
1195 }
1196
1197 _context->OMSetRenderTargets(0, nullptr, nullptr);
1198 SafeRelease(_backbufferRtv);
1199
1200 // The creation flags must be repeated here (0 would silently drop DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING and
1201 // make the next tearing present fail); 0 buffers / DXGI_FORMAT_UNKNOWN keep the existing count and format
1202 HRESULT hr = _swapchain->ResizeBuffers(0, static_cast<UINT>(width), static_cast<UINT>(height),
1203 DXGI_FORMAT_UNKNOWN, static_cast<UINT>(_swapchainFlags));
1204 if (FAILED(hr)) {
1205 LOGE("IDXGISwapChain::ResizeBuffers() failed: 0x{:.8x}", static_cast<std::uint32_t>(hr));
1206 return;
1207 }
1208
1209 CreateBackbufferRtv();
1210 _backbufferWidth = width;
1211 _backbufferHeight = height;
1212 CreatePresentResources(width, height);
1213 SetViewport(Recti(0, 0, width, height));
1214 }
1215
1216 bool D3D11Device::CreatePresentResources(std::int32_t width, std::int32_t height)
1217 {
1218 if (_device == nullptr || width <= 0 || height <= 0) {
1219 return false;
1220 }
1221
1222 ReleasePresentResources();
1223
1224 D3D11_TEXTURE2D_DESC desc = {};
1225 desc.Width = static_cast<UINT>(width);
1226 desc.Height = static_cast<UINT>(height);
1227 desc.MipLevels = 1;
1228 desc.ArraySize = 1;
1229 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1230 desc.SampleDesc.Count = 1;
1231 desc.Usage = D3D11_USAGE_DEFAULT;
1232 desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
1233 if (FAILED(_device->CreateTexture2D(&desc, nullptr, &_presentTexture))) {
1234 return false;
1235 }
1236 _device->CreateRenderTargetView(_presentTexture, nullptr, &_presentRtv);
1237 _device->CreateShaderResourceView(_presentTexture, nullptr, &_presentSrv);
1238
1239 // Compile the flip-blit shaders and sampler once (kept across resizes)
1240 if (_presentVs == nullptr || _presentPs == nullptr) {
1241 ID3DBlob* vsBlob = nullptr;
1242 ID3DBlob* psBlob = nullptr;
1243 if (SUCCEEDED(D3DCompile(kPresentVs, std::strlen(kPresentVs), nullptr, nullptr, nullptr, "VSMain", "vs_4_0", 0, 0, &vsBlob, nullptr)) &&
1244 SUCCEEDED(D3DCompile(kPresentPs, std::strlen(kPresentPs), nullptr, nullptr, nullptr, "PSMain", "ps_4_0", 0, 0, &psBlob, nullptr))) {
1245 _device->CreateVertexShader(vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), nullptr, &_presentVs);
1246 _device->CreatePixelShader(psBlob->GetBufferPointer(), psBlob->GetBufferSize(), nullptr, &_presentPs);
1247 } else {
1248 LOGE("Failed to compile the Direct3D 11 present flip-blit shaders");
1249 }
1250 SafeRelease(vsBlob);
1251 SafeRelease(psBlob);
1252 }
1253 if (_presentSampler == nullptr) {
1254 D3D11_SAMPLER_DESC sd = {};
1255 sd.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
1256 sd.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
1257 sd.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
1258 sd.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
1259 sd.ComparisonFunc = D3D11_COMPARISON_NEVER;
1260 sd.MaxLOD = D3D11_FLOAT32_MAX;
1261 _device->CreateSamplerState(&sd, &_presentSampler);
1262 }
1263 return true;
1264 }
1265
1266 void D3D11Device::ReleasePresentResources()
1267 {
1268 SafeRelease(_presentSrv);
1269 SafeRelease(_presentRtv);
1270 SafeRelease(_presentTexture);
1271 }
1272
1273 void D3D11Device::PresentFrame()
1274 {
1275 // Every draw was rendered GL-bottom-up (clip-space Y flipped in the projection) into the present texture;
1276 // flip-blit it vertically into the real back-buffer, then present. This is the single GL->D3D scan-out
1277 // correction (the software backend's SDL_FLIP_VERTICAL equivalent), applied only at the final output so it
1278 // is uniform across every path regardless of how many off-screen round-trips it made.
1279 if (_context != nullptr && _backbufferRtv != nullptr && _presentSrv != nullptr &&
1280 _presentVs != nullptr && _presentPs != nullptr) {
1281 _context->OMSetRenderTargets(1, &_backbufferRtv, nullptr);
1282 D3D11_VIEWPORT vp;
1283 vp.TopLeftX = 0.0f;
1284 vp.TopLeftY = 0.0f;
1285 vp.Width = static_cast<float>(_backbufferWidth);
1286 vp.Height = static_cast<float>(_backbufferHeight);
1287 vp.MinDepth = 0.0f;
1288 vp.MaxDepth = 1.0f;
1289 _context->RSSetViewports(1, &vp);
1290 _context->IASetInputLayout(nullptr);
1291 _context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1292 _context->RSSetState(nullptr);
1293 _context->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);
1294 _context->VSSetShader(_presentVs, nullptr, 0);
1295 _context->PSSetShader(_presentPs, nullptr, 0);
1296 _context->PSSetShaderResources(0, 1, &_presentSrv);
1297 _context->PSSetSamplers(0, 1, &_presentSampler);
1298 _context->Draw(3, 0);
1299 // Unbind so the present texture can be bound as a render target again next frame (no read/write hazard)
1300 ID3D11ShaderResourceView* nullSrv = nullptr;
1301 _context->PSSetShaderResources(0, 1, &nullSrv);
1302 // The blit bound its own shaders/state/target directly; drop the shadow state so the next frame's
1303 // first draw re-issues everything
1304 InvalidateCachedState();
1305 }
1306 if (_swapchain != nullptr) {
1307 // With vsync off, a flip-model chain created with ALLOW_TEARING must also be *presented* with the
1308 // tearing flag to actually run uncapped; without it the flip model paces every present to vblank
1309 // (the flag is only legal at sync interval 0, which is exactly the vsync-off case)
1310 const UINT presentFlags = (!_vsync && (_swapchainFlags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0
1311 ? DXGI_PRESENT_ALLOW_TEARING : 0u);
1312 _swapchain->Present(_vsync ? 1 : 0, presentFlags);
1313 }
1314 }
1315
1316 namespace
1317 {
1318 // Opaque payload behind the void* handle the *Secondary* functions hand out (ImGui keeps it in
1319 // ImGuiViewport::RendererUserData). Deliberately not a member type: nothing outside this file needs it.
1320 struct SecondarySwapchain
1321 {
1322 IDXGISwapChain* Swapchain = nullptr;
1323 ID3D11RenderTargetView* Rtv = nullptr;
1324 std::int32_t Width = 0;
1325 std::int32_t Height = 0;
1326 };
1327 }
1328
1329 void* D3D11Device::CreateSecondarySwapchain(void* windowHandle, std::int32_t width, std::int32_t height)
1330 {
1331 if (_device == nullptr || _swapchain == nullptr || windowHandle == nullptr) {
1332 return nullptr;
1333 }
1334 if (width <= 0) width = 1;
1335 if (height <= 0) height = 1;
1336
1337 // Every swap chain of a device must come from the factory that owns its adapter - reuse the main one's
1338 IDXGIFactory* factory = nullptr;
1339 if (FAILED(_swapchain->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory))) || factory == nullptr) {
1340 LOGE("Failed to obtain the DXGI factory for a secondary swap chain");
1341 return nullptr;
1342 }
1343
1344 // Same presentation-model preference as the main window (flip first, bitblt as the fallback), without
1345 // tearing: these windows carry UI, not gameplay, so they always present at the display's pace
1346 auto createChain = [&](DXGI_SWAP_EFFECT swapEffect) -> IDXGISwapChain* {
1347 DXGI_SWAP_CHAIN_DESC sd = {};
1348 sd.BufferCount = (swapEffect == DXGI_SWAP_EFFECT_DISCARD ? 1 : 2);
1349 sd.BufferDesc.Width = static_cast<UINT>(width);
1350 sd.BufferDesc.Height = static_cast<UINT>(height);
1351 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1352 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
1353 sd.OutputWindow = reinterpret_cast<HWND>(windowHandle);
1354 sd.SampleDesc.Count = 1;
1355 sd.Windowed = TRUE;
1356 sd.SwapEffect = swapEffect;
1357 IDXGISwapChain* result = nullptr;
1358 if (FAILED(factory->CreateSwapChain(_device, &sd, &result))) {
1359 return nullptr;
1360 }
1361 return result;
1362 };
1363
1364 IDXGISwapChain* chain = createChain(DXGI_SWAP_EFFECT_FLIP_DISCARD);
1365 if (chain == nullptr) {
1366 chain = createChain(DXGI_SWAP_EFFECT_DISCARD);
1367 }
1368 // The Alt+Enter association is deliberately left pointing at the main window (it is per factory, so
1369 // re-associating it here would move DXGI's fullscreen handling onto a transient UI window)
1370 SafeRelease(factory);
1371 if (chain == nullptr) {
1372 LOGE("Failed to create a secondary swap chain");
1373 return nullptr;
1374 }
1375
1376 SecondarySwapchain* sc = new SecondarySwapchain();
1377 sc->Swapchain = chain;
1378 sc->Width = width;
1379 sc->Height = height;
1380
1381 ID3D11Texture2D* backBuffer = nullptr;
1382 if (SUCCEEDED(chain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer))) && backBuffer != nullptr) {
1383 _device->CreateRenderTargetView(backBuffer, nullptr, &sc->Rtv);
1384 backBuffer->Release();
1385 }
1386 if (sc->Rtv == nullptr) {
1387 LOGE("Failed to create the render target view of a secondary swap chain");
1388 DestroySecondarySwapchain(sc);
1389 return nullptr;
1390 }
1391 return sc;
1392 }
1393
1394 void D3D11Device::DestroySecondarySwapchain(void* handle)
1395 {
1396 SecondarySwapchain* sc = static_cast<SecondarySwapchain*>(handle);
1397 if (sc == nullptr) {
1398 return;
1399 }
1400 if (_secondaryTargetRtv == sc->Rtv) {
1401 EndSecondaryFrame();
1402 }
1403 if (sc->Rtv != nullptr) {
1404 // Scrub the view from the last-bound shadow first: it is released right below and a new view
1405 // recycling the same pointer would otherwise be mistaken for still bound and its bind skipped
1406 OnRtvReleased(sc->Rtv);
1407 }
1408 SafeRelease(sc->Rtv);
1409 SafeRelease(sc->Swapchain);
1410 delete sc;
1411 }
1412
1413 void D3D11Device::ResizeSecondarySwapchain(void* handle, std::int32_t width, std::int32_t height)
1414 {
1415 SecondarySwapchain* sc = static_cast<SecondarySwapchain*>(handle);
1416 if (sc == nullptr || sc->Swapchain == nullptr || _device == nullptr || width <= 0 || height <= 0) {
1417 return;
1418 }
1419 if (sc->Width == width && sc->Height == height) {
1420 return;
1421 }
1422
1423 // Every reference to the back-buffer must be gone before ResizeBuffers
1424 if (_secondaryTargetRtv == sc->Rtv) {
1425 EndSecondaryFrame();
1426 }
1427 if (sc->Rtv != nullptr) {
1428 OnRtvReleased(sc->Rtv);
1429 }
1430 SafeRelease(sc->Rtv);
1431
1432 if (FAILED(sc->Swapchain->ResizeBuffers(0, static_cast<UINT>(width), static_cast<UINT>(height), DXGI_FORMAT_UNKNOWN, 0))) {
1433 LOGE("IDXGISwapChain::ResizeBuffers() failed for a secondary swap chain");
1434 return;
1435 }
1436 sc->Width = width;
1437 sc->Height = height;
1438
1439 ID3D11Texture2D* backBuffer = nullptr;
1440 if (SUCCEEDED(sc->Swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer))) && backBuffer != nullptr) {
1441 _device->CreateRenderTargetView(backBuffer, nullptr, &sc->Rtv);
1442 backBuffer->Release();
1443 }
1444 }
1445
1446 void D3D11Device::BeginSecondaryFrame(void* handle, bool clear)
1447 {
1448 SecondarySwapchain* sc = static_cast<SecondarySwapchain*>(handle);
1449 if (_context == nullptr || sc == nullptr || sc->Rtv == nullptr) {
1450 return;
1451 }
1452
1453 // The redirection works through the "screen" target (see ScreenRtv()), so any off-screen render target
1454 // left bound by the scene must be cleared first, and the shadow state dropped so the next draw rebinds
1455 _currentRenderTarget = nullptr;
1456 _secondaryTargetRtv = sc->Rtv;
1457 _secondaryTargetHeight = sc->Height;
1458 InvalidateCachedState();
1459
1460 if (clear) {
1461 const float black[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
1462 _context->ClearRenderTargetView(sc->Rtv, black);
1463 }
1464 }
1465
1466 void D3D11Device::EndSecondaryFrame()
1467 {
1468 if (_secondaryTargetRtv == nullptr) {
1469 return;
1470 }
1471 _secondaryTargetRtv = nullptr;
1472 _secondaryTargetHeight = 0;
1473 // The next draw must not keep writing into the window that is no longer bound
1474 InvalidateCachedState();
1475 }
1476
1477 void D3D11Device::PresentSecondaryFrame(void* handle)
1478 {
1479 SecondarySwapchain* sc = static_cast<SecondarySwapchain*>(handle);
1480 if (sc != nullptr && sc->Swapchain != nullptr) {
1481 sc->Swapchain->Present(0, 0);
1482 }
1483 }
1484
1485 void D3D11Device::ReleasePipelineObjects()
1486 {
1487 for (PooledCBuffer& e : _cbufferPool) {
1488 SafeRelease(e.Buffer);
1489 }
1490 _cbufferPool.clear();
1491 for (BlendStateEntry& e : _blendStates) {
1492 SafeRelease(e.State);
1493 }
1494 _blendStates.clear();
1495 for (RasterStateEntry& e : _rasterStates) {
1496 SafeRelease(e.State);
1497 }
1498 _rasterStates.clear();
1499 SafeRelease(_depthDisabledState);
1500 }
1501
1502 void D3D11Device::DestroySwapchain()
1503 {
1504 if (_context != nullptr) {
1505 _context->OMSetRenderTargets(0, nullptr, nullptr);
1506 _context->ClearState();
1507 _context->Flush();
1508 }
1509 // Secondary swap chains are owned by whoever created them (ImGui destroys its platform windows on
1510 // shutdown); just make sure a redirection cannot outlive the device
1511 _secondaryTargetRtv = nullptr;
1512 _secondaryTargetHeight = 0;
1513 InvalidateCachedState();
1514 ReleasePipelineObjects();
1515 ReleasePresentResources();
1516 SafeRelease(_presentSampler);
1517 SafeRelease(_presentPs);
1518 SafeRelease(_presentVs);
1519 SafeRelease(_backbufferRtv);
1520 SafeRelease(_swapchain);
1521 SafeRelease(_context);
1522 SafeRelease(_device);
1523 _swapchainFlags = 0;
1524 }
1525
1526 ID3D11Device* D3D11Device::GetD3DDevice() { return _device; }
1527 ID3D11DeviceContext* D3D11Device::GetD3DContext() { return _context; }
1528
1529 std::int32_t D3D11Device::GetMaxTextureDimension() { return _maxTextureDimension; }
1530 }