SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
DirectX11Renderer.cpp
Go to the documentation of this file.
2#ifdef PLATFORM_WIN
3
4#include <SDL3/SDL.h>
5#include <d3dcompiler.h>
6#include <dxgidebug.h>
7#include <imgui_internal.h>
8#include <psapi.h>
9#include <windows.h>
10#include <wrl/client.h>
11
12#include <Core/Window.hpp>
16#include <Runtime/MeshData.hpp>
17#include <algorithm>
18#include <cstring>
19#include <string>
20#include <thread>
21#include <vector>
22
26
27namespace Sleak {
28 namespace RenderEngine {
29
30 namespace {
31
32 constexpr const char* TONEMAP_SHADER_PATH = "assets/shaders/tonemap.hlsl";
33#ifdef SLEAK_HOT_RELOAD
34 constexpr const char* TONEMAP_STEM = "tonemap";
35#endif
36
37 // Transform CB layout: [WVP][World]; shadow CB: [LightVP*World][World]
38 constexpr int MATRIX_DIM = 4;
39 constexpr int MATRIX_FLOATS = MATRIX_DIM * MATRIX_DIM;
40 constexpr int TRANSFORM_CB_FLOATS = 2 * MATRIX_FLOATS;
41 constexpr UINT TRANSFORM_CB_BYTES = TRANSFORM_CB_FLOATS * sizeof(float);
42 constexpr size_t TRANSFORM_WORLD_OFFSET = MATRIX_FLOATS * sizeof(float);
43
44 /// Writes World * LightVP (row-major) followed by World into out.
45 void BuildShadowTransform(const float* world, const float* lightVP,
46 float* out) {
47 for (int r = 0; r < MATRIX_DIM; ++r) {
48 for (int c = 0; c < MATRIX_DIM; ++c) {
49 float sum = 0.0f;
50 for (int k = 0; k < MATRIX_DIM; ++k) {
51 sum +=
52 world[r * MATRIX_DIM + k] * lightVP[k * MATRIX_DIM + c];
53 }
54 out[r * MATRIX_DIM + c] = sum;
55 }
56 }
57 std::memcpy(out + MATRIX_FLOATS, world, MATRIX_FLOATS * sizeof(float));
58 }
59
60 /// Logs a failed D3DCompileFromFile call with the compiler output.
61 void LogCompileError(const char* path, const char* entry, HRESULT hr,
62 ID3DBlob* errors) {
63 if (errors) {
64 SLEAK_ERROR("{} ({}) compile error: {}", path, entry,
65 static_cast<const char*>(errors->GetBufferPointer()));
66 } else {
67 SLEAK_ERROR("{} ({}) compile error: 0x{:08X}", path, entry,
68 static_cast<unsigned int>(hr));
69 }
70 }
71
72 /// Compares two rasterizer descriptions field by field.
73 bool SameDesc(const D3D11_RASTERIZER_DESC& a,
74 const D3D11_RASTERIZER_DESC& b) {
75 return a.FillMode == b.FillMode && a.CullMode == b.CullMode &&
76 a.FrontCounterClockwise == b.FrontCounterClockwise &&
77 a.DepthBias == b.DepthBias &&
78 a.DepthBiasClamp == b.DepthBiasClamp &&
79 a.SlopeScaledDepthBias == b.SlopeScaledDepthBias &&
80 a.DepthClipEnable == b.DepthClipEnable &&
81 a.ScissorEnable == b.ScissorEnable &&
82 a.MultisampleEnable == b.MultisampleEnable &&
83 a.AntialiasedLineEnable == b.AntialiasedLineEnable;
84 }
85
86 /// Compares two stencil face descriptions field by field.
87 bool SameDesc(const D3D11_DEPTH_STENCILOP_DESC& a,
88 const D3D11_DEPTH_STENCILOP_DESC& b) {
89 return a.StencilFailOp == b.StencilFailOp &&
90 a.StencilDepthFailOp == b.StencilDepthFailOp &&
91 a.StencilPassOp == b.StencilPassOp &&
92 a.StencilFunc == b.StencilFunc;
93 }
94
95 /// Compares two depth-stencil descriptions field by field.
96 bool SameDesc(const D3D11_DEPTH_STENCIL_DESC& a,
97 const D3D11_DEPTH_STENCIL_DESC& b) {
98 return a.DepthEnable == b.DepthEnable &&
99 a.DepthWriteMask == b.DepthWriteMask &&
100 a.DepthFunc == b.DepthFunc &&
101 a.StencilEnable == b.StencilEnable &&
102 a.StencilReadMask == b.StencilReadMask &&
103 a.StencilWriteMask == b.StencilWriteMask &&
104 SameDesc(a.FrontFace, b.FrontFace) &&
105 SameDesc(a.BackFace, b.BackFace);
106 }
107
108 /// Finds the state cached for desc, or creates and caches it on a miss.
109 template <typename Desc, typename State, typename Create>
110 State* FindOrCreateState(
111 std::vector<std::pair<Desc, Microsoft::WRL::ComPtr<State>>>& cache,
112 const Desc& desc, Create create) {
113 for (const auto& [key, state] : cache) {
114 if (SameDesc(key, desc)) return state.Get();
115 }
116 Microsoft::WRL::ComPtr<State> state;
117 if (FAILED(create(&desc, state.GetAddressOf()))) return nullptr;
118 cache.emplace_back(desc, state);
119 return state.Get();
120 }
121
122 } // namespace
123
124/// Registers this backend's buffer/shader/texture factories with ResourceManager.
125DirectX11Renderer::DirectX11Renderer(Window* window)
126 : window(window),
127 device(nullptr),
128 deviceContext(nullptr),
129 swapChain(nullptr),
130 renderTargetView(nullptr) {
131 this->Type = RendererType::DirectX11;
132 this->cull = D3D11_CULL_FRONT;
133
134 ResourceManager::RegisterCreateBuffer(this,&DirectX11Renderer::CreateBuffer);
135 ResourceManager::RegisterCreateShader(this,&DirectX11Renderer::CreateShader);
136 ResourceManager::RegisterCreateTexture(this,&DirectX11Renderer::CreateTexture);
137 ResourceManager::RegisterCreateCubemapTexture(this,&DirectX11Renderer::CreateCubemapTexture);
138 ResourceManager::RegisterCreateCubemapTextureFromPanorama(this,&DirectX11Renderer::CreateCubemapTextureFromPanorama);
139 ResourceManager::RegisterCreateTextureFromMemory(
140 [this](const void* data, uint32_t w, uint32_t h, TextureFormat fmt, uint32_t) -> Texture* {
141 auto* tex = new DirectX11Texture(device);
142 if (tex->LoadFromMemory(data, w, h, fmt)) return tex;
143 delete tex;
144 return nullptr;
145 });
146
147 }
148
149DirectX11Renderer::~DirectX11Renderer() {
150 Cleanup();
151}
152
153bool DirectX11Renderer::Initialize() {
154 HWND hwnd = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window->GetSDLWindow()),
155 SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
156 // Create a DirectX 11 device and swap chain
157 DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
158 swapChainDesc.BufferCount = 2;
159 swapChainDesc.BufferDesc.Width = Window::GetWidth();
160 swapChainDesc.BufferDesc.Height = Window::GetHeight();
161 swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
162 swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
163 swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
164 swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
165 swapChainDesc.OutputWindow = hwnd;
166 swapChainDesc.SampleDesc.Count = 1;
167 swapChainDesc.SampleDesc.Quality = 0;
168 swapChainDesc.Windowed = TRUE;
169 swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
170
171 UINT createDeviceFlags = 0;
172#ifdef _DEBUG
173 createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
174#endif
175
176 D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 };
177 HRESULT hr = D3D11CreateDeviceAndSwapChain(
178 nullptr, // Use default adapter
179 D3D_DRIVER_TYPE_HARDWARE, // Use hardware rendering
180 nullptr, // No software device
181 createDeviceFlags, // No creation flags
182 featureLevels, // Feature levels
183 1, // Number of feature levels
184 D3D11_SDK_VERSION, // SDK version
185 &swapChainDesc, // Swap chain description
186 &swapChain, // Swap chain
187 &device, // Device
188 nullptr, // Supported feature level
189 &deviceContext // Device context
190 );
191
192#ifdef _DEBUG
193 if (hr == DXGI_ERROR_SDK_COMPONENT_MISSING) {
195 "D3D11 debug layer is not installed, creating device without it");
196 createDeviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
197 hr = D3D11CreateDeviceAndSwapChain(
198 nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags,
199 featureLevels, 1, D3D11_SDK_VERSION, &swapChainDesc, &swapChain,
200 &device, nullptr, &deviceContext);
201 }
202#endif
203
204 if (FAILED(hr)) {
205 SLEAK_ERROR("Failed to create device and swap chain! HRESULT: 0x{:X}",
206 (unsigned)hr);
207 return false;
208 }
209
210 CheckMSAASupport();
211
212 if (!CreateRenderTargetView() ||
213 !CreateDepthStencilBuffer(window->GetWidth(), window->GetHeight())) {
214 return false;
215 }
216
217 SetViewport(0, 0, window->GetWidth(), window->GetHeight());
218
219 SLEAK_INFO("DirectX 11 has successfully created!");
220
221#ifdef _DEBUG
222 ID3D11InfoQueue* infoQueue;
223 if (SUCCEEDED(device->QueryInterface(__uuidof(ID3D11InfoQueue),
224 (void**)&infoQueue))) {
225 // Only break on corruption (critical), not on errors — breaking on
226 // errors without a debugger attached silently drops draw calls.
227 infoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true);
228
229 D3D11_MESSAGE_SEVERITY severities[] = {D3D11_MESSAGE_SEVERITY_INFO};
230
231 D3D11_INFO_QUEUE_FILTER filter = {};
232 filter.DenyList.NumSeverities = _countof(severities);
233 filter.DenyList.pSeverityList = severities;
234
235 infoQueue->AddStorageFilterEntries(&filter);
236 infoQueue->Release();
237 }
238#endif
239
240 SetPerformanceCounter(true);
241 SetRenderMode(RenderMode::Fill);
242 SetRenderFace(RenderFace::Front);
243
244 ConfigureRenderMode();
245
246 SetDepthStencilState(true, true);
247
248 msaaSampleCount = 1;
249
250 D3D11_QUERY_DESC queryDesc;
251 queryDesc.Query = D3D11_QUERY::D3D11_QUERY_PIPELINE_STATISTICS;
252 queryDesc.MiscFlags = 0;
253 if (FAILED(device->CreateQuery(&queryDesc, &query)))
254 SLEAK_WARN("Could not create pipeline statics object!");
255
256 if (bEnabledPerformanceCounter && query) {
257 while (deviceContext->GetData(query, nullptr, 0, 0) == S_FALSE)
258 std::this_thread::yield();
259 deviceContext->Begin(query);
260 }
261
262 if (!CreateBlendState())
263 return false;
264
265 return true;
266}
267
268void DirectX11Renderer::BeginRender() {
269 if (m_msaaChangeRequested)
270 ApplyMSAAChange();
271
272 // Commit staged lightVP before shadow pass so shadow + main agree.
273 if (m_hasPendingLightVP &&
274 std::memcmp(m_lightVP, m_pendingLightVP, sizeof(m_lightVP)) != 0) {
275 std::memcpy(m_lightVP, m_pendingLightVP, sizeof(m_lightVP));
276 m_shadowCBCacheValid = false;
277 }
278
279 // Create tonemap resources on demand
280 if (m_tonemapEnabled && !m_tonemapResourcesCreated)
281 CreateTonemapResources();
282
283 // When tonemapping is enabled and no MSAA, render to HDR target
284 if (m_tonemapEnabled && m_tonemapResourcesCreated && msaaSampleCount <= 1) {
285 deviceContext->OMSetRenderTargets(1, &m_hdrRTV, depthStencilView);
286 } else if (msaaSampleCount > 1 && msaaRenderTargetView && msaaDepthStencilView) {
287 deviceContext->OMSetRenderTargets(1, &msaaRenderTargetView, msaaDepthStencilView);
288 } else {
289 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
290 }
291
292 ClearRenderTarget(0.39f, 0.58f, 0.93f, 1.0f);
293 ClearDepthStencil(true, false, 1.0, 0);
294
295 // Shadow pass: render shadow depth map before main pass
296 if (m_shadowPassEnabled) {
297 RenderShadowPass();
298 }
299
300 // Ensure shadow map SRV + comparison sampler stay bound at t3/s3
301 // for the main draw calls (guards against any intermediate state
302 // clearing the slots between shadow pass and ExecuteCommands).
303 if (m_shadowMapCreated && m_shadowSRV && m_shadowSampler) {
304 deviceContext->PSSetShaderResources(3, 1, &m_shadowSRV);
305 deviceContext->PSSetSamplers(3, 1, &m_shadowSampler);
306 }
307
308 if (bIsLayoutCreated)
309 deviceContext->IASetInputLayout(layout);
310
311 if(bImInitialized) {
312 ImGui_ImplDX11_NewFrame();
313 ImGui_ImplSDL3_NewFrame();
314 ImGui::NewFrame();
315 }
316}
317
318void DirectX11Renderer::EndRender() {
319 // Resolve MSAA before presenting
320 if (msaaSampleCount > 1) {
321 // Switch back to default render target for ImGui
322 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
323 ResolveMSAA();
324 }
325
326 // Run tonemapping post-process pass (HDR -> backbuffer)
327 if (m_tonemapEnabled && m_tonemapResourcesCreated && msaaSampleCount <= 1) {
328 ExecuteTonemapPass();
329 // Restore input layout after fullscreen pass
330 if (bIsLayoutCreated)
331 deviceContext->IASetInputLayout(layout);
332 }
333
334 // ImGui renders on top of tonemapped output
335 if (bImInitialized) {
336 // Ensure we're rendering to the backbuffer
337 deviceContext->OMSetRenderTargets(1, &renderTargetView, nullptr);
338 ImGui::Render();
339 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
340 }
341
342 swapChain->Present(m_vsync ? 1 : 0, 0);
343
344 UpdateFrameMetrics();
345}
346
347void DirectX11Renderer::Cleanup() {
348 bImInitialized = false;
349
350 // Cleanup post-process resources
351 CleanupTonemapResources();
352 CleanupShadowResources();
353
354 // Cleanup MSAA resources
355 if (msaaRenderTarget) { msaaRenderTarget->Release(); msaaRenderTarget = nullptr; }
356 if (msaaRenderTargetView) { msaaRenderTargetView->Release(); msaaRenderTargetView = nullptr; }
357 if (msaaDepthStencilBuffer) { msaaDepthStencilBuffer->Release(); msaaDepthStencilBuffer = nullptr; }
358 if (msaaDepthStencilView) { msaaDepthStencilView->Release(); msaaDepthStencilView = nullptr; }
359
360 if (renderTargetView) {
361 renderTargetView->Release();
362 renderTargetView = nullptr;
363 }
364 if (swapChain) {
365 swapChain->Release();
366 swapChain = nullptr;
367 }
368 if (deviceContext) {
369 deviceContext->Release();
370 deviceContext = nullptr;
371 }
372
373 if (depthStencilView) {
374 depthStencilView->Release();
375 depthStencilView = nullptr;
376 }
377 if (depthStencilBuffer) {
378 depthStencilBuffer->Release();
379 depthStencilBuffer = nullptr;
380 }
381 if (depthStencilState) {
382 depthStencilState->Release();
383 depthStencilState = nullptr;
384 }
385
386 if (blendState) {
387 blendState->Release();
388 blendState = nullptr;
389 }
390
391 m_rasterStates.clear();
392 m_depthStates.clear();
393
394 if(query)
395 {
396 query->Release();
397 query = nullptr;
398 }
399
400 if (bImInitialized) {
401 ImGui_ImplDX11_Shutdown();
402 ImGui_ImplSDL3_Shutdown();
403 ImGui::DestroyContext();
404 bImInitialized = false;
405 }
406
407#ifdef _DEBUG
408 if (device) {
409 ID3D11Debug* debugDevice;
410 device->QueryInterface(__uuidof(ID3D11Debug), (void**)&debugDevice);
411 if (debugDevice) {
412 debugDevice->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
413 debugDevice->Release();
414 }
415 }
416#endif
417
418 if (device) {
419 device->Release();
420 device = nullptr;
421 }
422}
423
424bool DirectX11Renderer::CreateDepthStencilBuffer(uint32_t width,uint32_t height) {
425
426 D3D11_TEXTURE2D_DESC depthDesc = {};
427 depthDesc.Width = width;
428 depthDesc.Height = height;
429 depthDesc.MipLevels = 1;
430 depthDesc.ArraySize = 1;
431 depthDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
432 depthDesc.SampleDesc.Count = 1;
433 depthDesc.SampleDesc.Quality = 0;
434 depthDesc.Usage = D3D11_USAGE_DEFAULT;
435 depthDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
436
437 HRESULT hr =
438 device->CreateTexture2D(&depthDesc, nullptr, &depthStencilBuffer);
439 if (FAILED(hr)) {
440 SLEAK_ERROR("Failed to create depth stencil buffer!");
441 return false;
442 }
443
444 hr = device->CreateDepthStencilView(depthStencilBuffer, nullptr,
445 &depthStencilView);
446 if (FAILED(hr)) {
447 SLEAK_ERROR("Failed to create depth stencil view!");
448 return false;
449 }
450
451 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
452 return true;
453}
454
455void DirectX11Renderer::SetDepthStencilState(bool enableDepth,
456 bool enableStencil) {
457 D3D11_DEPTH_STENCIL_DESC depthStencilDesc = {};
458 depthStencilDesc.DepthEnable = enableDepth;
459 depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
460 depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
461 depthStencilDesc.StencilEnable = enableStencil;
462 depthStencilDesc.StencilReadMask = 0xFF;
463 depthStencilDesc.StencilWriteMask = 0xFF;
464
465 // Front face stencil operations
466 depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
467 depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
468 depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
469 depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
470
471 // Back face stencil operations
472 depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
473 depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
474 depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
475 depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
476
477 ID3D11DepthStencilState* state = nullptr;
478 HRESULT hr = device->CreateDepthStencilState(&depthStencilDesc, &state);
479 if (FAILED(hr)) {
480 SLEAK_ERROR("Failed to create depth stencil state!");
481 return;
482 }
483
484 if (depthStencilState) depthStencilState->Release();
485 depthStencilState = state;
486 deviceContext->OMSetDepthStencilState(depthStencilState, 1);
487}
488
489void DirectX11Renderer::Resize(uint32_t width, uint32_t height) {
490 if (swapChain == nullptr || device == nullptr || deviceContext == nullptr) {
491 return;
492 }
493 if (width == 0 || height == 0) return;
494
495 // Unbind all pipeline resources so DXGI can release the back-buffer references
496 deviceContext->OMSetRenderTargets(0, nullptr, nullptr);
497 deviceContext->ClearState();
498 deviceContext->Flush();
499
500 // Release all references to the swap chain's buffers
501 if (renderTargetView) {
502 renderTargetView->Release();
503 renderTargetView = nullptr;
504 }
505
506 if (depthStencilView) {
507 depthStencilView->Release();
508 depthStencilView = nullptr;
509 }
510 if (depthStencilBuffer) {
511 depthStencilBuffer->Release();
512 depthStencilBuffer = nullptr;
513 }
514 if (depthStencilState) {
515 depthStencilState->Release();
516 depthStencilState = nullptr;
517 }
518
519 // Use 0 to preserve the existing buffer count (FLIP_DISCARD requires >=2)
520 // Use DXGI_FORMAT_UNKNOWN to preserve the existing format
521 HRESULT hr = swapChain->ResizeBuffers(0,
522 width, height,
523 DXGI_FORMAT_UNKNOWN,
524 0);
525
526 if (FAILED(hr)) {
527 SLEAK_ERROR("Failed to resize swap chain buffers! HRESULT: 0x{:X}", (unsigned)hr);
528 return;
529 }
530
531 // Recreate the render target view
532 if (!CreateRenderTargetView() || !CreateDepthStencilBuffer(width, height)) {
533 return;
534 }
535
536 // Recreate MSAA targets if MSAA is active
537 if (msaaSampleCount > 1) {
538 CreateMSAARenderTarget();
539 CreateMSAADepthStencil();
540 }
541
542 // Recreate HDR tonemap target at new size
543 if (m_tonemapResourcesCreated) {
544 CleanupTonemapResources();
545 CreateTonemapResources();
546 }
547
548 // Update the viewport
549 SetViewport(0, 0, width, height);
550
551 ImCon->IO.DisplaySize = ImVec2(width,height);
552
553 SLEAK_INFO("DirectX 11 resized to {}x{}", width, height);
554}
555
556void DirectX11Renderer::Draw(uint32_t vertexCount) { Draw(vertexCount, 0); }
557
558void DirectX11Renderer::Draw(uint32_t vertexCount, uint32_t firstVertex) {
559 deviceContext->Draw(vertexCount, firstVertex);
560}
561
562void DirectX11Renderer::DrawIndexed(uint32_t indexCount) {
563 DrawIndexed(indexCount, 0, 0);
564}
565
566void DirectX11Renderer::DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
567 int32_t baseVertex) {
568 deviceContext->DrawIndexed(indexCount, firstIndex, baseVertex);
569 DrawnVertices += indexCount;
570}
571
572void DirectX11Renderer::DrawInstance(uint32_t instanceCount,
573 uint32_t vertexPerInstance) {
574 deviceContext->DrawInstanced(vertexPerInstance, instanceCount, 0, 0);
575}
576
577void DirectX11Renderer::DrawIndexedInstance(uint32_t instanceCount,
578 uint32_t indexPerInstance) {
579 DrawIndexedInstance(instanceCount, indexPerInstance, 0, 0);
580}
581
582void DirectX11Renderer::DrawIndexedInstance(uint32_t instanceCount,
583 uint32_t indexPerInstance,
584 uint32_t firstIndex,
585 int32_t baseVertex) {
586 deviceContext->DrawIndexedInstanced(indexPerInstance, instanceCount,
587 firstIndex, baseVertex, 0);
588}
589
590void DirectX11Renderer::ClearRenderTarget(float r, float g, float b, float a) {
591 const float clearColor[4] = {r, g, b, a};
592
593 ID3D11RenderTargetView* target;
594 if (m_tonemapEnabled && m_tonemapResourcesCreated && msaaSampleCount <= 1)
595 target = m_hdrRTV;
596 else if (msaaSampleCount > 1)
597 target = msaaRenderTargetView;
598 else
599 target = renderTargetView;
600
601 if (target)
602 deviceContext->ClearRenderTargetView(target, clearColor);
603}
604
605void DirectX11Renderer::ClearDepthStencil(bool clearDepth, bool clearStencil,
606 float depth, uint8_t stencil) {
607 UINT clearFlags = 0;
608 if (clearDepth) clearFlags |= D3D11_CLEAR_DEPTH;
609 if (clearStencil) clearFlags |= D3D11_CLEAR_STENCIL;
610
611 ID3D11DepthStencilView* target = (msaaSampleCount > 1 && msaaDepthStencilView)
612 ? msaaDepthStencilView : depthStencilView;
613 if (target) {
614 deviceContext->ClearDepthStencilView(target, clearFlags, depth, stencil);
615 }
616}
617
618// Buffer binding
619void DirectX11Renderer::BindVertexBuffer(RefPtr<BufferBase> buffer, uint32_t slot) {
620 auto* dx11Buf = static_cast<DirectX11Buffer*>(buffer.get());
621 if (!dx11Buf) return;
622
623 ID3D11Buffer* d3d11Buffer = dx11Buf->GetD3DBuffer();
624 UINT stride = sizeof(Sleak::Vertex);
625 UINT offset = 0;
626 deviceContext->IASetVertexBuffers(slot, 1, &d3d11Buffer, &stride, &offset);
627}
628
629void DirectX11Renderer::BindIndexBuffer(RefPtr<BufferBase> buffer,
630 uint32_t slot) {
631 auto* dx11Buf = static_cast<DirectX11Buffer*>(buffer.get());
632 if (!dx11Buf) return;
633
634 deviceContext->IASetIndexBuffer(dx11Buf->GetD3DBuffer(),
635 DXGI_FORMAT_R32_UINT, 0);
636}
637
638void DirectX11Renderer::BindConstantBuffer(RefPtr<BufferBase> buffer,
639 uint32_t slot) {
640 auto* dx11Buf = static_cast<DirectX11Buffer*>(buffer.get());
641 if (!dx11Buf) return;
642
643 // Shadow pass: use dedicated shadow CB with LightVP*World for slot 0
644 if (m_inShadowPass && slot == 0 &&
645 dx11Buf->GetCPUShadowCopySize() >= TRANSFORM_CB_BYTES) {
646 const float* srcWorld = reinterpret_cast<const float*>(
647 static_cast<const char*>(dx11Buf->GetCPUShadowCopy()) +
648 TRANSFORM_WORLD_OFFSET);
649
650 // Create dedicated shadow transform CB on first use
651 if (!m_shadowTransformCB) {
652 D3D11_BUFFER_DESC desc{};
653 desc.ByteWidth = TRANSFORM_CB_BYTES;
654 desc.Usage = D3D11_USAGE_DYNAMIC;
655 desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
656 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
657 if (FAILED(
658 device->CreateBuffer(&desc, nullptr, &m_shadowTransformCB)))
659 return;
660 m_shadowCBCacheValid = false;
661 }
662
663 // The CB keeps its contents, so only a new World needs an upload
664 if (!m_shadowCBCacheValid ||
665 std::memcmp(srcWorld, m_shadowWorldCache,
666 sizeof(m_shadowWorldCache)) != 0) {
667 float shadowPC[TRANSFORM_CB_FLOATS];
668 BuildShadowTransform(srcWorld, m_lightVP, shadowPC);
669
670 D3D11_MAPPED_SUBRESOURCE mapped{};
671 if (SUCCEEDED(deviceContext->Map(m_shadowTransformCB, 0,
672 D3D11_MAP_WRITE_DISCARD, 0,
673 &mapped))) {
674 std::memcpy(mapped.pData, shadowPC, sizeof(shadowPC));
675 deviceContext->Unmap(m_shadowTransformCB, 0);
676 std::memcpy(m_shadowWorldCache, srcWorld,
677 sizeof(m_shadowWorldCache));
678 m_shadowCBCacheValid = true;
679 }
680 }
681 deviceContext->VSSetConstantBuffers(slot, 1, &m_shadowTransformCB);
682 deviceContext->PSSetConstantBuffers(slot, 1, &m_shadowTransformCB);
683 return;
684 }
685
686 auto d3d11Buffer = dx11Buf->GetD3DBuffer();
687 deviceContext->VSSetConstantBuffers(slot, 1, &d3d11Buffer);
688 deviceContext->PSSetConstantBuffers(slot, 1, &d3d11Buffer);
689}
690
691void DirectX11Renderer::ConfigureRenderMode() {
692 switch (Mode)
693 {
694 case RenderMode::Fill:
695 topology = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
696 fillMode = D3D11_FILL_MODE::D3D11_FILL_SOLID;
697 break;
698 case RenderMode::Points:
699 topology = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
700 fillMode = D3D11_FILL_MODE::D3D11_FILL_SOLID;
701 break;
702 case RenderMode::Wireframe :
703 topology = D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
704 fillMode = D3D11_FILL_MODE::D3D11_FILL_WIREFRAME;
705 break;
706 default:
707 SLEAK_ERROR("Unable to set render mode!");
708 break;
709 }
710
711 if (deviceContext)
712 deviceContext->IASetPrimitiveTopology(topology);
713
714 SetRasterState();
715}
716
717void DirectX11Renderer::ConfigureRenderFace() {
718 switch(Face) {
719 case RenderFace::None : cull = D3D11_CULL_MODE::D3D11_CULL_NONE; break;
720 case RenderFace::Front : cull = D3D11_CULL_MODE::D3D11_CULL_FRONT; break;
721 case RenderFace::Back : cull = D3D11_CULL_MODE::D3D11_CULL_BACK; break;
722 default: cull = D3D11_CULL_MODE::D3D11_CULL_FRONT;
723 }
724}
725
726bool DirectX11Renderer::SetRasterState() {
727 D3D11_RASTERIZER_DESC RasterDesc = {};
728 RasterDesc.AntialiasedLineEnable = true;
729 RasterDesc.MultisampleEnable = true;
730 RasterDesc.CullMode = cull;
731 RasterDesc.DepthBias = 0;
732 RasterDesc.DepthBiasClamp = 0.0f;
733 RasterDesc.SlopeScaledDepthBias = 0.0f;
734 RasterDesc.DepthClipEnable = true;
735 RasterDesc.ScissorEnable = false;
736 RasterDesc.FillMode = fillMode;
737 RasterDesc.FrontCounterClockwise = false;
738
739 ID3D11RasterizerState* rasterState = GetRasterState(RasterDesc);
740 if (!rasterState) return false;
741
742 deviceContext->RSSetState(rasterState);
743 return true;
744}
745
746ID3D11RasterizerState* DirectX11Renderer::GetRasterState(
747 const D3D11_RASTERIZER_DESC& desc) {
748 return FindOrCreateState(
749 m_rasterStates, desc,
750 [this](const D3D11_RASTERIZER_DESC* d, ID3D11RasterizerState** out) {
751 return device->CreateRasterizerState(d, out);
752 });
753}
754
755ID3D11DepthStencilState* DirectX11Renderer::GetDepthState(
756 const D3D11_DEPTH_STENCIL_DESC& desc) {
757 return FindOrCreateState(m_depthStates, desc,
758 [this](const D3D11_DEPTH_STENCIL_DESC* d,
759 ID3D11DepthStencilState** out) {
760 return device->CreateDepthStencilState(d, out);
761 });
762}
763
764void DirectX11Renderer::SetRenderMode(RenderMode mode) {
765 this->Mode = mode;
766 ConfigureRenderMode();
767}
768
769void DirectX11Renderer::SetRenderFace(RenderFace face) {
770 this->Face = face;
771 ConfigureRenderFace();
772}
773
774void DirectX11Renderer::SetViewport(float x, float y, float width, float height,
775 float minDepth,
776 float maxDepth) {
777 D3D11_VIEWPORT viewport = {};
778 viewport.Width = static_cast<float>(width);
779 viewport.Height = static_cast<float>(height);
780 viewport.MinDepth = minDepth;
781 viewport.MaxDepth = maxDepth;
782 viewport.TopLeftX = x;
783 viewport.TopLeftY = y;
784 deviceContext->RSSetViewports(1, &viewport);
785
786}
787
788bool DirectX11Renderer::CreateRenderTargetView() {
789 // Release the existing render target view if it exists
790 if (renderTargetView) {
791 renderTargetView->Release();
792 renderTargetView = nullptr;
793 }
794
795 // Get the back buffer from the swap chain
796 ID3D11Texture2D* backBuffer = nullptr;
797 HRESULT hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
798 reinterpret_cast<void**>(&backBuffer));
799 if (FAILED(hr)) {
800 SLEAK_ERROR("Failed to get back buffer!");
801 return false;
802 }
803
804 // Create the render target view
805 hr = device->CreateRenderTargetView(backBuffer, nullptr, &renderTargetView);
806 backBuffer->Release();
807 if (FAILED(hr)) {
808 SLEAK_ERROR("Failed to create render target view!");
809 return false;
810 }
811
812 // Set the render target
813 deviceContext->OMSetRenderTargets(1, &renderTargetView, nullptr);
814
815 SLEAK_INFO("Render target view created successfully.");
816 return true;
817}
818
819Texture* DirectX11Renderer::CreateTextureFromData(uint32_t width, uint32_t height, void* data) {
820 DirectX11Texture* texture = new DirectX11Texture(device);
821 if (texture->LoadFromMemory(data,width,height,TextureFormat::RGBA8)) {
822 return texture;
823 }
824 return nullptr;
825}
826
827Texture* DirectX11Renderer::CreateTexture(const std::string& TexturePath) {
828 DirectX11Texture* texture = new DirectX11Texture(device);
829 if (texture->LoadFromFile(TexturePath)) {
830 return texture;
831 }
832 return nullptr;
833}
834
835Texture* DirectX11Renderer::CreateCubemapTexture(
836 const std::array<std::string, 6>& facePaths) {
837 auto* texture = new DirectX11CubemapTexture(device);
838 if (texture->LoadCubemap(facePaths)) {
839 return texture;
840 }
841 delete texture;
842 return nullptr;
843}
844
845Texture* DirectX11Renderer::CreateCubemapTextureFromPanorama(
846 const std::string& panoramaPath) {
847 auto* texture = new DirectX11CubemapTexture(device);
848 if (texture->LoadEquirectangular(panoramaPath)) {
849 return texture;
850 }
851 delete texture;
852 return nullptr;
853}
854
855void DirectX11Renderer::SetDepthWrite(bool enabled) {
856 m_depthWriteEnabled = enabled;
857 ApplyDepthState();
858}
859
860void DirectX11Renderer::ApplyDepthState() {
861 D3D11_DEPTH_STENCIL_DESC desc = {};
862 desc.DepthEnable = TRUE;
863 desc.DepthWriteMask = m_depthWriteEnabled ? D3D11_DEPTH_WRITE_MASK_ALL
864 : D3D11_DEPTH_WRITE_MASK_ZERO;
865 desc.DepthFunc = m_depthFunc;
866 desc.StencilEnable = FALSE;
867
868 if (ID3D11DepthStencilState* state = GetDepthState(desc))
869 deviceContext->OMSetDepthStencilState(state, 1);
870}
871
872void DirectX11Renderer::SetDepthCompare(DepthCompare compare) {
873 switch (compare) {
874 case DepthCompare::Less: m_depthFunc = D3D11_COMPARISON_LESS; break;
875 case DepthCompare::LessEqual: m_depthFunc = D3D11_COMPARISON_LESS_EQUAL; break;
876 case DepthCompare::Greater: m_depthFunc = D3D11_COMPARISON_GREATER; break;
877 case DepthCompare::GreaterEqual: m_depthFunc = D3D11_COMPARISON_GREATER_EQUAL; break;
878 case DepthCompare::Equal: m_depthFunc = D3D11_COMPARISON_EQUAL; break;
879 case DepthCompare::NotEqual: m_depthFunc = D3D11_COMPARISON_NOT_EQUAL; break;
880 case DepthCompare::Always: m_depthFunc = D3D11_COMPARISON_ALWAYS; break;
881 case DepthCompare::Never: m_depthFunc = D3D11_COMPARISON_NEVER; break;
882 }
883
884 ApplyDepthState();
885}
886
887void DirectX11Renderer::SetCullEnabled(bool enabled) {
888 if (enabled) {
889 cull = D3D11_CULL_FRONT;
890 } else {
891 cull = D3D11_CULL_NONE;
892 }
893 SetRasterState();
894}
895
896void DirectX11Renderer::BindTexture(RefPtr<Sleak::Texture> texture,
897 uint32_t slot) {
898 if (texture.IsValid()) {
899 texture->Bind(slot);
900 }
901}
902
903void DirectX11Renderer::BeginSkyboxPass() {
904 // Save current state
905 m_savedCullMode = cull;
906 m_savedDepthStencilState = depthStencilState;
907 if (m_savedDepthStencilState) {
908 m_savedDepthStencilState->AddRef();
909 }
910}
911
912void DirectX11Renderer::EndSkyboxPass() {
913 // Restore depth stencil state
914 if (m_savedDepthStencilState) {
915 deviceContext->OMSetDepthStencilState(m_savedDepthStencilState, 1);
916 m_savedDepthStencilState->Release();
917 m_savedDepthStencilState = nullptr;
918 }
919
920 // Restore cull mode
921 cull = m_savedCullMode;
922 SetRasterState();
923
924 // Reset depth tracking
925 m_depthWriteEnabled = true;
926 m_depthFunc = D3D11_COMPARISON_LESS;
927}
928
929void DirectX11Renderer::BeginDebugLinePass() {
930 m_savedTopology = topology;
931 topology = D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
932 deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
933}
934
935void DirectX11Renderer::EndDebugLinePass() {
936 topology = m_savedTopology;
937 deviceContext->IASetPrimitiveTopology(topology);
938}
939
940BufferBase* DirectX11Renderer::CreateBuffer(BufferType Type, uint32_t size, void* data) {
941 assert(size > 0);
942
943 DirectX11Buffer* buffer = new DirectX11Buffer(device, size, Type);
944 if (!buffer->Initialize(data)) {
945 delete buffer;
946 return nullptr;
947 }
948 return static_cast<BufferBase*>(buffer);
949}
950
951Shader* DirectX11Renderer::CreateShader(const std::string& shaderSource) {
952 DirectX11Shader* shader = new DirectX11Shader(device);
953 if (shader->compile(shaderSource)) {
954 // Each shader creates its own input layout matching its VS inputs.
955 // The layout is stored per-shader and set in bind().
956 auto* il = shader->createInputLayout();
957 if (!bIsLayoutCreated && il) {
958 layout = il;
959 bIsLayoutCreated = true;
960 } else if (il) {
961 il->Release();
962 }
963 return static_cast<Shader*>(shader);
964 }
965 delete shader;
966 return nullptr;
967}
968
969#ifdef SLEAK_HOT_RELOAD
970bool DirectX11Renderer::ReloadShaders(const std::vector<std::string>& stems) {
971 const auto usesAnyStem = [&stems](const DirectX11Shader* shader) {
972 return std::ranges::any_of(stems, [shader](const std::string& stem) {
973 return shader->UsesStem(stem);
974 });
975 };
976
977 // Shaders built from the same files compile once and share the result
978 std::vector<const DirectX11Shader*> rebuilt;
979 std::vector<const DirectX11Shader*> failed;
980 for (DirectX11Shader* shader : DirectX11Shader::GetLiveShaders()) {
981 if (!usesAnyStem(shader)) continue;
982 const auto sameSources = [shader](const DirectX11Shader* other) {
983 return shader->HasSameSources(*other);
984 };
985 if (std::ranges::any_of(failed, sameSources)) continue;
986
987 ID3D11InputLayout* oldLayout = shader->getInputLayout();
988 const auto twin = std::ranges::find_if(rebuilt, sameSources);
989 if (twin != rebuilt.end()) {
990 shader->AdoptStages(**twin);
991 } else if (shader->Reload()) {
992 rebuilt.push_back(shader);
993 SLEAK_INFO("Reloaded DirectX 11 shader '{}'", shader->GetStem());
994 } else {
995 failed.push_back(shader);
996 SLEAK_WARN("Shader '{}' failed to reload, keeping the old one",
997 shader->GetStem());
998 continue;
999 }
1000
1001 // The renderer holds its own reference to the first shader's layout
1002 if (bIsLayoutCreated && oldLayout && oldLayout == layout) {
1003 ID3D11InputLayout* fresh = shader->getInputLayout();
1004 if (fresh) fresh->AddRef();
1005 layout->Release();
1006 layout = fresh;
1007 }
1008 }
1009
1010 if (std::find(stems.begin(), stems.end(), TONEMAP_STEM) != stems.end())
1011 ReloadTonemapShaders();
1012
1013 for (const std::string& stem : stems) {
1014 const bool used =
1015 stem == TONEMAP_STEM ||
1016 std::ranges::any_of(DirectX11Shader::GetLiveShaders(),
1017 [&stem](const DirectX11Shader* shader) {
1018 return shader->UsesStem(stem);
1019 });
1020 if (!used)
1021 SLEAK_WARN(
1022 "Hot reload: no loaded DirectX 11 shader is built from '{}'",
1023 stem);
1024 }
1025 return true;
1026}
1027#endif
1028
1029bool DirectX11Renderer::CreateBlendState() {
1030 //(+) : Binary Operator
1031 // Color = SourceP (X) SourceFactor (+) DestP (X) DestFactor
1032 // Alpha = SourceA SourceFactor (+) DestA DestFactor
1033
1034 D3D11_BLEND_DESC desc;
1035 desc.AlphaToCoverageEnable = false;
1036 desc.IndependentBlendEnable = false;
1037
1038 desc.RenderTarget[0].BlendEnable = true;
1039
1040 desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
1041 desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
1042
1043 desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
1044 desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
1045
1046 desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
1047 desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
1048
1049 desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
1050
1051 if (FAILED(device->CreateBlendState(&desc, &blendState)))
1052 return false;
1053
1054 return true;
1055}
1056
1057void DirectX11Renderer::SetBlendState(float r, float g, float b, float a, UINT Mask) {
1058 float BlendFactor[4] = {r,g,b,a};
1059 deviceContext->OMSetBlendState(blendState, BlendFactor, Mask);
1060}
1061
1062void DirectX11Renderer::CheckMSAASupport() {
1063 m_maxMsaaSampleCount = 1;
1064 for (UINT sampleCount = 1;
1065 sampleCount <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT;
1066 sampleCount *= 2)
1067 {
1068 UINT quality = 0;
1069 HRESULT hr = device->CheckMultisampleQualityLevels(
1070 DXGI_FORMAT_R8G8B8A8_UNORM, sampleCount, &quality);
1071 if (SUCCEEDED(hr) && quality > 0) {
1072 SLEAK_INFO("MSAA {}x supported with {} quality levels.",
1073 sampleCount, quality);
1074 if (sampleCount <= 8)
1075 m_maxMsaaSampleCount = sampleCount;
1076 }
1077 }
1078}
1079
1080bool DirectX11Renderer::CreateMSAARenderTarget() {
1081
1082 if (msaaRenderTarget) msaaRenderTarget->Release();
1083 if (msaaRenderTargetView) msaaRenderTargetView->Release();
1084
1085 D3D11_TEXTURE2D_DESC texDesc;
1086 texDesc.Width = window->GetWidth();
1087 texDesc.Height = window->GetHeight();
1088 texDesc.MipLevels = 1;
1089 texDesc.ArraySize = 1;
1090 texDesc.SampleDesc.Count = msaaSampleCount;
1091 texDesc.SampleDesc.Quality = msaaQualityLevel;
1092 texDesc.BindFlags = D3D11_BIND_RENDER_TARGET;
1093 texDesc.CPUAccessFlags = 0;
1094 texDesc.MiscFlags = 0;
1095 texDesc.Usage = D3D11_USAGE_DEFAULT;
1096 texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1097
1098 if (FAILED(device->CreateTexture2D(&texDesc, nullptr, &msaaRenderTarget)))
1099 return false;
1100
1101 if (FAILED(device->CreateRenderTargetView(msaaRenderTarget,nullptr,&msaaRenderTargetView)))
1102 return false;
1103
1104 return true;
1105}
1106
1107bool DirectX11Renderer::CreateMSAADepthStencil() {
1108 if (msaaDepthStencilBuffer) msaaDepthStencilBuffer->Release();
1109 if (msaaDepthStencilView) msaaDepthStencilView->Release();
1110
1111 D3D11_TEXTURE2D_DESC texDesc;
1112 texDesc.Width = window->GetWidth();
1113 texDesc.Height = window->GetHeight();
1114 texDesc.MipLevels = 1;
1115 texDesc.ArraySize = 1;
1116 texDesc.SampleDesc.Count = msaaSampleCount;
1117 texDesc.SampleDesc.Quality = msaaQualityLevel;
1118 texDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
1119 texDesc.CPUAccessFlags = 0;
1120 texDesc.MiscFlags = 0;
1121 texDesc.Usage = D3D11_USAGE_DEFAULT;
1122 texDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
1123
1124 if (FAILED(device->CreateTexture2D(&texDesc,nullptr,&msaaDepthStencilBuffer))) return false;
1125
1126 if (FAILED(device->CreateDepthStencilView(msaaDepthStencilBuffer,nullptr,&msaaDepthStencilView))) return false;
1127
1128
1129 return true;
1130}
1131
1132void DirectX11Renderer::ResolveMSAA() {
1133 if (msaaSampleCount <= 1 || msaaSampleCount % 2 != 0)
1134 return;
1135
1136 ID3D11Texture2D* back;
1137 if (FAILED(swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&back))) {
1138 SLEAK_ERROR("Failed to get back buffer for MSAA!");
1139 return;
1140 }
1141 deviceContext->ResolveSubresource(back,0,msaaRenderTarget,0,DXGI_FORMAT_R8G8B8A8_UNORM);
1142
1143 back->Release();
1144}
1145
1146void DirectX11Renderer::ApplyMSAAChange() {
1147 if (!m_msaaChangeRequested)
1148 return;
1149 m_msaaChangeRequested = false;
1150
1151 m_msaaSampleCount = m_pendingMsaaSampleCount;
1152 msaaSampleCount = m_pendingMsaaSampleCount;
1153
1154 // Query quality level for new sample count
1155 UINT quality = 0;
1156 device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM,
1157 msaaSampleCount, &quality);
1158 msaaQualityLevel = (quality > 0) ? quality - 1 : 0;
1159
1160 // Cleanup old MSAA resources
1161 if (msaaRenderTarget) { msaaRenderTarget->Release(); msaaRenderTarget = nullptr; }
1162 if (msaaRenderTargetView) { msaaRenderTargetView->Release(); msaaRenderTargetView = nullptr; }
1163 if (msaaDepthStencilBuffer) { msaaDepthStencilBuffer->Release(); msaaDepthStencilBuffer = nullptr; }
1164 if (msaaDepthStencilView) { msaaDepthStencilView->Release(); msaaDepthStencilView = nullptr; }
1165
1166 if (msaaSampleCount > 1) {
1167 CreateMSAARenderTarget();
1168 CreateMSAADepthStencil();
1169 } else {
1170 // Re-bind non-MSAA render targets since pipeline still references released MSAA views
1171 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
1172 }
1173
1174 SLEAK_INFO("DX11 MSAA changed to {}x", msaaSampleCount);
1175}
1176
1177bool DirectX11Renderer::CreateImGUI()
1178{
1179 IMGUI_CHECKVERSION();
1180 ImCon = ImGui::CreateContext();
1181 ImCon->IO.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
1182
1183 ImGui::StyleColorsDark();
1184
1185 if(!ImGui_ImplSDL3_InitForD3D(window->GetSDLWindow()))
1186 return false;
1187
1188 if(!ImGui_ImplDX11_Init(device, deviceContext))
1189 return false;
1190
1191 if(!ImGui_ImplDX11_CreateDeviceObjects())
1192 return false;
1193
1194
1195 bImInitialized = true;
1196
1197 return true;
1198}
1199
1200
1201// ---- Shadow Constant Buffer ----
1202
1203bool DirectX11Renderer::CreateShadowConstantBuffer() {
1204 if (m_shadowCBCreated) return true;
1205
1206 D3D11_BUFFER_DESC desc{};
1207 desc.ByteWidth = sizeof(PCSSShadowGPUData);
1208 desc.Usage = D3D11_USAGE_DYNAMIC;
1209 desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1210 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
1211
1212 HRESULT hr = device->CreateBuffer(&desc, nullptr, &m_shadowCB);
1213 if (FAILED(hr)) {
1214 SLEAK_ERROR("Failed to create shadow constant buffer!");
1215 return false;
1216 }
1217
1218 m_shadowCBCreated = true;
1219 return true;
1220}
1221
1222void DirectX11Renderer::CleanupShadowResources() {
1223 if (m_shadowCB) { m_shadowCB->Release(); m_shadowCB = nullptr; }
1224 m_shadowCBCreated = false;
1225 if (m_shadowTransformCB) { m_shadowTransformCB->Release(); m_shadowTransformCB = nullptr; }
1226 m_shadowCBCacheValid = false;
1227 if (m_shadowRasterState) { m_shadowRasterState->Release(); m_shadowRasterState = nullptr; }
1228 if (m_shadowSampler) { m_shadowSampler->Release(); m_shadowSampler = nullptr; }
1229 if (m_shadowSRV) { m_shadowSRV->Release(); m_shadowSRV = nullptr; }
1230 if (m_shadowDSV) { m_shadowDSV->Release(); m_shadowDSV = nullptr; }
1231 if (m_shadowDepthTex) { m_shadowDepthTex->Release(); m_shadowDepthTex = nullptr; }
1232 m_shadowMapCreated = false;
1233}
1234
1235void DirectX11Renderer::SetLightVP(const float* mat) {
1236 if (mat) {
1237 std::memcpy(m_pendingLightVP, mat, sizeof(m_pendingLightVP));
1238 m_hasPendingLightVP = true;
1239 }
1240}
1241
1242bool DirectX11Renderer::CreateShadowMapResources() {
1243 if (m_shadowMapCreated) return true;
1244
1245 // Create depth texture
1246 D3D11_TEXTURE2D_DESC texDesc{};
1247 texDesc.Width = m_shadowMapResolution;
1248 texDesc.Height = m_shadowMapResolution;
1249 texDesc.MipLevels = 1;
1250 texDesc.ArraySize = 1;
1251 texDesc.Format = DXGI_FORMAT_R32_TYPELESS;
1252 texDesc.SampleDesc.Count = 1;
1253 texDesc.SampleDesc.Quality = 0;
1254 texDesc.Usage = D3D11_USAGE_DEFAULT;
1255 texDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
1256
1257 HRESULT hr = device->CreateTexture2D(&texDesc, nullptr, &m_shadowDepthTex);
1258 if (FAILED(hr)) {
1259 SLEAK_ERROR("Failed to create shadow depth texture!");
1260 return false;
1261 }
1262
1263 // Create DSV
1264 D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc{};
1265 dsvDesc.Format = DXGI_FORMAT_D32_FLOAT;
1266 dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
1267 hr = device->CreateDepthStencilView(m_shadowDepthTex, &dsvDesc, &m_shadowDSV);
1268 if (FAILED(hr)) {
1269 SLEAK_ERROR("Failed to create shadow DSV!");
1270 return false;
1271 }
1272
1273 // Create SRV for sampling
1274 D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{};
1275 srvDesc.Format = DXGI_FORMAT_R32_FLOAT;
1276 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
1277 srvDesc.Texture2D.MipLevels = 1;
1278 hr = device->CreateShaderResourceView(m_shadowDepthTex, &srvDesc, &m_shadowSRV);
1279 if (FAILED(hr)) {
1280 SLEAK_ERROR("Failed to create shadow SRV!");
1281 return false;
1282 }
1283
1284 // Create comparison sampler
1285 D3D11_SAMPLER_DESC sampDesc{};
1286 sampDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
1287 sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER;
1288 sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER;
1289 sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER;
1290 sampDesc.BorderColor[0] = 1.0f;
1291 sampDesc.BorderColor[1] = 1.0f;
1292 sampDesc.BorderColor[2] = 1.0f;
1293 sampDesc.BorderColor[3] = 1.0f;
1294 sampDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
1295 sampDesc.MinLOD = 0;
1296 sampDesc.MaxLOD = 0;
1297 hr = device->CreateSamplerState(&sampDesc, &m_shadowSampler);
1298 if (FAILED(hr)) {
1299 SLEAK_ERROR("Failed to create shadow sampler!");
1300 return false;
1301 }
1302
1303 // Create shadow rasterizer state with depth bias
1304 D3D11_RASTERIZER_DESC rasterDesc{};
1305 rasterDesc.FillMode = D3D11_FILL_SOLID;
1306 rasterDesc.CullMode = D3D11_CULL_NONE; // all faces cast shadow regardless of orientation
1307 rasterDesc.FrontCounterClockwise = FALSE;
1308 rasterDesc.DepthBias = 100;
1309 rasterDesc.SlopeScaledDepthBias = 2.0f;
1310 rasterDesc.DepthBiasClamp = 0.01f;
1311 rasterDesc.DepthClipEnable = TRUE;
1312 hr = device->CreateRasterizerState(&rasterDesc, &m_shadowRasterState);
1313 if (FAILED(hr)) {
1314 SLEAK_ERROR("Failed to create shadow rasterizer state!");
1315 return false;
1316 }
1317
1318 m_shadowMapCreated = true;
1319 m_shadowResourcesCreated = true;
1320 SLEAK_INFO("D3D11 shadow map resources created ({}x{})", m_shadowMapResolution, m_shadowMapResolution);
1321 return true;
1322}
1323
1324void DirectX11Renderer::RenderShadowPass() {
1325 // Skip if no cached draws — preserve previous frame's shadow map
1326 auto* queue = RenderCommandQueue::GetInstance();
1327 if (!queue || !queue->HasCachedShadowDraws()) return;
1328
1329 if (!m_shadowMapCreated) {
1330 if (!CreateShadowMapResources()) return;
1331 }
1332
1333 // Save current render targets and viewport
1334 ID3D11RenderTargetView* savedRTV = nullptr;
1335 ID3D11DepthStencilView* savedDSV = nullptr;
1336 deviceContext->OMGetRenderTargets(1, &savedRTV, &savedDSV);
1337
1338 D3D11_VIEWPORT savedViewport;
1339 UINT numViewports = 1;
1340 deviceContext->RSGetViewports(&numViewports, &savedViewport);
1341
1342 // Unbind shadow SRV to avoid D3D11 warning (resource bound as both input and output)
1343 ID3D11ShaderResourceView* nullSRV = nullptr;
1344 deviceContext->PSSetShaderResources(3, 1, &nullSRV);
1345
1346 // Set shadow render target (depth only, no color)
1347 ID3D11RenderTargetView* nullRTV = nullptr;
1348 deviceContext->OMSetRenderTargets(1, &nullRTV, m_shadowDSV);
1349
1350 // Set shadow viewport
1351 D3D11_VIEWPORT shadowViewport{};
1352 shadowViewport.Width = static_cast<float>(m_shadowMapResolution);
1353 shadowViewport.Height = static_cast<float>(m_shadowMapResolution);
1354 shadowViewport.MinDepth = 0.0f;
1355 shadowViewport.MaxDepth = 1.0f;
1356 deviceContext->RSSetViewports(1, &shadowViewport);
1357
1358 // Clear shadow depth
1359 deviceContext->ClearDepthStencilView(m_shadowDSV, D3D11_CLEAR_DEPTH, 1.0f, 0);
1360
1361 // Set shadow rasterizer state
1362 deviceContext->RSSetState(m_shadowRasterState);
1363
1364 // Set primitive topology (same as main pass)
1365 deviceContext->IASetPrimitiveTopology(topology);
1366 if (bIsLayoutCreated)
1367 deviceContext->IASetInputLayout(layout);
1368
1369 // Execute shadow draw commands
1370 m_inShadowPass = true;
1371 if (queue) {
1372 queue->ExecuteShadowPass(this);
1373 }
1374 m_inShadowPass = false;
1375
1376 // Restore raster state
1377 SetRasterState();
1378
1379 // Restore render targets and viewport
1380 deviceContext->OMSetRenderTargets(1, &savedRTV, savedDSV);
1381 deviceContext->RSSetViewports(1, &savedViewport);
1382 if (savedRTV) savedRTV->Release();
1383 if (savedDSV) savedDSV->Release();
1384
1385 // Bind shadow map SRV and sampler for main pass
1386 deviceContext->PSSetShaderResources(3, 1, &m_shadowSRV);
1387 deviceContext->PSSetSamplers(3, 1, &m_shadowSampler);
1388}
1389
1390void DirectX11Renderer::UpdateShadowLightUBO(const void* data, uint32_t size) {
1391 if (!device || !deviceContext) return;
1392
1393 // Create shadow CB on first call
1394 if (!m_shadowCBCreated) {
1395 if (!CreateShadowConstantBuffer()) return;
1396 }
1397
1398 // Map the ShadowLightUBO data into our PCSSShadowGPUData format
1399 const auto* ubo = static_cast<const ShadowLightUBO*>(data);
1400
1401 PCSSShadowGPUData shadowData{};
1402 std::memcpy(shadowData.LightVP, ubo->LightVP, sizeof(float) * 16);
1403 shadowData.ShadowBias = ubo->ShadowBias;
1404 shadowData.ShadowStrength = ubo->ShadowStrength;
1405 shadowData.ShadowTexelSize = ubo->ShadowTexelSize;
1406 shadowData.ShadowLightSize = ubo->LightSize;
1407 shadowData.PCSSEnabled = m_pcssEnabled ? 1 : 0;
1408 shadowData.ShadowMapEnabled = m_shadowPassEnabled ? 1 : 0;
1409
1410 D3D11_MAPPED_SUBRESOURCE mapped{};
1411 HRESULT hr = deviceContext->Map(m_shadowCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
1412 if (SUCCEEDED(hr)) {
1413 std::memcpy(mapped.pData, &shadowData, sizeof(shadowData));
1414 deviceContext->Unmap(m_shadowCB, 0);
1415 }
1416
1417 // Bind shadow CB at slot 5 (both VS and PS)
1418 deviceContext->VSSetConstantBuffers(5, 1, &m_shadowCB);
1419 deviceContext->PSSetConstantBuffers(5, 1, &m_shadowCB);
1420}
1421
1422// ---- Post-Process: Tonemapping ----
1423
1424bool DirectX11Renderer::CreateTonemapResources() {
1425 if (m_tonemapResourcesCreated) return true;
1426 if (!device) return false;
1427
1428 // Get back buffer dimensions
1429 ID3D11Texture2D* backBuffer = nullptr;
1430 swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBuffer);
1431 if (!backBuffer) return false;
1432
1433 D3D11_TEXTURE2D_DESC bbDesc{};
1434 backBuffer->GetDesc(&bbDesc);
1435 backBuffer->Release();
1436
1437 // Create HDR render target (R16G16B16A16_FLOAT)
1438 D3D11_TEXTURE2D_DESC texDesc{};
1439 texDesc.Width = bbDesc.Width;
1440 texDesc.Height = bbDesc.Height;
1441 texDesc.MipLevels = 1;
1442 texDesc.ArraySize = 1;
1443 texDesc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
1444 texDesc.SampleDesc.Count = 1;
1445 texDesc.SampleDesc.Quality = 0;
1446 texDesc.Usage = D3D11_USAGE_DEFAULT;
1447 texDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
1448
1449 HRESULT hr = device->CreateTexture2D(&texDesc, nullptr, &m_hdrTexture);
1450 if (FAILED(hr)) {
1451 SLEAK_ERROR("Failed to create HDR texture for tonemapping!");
1452 return false;
1453 }
1454
1455 hr = device->CreateRenderTargetView(m_hdrTexture, nullptr, &m_hdrRTV);
1456 if (FAILED(hr)) return false;
1457
1458 hr = device->CreateShaderResourceView(m_hdrTexture, nullptr, &m_hdrSRV);
1459 if (FAILED(hr)) return false;
1460
1461 // Create point sampler
1462 D3D11_SAMPLER_DESC sampDesc{};
1463 sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
1464 sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
1465 sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
1466 sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
1467 hr = device->CreateSamplerState(&sampDesc, &m_pointSampler);
1468 if (FAILED(hr)) return false;
1469
1470 // Create post-process constant buffer
1471 D3D11_BUFFER_DESC cbDesc{};
1472 cbDesc.ByteWidth = sizeof(PostProcessGPUData);
1473 cbDesc.Usage = D3D11_USAGE_DYNAMIC;
1474 cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1475 cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
1476 hr = device->CreateBuffer(&cbDesc, nullptr, &m_postProcessCB);
1477 if (FAILED(hr)) return false;
1478
1479 if (!CompileTonemapShaders(&m_tonemapVS, &m_tonemapPS)) return false;
1480
1481 m_tonemapResourcesCreated = true;
1482 SLEAK_INFO("Tonemapping post-process resources created successfully");
1483 return true;
1484}
1485
1486bool DirectX11Renderer::CompileTonemapShaders(ID3D11VertexShader** vs,
1487 ID3D11PixelShader** ps) {
1488 // Path is relative to the working directory (bin/)
1489 const std::string narrowPath = TONEMAP_SHADER_PATH;
1490 const std::wstring shaderPath(narrowPath.begin(), narrowPath.end());
1491
1492 Microsoft::WRL::ComPtr<ID3DBlob> vsBlob;
1493 Microsoft::WRL::ComPtr<ID3DBlob> psBlob;
1494 Microsoft::WRL::ComPtr<ID3DBlob> errorBlob;
1495 HRESULT hr = D3DCompileFromFile(
1496 shaderPath.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
1497 "VS_Main", "vs_5_0", D3DCOMPILE_DEBUG, 0, &vsBlob, &errorBlob);
1498 if (FAILED(hr)) {
1499 LogCompileError(TONEMAP_SHADER_PATH, "VS_Main", hr, errorBlob.Get());
1500 return false;
1501 }
1502 hr = D3DCompileFromFile(shaderPath.c_str(), nullptr,
1503 D3D_COMPILE_STANDARD_FILE_INCLUDE, "PS_Main",
1504 "ps_5_0", D3DCOMPILE_DEBUG, 0, &psBlob, &errorBlob);
1505 if (FAILED(hr)) {
1506 LogCompileError(TONEMAP_SHADER_PATH, "PS_Main", hr, errorBlob.Get());
1507 return false;
1508 }
1509
1510 Microsoft::WRL::ComPtr<ID3D11VertexShader> vertexShader;
1511 Microsoft::WRL::ComPtr<ID3D11PixelShader> pixelShader;
1512 if (FAILED(device->CreateVertexShader(vsBlob->GetBufferPointer(),
1513 vsBlob->GetBufferSize(), nullptr,
1514 &vertexShader)) ||
1515 FAILED(device->CreatePixelShader(psBlob->GetBufferPointer(),
1516 psBlob->GetBufferSize(), nullptr,
1517 &pixelShader))) {
1518 SLEAK_ERROR("Failed to create tonemap shader objects");
1519 return false;
1520 }
1521 *vs = vertexShader.Detach();
1522 *ps = pixelShader.Detach();
1523 return true;
1524}
1525
1526#ifdef SLEAK_HOT_RELOAD
1527void DirectX11Renderer::ReloadTonemapShaders() {
1528 // Not built yet, the first tonemap pass compiles the new file
1529 if (!m_tonemapResourcesCreated) return;
1530
1531 ID3D11VertexShader* vs = nullptr;
1532 ID3D11PixelShader* ps = nullptr;
1533 if (!CompileTonemapShaders(&vs, &ps)) {
1534 SLEAK_WARN("Shader '{}' failed to reload, keeping the old one",
1535 TONEMAP_STEM);
1536 return;
1537 }
1538 if (m_tonemapVS) m_tonemapVS->Release();
1539 if (m_tonemapPS) m_tonemapPS->Release();
1540 m_tonemapVS = vs;
1541 m_tonemapPS = ps;
1542 SLEAK_INFO("Reloaded DirectX 11 shader '{}'", TONEMAP_STEM);
1543}
1544#endif
1545
1546void DirectX11Renderer::CleanupTonemapResources() {
1547 if (m_tonemapVS) { m_tonemapVS->Release(); m_tonemapVS = nullptr; }
1548 if (m_tonemapPS) { m_tonemapPS->Release(); m_tonemapPS = nullptr; }
1549 if (m_postProcessCB) { m_postProcessCB->Release(); m_postProcessCB = nullptr; }
1550 if (m_hdrSRV) { m_hdrSRV->Release(); m_hdrSRV = nullptr; }
1551 if (m_hdrRTV) { m_hdrRTV->Release(); m_hdrRTV = nullptr; }
1552 if (m_hdrTexture) { m_hdrTexture->Release(); m_hdrTexture = nullptr; }
1553 if (m_pointSampler) { m_pointSampler->Release(); m_pointSampler = nullptr; }
1554 m_tonemapResourcesCreated = false;
1555}
1556
1557void DirectX11Renderer::ExecuteTonemapPass() {
1558 if (!m_tonemapResourcesCreated || !m_tonemapVS || !m_tonemapPS)
1559 return;
1560
1561 // Update post-process constant buffer
1562 PostProcessGPUData ppData{};
1563 ppData.Exposure = m_exposure;
1564 ppData.Gamma = m_gamma;
1565 ppData.TonemapEnabled = m_tonemapEnabled ? 1 : 0;
1566
1567 D3D11_MAPPED_SUBRESOURCE mapped{};
1568 HRESULT hr = deviceContext->Map(m_postProcessCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
1569 if (SUCCEEDED(hr)) {
1570 std::memcpy(mapped.pData, &ppData, sizeof(ppData));
1571 deviceContext->Unmap(m_postProcessCB, 0);
1572 }
1573
1574 // Switch render target to backbuffer
1575 deviceContext->OMSetRenderTargets(1, &renderTargetView, nullptr);
1576
1577 // Bind HDR texture as input
1578 deviceContext->PSSetShaderResources(0, 1, &m_hdrSRV);
1579 deviceContext->PSSetSamplers(0, 1, &m_pointSampler);
1580 deviceContext->PSSetConstantBuffers(0, 1, &m_postProcessCB);
1581
1582 // Set tonemap shaders
1583 deviceContext->VSSetShader(m_tonemapVS, nullptr, 0);
1584 deviceContext->PSSetShader(m_tonemapPS, nullptr, 0);
1585
1586 // Draw fullscreen triangle (no input layout needed for SV_VertexID)
1587 deviceContext->IASetInputLayout(nullptr);
1588 deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1589 deviceContext->Draw(3, 0);
1590
1591 // Unbind HDR SRV to prevent read/write conflict
1592 ID3D11ShaderResourceView* nullSRV = nullptr;
1593 deviceContext->PSSetShaderResources(0, 1, &nullSRV);
1594}
1595
1596} // namespace RenderEngine
1597} // namespace Sleak
1598
1599#else
1600namespace Sleak::RenderEngine {class DirectX11Renderer;}
1601
1602#endif
int width
int height
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
class ENGINE_API Window