SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
DirectX11Shader.cpp
Go to the documentation of this file.
2
3#include <d3d11.h>
4#include <d3d11shader.h>
5#include <d3dcompiler.h>
6#include <wrl/client.h>
7
8#include <Core/Logger.hpp>
9#include <stdexcept>
10#include <string>
11#include <utility>
12#ifdef SLEAK_HOT_RELOAD
13#include <filesystem>
14#endif
15
16namespace Sleak {
17namespace RenderEngine {
18
19namespace {
20
21constexpr const char* VERTEX_ENTRY = "VS_Main";
22constexpr const char* PIXEL_ENTRY = "PS_Main";
23constexpr const char* SPLIT_FILE_ENTRY = "Main";
24constexpr const char* VERTEX_PROFILE = "vs_5_0";
25constexpr const char* PIXEL_PROFILE = "ps_5_0";
26
27#ifdef SLEAK_HOT_RELOAD
28/// Returns the file name up to its first '.', e.g. skybox for skybox.hlsl.
29std::string StemFromPath(const std::string& path) {
30 const std::string name = std::filesystem::path(path).filename().string();
31 return name.substr(0, name.find('.'));
32}
33
34/// Returns the live shader registry, leaked to survive static teardown.
35std::unordered_set<DirectX11Shader*>& LiveShaders() {
36 static auto* shaders = new std::unordered_set<DirectX11Shader*>();
37 return *shaders;
38}
39#endif
40
41} // namespace
42
43DirectX11Shader::DirectX11Shader(ID3D11Device* device) : m_device(device) {
44 assert(m_device != nullptr); // Ensure the device is valid
45 m_device->GetImmediateContext(m_deviceContext.GetAddressOf());
46#ifdef SLEAK_HOT_RELOAD
47 LiveShaders().insert(this);
48#endif
49}
50
52#ifdef SLEAK_HOT_RELOAD
53 LiveShaders().erase(this);
54#endif
55}
56
57#ifdef SLEAK_HOT_RELOAD
58const std::unordered_set<DirectX11Shader*>& DirectX11Shader::GetLiveShaders() {
59 return LiveShaders();
60}
61
62bool DirectX11Shader::Reload() {
63 if (m_sources.vertPath.empty() || m_sources.fragPath.empty()) return false;
64 return BuildStages(m_sources);
65}
66
67void DirectX11Shader::AdoptStages(const DirectX11Shader& source) {
68 m_vertexShader = source.m_vertexShader;
69 m_pixelShader = source.m_pixelShader;
70 m_vertexShaderBlob = source.m_vertexShaderBlob;
71 m_pixelShaderBlob = source.m_pixelShaderBlob;
72 Layout = source.Layout;
73}
74#endif
75
76bool DirectX11Shader::compile(const std::string& shaderPath) {
77 return BuildStages({shaderPath, VERTEX_ENTRY, shaderPath, PIXEL_ENTRY});
78}
79
80bool DirectX11Shader::compile(const std::string& vertPath,
81 const std::string& fragPath) {
82 return BuildStages(
83 {vertPath, SPLIT_FILE_ENTRY, fragPath, SPLIT_FILE_ENTRY});
84}
85
86bool DirectX11Shader::BuildStages(StageSources sources) {
87 Microsoft::WRL::ComPtr<ID3D11VertexShader> vertexShader;
88 Microsoft::WRL::ComPtr<ID3D11PixelShader> pixelShader;
89 Microsoft::WRL::ComPtr<ID3DBlob> vertexBlob;
90 Microsoft::WRL::ComPtr<ID3DBlob> pixelBlob;
91 if (!compileShader(sources.vertPath, sources.vertEntry, VERTEX_PROFILE,
92 vertexShader, vertexBlob)) {
93 SLEAK_ERROR("Failed to compile vertex shader {}", sources.vertPath);
94 return false;
95 }
96 if (!compileShader(sources.fragPath, sources.fragEntry, PIXEL_PROFILE,
97 pixelShader, pixelBlob)) {
98 SLEAK_ERROR("Failed to compile pixel shader {}", sources.fragPath);
99 return false;
100 }
101
102 // A rebuild needs a layout validated against the new vertex inputs
103 Microsoft::WRL::ComPtr<ID3D11InputLayout> layout;
104 if (Layout && !CreateLayoutFor(vertexBlob.Get(), layout)) return false;
105
106 m_vertexShader = std::move(vertexShader);
107 m_pixelShader = std::move(pixelShader);
108 m_vertexShaderBlob = std::move(vertexBlob);
109 m_pixelShaderBlob = std::move(pixelBlob);
110 if (layout) Layout = std::move(layout);
111#ifdef SLEAK_HOT_RELOAD
112 m_vertStem = StemFromPath(sources.vertPath);
113 m_fragStem = StemFromPath(sources.fragPath);
114 m_sources = std::move(sources);
115#endif
116 return true;
117}
118
120 if (!m_vertexShader || !m_pixelShader) {
121 throw std::runtime_error("Shaders are not compiled!");
122 }
123
124 m_deviceContext->VSSetShader(m_vertexShader.Get(), nullptr, 0);
125 m_deviceContext->PSSetShader(m_pixelShader.Get(), nullptr, 0);
126 if (Layout)
127 m_deviceContext->IASetInputLayout(Layout.Get());
128}
129
131 return m_vertexShaderBlob.Get();
132}
133
135 Microsoft::WRL::ComPtr<ID3D11InputLayout> layout;
136 if (!m_vertexShaderBlob ||
137 !CreateLayoutFor(m_vertexShaderBlob.Get(), layout))
138 return nullptr;
139
140 // Store per-shader so bind() can set it, and keep a ref for the caller
141 Layout = layout;
142 return layout.Detach();
143}
144
145bool DirectX11Shader::CreateLayoutFor(
146 ID3DBlob* vertexBlob, Microsoft::WRL::ComPtr<ID3D11InputLayout>& layout) {
147 // Check via reflection if the shader uses BLENDINDICES (skinned shader)
148 bool isSkinned = false;
149 Microsoft::WRL::ComPtr<ID3D11ShaderReflection> reflector;
150 HRESULT hr =
151 D3DReflect(vertexBlob->GetBufferPointer(), vertexBlob->GetBufferSize(),
152 IID_ID3D11ShaderReflection,
153 reinterpret_cast<void**>(reflector.GetAddressOf()));
154 if (SUCCEEDED(hr)) {
155 D3D11_SHADER_DESC shaderDesc;
156 reflector->GetDesc(&shaderDesc);
157 for (UINT p = 0; p < shaderDesc.InputParameters; ++p) {
158 D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
159 reflector->GetInputParameterDesc(p, &paramDesc);
160 if (strcmp(paramDesc.SemanticName, "BLENDINDICES") == 0) {
161 isSkinned = true;
162 break;
163 }
164 }
165 }
166
167 D3D11_INPUT_ELEMENT_DESC* layoutDesc = isSkinned ? SkinnedLayout : DefaultLayout;
168 UINT layoutCount = isSkinned ? ARRAYSIZE(SkinnedLayout) : ARRAYSIZE(DefaultLayout);
169
170 hr = m_device->CreateInputLayout(
171 layoutDesc, layoutCount, vertexBlob->GetBufferPointer(),
172 vertexBlob->GetBufferSize(), layout.ReleaseAndGetAddressOf());
173
174 if (FAILED(hr)) {
175 SLEAK_ERROR("Failed to create input layout: 0x{:08X}",
176 static_cast<unsigned int>(hr));
177 return false;
178 }
179 return true;
180}
181
182/// Compiles a shader stage from an HLSL file and creates the matching D3D11 shader object.
183template <typename T>
184bool DirectX11Shader::compileShader(const std::string& filePath,
185 const std::string& entryPoint,
186 const std::string& profile,
187 Microsoft::WRL::ComPtr<T>& shader,
188 Microsoft::WRL::ComPtr<ID3DBlob>& blob) {
189 Microsoft::WRL::ComPtr<ID3DBlob> errorBlob;
190 HRESULT hr = D3DCompileFromFile(
191 std::wstring(filePath.begin(), filePath.end()).c_str(), // File path
192 nullptr, // Defines
193 D3D_COMPILE_STANDARD_FILE_INCLUDE, // Includes
194 entryPoint.c_str(), // Entry point
195 profile.c_str(), // Shader profile (e.g., "vs_5_0")
196 D3DCOMPILE_DEBUG, // Flags
197 0, // Flags 2
198 &blob, // Output blob
199 &errorBlob // Error blob
200 );
201
202 if (FAILED(hr)) {
203 if (errorBlob) {
204 SLEAK_ERROR("Shader compilation error in {} ({}): {}", filePath,
205 entryPoint, (char*)errorBlob->GetBufferPointer());
206 } else {
207 SLEAK_ERROR("Shader compilation error in {} ({}): 0x{:08X}",
208 filePath, entryPoint, static_cast<unsigned int>(hr));
209 }
210 return false;
211 }
212
213 // Create the shader object
214 if constexpr (std::is_same_v<T, ID3D11VertexShader>) {
215 hr = m_device->CreateVertexShader(
216 blob->GetBufferPointer(), blob->GetBufferSize(), nullptr,
217 reinterpret_cast<ID3D11VertexShader**>(shader.GetAddressOf()));
218 } else if constexpr (std::is_same_v<T, ID3D11PixelShader>) {
219 hr = m_device->CreatePixelShader(
220 blob->GetBufferPointer(), blob->GetBufferSize(), nullptr,
221 reinterpret_cast<ID3D11PixelShader**>(shader.GetAddressOf()));
222 }
223
224 if (FAILED(hr)) {
225 SLEAK_ERROR("Failed to create shader object for {} ({}): 0x{:08X}",
226 filePath, entryPoint, static_cast<unsigned int>(hr));
227 }
228 return SUCCEEDED(hr);
229}
230
231} // namespace RenderEngine
232} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
ID3D11InputLayout * createInputLayout()
Builds the input layout matching DefaultLayout or SkinnedLayout from the vertex shader bytecode.
bool compile(const std::string &shaderPath) override
Compiles the combined-path convention (vs_main/ps_main entry points) from a single HLSL file.
void bind() override
Binds this program as the active shader for subsequent draws.
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10