Debian Codegraph @

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

raw
1 #pragma once
2
3 #include "VulkanShaderTypes.h"
4 #include "VulkanVertexFormat.h"
5 #include "../RhiTypes.h"
6
7 #include <cstdint>
8 #include <string>
9 #include <vector>
10
11 #include <Containers/ArrayView.h>
12 #include <Containers/String.h>
13 #include <Containers/StringView.h>
14
15 using namespace Death::Containers;
16
17 namespace ShaderCompiler
18 {
19 struct ProgramVariant;
20 }
21
22 namespace nCine::RHI::Vulkan
23 {
24 class VulkanBufferObject;
25 class VulkanShaderUniforms;
26 class VulkanShaderUniformBlocks;
27
28 /**
29 @brief Shader program of the Vulkan backend (aliased as `RHI::ShaderProgram`)
30
31 Carries the offline ShaderCompiler reflection (set with @ref SetReflection() like the OpenGL backend)
32 from which it imports uniforms, uniform blocks and attributes so the pipeline's uniform machinery runs.
33 It also builds the `VkShaderModule` pair from the reflection's embedded `VkVsSpirv`/`VkFsSpirv`, a
34 `VkDescriptorSetLayout` from the same reflection (set 0: optional `_Globals` UBO, then the std140 blocks,
35 then the combined-image-samplers, in reflection order) and a `VkPipeline` per vertex format. @ref Use()
36 records the program as current on the device.
37 */
38 class VulkanShaderProgram
39 {
40 friend class VulkanShaderUniforms;
41 friend class VulkanShaderUniformBlocks;
42
43 public:
44 enum class Introspection
45 {
46 Enabled,
47 NoUniformsInBlocks,
48 Disabled
49 };
50
51 enum class Status
52 {
53 NotLinked,
54 CompilationFailed,
55 LinkingFailed,
56 Linked,
57 LinkedWithDeferredQueries,
58 LinkedWithIntrospection
59 };
60
61 enum class QueryPhase
62 {
63 Immediate,
64 Deferred
65 };
66
67 /** @brief Default batch size, indicating the shader is not batched */
68 static constexpr std::int32_t DefaultBatchSize = -1;
69
70 VulkanShaderProgram();
71 explicit VulkanShaderProgram(QueryPhase queryPhase);
72 VulkanShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase);
73 VulkanShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection);
74 VulkanShaderProgram(StringView vertexFile, StringView fragmentFile);
75 ~VulkanShaderProgram();
76
77 VulkanShaderProgram(const VulkanShaderProgram&) = delete;
78 VulkanShaderProgram& operator=(const VulkanShaderProgram&) = delete;
79
80 /** @brief Returns a backend-neutral identifier uniquely identifying the program (feeds material sort keys; also keys the Vulkan pipeline/descriptor caches) */
81 inline std::uint32_t GetUniqueId() const {
82 return _handle;
83 }
84 inline Status GetStatus() const {
85 return _status;
86 }
87 inline Introspection GetIntrospection() const {
88 return _introspection;
89 }
90 inline QueryPhase GetQueryPhase() const {
91 return _queryPhase;
92 }
93 inline std::uint32_t GetBatchSize() const {
94 return _batchSize;
95 }
96 inline void SetBatchSize(std::uint32_t value) {
97 _batchSize = value;
98 }
99
100 bool IsLinked() const;
101
102 std::uint32_t RetrieveInfoLogLength() const {
103 return 0;
104 }
105 void RetrieveInfoLog(std::string& infoLog) const {
106 static_cast<void>(infoLog);
107 }
108
109 inline std::uint32_t GetUniformsSize() const {
110 return _uniformsSize;
111 }
112 inline std::uint32_t GetUniformBlocksSize() const {
113 return _uniformBlocksSize;
114 }
115
116 bool AttachShaderFromFile(ShaderStage stage, StringView filename);
117 bool AttachShaderFromString(ShaderStage stage, StringView string);
118 bool AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings);
119 bool AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename);
120
121 /** @brief Sets the offline reflection consumed by @ref Link() to import uniforms/blocks/attributes */
122 inline void SetReflection(const ShaderCompiler::ProgramVariant* reflection) {
123 _reflection = reflection;
124 }
125 /**
126 @brief Records the true (program, variant) identity of the loaded shader
127
128 Only the fixed-function console backends consume it (they resolve their generated
129 effect tables from this identity instead of the object label); this backend runs
130 real shaders and ignores it.
131 */
132 inline void SetProgramIdentity(const char* programName, const char* variantName) {
133 static_cast<void>(programName);
134 static_cast<void>(variantName);
135 }
136
137
138 bool Link(Introspection introspection);
139 void Use();
140 bool Validate() {
141 return true;
142 }
143 bool FinalizeAfterLinking(Introspection introspection);
144
145 inline std::uint32_t GetAttributeCount() const {
146 return std::uint32_t(_attributes.size());
147 }
148 bool HasAttribute(const char* name) const;
149 VulkanVertexFormat::Attribute* GetAttribute(const char* name);
150
151 inline void DefineVertexFormat(const VulkanBufferObject* vbo) {
152 DefineVertexFormat(vbo, nullptr, 0);
153 }
154 inline void DefineVertexFormat(const VulkanBufferObject* vbo, const VulkanBufferObject* ibo) {
155 DefineVertexFormat(vbo, ibo, 0);
156 }
157 void DefineVertexFormat(const VulkanBufferObject* vbo, const VulkanBufferObject* ibo, std::uint32_t vboOffset);
158
159 void Reset();
160 void SetObjectLabel(StringView label);
161
162 inline bool GetLogOnErrors() const {
163 return _shouldLogOnErrors;
164 }
165 inline void SetLogOnErrors(bool shouldLogOnErrors) {
166 _shouldLogOnErrors = shouldLogOnErrors;
167 }
168
169 // -- Backend extensions (used by the uniform caches and the device draw path) --
170
171 /** @brief Publishes a committed loose-uniform value pointer for the device to gather into `_Globals` */
172 void SetResolvedUniform(const char* name, const std::uint8_t* data);
173 /** @brief Returns the last published value pointer of the named loose uniform, or `nullptr` */
174 const std::uint8_t* ResolveUniform(const char* name) const;
175
176 /** @brief Returns `true` if the vertex shader reads vertex attributes (needs vertex input state + a vertex buffer) */
177 inline bool HasVertexAttributes() const {
178 return !_attributes.empty();
179 }
180 /** @brief Returns the vertex buffer bound by @ref DefineVertexFormat(), or `nullptr` */
181 inline const VulkanBufferObject* GetBoundVbo() const {
182 return _boundVbo;
183 }
184 /** @brief Returns the index buffer bound by @ref DefineVertexFormat(), or `nullptr` */
185 inline const VulkanBufferObject* GetBoundIbo() const {
186 return _boundIbo;
187 }
188
189 // -- SPIR-V modules, descriptor-set layout and the reflection metadata the device uses to
190 // build pipelines + descriptor sets. Vulkan handles are opaque integers so this contract header stays
191 // free of <vulkan/vulkan.h>; the .cpp reinterprets them. --
192
193 /** @brief One entry of the descriptor set (set 0), matching the offline emitter's binding scheme */
194 struct DescriptorBinding
195 {
196 enum class Kind { Globals, Block, Sampler };
197 Kind kind;
198 std::uint32_t binding; // the layout(binding=) number in the SPIR-V
199 std::int32_t slot; // Block: reflection block index (device uniform-range slot); Sampler: texture unit
200 };
201
202 /** @brief A loose (default-block) uniform gathered into the "_Globals" UBO, with its std140 placement */
203 struct LooseUniform
204 {
205 String Name;
206 std::uint32_t Offset; // std140 byte offset within _Globals
207 std::uint32_t Size; // byte size of the value
208 };
209
210 /** @brief Returns `true` if the SPIR-V modules and layouts were built successfully (draws are skipped otherwise) */
211 inline bool HasPipelineState() const {
212 return (_vsModule != 0 && _fsModule != 0 && _pipelineLayout != 0);
213 }
214 /** @brief The vertex-stage `VkShaderModule` (as `std::uint64_t`) */
215 inline std::uint64_t GetVsModule() const { return _vsModule; }
216 /** @brief The fragment-stage `VkShaderModule` */
217 inline std::uint64_t GetFsModule() const { return _fsModule; }
218 /** @brief The `VkPipelineLayout` (one descriptor set, set 0) */
219 inline std::uint64_t GetPipelineLayout() const { return _pipelineLayout; }
220 /** @brief The `VkDescriptorSetLayout` for set 0 */
221 inline std::uint64_t GetDescriptorSetLayout() const { return _descriptorSetLayout; }
222 /** @brief The descriptor bindings (in reflection order) the device writes each draw */
223 inline const std::vector<DescriptorBinding>& GetDescriptorBindings() const { return _descriptorBindings; }
224 /** @brief The loose uniforms gathered into "_Globals" (empty if the program has none) */
225 inline const std::vector<LooseUniform>& GetLooseUniforms() const { return _looseUniforms; }
226 /** @brief std140 byte size of the "_Globals" UBO (0 if the program has no loose uniforms) */
227 inline std::uint32_t GetGlobalsSize() const { return _globalsSize; }
228 /** @brief The binding number of the "_Globals" UBO (always 0 when present) */
229 inline bool HasGlobals() const { return _globalsSize > 0; }
230
231 /** @brief A vertex attribute for building the pipeline's vertex input state */
232 struct VertexAttrib
233 {
234 std::uint32_t Location;
235 std::int32_t ComponentCount;
236 std::uint32_t Offset; // byte offset within the vertex
237 std::uint32_t Type; // component type (VertexAttribType numeric value; 0 = float)
238 bool Normalized; // integer components normalized to [0,1] (e.g. u8 colors)
239 };
240 /**
241 * @brief Fills the current vertex input layout (attributes + per-vertex stride) from the bound vertex format
242 *
243 * Writes at most @p maxAttribs entries into @p outAttribs (a caller-provided array, so the per-draw
244 * pipeline-key computation never touches the heap) and returns the number written.
245 */
246 std::uint32_t GetVertexInput(VertexAttrib* outAttribs, std::uint32_t maxAttribs, std::uint32_t& outStride) const;
247
248 private:
249 static std::uint32_t _nextHandle;
250
251 std::uint32_t _handle;
252 Status _status;
253 Introspection _introspection;
254 QueryPhase _queryPhase;
255 std::uint32_t _batchSize;
256 bool _shouldLogOnErrors;
257 std::uint32_t _uniformsSize;
258 std::uint32_t _uniformBlocksSize;
259
260 std::vector<VulkanUniform> _uniforms;
261 std::vector<VulkanUniformBlock> _uniformBlocks;
262 std::vector<VulkanAttribute> _attributes;
263
264 const ShaderCompiler::ProgramVariant* _reflection;
265
266 VulkanVertexFormat _vertexFormat;
267 const VulkanBufferObject* _boundVbo;
268 const VulkanBufferObject* _boundIbo;
269
270 struct ResolvedUniform
271 {
272 String Name;
273 const std::uint8_t* Data;
274 };
275 std::vector<ResolvedUniform> _resolvedUniforms;
276
277 // GPU objects (opaque integers; see the getters above)
278 std::uint64_t _vsModule;
279 std::uint64_t _fsModule;
280 std::uint64_t _descriptorSetLayout;
281 std::uint64_t _pipelineLayout;
282 std::vector<DescriptorBinding> _descriptorBindings;
283 std::vector<LooseUniform> _looseUniforms;
284 std::uint32_t _globalsSize;
285
286 void PerformIntrospection();
287 void ImportReflection();
288 /** @brief Builds the SPIR-V modules, descriptor-set layout, pipeline layout and reflection metadata (during introspection, while the reflection is still available) */
289 void BuildPipelineState();
290 };
291 }