Rise
The Vieneo Province
Loading...
Searching...
No Matches
Program11.cpp
Go to the documentation of this file.
1#include "Program11.h"
2#include "FrameProfiler11.h"
3#include <d3dcompiler.h>
4#include <algorithm>
5#include <cstring>
6#include <atomic>
7#include <memory>
8#if defined(_M_IX86) || defined(_M_X64)
9#include <emmintrin.h>
10#endif
11
12using Microsoft::WRL::ComPtr;
13namespace Rendering
14{
15 // Value revisions identify their contents across copies, moves and unrelated
16 // parameter sets. Object-local counters can collide when a program switches
17 // between two sets that happened to receive the same number of edits.
18 namespace { std::atomic<uint64_t> parameterRevision{0}; }
19 Parameters11::Parameters11(const Parameters11& other) { *this = other; }
21 {
22 if (this != &other)
23 {
24 // Invalidate before assignments that can reallocate nodes or throw.
25 layoutVersion = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
27 values = other.values; textures = other.textures; samplers = other.samplers;
28 version = other.version;
29 }
30 return *this;
31 }
32 Parameters11::Parameters11(Parameters11&& other) noexcept { *this = std::move(other); }
34 {
35 if (this != &other)
36 {
37 layoutVersion = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
38 other.layoutVersion = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
39 values = std::move(other.values); textures = std::move(other.textures); samplers = std::move(other.samplers);
40 version = other.version;
41 other.values.clear(); other.version = 0;
42 }
43 return *this;
44 }
45 void Parameters11::Set(const std::string& name, const void* data, size_t bytes)
46 {
47 const auto inserted = values.try_emplace(name);
48 if (inserted.second) layoutVersion = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
49 auto& value = inserted.first->second;
50 if (value.data.size() == bytes && (!bytes || !memcmp(value.data.data(), data, bytes))) return;
51 value.data.resize(bytes);
52 if (bytes) memcpy(value.data.data(), data, bytes);
53 value.version = version = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
54 }
55 void Parameters11::Texture(const std::string& name, ID3D11ShaderResourceView* value)
56 {
57 const auto inserted = textures.try_emplace(name);
58 if (inserted.second) layoutVersion = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
59 auto& texture = inserted.first->second;
60 if (texture.resource.Get() == value) return;
61 texture.resource = value;
62 D3D11_SHADER_RESOURCE_VIEW_DESC desc{};
63 if (value) value->GetDesc(&desc); // Views have immutable descriptions.
64 texture.dimension = desc.ViewDimension;
65 }
66 void Parameters11::Sampler(const std::string& name, ID3D11SamplerState* value)
67 {
68 const auto inserted = samplers.try_emplace(name);
69 if (inserted.second) layoutVersion = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
70 inserted.first->second = value;
71 }
73 {
74 if (textures.empty()) return;
75 layoutVersion = parameterRevision.fetch_add(1, std::memory_order_relaxed) + 1;
76 textures.clear();
77 }
78
79 HRESULT Program11::Error(const std::string& message, HRESULT hr) { status = message; return hr; }
81 {
82 ready=false; layout.Reset(); pixel.Reset(); vertex.Reset(); vertexStage = {}; pixelStage = {}; bgraColorMask = 0; status.clear();
83 }
84 HRESULT Program11::Reflect(ID3D11Device* device, const void* code, size_t size, Stage& stage)
85 {
86 ComPtr<ID3D11ShaderReflection> reflection;
87 HRESULT hr = D3DReflect(code, size, IID_PPV_ARGS(&reflection));
88 if (FAILED(hr)) return Error("reflect native shader", hr);
89 D3D11_SHADER_DESC desc{};
90 if (FAILED(hr = reflection->GetDesc(&desc))) return hr;
91 for (UINT i = 0; i < desc.BoundResources; ++i)
92 {
93 D3D11_SHADER_INPUT_BIND_DESC binding{};
94 if (FAILED(hr = reflection->GetResourceBindingDesc(i, &binding))) return hr;
95 if (binding.BindCount != 1) return Error("resource arrays require explicit binding: " + std::string(binding.Name), E_NOTIMPL);
96 if (binding.Type == D3D_SIT_TEXTURE) stage.textures.push_back({binding.Name, binding.BindPoint, binding.Dimension});
97 else if (binding.Type == D3D_SIT_SAMPLER) stage.samplers.push_back({binding.Name, binding.BindPoint});
98 else if (binding.Type == D3D_SIT_CBUFFER)
99 {
100 auto* reflected = reflection->GetConstantBufferByName(binding.Name);
101 D3D11_SHADER_BUFFER_DESC bufferDesc{};
102 if (FAILED(hr = reflected->GetDesc(&bufferDesc))) return hr;
103 ConstantBuffer buffer;
104 buffer.slot = binding.BindPoint;
105 buffer.defaults.resize(bufferDesc.Size);
106 for (UINT j = 0; j < bufferDesc.Variables; ++j)
107 {
108 auto* reflectedVar = reflected->GetVariableByIndex(j);
109 D3D11_SHADER_VARIABLE_DESC variableDesc{};
110 D3D11_SHADER_TYPE_DESC typeDesc{};
111 if (FAILED(hr = reflectedVar->GetDesc(&variableDesc)) || FAILED(hr = reflectedVar->GetType()->GetDesc(&typeDesc))) return hr;
112 if (!(variableDesc.uFlags & D3D_SVF_USED)) continue;
113 if (typeDesc.Class == D3D_SVC_STRUCT || typeDesc.Class == D3D_SVC_OBJECT)
114 return Error("unsupported constant type: " + std::string(variableDesc.Name), E_NOTIMPL);
115 buffer.variables.push_back({variableDesc.Name, variableDesc.StartOffset, variableDesc.Size,
116 typeDesc.Elements, typeDesc.Rows, typeDesc.Columns, typeDesc.Class});
117 if (variableDesc.DefaultValue)
118 memcpy(buffer.defaults.data() + variableDesc.StartOffset, variableDesc.DefaultValue, variableDesc.Size);
119 }
120 // Force initial upload, even when every value equals zero.
121 buffer.data.clear();
122 buffer.packed = buffer.defaults;
123 D3D11_BUFFER_DESC native{};
124 native.ByteWidth = bufferDesc.Size; native.Usage = D3D11_USAGE_DYNAMIC;
125 native.BindFlags = D3D11_BIND_CONSTANT_BUFFER; native.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
126 if (FAILED(hr = device->CreateBuffer(&native, nullptr, &buffer.buffer))) return Error("create constant buffer", hr);
127 stage.constants.push_back(std::move(buffer));
128 }
129 else return Error("unsupported shader resource: " + std::string(binding.Name), E_NOTIMPL);
130 }
131 return S_OK;
132 }
133
134 HRESULT Program11::Create(ID3D11Device* device, const void* vsCode, size_t vsSize,
135 const void* psCode, size_t psSize, const D3D11_INPUT_ELEMENT_DESC* elements, UINT count, UINT packedColors)
136 {
137 ProfileScope11 timing("Shader program creation",false);
138 Reset();
139 if (!device || !vsCode || !vsSize || !psCode || !psSize || (count && !elements)) return E_INVALIDARG;
140 UINT validPackedColors = 0;
141 for (UINT i = 0; i < count; ++i)
142 if (elements[i].SemanticName && !_stricmp(elements[i].SemanticName, "COLOR") && elements[i].SemanticIndex < 32
143 && elements[i].Format == DXGI_FORMAT_R8G8B8A8_UNORM) validPackedColors |= 1u << elements[i].SemanticIndex;
144 if (packedColors & ~validPackedColors) return Error("packed color mask requires a matching R8G8B8A8 COLOR attribute", E_INVALIDARG);
145 bgraColorMask = packedColors;
146 ComPtr<ID3D11ShaderReflection> vsReflection, psReflection;
147 HRESULT hr = D3DReflect(vsCode, vsSize, IID_PPV_ARGS(&vsReflection));
148 if (FAILED(hr)) return Error("reflect vertex signature", hr);
149 if (FAILED(hr = D3DReflect(psCode, psSize, IID_PPV_ARGS(&psReflection)))) return Error("reflect pixel signature", hr);
150 D3D11_SHADER_DESC vsDesc{}, psDesc{};
151 if (FAILED(hr = vsReflection->GetDesc(&vsDesc)) || FAILED(hr = psReflection->GetDesc(&psDesc))) return hr;
152 for (UINT i = 0; i < psDesc.InputParameters; ++i)
153 {
154 D3D11_SIGNATURE_PARAMETER_DESC input{};
155 if (FAILED(hr = psReflection->GetInputParameterDesc(i, &input))) return hr;
156 if (!input.ReadWriteMask || input.SystemValueType == D3D_NAME_SAMPLE_INDEX
157 || input.SystemValueType == D3D_NAME_PRIMITIVE_ID || input.SystemValueType == D3D_NAME_IS_FRONT_FACE) continue;
158 bool matched = false;
159 for (UINT j = 0; j < vsDesc.OutputParameters; ++j)
160 {
161 D3D11_SIGNATURE_PARAMETER_DESC output{};
162 if (FAILED(hr = vsReflection->GetOutputParameterDesc(j, &output))) return hr;
163 if (_stricmp(input.SemanticName, output.SemanticName) == 0 && input.SemanticIndex == output.SemanticIndex)
164 matched = input.Register == output.Register && input.ComponentType == output.ComponentType
165 && (input.ReadWriteMask & output.Mask) == input.ReadWriteMask;
166 }
167 if (!matched) return Error("vertex/pixel signature mismatch: " + std::string(input.SemanticName)
168 + std::to_string(input.SemanticIndex), E_INVALIDARG);
169 }
170 hr = device->CreateVertexShader(vsCode, vsSize, nullptr, &vertex);
171 if (FAILED(hr)) return Error("create vertex shader", hr);
172 if (FAILED(hr = device->CreatePixelShader(psCode, psSize, nullptr, &pixel))) return Error("create pixel shader", hr);
173 if (count && FAILED(hr = device->CreateInputLayout(elements, count, vsCode, vsSize, &layout))) return Error("create input layout", hr);
174 if (FAILED(hr = Reflect(device, vsCode, vsSize, vertexStage))) return hr;
175 if (FAILED(hr = Reflect(device, psCode, psSize, pixelStage))) return hr;
176 bool needsColorSwizzle = false, hasColorSwizzle = false;
177 for (UINT i = 0; i < vsDesc.InputParameters; ++i)
178 {
179 D3D11_SIGNATURE_PARAMETER_DESC input{};
180 if (FAILED(hr = vsReflection->GetInputParameterDesc(i, &input))) return hr;
181 if (!_stricmp(input.SemanticName, "COLOR") && input.SemanticIndex < 32 && input.ReadWriteMask
182 && (packedColors & (1u << input.SemanticIndex))) needsColorSwizzle = true;
183 }
184 for (const auto& buffer : vertexStage.constants) for (const auto& variable : buffer.variables)
185 if (variable.name == "_risePackedColorMask") hasColorSwizzle = true;
186 if (needsColorSwizzle && !hasColorSwizzle) return Error("vertex shader lacks requested packed-color conversion", E_INVALIDARG);
187 status = "native vertex/pixel program ready";
188 ready=true;
189 return S_OK;
190 }
191
192 HRESULT Program11::BindStage(ID3D11DeviceContext* context, const Parameters11& parameters, Stage& stage, bool isVertex)
193 {
194 if (stage.layoutVersion != parameters.layoutVersion)
195 {
196 for (auto& buffer : stage.constants) for (auto& variable : buffer.variables)
197 {
198 const auto found = parameters.values.find(variable.name);
199 variable.source = found == parameters.values.end() ? nullptr : &found->second;
200 }
201 for (auto& binding : stage.textures)
202 {
203 auto found = parameters.textures.find(binding.name);
204 // Preserve the typed-volume fallback and explicit-null override.
205 if (found == parameters.textures.end() && binding.name.size() > 6 && binding.name.compare(binding.name.size() - 6, 6, "Volume") == 0)
206 found = parameters.textures.find(binding.name.substr(0, binding.name.size() - 6));
207 binding.texture = found == parameters.textures.end() ? nullptr : &found->second;
208 }
209 for (auto& binding : stage.samplers)
210 {
211 const auto found = parameters.samplers.find(binding.name);
212 binding.sampler = found == parameters.samplers.end() ? nullptr : std::addressof(found->second);
213 }
214 stage.layoutVersion = parameters.layoutVersion;
215 }
216 for (auto& buffer : stage.constants)
217 {
218 auto& next = buffer.packed;
219 if (buffer.packedVersion != parameters.version)
220 {
221 // Packing can fail partway through; do not advertise the previous
222 // complete set after any of its cached variable bytes have changed.
223 buffer.packedVersion = UINT64_MAX;
224 for (auto& variable : buffer.variables)
225 {
226 if (isVertex && variable.name == "_risePackedColorMask")
227 {
228 if (variable.size != sizeof(bgraColorMask)) return Error("invalid packed color constant", E_INVALIDARG);
229 memcpy(next.data() + variable.offset, &bgraColorMask, sizeof(bgraColorMask));
230 continue;
231 }
232 const auto* found = variable.source;
233 const uint64_t revision = found ? found->version : 0;
234 if (variable.packedVersion == revision) continue;
235 // Restore defaults when an array shrinks or a value disappears.
236 // Keep the GPU copy separate: a failed Map must retry its upload.
237 if (!found)
238 {
239 memcpy(next.data() + variable.offset, buffer.defaults.data() + variable.offset, variable.size);
240 variable.packedVersion = revision; continue;
241 }
242 const auto& source = found->data;
243 const UINT elements = (std::max)(1u, variable.elements);
244 const UINT valueBytes = variable.rows * variable.columns * sizeof(float);
245 if (source.size() > size_t(elements) * valueBytes || source.size() % valueBytes)
246 return Error("constant size mismatch: " + variable.name, E_INVALIDARG);
247 memcpy(next.data() + variable.offset, buffer.defaults.data() + variable.offset, variable.size);
248 // HLSL arrays occupy 16-byte registers; e.g. int flags[5] is
249 // not a tightly packed 20-byte memcpy into the constant buffer.
250 const bool matrix = variable.typeClass == D3D_SVC_MATRIX_ROWS || variable.typeClass == D3D_SVC_MATRIX_COLUMNS;
251 const UINT vectors = matrix ? (variable.typeClass == D3D_SVC_MATRIX_ROWS ? variable.rows : variable.columns) : 1;
252 const UINT stride = vectors * 16;
253 for (UINT i = 0; i < source.size() / valueBytes; ++i)
254 {
255 auto* destination = next.data() + variable.offset + (variable.elements ? stride * i : 0);
256 const auto* input = source.data() + valueBytes * i;
257 if (!matrix) memcpy(destination, input, valueBytes);
258#if defined(_M_IX86) || defined(_M_X64)
259 else if (variable.rows == 4 && variable.columns == 4)
260 {
261 // Matrix packing is a byte rearrangement, not a math
262 // operation. Four SIMD loads/stores preserve every bit
263 // while avoiding sixteen dynamic scalar copy iterations.
264 if (variable.typeClass == D3D_SVC_MATRIX_ROWS) memcpy(destination,input,64);
265 else
266 {
267 auto a=_mm_loadu_ps(reinterpret_cast<const float*>(input));
268 auto b=_mm_loadu_ps(reinterpret_cast<const float*>(input+16));
269 auto c=_mm_loadu_ps(reinterpret_cast<const float*>(input+32));
270 auto d=_mm_loadu_ps(reinterpret_cast<const float*>(input+48));
271 _MM_TRANSPOSE4_PS(a,b,c,d);
272 _mm_storeu_ps(reinterpret_cast<float*>(destination),a);
273 _mm_storeu_ps(reinterpret_cast<float*>(destination+16),b);
274 _mm_storeu_ps(reinterpret_cast<float*>(destination+32),c);
275 _mm_storeu_ps(reinterpret_cast<float*>(destination+48),d);
276 }
277 }
278#endif
279 else for (UINT row = 0; row < variable.rows; ++row) for (UINT column = 0; column < variable.columns; ++column)
280 {
281 const UINT offset = variable.typeClass == D3D_SVC_MATRIX_ROWS ? row * 16 + column * 4 : column * 16 + row * 4;
282 memcpy(destination + offset, input + (row * variable.columns + column) * 4, 4);
283 }
284 }
285 variable.packedVersion = revision;
286 }
287 buffer.packedVersion = parameters.version;
288 }
289 if (next != buffer.data)
290 {
291 D3D11_MAPPED_SUBRESOURCE mapped{};
292 const HRESULT hr = context->Map(buffer.buffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
293 if (FAILED(hr)) return Error("upload constant buffer", hr);
294 memcpy(mapped.pData, next.data(), next.size());
295 context->Unmap(buffer.buffer.Get(), 0);
296 FrameProfiler11::Get().ConstantUpload(UINT(next.size()));
297 buffer.data = next;
298 }
299 auto* resource = buffer.buffer.Get();
300 if (isVertex) context->VSSetConstantBuffers(buffer.slot, 1, &resource);
301 else context->PSSetConstantBuffers(buffer.slot, 1, &resource);
302 }
303 // Submit adjacent reflected slots together. Keep holes untouched and
304 // still rebind every draw: native passes can change the context directly.
305 ID3D11ShaderResourceView* textureResources[D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT];
306 UINT textureFirst=0,textureCount=0;
307 const auto bindTextures=[&]() {
308 if(!textureCount)return;
309 if(isVertex)context->VSSetShaderResources(textureFirst,textureCount,textureResources);
310 else context->PSSetShaderResources(textureFirst,textureCount,textureResources);
311 textureCount=0;
312 };
313 for (const auto& binding : stage.textures)
314 {
315 if(textureCount && binding.slot!=textureFirst+textureCount)bindTextures();
316 if(!textureCount)textureFirst=binding.slot;
317 ID3D11ShaderResourceView* resource = binding.texture ? binding.texture->resource.Get() : nullptr;
318 if (resource)
319 {
320 if (UINT(binding.texture->dimension) != UINT(binding.dimension))
321 {
322 // Preserve the old partial bindings when validation fails.
323 bindTextures();return Error("texture dimension mismatch: " + binding.name, E_INVALIDARG);
324 }
325 }
326 textureResources[textureCount++]=resource;
327 }
328 bindTextures();
329 ID3D11SamplerState* samplerResources[D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT];
330 UINT samplerFirst=0,samplerCount=0;
331 const auto bindSamplers=[&]() {
332 if(!samplerCount)return;
333 if(isVertex)context->VSSetSamplers(samplerFirst,samplerCount,samplerResources);
334 else context->PSSetSamplers(samplerFirst,samplerCount,samplerResources);
335 samplerCount=0;
336 };
337 for (const auto& binding : stage.samplers)
338 {
339 if(samplerCount && binding.slot!=samplerFirst+samplerCount)bindSamplers();
340 if(!samplerCount)samplerFirst=binding.slot;
341 if (!binding.sampler || !*binding.sampler)
342 {
343 bindSamplers();return Error("missing sampler: " + binding.name, E_INVALIDARG);
344 }
345 samplerResources[samplerCount++]=binding.sampler->Get();
346 }
347 bindSamplers();
348 return S_OK;
349 }
350
351 HRESULT Program11::Bind(ID3D11DeviceContext* context, const Parameters11& parameters)
352 {
353 ProfileShaderBind11 timing;
354 if (!context || !vertex || !pixel) return E_UNEXPECTED;
355 HRESULT hr = BindStage(context, parameters, vertexStage, true);
356 if (FAILED(hr)) return hr;
357 if (FAILED(hr = BindStage(context, parameters, pixelStage, false))) return hr;
358 context->VSSetShader(vertex.Get(), nullptr, 0); context->PSSetShader(pixel.Get(), nullptr, 0);
359 context->IASetInputLayout(layout.Get());
360 return S_OK;
361 }
362}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
void ConstantUpload(UINT bytes)
static FrameProfiler11 & Get()
Parameters11 & operator=(const Parameters11 &other)
Definition Program11.cpp:20
std::map< std::string, Value > values
Definition Program11.h:50
void Set(const std::string &name, const void *data, size_t bytes)
Definition Program11.cpp:45
std::map< std::string, Microsoft::WRL::ComPtr< ID3D11SamplerState > > samplers
Definition Program11.h:52
std::map< std::string, TextureValue > textures
Definition Program11.h:51
void Texture(const std::string &name, ID3D11ShaderResourceView *value)
Definition Program11.cpp:55
void Sampler(const std::string &name, ID3D11SamplerState *value)
Definition Program11.cpp:66
HRESULT Create(ID3D11Device *device, const void *vertexCode, size_t vertexSize, const void *pixelCode, size_t pixelSize, const D3D11_INPUT_ELEMENT_DESC *elements=nullptr, UINT elementCount=0, UINT bgraColorMask=0)
Microsoft::WRL::ComPtr< ID3D11InputLayout > layout
Definition Program11.h:108
HRESULT Reflect(ID3D11Device *device, const void *code, size_t size, Stage &stage)
Definition Program11.cpp:84
std::string status
Definition Program11.h:109
HRESULT BindStage(ID3D11DeviceContext *context, const Parameters11 &parameters, Stage &stage, bool vertexStage)
Microsoft::WRL::ComPtr< ID3D11VertexShader > vertex
Definition Program11.h:106
Microsoft::WRL::ComPtr< ID3D11PixelShader > pixel
Definition Program11.h:107
HRESULT Bind(ID3D11DeviceContext *context, const Parameters11 &parameters)
HRESULT Error(const std::string &message, HRESULT hr)
Definition Program11.cpp:79
std::vector< unsigned char > data
Definition Program11.h:83
Microsoft::WRL::ComPtr< ID3D11Buffer > buffer
Definition Program11.h:85
std::vector< Variable > variables
Definition Program11.h:82
std::vector< unsigned char > defaults
Definition Program11.h:83
std::vector< unsigned char > packed
Definition Program11.h:83
std::vector< ConstantBuffer > constants
Definition Program11.h:98
std::vector< Resource > samplers
Definition Program11.h:99
std::vector< Resource > textures
Definition Program11.h:99