Debian Codegraph @

Sources/nCine/Graphics/RHI/Vulkan/VulkanShaderProgram.cpp

raw
1 #include "VulkanShaderProgram.h"
2 #include "VulkanDevice.h"
3 #include "VulkanBufferObject.h"
4 #include "VulkanCommon.h"
5 #include "../../RenderResources.h"
6
7 #include "../../../../Shaders/Generated/ShaderCompilerTypes.h"
8
9 #include <cstring>
10
11 namespace nCine::RHI::Vulkan
12 {
13 namespace
14 {
15 // std140 base alignment and size (unpadded) of a scalar/vector/matrix uniform type
16 void Std140BaseLayout(ShaderCompiler::UniformType type, std::uint32_t& align, std::uint32_t& size)
17 {
18 switch (type) {
19 case ShaderCompiler::UniformType::Float:
20 case ShaderCompiler::UniformType::Int:
21 case ShaderCompiler::UniformType::UInt:
22 case ShaderCompiler::UniformType::Bool: align = 4; size = 4; break;
23 case ShaderCompiler::UniformType::Vec2:
24 case ShaderCompiler::UniformType::IVec2:
25 case ShaderCompiler::UniformType::UVec2:
26 case ShaderCompiler::UniformType::BVec2: align = 8; size = 8; break;
27 case ShaderCompiler::UniformType::Vec3:
28 case ShaderCompiler::UniformType::IVec3:
29 case ShaderCompiler::UniformType::UVec3:
30 case ShaderCompiler::UniformType::BVec3: align = 16; size = 12; break;
31 case ShaderCompiler::UniformType::Vec4:
32 case ShaderCompiler::UniformType::IVec4:
33 case ShaderCompiler::UniformType::UVec4:
34 case ShaderCompiler::UniformType::BVec4: align = 16; size = 16; break;
35 case ShaderCompiler::UniformType::Mat2: align = 16; size = 32; break;
36 case ShaderCompiler::UniformType::Mat3: align = 16; size = 48; break;
37 case ShaderCompiler::UniformType::Mat4: align = 16; size = 64; break;
38 default: align = 16; size = 16; break;
39 }
40 }
41
42 std::uint32_t RoundUp(std::uint32_t value, std::uint32_t alignment)
43 {
44 return (alignment == 0) ? value : ((value + alignment - 1) / alignment) * alignment;
45 }
46 }
47
48 std::uint32_t VulkanShaderProgram::_nextHandle = 1;
49
50 VulkanShaderProgram::VulkanShaderProgram()
51 : VulkanShaderProgram(QueryPhase::Immediate)
52 {
53 }
54
55 VulkanShaderProgram::VulkanShaderProgram(QueryPhase queryPhase)
56 : _handle(_nextHandle++), _status(Status::NotLinked), _introspection(Introspection::Disabled), _queryPhase(queryPhase),
57 _batchSize(DefaultBatchSize), _shouldLogOnErrors(true), _uniformsSize(0), _uniformBlocksSize(0),
58 _reflection(nullptr), _boundVbo(nullptr), _boundIbo(nullptr),
59 _vsModule(0), _fsModule(0), _descriptorSetLayout(0), _pipelineLayout(0), _globalsSize(0)
60 {
61 }
62
63 VulkanShaderProgram::VulkanShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase)
64 : VulkanShaderProgram(queryPhase)
65 {
66 static_cast<void>(vertexFile);
67 static_cast<void>(fragmentFile);
68 static_cast<void>(introspection);
69 }
70
71 VulkanShaderProgram::VulkanShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection)
72 : VulkanShaderProgram(vertexFile, fragmentFile, introspection, QueryPhase::Immediate)
73 {
74 }
75
76 VulkanShaderProgram::VulkanShaderProgram(StringView vertexFile, StringView fragmentFile)
77 : VulkanShaderProgram(vertexFile, fragmentFile, Introspection::Enabled, QueryPhase::Immediate)
78 {
79 }
80
81 VulkanShaderProgram::~VulkanShaderProgram()
82 {
83 // Drop any cached pipelines keyed on this program, then destroy the modules / layouts. The device
84 // waits for the GPU to go idle on teardown, so destroying here is safe.
85 VulkanDevice::OnShaderProgramDestroyed(this);
86 VkDevice device = VkDeviceHandle();
87 if (device != VK_NULL_HANDLE) {
88 if (_pipelineLayout != 0) { vkDestroyPipelineLayout(device, reinterpret_cast<VkPipelineLayout>(_pipelineLayout), nullptr); }
89 if (_descriptorSetLayout != 0) { vkDestroyDescriptorSetLayout(device, reinterpret_cast<VkDescriptorSetLayout>(_descriptorSetLayout), nullptr); }
90 if (_vsModule != 0) { vkDestroyShaderModule(device, reinterpret_cast<VkShaderModule>(_vsModule), nullptr); }
91 if (_fsModule != 0) { vkDestroyShaderModule(device, reinterpret_cast<VkShaderModule>(_fsModule), nullptr); }
92 }
93 _vsModule = _fsModule = _descriptorSetLayout = _pipelineLayout = 0;
94 // The pipeline keys per-shader camera uniform data on the program pointer; drop this program's
95 // entry so RenderResources::Dispose() finds the map empty (mirrors GLShaderProgram's destructor)
96 RenderResources::RemoveCameraUniformData(this);
97 }
98
99 bool VulkanShaderProgram::IsLinked() const
100 {
101 return (_status == Status::Linked || _status == Status::LinkedWithDeferredQueries || _status == Status::LinkedWithIntrospection);
102 }
103
104 bool VulkanShaderProgram::AttachShaderFromFile(ShaderStage stage, StringView filename)
105 {
106 static_cast<void>(stage);
107 static_cast<void>(filename);
108 return true;
109 }
110
111 bool VulkanShaderProgram::AttachShaderFromString(ShaderStage stage, StringView string)
112 {
113 static_cast<void>(stage);
114 static_cast<void>(string);
115 return true;
116 }
117
118 bool VulkanShaderProgram::AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings)
119 {
120 static_cast<void>(stage);
121 static_cast<void>(strings);
122 return true;
123 }
124
125 bool VulkanShaderProgram::AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename)
126 {
127 static_cast<void>(stage);
128 static_cast<void>(strings);
129 static_cast<void>(filename);
130 return true;
131 }
132
133 bool VulkanShaderProgram::Link(Introspection introspection)
134 {
135 return FinalizeAfterLinking(introspection);
136 }
137
138 bool VulkanShaderProgram::FinalizeAfterLinking(Introspection introspection)
139 {
140 _introspection = introspection;
141 PerformIntrospection();
142 return true;
143 }
144
145 void VulkanShaderProgram::Use()
146 {
147 VulkanDevice::BindProgram(this);
148 }
149
150 void VulkanShaderProgram::PerformIntrospection()
151 {
152 if (_introspection != Introspection::Disabled && _status != Status::LinkedWithIntrospection) {
153 _uniformsSize = 0;
154 _uniformBlocksSize = 0;
155
156 if (_reflection != nullptr) {
157 ImportReflection();
158 // Build the SPIR-V modules, descriptor-set layout, pipeline layout and gather metadata while
159 // the reflection (and its embedded SPIR-V) is still available.
160 BuildPipelineState();
161 }
162 _status = Status::LinkedWithIntrospection;
163 }
164 // The reflection is consumed by introspection (its layout is imported into the members above)
165 _reflection = nullptr;
166 }
167
168 void VulkanShaderProgram::BuildPipelineState()
169 {
170 const ShaderCompiler::ProgramVariant& reflection = *_reflection;
171 VkDevice device = VkDeviceHandle();
172 if (device == VK_NULL_HANDLE) {
173 LOGE("Cannot build Vulkan pipeline state: device is not created yet");
174 return;
175 }
176 if (reflection.VkVsSpirv == nullptr || reflection.VkFsSpirv == nullptr ||
177 reflection.VkVsSpirvSize == 0 || reflection.VkFsSpirvSize == 0) {
178 // No SPIR-V (e.g. a runtime-compiled shader outside the emitter's subset); draws are skipped
179 if (_shouldLogOnErrors) {
180 LOGW("Program {} has no SPIR-V modules; draws with it are skipped", _handle);
181 }
182 return;
183 }
184
185 // -- Shader modules (just wrap the pre-compiled SPIR-V words) --
186 auto createModule = [device](const std::uint32_t* words, std::size_t wordCount) -> std::uint64_t {
187 VkShaderModuleCreateInfo smci = {};
188 smci.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
189 smci.codeSize = wordCount * sizeof(std::uint32_t);
190 smci.pCode = words;
191 VkShaderModule module = VK_NULL_HANDLE;
192 if (vkCreateShaderModule(device, &smci, nullptr, &module) != VK_SUCCESS) {
193 return 0;
194 }
195 return reinterpret_cast<std::uint64_t>(module);
196 };
197 _vsModule = createModule(reflection.VkVsSpirv, reflection.VkVsSpirvSize);
198 _fsModule = createModule(reflection.VkFsSpirv, reflection.VkFsSpirvSize);
199 if (_vsModule == 0 || _fsModule == 0) {
200 LOGE("Failed to create Vulkan shader modules for program {}", _handle);
201 _status = Status::CompilationFailed;
202 return;
203 }
204
205 // -- Descriptor bindings, in the offline emitter's scheme (set 0: optional _Globals UBO at binding 0, then the
206 // std140 blocks at uboBase+i, then the combined image samplers at uboBase+BlockCount+j). --
207 const bool hasGlobals = (reflection.UniformCount > 0);
208 const std::uint32_t uboBase = (hasGlobals ? 1u : 0u);
209 std::vector<VkDescriptorSetLayoutBinding> layoutBindings;
210 _descriptorBindings.clear();
211 _looseUniforms.clear();
212 _globalsSize = 0;
213
214 const VkShaderStageFlags allStages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
215
216 if (hasGlobals) {
217 // Gather the loose uniforms into a std140 _Globals block layout (matches the offline emitter)
218 std::uint32_t offset = 0;
219 for (std::size_t i = 0; i < reflection.UniformCount; i++) {
220 const ShaderCompiler::Uniform& u = reflection.Uniforms[i];
221 std::uint32_t baseAlign = 0, baseSize = 0;
222 Std140BaseLayout(u.Type, baseAlign, baseSize);
223 std::uint32_t align = baseAlign, size = baseSize;
224 if (u.ArraySize > 0) {
225 align = RoundUp(baseAlign, 16);
226 const std::uint32_t stride = RoundUp(baseSize, 16);
227 size = stride * u.ArraySize;
228 }
229 offset = RoundUp(offset, align);
230 _looseUniforms.push_back({ String(u.Name), offset, size });
231 offset += size;
232 }
233 _globalsSize = RoundUp(offset, 16);
234
235 VkDescriptorSetLayoutBinding b = {};
236 b.binding = 0;
237 b.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
238 b.descriptorCount = 1;
239 b.stageFlags = allStages;
240 layoutBindings.push_back(b);
241 _descriptorBindings.push_back({ DescriptorBinding::Kind::Globals, 0, -1 });
242 }
243
244 for (std::size_t i = 0; i < reflection.BlockCount; i++) {
245 const std::uint32_t binding = uboBase + std::uint32_t(i);
246 VkDescriptorSetLayoutBinding b = {};
247 b.binding = binding;
248 b.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
249 b.descriptorCount = 1;
250 b.stageFlags = allStages;
251 layoutBindings.push_back(b);
252 // The device records block i's bound range in _boundUniformRanges[i] (see VulkanShaderUniformBlocks)
253 _descriptorBindings.push_back({ DescriptorBinding::Kind::Block, binding, std::int32_t(i) });
254 }
255
256 for (std::size_t j = 0; j < reflection.TextureCount; j++) {
257 const std::uint32_t binding = uboBase + std::uint32_t(reflection.BlockCount) + std::uint32_t(j);
258 VkDescriptorSetLayoutBinding b = {};
259 b.binding = binding;
260 b.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
261 b.descriptorCount = 1;
262 b.stageFlags = allStages;
263 layoutBindings.push_back(b);
264 const std::int32_t unit = (reflection.Textures[j].Unit >= 0 ? reflection.Textures[j].Unit : std::int32_t(j));
265 _descriptorBindings.push_back({ DescriptorBinding::Kind::Sampler, binding, unit });
266 }
267
268 VkDescriptorSetLayoutCreateInfo dslci = {};
269 dslci.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
270 dslci.bindingCount = std::uint32_t(layoutBindings.size());
271 dslci.pBindings = layoutBindings.empty() ? nullptr : layoutBindings.data();
272 VkDescriptorSetLayout setLayout = VK_NULL_HANDLE;
273 if (vkCreateDescriptorSetLayout(device, &dslci, nullptr, &setLayout) != VK_SUCCESS) {
274 LOGE("Failed to create Vulkan descriptor set layout for program {}", _handle);
275 _status = Status::CompilationFailed;
276 return;
277 }
278 _descriptorSetLayout = reinterpret_cast<std::uint64_t>(setLayout);
279
280 VkPipelineLayoutCreateInfo plci = {};
281 plci.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
282 plci.setLayoutCount = 1;
283 plci.pSetLayouts = &setLayout;
284 VkPipelineLayout layout = VK_NULL_HANDLE;
285 if (vkCreatePipelineLayout(device, &plci, nullptr, &layout) != VK_SUCCESS) {
286 LOGE("Failed to create Vulkan pipeline layout for program {}", _handle);
287 _status = Status::CompilationFailed;
288 return;
289 }
290 _pipelineLayout = reinterpret_cast<std::uint64_t>(layout);
291 }
292
293 std::uint32_t VulkanShaderProgram::GetVertexInput(VertexAttrib* outAttribs, std::uint32_t maxAttribs, std::uint32_t& outStride) const
294 {
295 std::uint32_t count = 0;
296 outStride = 0;
297 for (const VulkanAttribute& a : _attributes) {
298 const std::int32_t loc = a.GetLocation();
299 if (loc < 0) {
300 continue;
301 }
302 const VulkanVertexFormat::Attribute& fa = _vertexFormat[std::uint32_t(loc)];
303 if (!fa.IsEnabled()) {
304 continue;
305 }
306 if (count < maxAttribs) {
307 VertexAttrib& attr = outAttribs[count++];
308 attr.Location = std::uint32_t(loc);
309 attr.ComponentCount = fa.GetSize();
310 attr.Offset = std::uint32_t(reinterpret_cast<std::uintptr_t>(fa.GetPointer()));
311 attr.Type = fa.GetType();
312 attr.Normalized = fa.IsNormalized();
313 }
314 if (fa.GetStride() > 0) {
315 outStride = std::uint32_t(fa.GetStride());
316 }
317 }
318 return count;
319 }
320
321 void VulkanShaderProgram::ImportReflection()
322 {
323 const ShaderCompiler::ProgramVariant& reflection = *_reflection;
324 std::int32_t nextLocation = 0;
325
326 // Loose uniforms - samplers are kept in a separate reflection list but treated as loose uniforms here
327 for (std::size_t i = 0; i < reflection.UniformCount; i++) {
328 const ShaderCompiler::Uniform& u = reflection.Uniforms[i];
329 _uniforms.emplace_back(this, u.Name, u.Type, std::int32_t(u.ArraySize), nextLocation++);
330 _uniformsSize += _uniforms.back().GetMemorySize();
331 }
332 for (std::size_t i = 0; i < reflection.TextureCount; i++) {
333 const ShaderCompiler::TextureBinding& t = reflection.Textures[i];
334 _uniforms.emplace_back(this, t.Name, ShaderCompiler::UniformType::Sampler2D, 1, nextLocation++);
335 _uniformsSize += _uniforms.back().GetMemorySize();
336 }
337
338 _uniformBlocks.reserve(reflection.BlockCount);
339 for (std::size_t i = 0; i < reflection.BlockCount; i++) {
340 const ShaderCompiler::UniformBlock& b = reflection.Blocks[i];
341
342 // A BATCH_SIZE-sized instance array uses the explicitly set batch size, or the same 64 KB-based
343 // fallback the in-shader "#ifndef BATCH_SIZE" defaults assume when no size is injected
344 std::uint32_t effectiveBatchSize = 0;
345 std::uint32_t dataSize = b.BaseSize;
346 if (b.InstanceStride > 0) {
347 effectiveBatchSize = (_batchSize != std::uint32_t(DefaultBatchSize) && _batchSize > 0)
348 ? _batchSize : (64u * 1024u) / b.InstanceStride;
349 dataSize += b.InstanceStride * effectiveBatchSize;
350 }
351
352 const std::uint32_t blockIndex = std::uint32_t(_uniformBlocks.size());
353 _uniformBlocks.emplace_back(blockIndex, b.Name, std::int32_t(dataSize));
354 VulkanUniformBlock& block = _uniformBlocks.back();
355 _uniformBlocksSize += block.GetSize();
356
357 if (_introspection != Introspection::NoUniformsInBlocks) {
358 block._members.reserve(b.MemberCount);
359 for (std::size_t j = 0; j < b.MemberCount; j++) {
360 const ShaderCompiler::BlockMember& m = b.Members[j];
361 if (m.Type == ShaderCompiler::UniformType::Struct) {
362 // Struct aggregates are never read by name; only flat leaf members matter
363 continue;
364 }
365 VulkanUniform member;
366 member.SetName(m.Name);
367 member._type = m.Type;
368 member._size = (m.ArraySize == ShaderCompiler::SymbolicArraySize)
369 ? std::int32_t(effectiveBatchSize)
370 : (m.ArraySize > 0 ? std::int32_t(m.ArraySize) : 1);
371 member._blockIndex = std::int32_t(blockIndex);
372 member._offset = std::int32_t(m.Offset);
373 member._owner = this;
374 block._members.push_back(member);
375 }
376 }
377 }
378
379 for (std::size_t i = 0; i < reflection.AttributeCount; i++) {
380 const ShaderCompiler::Attribute& a = reflection.Attributes[i];
381 const std::int32_t location = (a.Location >= 0 ? a.Location : std::int32_t(i));
382 _attributes.emplace_back(a.Name, a.Type, location);
383 _vertexFormat[std::uint32_t(location)].Init(std::uint32_t(location), std::int32_t(UniformTypeInfo::ComponentCount(a.Type)), 0);
384 }
385 }
386
387 bool VulkanShaderProgram::HasAttribute(const char* name) const
388 {
389 for (const VulkanAttribute& a : _attributes) {
390 if (std::strcmp(a.GetName(), name) == 0) {
391 return true;
392 }
393 }
394 return false;
395 }
396
397 VulkanVertexFormat::Attribute* VulkanShaderProgram::GetAttribute(const char* name)
398 {
399 for (const VulkanAttribute& a : _attributes) {
400 if (std::strcmp(a.GetName(), name) == 0 && a.GetLocation() >= 0) {
401 return &_vertexFormat[std::uint32_t(a.GetLocation())];
402 }
403 }
404 return nullptr;
405 }
406
407 void VulkanShaderProgram::DefineVertexFormat(const VulkanBufferObject* vbo, const VulkanBufferObject* ibo, std::uint32_t vboOffset)
408 {
409 _boundVbo = vbo;
410 _boundIbo = ibo;
411 if (vbo != nullptr) {
412 for (const VulkanAttribute& a : _attributes) {
413 if (a.GetLocation() >= 0) {
414 VulkanVertexFormat::Attribute& attr = _vertexFormat[std::uint32_t(a.GetLocation())];
415 attr.setVbo(vbo);
416 attr.SetBaseOffset(vboOffset);
417 }
418 }
419 _vertexFormat.SetIbo(ibo);
420 }
421 }
422
423 void VulkanShaderProgram::Reset()
424 {
425 _uniforms.clear();
426 _uniformBlocks.clear();
427 _attributes.clear();
428 _resolvedUniforms.clear();
429 _vertexFormat.Reset();
430
431 VulkanDevice::OnShaderProgramDestroyed(this);
432 VkDevice device = VkDeviceHandle();
433 if (device != VK_NULL_HANDLE) {
434 if (_pipelineLayout != 0) { vkDestroyPipelineLayout(device, reinterpret_cast<VkPipelineLayout>(_pipelineLayout), nullptr); }
435 if (_descriptorSetLayout != 0) { vkDestroyDescriptorSetLayout(device, reinterpret_cast<VkDescriptorSetLayout>(_descriptorSetLayout), nullptr); }
436 if (_vsModule != 0) { vkDestroyShaderModule(device, reinterpret_cast<VkShaderModule>(_vsModule), nullptr); }
437 if (_fsModule != 0) { vkDestroyShaderModule(device, reinterpret_cast<VkShaderModule>(_fsModule), nullptr); }
438 }
439 _vsModule = _fsModule = _descriptorSetLayout = _pipelineLayout = 0;
440 _descriptorBindings.clear();
441 _looseUniforms.clear();
442 _globalsSize = 0;
443
444 _status = Status::NotLinked;
445 _batchSize = DefaultBatchSize;
446 _reflection = nullptr;
447 }
448
449 void VulkanShaderProgram::SetObjectLabel(StringView label)
450 {
451 // The backend selects the SPIR-V variant from the reflection, not the label, so this is informational only
452 static_cast<void>(label);
453 }
454
455 void VulkanShaderProgram::SetResolvedUniform(const char* name, const std::uint8_t* data)
456 {
457 for (ResolvedUniform& r : _resolvedUniforms) {
458 if (r.Name == name) {
459 r.Data = data;
460 return;
461 }
462 }
463 _resolvedUniforms.push_back({name, data});
464 }
465
466 const std::uint8_t* VulkanShaderProgram::ResolveUniform(const char* name) const
467 {
468 for (const ResolvedUniform& r : _resolvedUniforms) {
469 if (r.Name == name) {
470 return r.Data;
471 }
472 }
473 return nullptr;
474 }
475 }