Debian Codegraph @

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

raw
1 #pragma once
2
3 #include "../RhiTypes.h"
4 #include "../../../Primitives/Rect.h"
5 #include "../../../Primitives/Colorf.h"
6
7 #include <cstdint>
8
9 #include <Containers/SmallVector.h>
10
11 using namespace Death::Containers;
12
13 // Direct3D 11 / DXGI COM interfaces referenced only as opaque pointers here, so <d3d11.h> stays out of the
14 // contract headers the whole pipeline pulls in through Rhi.h — it is included only by D3D11Device.cpp.
15 struct ID3D11Device;
16 struct ID3D11DeviceContext;
17 struct IDXGISwapChain;
18 struct ID3D11RenderTargetView;
19 struct ID3D11Buffer;
20 struct ID3D11BlendState;
21 struct ID3D11DepthStencilState;
22 struct ID3D11RasterizerState;
23 struct ID3D11Texture2D;
24 struct ID3D11ShaderResourceView;
25 struct ID3D11VertexShader;
26 struct ID3D11PixelShader;
27 struct ID3D11SamplerState;
28
29 namespace nCine::RHI::D3D11
30 {
31 class D3D11ShaderProgram;
32 class D3D11RenderTarget;
33 class D3D11Texture;
34
35 /**
36 @brief Pipeline-state and draw-call facade of the Direct3D 11 backend (aliased as `RHI::Device`)
37
38 Exposes the OpenGL device's surface (blending, depth, cull, scissor, viewport, clear and the draw
39 calls) so the backend-neutral render pipeline drives it unchanged.
40
41 The device also owns the real `ID3D11Device`, immediate `ID3D11DeviceContext` and the DXGI
42 `IDXGISwapChain` created from the SDL window (via @ref CreateSwapchain(), called by the SDL window
43 backend). @ref PresentFrame() blits the rendered scene into the back-buffer and presents it (the
44 buffer-swap equivalent).
45 */
46 class D3D11Device
47 {
48 public:
49 D3D11Device() = delete;
50 ~D3D11Device() = delete;
51
52 struct ScissorState
53 {
54 bool Enabled = false;
55 Recti Rect = Recti(0, 0, 0, 0);
56 };
57
58 struct BlendingState
59 {
60 bool Enabled = false;
61 nCine::BlendingFactor SrcRgb = nCine::BlendingFactor::One;
62 nCine::BlendingFactor DstRgb = nCine::BlendingFactor::Zero;
63 nCine::BlendingFactor SrcAlpha = nCine::BlendingFactor::One;
64 nCine::BlendingFactor DstAlpha = nCine::BlendingFactor::Zero;
65 };
66
67 struct DepthTestState
68 {
69 bool TestEnabled = false;
70 bool MaskEnabled = true;
71 };
72
73 struct CullFaceState
74 {
75 bool Enabled = false;
76 CullFaceMode Mode = CullFaceMode::Back;
77 };
78
79 static void SetBlendingEnabled(bool enabled);
80 static void SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha);
81 static BlendingState GetBlendingState();
82 static void SetBlendingState(const BlendingState& state);
83
84 static void SetDepthTestEnabled(bool enabled);
85 static void SetDepthMaskEnabled(bool enabled);
86 static DepthTestState GetDepthTestState();
87 static void SetDepthTestState(const DepthTestState& state);
88
89 static void SetCullFaceEnabled(bool enabled);
90 static CullFaceState GetCullFaceState();
91 static void SetCullFaceState(const CullFaceState& state);
92
93 static ScissorState GetScissorState();
94 static void SetScissorState(const ScissorState& state);
95 static void SetScissor(const Recti& rect);
96 static void SetScissorTestEnabled(bool enabled);
97
98 static Recti GetViewport();
99 static void SetViewport(const Recti& rect);
100 static void InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height);
101
102 static Colorf GetClearColor();
103 static void SetClearColor(const Colorf& color);
104 static void Clear(ClearFlags flags);
105
106 static void DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
107 static void DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances);
108 static void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex);
109 static inline void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t baseVertex) {
110 DrawElements(primitive, numIndices, IndexFormat::UInt16, indexOffset, baseVertex);
111 }
112 static void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex);
113 static inline void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex) {
114 DrawElementsInstanced(primitive, numIndices, IndexFormat::UInt16, indexOffset, numInstances, baseVertex);
115 }
116
117 static FenceHandle InsertFence();
118 static void DeleteFence(FenceHandle& fence);
119 static bool ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs);
120
121 static void SetupInitialState();
122
123 // -- Backend extensions (called by the resource types) --
124
125 /** @brief Records the currently bound shader program */
126 static void BindProgram(D3D11ShaderProgram* program);
127 /** @brief Returns the currently bound shader program */
128 static D3D11ShaderProgram* CurrentProgram();
129 /** @brief Records the texture bound to a texture unit */
130 static void BindTexture(std::uint32_t unit, const D3D11Texture* texture);
131 /** @brief Clears a texture from every unit it is bound to (called from ~D3D11Texture to avoid a dangling pointer) */
132 static void UnbindTexture(const D3D11Texture* texture);
133 /** @brief Returns the texture bound to a texture unit */
134 static const D3D11Texture* GetBoundTexture(std::uint32_t unit);
135 /** @brief Records the host data range bound to a uniform binding point */
136 static void BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size);
137 /** @brief Clears a render target from the device if it is the current one (called from ~D3D11RenderTarget) */
138 static void UnbindRenderTarget(const D3D11RenderTarget* renderTarget);
139 /** @brief Scrubs a released render target view from the last-bound shadow so a recycled pointer can't be mistaken for still bound (called by D3D11RenderTarget whenever it releases an RTV) */
140 static void OnRtvReleased(const ID3D11RenderTargetView* rtv);
141 /** @brief Records the current draw render target (its bound color attachments receive the pixels) */
142 static void SetRenderTarget(D3D11RenderTarget* renderTarget);
143 /** @brief Clears a destroyed program from the device's current-program and shadow-state tracking (called from ~D3D11ShaderProgram) */
144 static void OnProgramDestroyed(const D3D11ShaderProgram* program);
145
146 // -- Direct3D 11 device / swap-chain lifecycle (called by the window backend) --
147
148 /**
149 @brief Creates the D3D11 device, immediate context and DXGI swap chain for the given native window
150
151 Two window kinds are supported, selected at compile time by @ref DEATH_TARGET_WINDOWS_RT:
152 - Desktop (SDL2): @p windowHandle is a native `HWND`; a windowed bitblt swap chain is created via
153 `D3D11CreateDeviceAndSwapChain`.
154 - UWP (Windows Store / Xbox): @p windowHandle is the `CoreWindow` as an opaque `IUnknown*`; a
155 flip-model swap chain is created via `IDXGIFactory2::CreateSwapChainForCoreWindow` (UWP forbids
156 the desktop bitblt swap chain).
157
158 @param windowHandle Native `HWND` (desktop) or `CoreWindow` `IUnknown*` (UWP), passed as a `void*`
159 so the window backend does not need the D3D11/DXGI headers
160 @param width Back-buffer width in pixels
161 @param height Back-buffer height in pixels
162 @param vsync Whether @ref PresentFrame() presents with vertical sync
163 @returns `true` if the device and swap chain were created
164 */
165 static bool CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync);
166 /** @brief Releases the swap chain, context and device */
167 static void DestroySwapchain();
168 /** @brief Resizes the swap-chain back-buffer (releases and recreates the back-buffer RTV around `ResizeBuffers`) */
169 static void ResizeSwapchain(std::int32_t width, std::int32_t height);
170 /** @brief Blits the rendered scene into the back-buffer and presents it (the buffer-swap equivalent) */
171 static void PresentFrame();
172
173 /**
174 @brief Creates an additional swap chain for a secondary window
175
176 Used by the ImGui multi-viewport support to render into the platform windows it spawns when a panel
177 is dragged out of the main window. Unlike the main swap chain, a secondary one is rendered into and
178 presented directly - there is no intermediate present texture, and hence no flip-blit - so
179 @ref BeginSecondaryFrame() also suppresses the projection Y flip for its draws.
180
181 @param windowHandle Native `HWND` of the secondary window, passed as a `void*`
182 @param width Back-buffer width in pixels
183 @param height Back-buffer height in pixels
184 @returns An opaque handle to pass to the other `*Secondary*` functions, or `nullptr` on failure
185 */
186 static void* CreateSecondarySwapchain(void* windowHandle, std::int32_t width, std::int32_t height);
187 /** @brief Releases a secondary swap chain created by @ref CreateSecondarySwapchain() */
188 static void DestroySecondarySwapchain(void* handle);
189 /** @brief Resizes a secondary swap chain's back-buffer */
190 static void ResizeSecondarySwapchain(void* handle, std::int32_t width, std::int32_t height);
191 /** @brief Directs the following draws (and clears) into a secondary swap chain's back-buffer, optionally clearing it first */
192 static void BeginSecondaryFrame(void* handle, bool clear);
193 /** @brief Ends the redirection started by @ref BeginSecondaryFrame() (the next draw targets the main window again) */
194 static void EndSecondaryFrame();
195 /** @brief Presents a secondary swap chain */
196 static void PresentSecondaryFrame(void* handle);
197
198 /** @brief Returns the D3D11 device (for resource creation), or `nullptr` before creation */
199 static ID3D11Device* GetD3DDevice();
200 /** @brief Returns the D3D11 immediate context, or `nullptr` before creation */
201 static ID3D11DeviceContext* GetD3DContext();
202 /** @brief Returns the largest supported 2D texture dimension of the obtained feature level (16384 on 11_0, 8192 on 10.x; consumed by D3D11RhiCapabilities) */
203 static std::int32_t GetMaxTextureDimension();
204
205 private:
206 static constexpr std::uint32_t MaxTextureUnits = 8;
207 static constexpr std::uint32_t MaxUniformBindings = 8;
208 // Simultaneously bound color render targets (matches D3D11RenderTarget::MaxColorAttachments and
209 // D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; asserted in BindCurrentRenderTarget)
210 static constexpr std::uint32_t MaxRenderTargets = 8;
211
212 struct UniformRange
213 {
214 const std::uint8_t* Data = nullptr;
215 std::uint32_t Size = 0;
216 };
217
218 static BlendingState _blending;
219 static DepthTestState _depthTest;
220 static CullFaceState _cullFace;
221 static ScissorState _scissor;
222 static Recti _viewport;
223 static Colorf _clearColor;
224
225 static D3D11ShaderProgram* _currentProgram;
226 static const D3D11Texture* _boundTextures[MaxTextureUnits];
227 static UniformRange _boundUniformRanges[MaxUniformBindings];
228 static D3D11RenderTarget* _currentRenderTarget;
229
230 // Real Direct3D 11 objects (owned)
231 static ID3D11Device* _device;
232 static ID3D11DeviceContext* _context;
233 static IDXGISwapChain* _swapchain;
234 static ID3D11RenderTargetView* _backbufferRtv;
235 static bool _vsync;
236 // DXGI_SWAP_CHAIN_FLAGs the swap chain was actually created with (the presentation model is negotiated
237 // with fallbacks, see CreateSwapchain): ResizeBuffers() must repeat them, and tearing may only be
238 // requested at present time when the chain carries DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING
239 static std::uint32_t _swapchainFlags;
240 static std::int32_t _backbufferWidth;
241 static std::int32_t _backbufferHeight;
242 // Largest 2D texture dimension of the obtained feature level (set by CreateSwapchain)
243 static std::int32_t _maxTextureDimension;
244
245 // The engine renders in the OpenGL convention. The D3D backend replays that faithfully: every draw's
246 // clip-space Y is flipped (projection matrix, see BindConstantBuffers) so all targets - the back-buffer and
247 // every off-screen render target - are stored bottom-up exactly like GL, keeping the scene composite and the
248 // direct-drawn HUD/menu consistent regardless of how many off-screen round-trips a path makes. "Screen"
249 // (no render target) is drawn into this intermediate texture and PresentFrame() flip-blits it into the DXGI
250 // back-buffer (the single GL bottom-up -> D3D top-down scan-out correction, the software backend's
251 // SDL_FLIP_VERTICAL equivalent). A negative-height viewport, the usual remedy, is ignored by the runtime here.
252 static ID3D11Texture2D* _presentTexture;
253 static ID3D11RenderTargetView* _presentRtv;
254 static ID3D11ShaderResourceView* _presentSrv;
255
256 // Set while BeginSecondaryFrame() redirects drawing into a secondary swap chain (an ImGui platform
257 // window): its back-buffer view stands in for the screen target, and because it is presented directly -
258 // without the intermediate texture and its flip-blit - that surface is the one place the backend renders
259 // TOP-DOWN. Both exceptions the orientation implies are keyed on these: no projection Y flip
260 // (BindConstantBuffers) and a flipped scissor rectangle (ApplyRenderState, hence the height).
261 static ID3D11RenderTargetView* _secondaryTargetRtv;
262 static std::int32_t _secondaryTargetHeight;
263 static ID3D11VertexShader* _presentVs;
264 static ID3D11PixelShader* _presentPs;
265 static ID3D11SamplerState* _presentSampler;
266
267 // Dynamic constant-buffer pool: one reusable DYNAMIC buffer per pool slot, updated with WRITE_DISCARD
268 // when its bytes actually change (the driver versions it so previously recorded draws keep their data).
269 // ContentHash/ContentSize cache the bytes last written to the buffer so a draw whose cbuffer is
270 // byte-identical to the pool slot's current contents (e.g. the _Globals/projection block, unchanged
271 // across every draw of a pass) skips the Map/Unmap entirely and only re-binds.
272 struct PooledCBuffer
273 {
274 std::uint32_t Size = 0; // backing buffer capacity (16-aligned), grow-only
275 ID3D11Buffer* Buffer = nullptr;
276 std::uint64_t ContentHash = 0; // xxHash3 of the bytes last uploaded to Buffer
277 std::uint32_t ContentSize = 0; // number of those bytes (0 = buffer just (re)created, cache invalid)
278 };
279 static SmallVector<PooledCBuffer, 0> _cbufferPool;
280 // Reusable scratch for gathering a _Globals cbuffer's scattered loose uniforms into one contiguous
281 // block so it can be hashed and uploaded in a single copy
282 static SmallVector<std::uint8_t, 0> _cbufferStaging;
283
284 // Cached pipeline-state objects, created on demand from the recorded blend/cull/scissor state
285 struct BlendStateEntry
286 {
287 std::uint64_t Key;
288 ID3D11BlendState* State;
289 };
290 static SmallVector<BlendStateEntry, 8> _blendStates;
291 struct RasterStateEntry
292 {
293 std::uint32_t Key;
294 ID3D11RasterizerState* State;
295 };
296 static SmallVector<RasterStateEntry, 8> _rasterStates;
297 static ID3D11DepthStencilState* _depthDisabledState;
298
299 // Last-applied context state (redundant-bind elimination). DrawCommon re-applies everything each draw
300 // and D3D11 does not filter redundant calls itself, so these shadows skip the API call when the value
301 // is unchanged. They are invalidated whenever something else touches the context (the present blit,
302 // resize, device creation) and scrubbed when an object they point to dies (texture SRVs, render-target
303 // RTVs, program shaders), so a recycled pointer can never be mistaken for the one still bound.
304 struct CachedRect
305 {
306 std::int32_t L = 0, T = 0, R = 0, B = 0;
307 };
308 static ID3D11BlendState* _lastBlendState;
309 static ID3D11RasterizerState* _lastRasterState;
310 static bool _depthStateApplied;
311 static ID3D11VertexShader* _lastVs;
312 static ID3D11PixelShader* _lastPs;
313 static std::uint32_t _lastTopology; // D3D11_PRIMITIVE_TOPOLOGY value; 0 (UNDEFINED) = unknown
314 // The RTV set last passed to OMSetRenderTargets (all bound color attachments, in slot order)
315 static ID3D11RenderTargetView* _lastRtvs[MaxRenderTargets];
316 static std::uint32_t _lastRtvCount;
317 static bool _lastRtvValid;
318 static Recti _lastViewport;
319 static bool _lastViewportValid;
320 static CachedRect _lastScissorRect;
321 static bool _lastScissorValid;
322 static ID3D11ShaderResourceView* _lastSrvs[2][MaxTextureUnits]; // [0] = PS stage, [1] = VS stage
323 static ID3D11SamplerState* _lastSamplers[2][MaxTextureUnits];
324 static bool _srvShadowValid;
325
326 /** @brief Forgets all last-applied context state so the next draw re-issues every binding */
327 static void InvalidateCachedState();
328
329 /** @brief Returns the view standing in for the "screen" target: the present texture, or a secondary swap chain's back-buffer while one is bound */
330 static ID3D11RenderTargetView* ScreenRtv();
331
332 /** @brief (Re)creates @ref _backbufferRtv from the current swap-chain back-buffer and binds it */
333 static bool CreateBackbufferRtv();
334 /** @brief (Re)creates the intermediate present texture (RTV+SRV) and the flip-blit shaders/sampler at @p width x @p height */
335 static bool CreatePresentResources(std::int32_t width, std::int32_t height);
336 /** @brief Releases the intermediate present texture and its views (keeps the blit shaders/sampler) */
337 static void ReleasePresentResources();
338 /** @brief Returns the pool slot index of a reusable dynamic constant buffer at least @p size bytes (16-aligned); resets that slot's content cache if the buffer had to be (re)created */
339 static std::uint32_t AcquireConstantBuffer(std::uint32_t size);
340 /** @brief Builds each stage's constant buffers from the current program + bound ranges and binds them */
341 static void BindConstantBuffers();
342 /** @brief Binds the bound textures' SRVs and samplers to the VS and PS stages */
343 static void BindTextures();
344 /** @brief Applies the recorded blend/depth/rasterizer/scissor state to the context */
345 static void ApplyRenderState();
346 /** @brief Binds the currently bound render target (or the back-buffer) as the output */
347 static void BindCurrentRenderTarget();
348 /** @brief Shared body of the draw calls: binds program/state/resources then issues the draw */
349 static void DrawCommon(PrimitiveType primitive, std::int32_t firstVertex, std::uint32_t count,
350 bool indexed, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex);
351 /** @brief Releases the pooled constant buffers and cached state objects */
352 static void ReleasePipelineObjects();
353 };
354 }