5#include <d3dcompiler.h>
7#include <imgui_internal.h>
10#include <wrl/client.h>
32 constexpr const char* TONEMAP_SHADER_PATH =
"assets/shaders/tonemap.hlsl";
33#ifdef SLEAK_HOT_RELOAD
34 constexpr const char* TONEMAP_STEM =
"tonemap";
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);
45 void BuildShadowTransform(
const float* world,
const float* lightVP,
47 for (
int r = 0; r < MATRIX_DIM; ++r) {
48 for (
int c = 0; c < MATRIX_DIM; ++c) {
50 for (
int k = 0; k < MATRIX_DIM; ++k) {
52 world[r * MATRIX_DIM + k] * lightVP[k * MATRIX_DIM + c];
54 out[r * MATRIX_DIM + c] = sum;
57 std::memcpy(out + MATRIX_FLOATS, world, MATRIX_FLOATS *
sizeof(
float));
61 void LogCompileError(
const char* path,
const char* entry, HRESULT hr,
64 SLEAK_ERROR(
"{} ({}) compile error: {}", path, entry,
65 static_cast<const char*
>(errors->GetBufferPointer()));
67 SLEAK_ERROR(
"{} ({}) compile error: 0x{:08X}", path, entry,
68 static_cast<unsigned int>(hr));
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;
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;
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);
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();
116 Microsoft::WRL::ComPtr<State> state;
117 if (FAILED(create(&desc, state.GetAddressOf())))
return nullptr;
118 cache.emplace_back(desc, state);
125DirectX11Renderer::DirectX11Renderer(
Window* window)
128 deviceContext(nullptr),
130 renderTargetView(nullptr) {
131 this->Type = RendererType::DirectX11;
132 this->cull = D3D11_CULL_FRONT;
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;
149DirectX11Renderer::~DirectX11Renderer() {
153bool DirectX11Renderer::Initialize() {
154 HWND hwnd = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window->GetSDLWindow()),
155 SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
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;
171 UINT createDeviceFlags = 0;
173 createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
176 D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 };
177 HRESULT hr = D3D11CreateDeviceAndSwapChain(
179 D3D_DRIVER_TYPE_HARDWARE,
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);
205 SLEAK_ERROR(
"Failed to create device and swap chain! HRESULT: 0x{:X}",
212 if (!CreateRenderTargetView() ||
213 !CreateDepthStencilBuffer(window->GetWidth(), window->GetHeight())) {
217 SetViewport(0, 0, window->GetWidth(), window->GetHeight());
219 SLEAK_INFO(
"DirectX 11 has successfully created!");
222 ID3D11InfoQueue* infoQueue;
223 if (SUCCEEDED(device->QueryInterface(__uuidof(ID3D11InfoQueue),
224 (
void**)&infoQueue))) {
227 infoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION,
true);
229 D3D11_MESSAGE_SEVERITY severities[] = {D3D11_MESSAGE_SEVERITY_INFO};
231 D3D11_INFO_QUEUE_FILTER filter = {};
232 filter.DenyList.NumSeverities = _countof(severities);
233 filter.DenyList.pSeverityList = severities;
235 infoQueue->AddStorageFilterEntries(&filter);
236 infoQueue->Release();
240 SetPerformanceCounter(
true);
241 SetRenderMode(RenderMode::Fill);
242 SetRenderFace(RenderFace::Front);
244 ConfigureRenderMode();
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!");
256 if (bEnabledPerformanceCounter && query) {
257 while (deviceContext->GetData(query,
nullptr, 0, 0) == S_FALSE)
258 std::this_thread::yield();
259 deviceContext->Begin(query);
262 if (!CreateBlendState())
268void DirectX11Renderer::BeginRender() {
269 if (m_msaaChangeRequested)
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;
280 if (m_tonemapEnabled && !m_tonemapResourcesCreated)
281 CreateTonemapResources();
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);
289 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
293 ClearDepthStencil(
true,
false, 1.0, 0);
296 if (m_shadowPassEnabled) {
303 if (m_shadowMapCreated && m_shadowSRV && m_shadowSampler) {
304 deviceContext->PSSetShaderResources(3, 1, &m_shadowSRV);
305 deviceContext->PSSetSamplers(3, 1, &m_shadowSampler);
308 if (bIsLayoutCreated)
309 deviceContext->IASetInputLayout(layout);
312 ImGui_ImplDX11_NewFrame();
313 ImGui_ImplSDL3_NewFrame();
318void DirectX11Renderer::EndRender() {
320 if (msaaSampleCount > 1) {
322 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
327 if (m_tonemapEnabled && m_tonemapResourcesCreated && msaaSampleCount <= 1) {
328 ExecuteTonemapPass();
330 if (bIsLayoutCreated)
331 deviceContext->IASetInputLayout(layout);
335 if (bImInitialized) {
337 deviceContext->OMSetRenderTargets(1, &renderTargetView,
nullptr);
339 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
342 swapChain->Present(m_vsync ? 1 : 0, 0);
344 UpdateFrameMetrics();
347void DirectX11Renderer::Cleanup() {
348 bImInitialized =
false;
351 CleanupTonemapResources();
352 CleanupShadowResources();
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; }
360 if (renderTargetView) {
361 renderTargetView->Release();
362 renderTargetView =
nullptr;
365 swapChain->Release();
369 deviceContext->Release();
370 deviceContext =
nullptr;
373 if (depthStencilView) {
374 depthStencilView->Release();
375 depthStencilView =
nullptr;
377 if (depthStencilBuffer) {
378 depthStencilBuffer->Release();
379 depthStencilBuffer =
nullptr;
381 if (depthStencilState) {
382 depthStencilState->Release();
383 depthStencilState =
nullptr;
387 blendState->Release();
388 blendState =
nullptr;
391 m_rasterStates.clear();
392 m_depthStates.clear();
400 if (bImInitialized) {
401 ImGui_ImplDX11_Shutdown();
402 ImGui_ImplSDL3_Shutdown();
403 ImGui::DestroyContext();
404 bImInitialized =
false;
409 ID3D11Debug* debugDevice;
410 device->QueryInterface(__uuidof(ID3D11Debug), (
void**)&debugDevice);
412 debugDevice->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
413 debugDevice->Release();
424bool DirectX11Renderer::CreateDepthStencilBuffer(uint32_t
width,uint32_t
height) {
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;
438 device->CreateTexture2D(&depthDesc,
nullptr, &depthStencilBuffer);
440 SLEAK_ERROR(
"Failed to create depth stencil buffer!");
444 hr = device->CreateDepthStencilView(depthStencilBuffer,
nullptr,
447 SLEAK_ERROR(
"Failed to create depth stencil view!");
451 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
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;
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;
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;
477 ID3D11DepthStencilState* state =
nullptr;
478 HRESULT hr = device->CreateDepthStencilState(&depthStencilDesc, &state);
480 SLEAK_ERROR(
"Failed to create depth stencil state!");
484 if (depthStencilState) depthStencilState->Release();
485 depthStencilState = state;
486 deviceContext->OMSetDepthStencilState(depthStencilState, 1);
489void DirectX11Renderer::Resize(uint32_t
width, uint32_t
height) {
490 if (swapChain ==
nullptr || device ==
nullptr || deviceContext ==
nullptr) {
496 deviceContext->OMSetRenderTargets(0,
nullptr,
nullptr);
497 deviceContext->ClearState();
498 deviceContext->Flush();
501 if (renderTargetView) {
502 renderTargetView->Release();
503 renderTargetView =
nullptr;
506 if (depthStencilView) {
507 depthStencilView->Release();
508 depthStencilView =
nullptr;
510 if (depthStencilBuffer) {
511 depthStencilBuffer->Release();
512 depthStencilBuffer =
nullptr;
514 if (depthStencilState) {
515 depthStencilState->Release();
516 depthStencilState =
nullptr;
521 HRESULT hr = swapChain->ResizeBuffers(0,
527 SLEAK_ERROR(
"Failed to resize swap chain buffers! HRESULT: 0x{:X}", (
unsigned)hr);
532 if (!CreateRenderTargetView() || !CreateDepthStencilBuffer(
width,
height)) {
537 if (msaaSampleCount > 1) {
538 CreateMSAARenderTarget();
539 CreateMSAADepthStencil();
543 if (m_tonemapResourcesCreated) {
544 CleanupTonemapResources();
545 CreateTonemapResources();
556void DirectX11Renderer::Draw(uint32_t vertexCount) {
Draw(vertexCount, 0); }
558void DirectX11Renderer::Draw(uint32_t vertexCount, uint32_t firstVertex) {
559 deviceContext->Draw(vertexCount, firstVertex);
562void DirectX11Renderer::DrawIndexed(uint32_t indexCount) {
566void DirectX11Renderer::DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
567 int32_t baseVertex) {
568 deviceContext->DrawIndexed(indexCount, firstIndex, baseVertex);
569 DrawnVertices += indexCount;
572void DirectX11Renderer::DrawInstance(uint32_t instanceCount,
573 uint32_t vertexPerInstance) {
574 deviceContext->DrawInstanced(vertexPerInstance, instanceCount, 0, 0);
577void DirectX11Renderer::DrawIndexedInstance(uint32_t instanceCount,
578 uint32_t indexPerInstance) {
579 DrawIndexedInstance(instanceCount, indexPerInstance, 0, 0);
582void DirectX11Renderer::DrawIndexedInstance(uint32_t instanceCount,
583 uint32_t indexPerInstance,
585 int32_t baseVertex) {
586 deviceContext->DrawIndexedInstanced(indexPerInstance, instanceCount,
587 firstIndex, baseVertex, 0);
590void DirectX11Renderer::ClearRenderTarget(
float r,
float g,
float b,
float a) {
591 const float clearColor[4] = {r, g, b, a};
593 ID3D11RenderTargetView* target;
594 if (m_tonemapEnabled && m_tonemapResourcesCreated && msaaSampleCount <= 1)
596 else if (msaaSampleCount > 1)
597 target = msaaRenderTargetView;
599 target = renderTargetView;
602 deviceContext->ClearRenderTargetView(target, clearColor);
605void DirectX11Renderer::ClearDepthStencil(
bool clearDepth,
bool clearStencil,
606 float depth, uint8_t stencil) {
608 if (clearDepth) clearFlags |= D3D11_CLEAR_DEPTH;
609 if (clearStencil) clearFlags |= D3D11_CLEAR_STENCIL;
611 ID3D11DepthStencilView* target = (msaaSampleCount > 1 && msaaDepthStencilView)
612 ? msaaDepthStencilView : depthStencilView;
614 deviceContext->ClearDepthStencilView(target, clearFlags, depth, stencil);
619void DirectX11Renderer::BindVertexBuffer(RefPtr<BufferBase> buffer, uint32_t slot) {
620 auto* dx11Buf =
static_cast<DirectX11Buffer*
>(buffer.get());
621 if (!dx11Buf)
return;
623 ID3D11Buffer* d3d11Buffer = dx11Buf->GetD3DBuffer();
626 deviceContext->IASetVertexBuffers(slot, 1, &d3d11Buffer, &stride, &offset);
629void DirectX11Renderer::BindIndexBuffer(RefPtr<BufferBase> buffer,
631 auto* dx11Buf =
static_cast<DirectX11Buffer*
>(buffer.get());
632 if (!dx11Buf)
return;
634 deviceContext->IASetIndexBuffer(dx11Buf->GetD3DBuffer(),
635 DXGI_FORMAT_R32_UINT, 0);
638void DirectX11Renderer::BindConstantBuffer(RefPtr<BufferBase> buffer,
640 auto* dx11Buf =
static_cast<DirectX11Buffer*
>(buffer.get());
641 if (!dx11Buf)
return;
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);
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;
658 device->CreateBuffer(&desc,
nullptr, &m_shadowTransformCB)))
660 m_shadowCBCacheValid =
false;
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);
670 D3D11_MAPPED_SUBRESOURCE mapped{};
671 if (SUCCEEDED(deviceContext->Map(m_shadowTransformCB, 0,
672 D3D11_MAP_WRITE_DISCARD, 0,
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;
681 deviceContext->VSSetConstantBuffers(slot, 1, &m_shadowTransformCB);
682 deviceContext->PSSetConstantBuffers(slot, 1, &m_shadowTransformCB);
686 auto d3d11Buffer = dx11Buf->GetD3DBuffer();
687 deviceContext->VSSetConstantBuffers(slot, 1, &d3d11Buffer);
688 deviceContext->PSSetConstantBuffers(slot, 1, &d3d11Buffer);
691void DirectX11Renderer::ConfigureRenderMode() {
694 case RenderMode::Fill:
695 topology = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
696 fillMode = D3D11_FILL_MODE::D3D11_FILL_SOLID;
698 case RenderMode::Points:
699 topology = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
700 fillMode = D3D11_FILL_MODE::D3D11_FILL_SOLID;
702 case RenderMode::Wireframe :
703 topology = D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
704 fillMode = D3D11_FILL_MODE::D3D11_FILL_WIREFRAME;
712 deviceContext->IASetPrimitiveTopology(topology);
717void DirectX11Renderer::ConfigureRenderFace() {
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;
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;
739 ID3D11RasterizerState* rasterState = GetRasterState(RasterDesc);
740 if (!rasterState)
return false;
742 deviceContext->RSSetState(rasterState);
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);
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);
764void DirectX11Renderer::SetRenderMode(RenderMode mode) {
766 ConfigureRenderMode();
769void DirectX11Renderer::SetRenderFace(RenderFace face) {
771 ConfigureRenderFace();
774void DirectX11Renderer::SetViewport(
float x,
float y,
float width,
float height,
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);
788bool DirectX11Renderer::CreateRenderTargetView() {
790 if (renderTargetView) {
791 renderTargetView->Release();
792 renderTargetView =
nullptr;
796 ID3D11Texture2D* backBuffer =
nullptr;
797 HRESULT hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
798 reinterpret_cast<void**
>(&backBuffer));
805 hr = device->CreateRenderTargetView(backBuffer,
nullptr, &renderTargetView);
806 backBuffer->Release();
808 SLEAK_ERROR(
"Failed to create render target view!");
813 deviceContext->OMSetRenderTargets(1, &renderTargetView,
nullptr);
815 SLEAK_INFO(
"Render target view created successfully.");
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)) {
827Texture* DirectX11Renderer::CreateTexture(
const std::string& TexturePath) {
828 DirectX11Texture* texture =
new DirectX11Texture(device);
829 if (texture->LoadFromFile(TexturePath)) {
835Texture* DirectX11Renderer::CreateCubemapTexture(
836 const std::array<std::string, 6>& facePaths) {
837 auto* texture =
new DirectX11CubemapTexture(device);
838 if (texture->LoadCubemap(facePaths)) {
845Texture* DirectX11Renderer::CreateCubemapTextureFromPanorama(
846 const std::string& panoramaPath) {
847 auto* texture =
new DirectX11CubemapTexture(device);
848 if (texture->LoadEquirectangular(panoramaPath)) {
855void DirectX11Renderer::SetDepthWrite(
bool enabled) {
856 m_depthWriteEnabled = enabled;
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;
868 if (ID3D11DepthStencilState* state = GetDepthState(desc))
869 deviceContext->OMSetDepthStencilState(state, 1);
872void DirectX11Renderer::SetDepthCompare(DepthCompare 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;
887void DirectX11Renderer::SetCullEnabled(
bool enabled) {
889 cull = D3D11_CULL_FRONT;
891 cull = D3D11_CULL_NONE;
896void DirectX11Renderer::BindTexture(RefPtr<Sleak::Texture> texture,
898 if (texture.IsValid()) {
903void DirectX11Renderer::BeginSkyboxPass() {
905 m_savedCullMode = cull;
906 m_savedDepthStencilState = depthStencilState;
907 if (m_savedDepthStencilState) {
908 m_savedDepthStencilState->AddRef();
912void DirectX11Renderer::EndSkyboxPass() {
914 if (m_savedDepthStencilState) {
915 deviceContext->OMSetDepthStencilState(m_savedDepthStencilState, 1);
916 m_savedDepthStencilState->Release();
917 m_savedDepthStencilState =
nullptr;
921 cull = m_savedCullMode;
925 m_depthWriteEnabled =
true;
926 m_depthFunc = D3D11_COMPARISON_LESS;
929void DirectX11Renderer::BeginDebugLinePass() {
930 m_savedTopology = topology;
931 topology = D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
932 deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
935void DirectX11Renderer::EndDebugLinePass() {
936 topology = m_savedTopology;
937 deviceContext->IASetPrimitiveTopology(topology);
940BufferBase* DirectX11Renderer::CreateBuffer(BufferType Type, uint32_t size,
void* data) {
943 DirectX11Buffer* buffer =
new DirectX11Buffer(device, size, Type);
944 if (!buffer->Initialize(data)) {
948 return static_cast<BufferBase*
>(buffer);
951Shader* DirectX11Renderer::CreateShader(
const std::string& shaderSource) {
952 DirectX11Shader* shader =
new DirectX11Shader(device);
953 if (shader->compile(shaderSource)) {
956 auto* il = shader->createInputLayout();
957 if (!bIsLayoutCreated && il) {
959 bIsLayoutCreated =
true;
963 return static_cast<Shader*
>(shader);
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);
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);
985 if (std::ranges::any_of(failed, sameSources))
continue;
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());
995 failed.push_back(shader);
996 SLEAK_WARN(
"Shader '{}' failed to reload, keeping the old one",
1002 if (bIsLayoutCreated && oldLayout && oldLayout == layout) {
1003 ID3D11InputLayout* fresh = shader->getInputLayout();
1004 if (fresh) fresh->AddRef();
1010 if (std::find(stems.begin(), stems.end(), TONEMAP_STEM) != stems.end())
1011 ReloadTonemapShaders();
1013 for (
const std::string& stem : stems) {
1015 stem == TONEMAP_STEM ||
1016 std::ranges::any_of(DirectX11Shader::GetLiveShaders(),
1017 [&stem](
const DirectX11Shader* shader) {
1018 return shader->UsesStem(stem);
1022 "Hot reload: no loaded DirectX 11 shader is built from '{}'",
1029bool DirectX11Renderer::CreateBlendState() {
1034 D3D11_BLEND_DESC desc;
1035 desc.AlphaToCoverageEnable =
false;
1036 desc.IndependentBlendEnable =
false;
1038 desc.RenderTarget[0].BlendEnable =
true;
1040 desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
1041 desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
1043 desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
1044 desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
1046 desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
1047 desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
1049 desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
1051 if (FAILED(device->CreateBlendState(&desc, &blendState)))
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);
1062void DirectX11Renderer::CheckMSAASupport() {
1063 m_maxMsaaSampleCount = 1;
1064 for (UINT sampleCount = 1;
1065 sampleCount <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT;
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;
1080bool DirectX11Renderer::CreateMSAARenderTarget() {
1082 if (msaaRenderTarget) msaaRenderTarget->Release();
1083 if (msaaRenderTargetView) msaaRenderTargetView->Release();
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;
1098 if (FAILED(device->CreateTexture2D(&texDesc,
nullptr, &msaaRenderTarget)))
1101 if (FAILED(device->CreateRenderTargetView(msaaRenderTarget,
nullptr,&msaaRenderTargetView)))
1107bool DirectX11Renderer::CreateMSAADepthStencil() {
1108 if (msaaDepthStencilBuffer) msaaDepthStencilBuffer->Release();
1109 if (msaaDepthStencilView) msaaDepthStencilView->Release();
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;
1124 if (FAILED(device->CreateTexture2D(&texDesc,
nullptr,&msaaDepthStencilBuffer)))
return false;
1126 if (FAILED(device->CreateDepthStencilView(msaaDepthStencilBuffer,
nullptr,&msaaDepthStencilView)))
return false;
1132void DirectX11Renderer::ResolveMSAA() {
1133 if (msaaSampleCount <= 1 || msaaSampleCount % 2 != 0)
1136 ID3D11Texture2D* back;
1137 if (FAILED(swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (
void**)&back))) {
1138 SLEAK_ERROR(
"Failed to get back buffer for MSAA!");
1141 deviceContext->ResolveSubresource(back,0,msaaRenderTarget,0,DXGI_FORMAT_R8G8B8A8_UNORM);
1146void DirectX11Renderer::ApplyMSAAChange() {
1147 if (!m_msaaChangeRequested)
1149 m_msaaChangeRequested =
false;
1151 m_msaaSampleCount = m_pendingMsaaSampleCount;
1152 msaaSampleCount = m_pendingMsaaSampleCount;
1156 device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM,
1157 msaaSampleCount, &quality);
1158 msaaQualityLevel = (quality > 0) ? quality - 1 : 0;
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; }
1166 if (msaaSampleCount > 1) {
1167 CreateMSAARenderTarget();
1168 CreateMSAADepthStencil();
1171 deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
1174 SLEAK_INFO(
"DX11 MSAA changed to {}x", msaaSampleCount);
1177bool DirectX11Renderer::CreateImGUI()
1179 IMGUI_CHECKVERSION();
1180 ImCon = ImGui::CreateContext();
1181 ImCon->IO.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
1183 ImGui::StyleColorsDark();
1185 if(!ImGui_ImplSDL3_InitForD3D(window->GetSDLWindow()))
1188 if(!ImGui_ImplDX11_Init(device, deviceContext))
1191 if(!ImGui_ImplDX11_CreateDeviceObjects())
1195 bImInitialized =
true;
1203bool DirectX11Renderer::CreateShadowConstantBuffer() {
1204 if (m_shadowCBCreated)
return true;
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;
1212 HRESULT hr = device->CreateBuffer(&desc,
nullptr, &m_shadowCB);
1214 SLEAK_ERROR(
"Failed to create shadow constant buffer!");
1218 m_shadowCBCreated =
true;
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;
1235void DirectX11Renderer::SetLightVP(
const float* mat) {
1237 std::memcpy(m_pendingLightVP, mat,
sizeof(m_pendingLightVP));
1238 m_hasPendingLightVP =
true;
1242bool DirectX11Renderer::CreateShadowMapResources() {
1243 if (m_shadowMapCreated)
return true;
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;
1257 HRESULT hr = device->CreateTexture2D(&texDesc,
nullptr, &m_shadowDepthTex);
1259 SLEAK_ERROR(
"Failed to create shadow depth texture!");
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);
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);
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);
1304 D3D11_RASTERIZER_DESC rasterDesc{};
1305 rasterDesc.FillMode = D3D11_FILL_SOLID;
1306 rasterDesc.CullMode = D3D11_CULL_NONE;
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);
1314 SLEAK_ERROR(
"Failed to create shadow rasterizer state!");
1318 m_shadowMapCreated =
true;
1319 m_shadowResourcesCreated =
true;
1320 SLEAK_INFO(
"D3D11 shadow map resources created ({}x{})", m_shadowMapResolution, m_shadowMapResolution);
1324void DirectX11Renderer::RenderShadowPass() {
1326 auto* queue = RenderCommandQueue::GetInstance();
1327 if (!queue || !queue->HasCachedShadowDraws())
return;
1329 if (!m_shadowMapCreated) {
1330 if (!CreateShadowMapResources())
return;
1334 ID3D11RenderTargetView* savedRTV =
nullptr;
1335 ID3D11DepthStencilView* savedDSV =
nullptr;
1336 deviceContext->OMGetRenderTargets(1, &savedRTV, &savedDSV);
1338 D3D11_VIEWPORT savedViewport;
1339 UINT numViewports = 1;
1340 deviceContext->RSGetViewports(&numViewports, &savedViewport);
1343 ID3D11ShaderResourceView* nullSRV =
nullptr;
1344 deviceContext->PSSetShaderResources(3, 1, &nullSRV);
1347 ID3D11RenderTargetView* nullRTV =
nullptr;
1348 deviceContext->OMSetRenderTargets(1, &nullRTV, m_shadowDSV);
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);
1359 deviceContext->ClearDepthStencilView(m_shadowDSV, D3D11_CLEAR_DEPTH, 1.0f, 0);
1362 deviceContext->RSSetState(m_shadowRasterState);
1365 deviceContext->IASetPrimitiveTopology(topology);
1366 if (bIsLayoutCreated)
1367 deviceContext->IASetInputLayout(layout);
1370 m_inShadowPass =
true;
1372 queue->ExecuteShadowPass(
this);
1374 m_inShadowPass =
false;
1380 deviceContext->OMSetRenderTargets(1, &savedRTV, savedDSV);
1381 deviceContext->RSSetViewports(1, &savedViewport);
1382 if (savedRTV) savedRTV->Release();
1383 if (savedDSV) savedDSV->Release();
1386 deviceContext->PSSetShaderResources(3, 1, &m_shadowSRV);
1387 deviceContext->PSSetSamplers(3, 1, &m_shadowSampler);
1390void DirectX11Renderer::UpdateShadowLightUBO(
const void* data, uint32_t size) {
1391 if (!device || !deviceContext)
return;
1394 if (!m_shadowCBCreated) {
1395 if (!CreateShadowConstantBuffer())
return;
1399 const auto* ubo =
static_cast<const ShadowLightUBO*
>(data);
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;
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);
1418 deviceContext->VSSetConstantBuffers(5, 1, &m_shadowCB);
1419 deviceContext->PSSetConstantBuffers(5, 1, &m_shadowCB);
1424bool DirectX11Renderer::CreateTonemapResources() {
1425 if (m_tonemapResourcesCreated)
return true;
1426 if (!device)
return false;
1429 ID3D11Texture2D* backBuffer =
nullptr;
1430 swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (
void**)&backBuffer);
1431 if (!backBuffer)
return false;
1433 D3D11_TEXTURE2D_DESC bbDesc{};
1434 backBuffer->GetDesc(&bbDesc);
1435 backBuffer->Release();
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;
1449 HRESULT hr = device->CreateTexture2D(&texDesc,
nullptr, &m_hdrTexture);
1451 SLEAK_ERROR(
"Failed to create HDR texture for tonemapping!");
1455 hr = device->CreateRenderTargetView(m_hdrTexture,
nullptr, &m_hdrRTV);
1456 if (FAILED(hr))
return false;
1458 hr = device->CreateShaderResourceView(m_hdrTexture,
nullptr, &m_hdrSRV);
1459 if (FAILED(hr))
return false;
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;
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;
1479 if (!CompileTonemapShaders(&m_tonemapVS, &m_tonemapPS))
return false;
1481 m_tonemapResourcesCreated =
true;
1482 SLEAK_INFO(
"Tonemapping post-process resources created successfully");
1486bool DirectX11Renderer::CompileTonemapShaders(ID3D11VertexShader** vs,
1487 ID3D11PixelShader** ps) {
1489 const std::string narrowPath = TONEMAP_SHADER_PATH;
1490 const std::wstring shaderPath(narrowPath.begin(), narrowPath.end());
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);
1499 LogCompileError(TONEMAP_SHADER_PATH,
"VS_Main", hr, errorBlob.Get());
1502 hr = D3DCompileFromFile(shaderPath.c_str(),
nullptr,
1503 D3D_COMPILE_STANDARD_FILE_INCLUDE,
"PS_Main",
1504 "ps_5_0", D3DCOMPILE_DEBUG, 0, &psBlob, &errorBlob);
1506 LogCompileError(TONEMAP_SHADER_PATH,
"PS_Main", hr, errorBlob.Get());
1510 Microsoft::WRL::ComPtr<ID3D11VertexShader> vertexShader;
1511 Microsoft::WRL::ComPtr<ID3D11PixelShader> pixelShader;
1512 if (FAILED(device->CreateVertexShader(vsBlob->GetBufferPointer(),
1513 vsBlob->GetBufferSize(),
nullptr,
1515 FAILED(device->CreatePixelShader(psBlob->GetBufferPointer(),
1516 psBlob->GetBufferSize(),
nullptr,
1518 SLEAK_ERROR(
"Failed to create tonemap shader objects");
1521 *vs = vertexShader.Detach();
1522 *ps = pixelShader.Detach();
1526#ifdef SLEAK_HOT_RELOAD
1527void DirectX11Renderer::ReloadTonemapShaders() {
1529 if (!m_tonemapResourcesCreated)
return;
1531 ID3D11VertexShader* vs =
nullptr;
1532 ID3D11PixelShader* ps =
nullptr;
1533 if (!CompileTonemapShaders(&vs, &ps)) {
1534 SLEAK_WARN(
"Shader '{}' failed to reload, keeping the old one",
1538 if (m_tonemapVS) m_tonemapVS->Release();
1539 if (m_tonemapPS) m_tonemapPS->Release();
1542 SLEAK_INFO(
"Reloaded DirectX 11 shader '{}'", TONEMAP_STEM);
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;
1557void DirectX11Renderer::ExecuteTonemapPass() {
1558 if (!m_tonemapResourcesCreated || !m_tonemapVS || !m_tonemapPS)
1562 PostProcessGPUData ppData{};
1563 ppData.Exposure = m_exposure;
1564 ppData.Gamma = m_gamma;
1565 ppData.TonemapEnabled = m_tonemapEnabled ? 1 : 0;
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);
1575 deviceContext->OMSetRenderTargets(1, &renderTargetView,
nullptr);
1578 deviceContext->PSSetShaderResources(0, 1, &m_hdrSRV);
1579 deviceContext->PSSetSamplers(0, 1, &m_pointSampler);
1580 deviceContext->PSSetConstantBuffers(0, 1, &m_postProcessCB);
1583 deviceContext->VSSetShader(m_tonemapVS,
nullptr, 0);
1584 deviceContext->PSSetShader(m_tonemapPS,
nullptr, 0);
1587 deviceContext->IASetInputLayout(
nullptr);
1588 deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1589 deviceContext->Draw(3, 0);
1592 ID3D11ShaderResourceView* nullSRV =
nullptr;
1593 deviceContext->PSSetShaderResources(0, 1, &nullSRV);
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.