Debian Codegraph @

Sources/nCine/Graphics/RHI/GS/GsShaderProgram.cpp

raw
1 #include "GsShaderProgram.h"
2 #include "GsDevice.h"
3 #include "../../RenderResources.h"
4
5 #include <cstring>
6
7 #include <Asserts.h>
8
9 namespace nCine::RHI::GS
10 {
11 std::uint32_t GsShaderProgram::_nextHandle = 1;
12
13 GsShaderProgram::GsShaderProgram()
14 : GsShaderProgram(QueryPhase::Immediate)
15 {
16 }
17
18 GsShaderProgram::GsShaderProgram(QueryPhase queryPhase)
19 : _handle(_nextHandle++), _status(Status::NotLinked), _introspection(Introspection::Disabled), _queryPhase(queryPhase),
20 _batchSize(DefaultBatchSize), _shouldLogOnErrors(true), _uniformsSize(0), _uniformBlocksSize(0),
21 _reflection(nullptr), _effectReflection(nullptr), _generatedEffect(nullptr), _ditherVariant(false), _usesPalette(false),
22 _boundVbo(nullptr), _boundVboOffset(0), _boundIbo(nullptr)
23 {
24 }
25
26 GsShaderProgram::GsShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase)
27 : GsShaderProgram(queryPhase)
28 {
29 static_cast<void>(vertexFile);
30 static_cast<void>(fragmentFile);
31 static_cast<void>(introspection);
32 }
33
34 GsShaderProgram::GsShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection)
35 : GsShaderProgram(vertexFile, fragmentFile, introspection, QueryPhase::Immediate)
36 {
37 }
38
39 GsShaderProgram::GsShaderProgram(StringView vertexFile, StringView fragmentFile)
40 : GsShaderProgram(vertexFile, fragmentFile, Introspection::Enabled, QueryPhase::Immediate)
41 {
42 }
43
44 GsShaderProgram::~GsShaderProgram()
45 {
46 // The pipeline keys per-shader camera uniform data on the program pointer; drop this program's entry
47 // so RenderResources::Dispose() finds the map empty (mirrors GLShaderProgram's destructor)
48 RenderResources::RemoveCameraUniformData(this);
49 }
50
51 bool GsShaderProgram::IsLinked() const
52 {
53 return (_status == Status::Linked || _status == Status::LinkedWithDeferredQueries || _status == Status::LinkedWithIntrospection);
54 }
55
56 bool GsShaderProgram::AttachShaderFromFile(ShaderStage stage, StringView filename)
57 {
58 static_cast<void>(stage);
59 static_cast<void>(filename);
60 return true;
61 }
62
63 bool GsShaderProgram::AttachShaderFromString(ShaderStage stage, StringView string)
64 {
65 static_cast<void>(stage);
66 static_cast<void>(string);
67 return true;
68 }
69
70 bool GsShaderProgram::AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings)
71 {
72 static_cast<void>(stage);
73 static_cast<void>(strings);
74 return true;
75 }
76
77 bool GsShaderProgram::AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename)
78 {
79 static_cast<void>(stage);
80 static_cast<void>(strings);
81 static_cast<void>(filename);
82 return true;
83 }
84
85 bool GsShaderProgram::Link(Introspection introspection)
86 {
87 return FinalizeAfterLinking(introspection);
88 }
89
90 bool GsShaderProgram::FinalizeAfterLinking(Introspection introspection)
91 {
92 _introspection = introspection;
93 PerformIntrospection();
94 return true;
95 }
96
97 void GsShaderProgram::Use()
98 {
99 GsDevice::BindProgram(this);
100 }
101
102 void GsShaderProgram::PerformIntrospection()
103 {
104 if (_introspection != Introspection::Disabled && _status != Status::LinkedWithIntrospection) {
105 _uniformsSize = 0;
106 _uniformBlocksSize = 0;
107
108 if (_reflection != nullptr) {
109 _effectReflection = _reflection;
110 ImportReflection();
111 // A program samples indexed textures through the shared palette exactly when its
112 // (variant-resolved) reflection binds the palette sampler - the "...Palette" programs and the
113 // USE_PALETTE variants all declare it, everything else cannot possibly remap
114 _usesPalette = false;
115 for (std::size_t i = 0; i < _reflection->TextureCount; i++) {
116 if (std::strcmp(_reflection->Textures[i].Name, "uTexturePalette") == 0) {
117 _usesPalette = true;
118 break;
119 }
120 }
121 }
122 // Resolve the generated fixed-function effect of this (program, variant) once here, so the draw
123 // path only reads a pointer. The key is the TRUE identity plumbed by the loaders via
124 // SetProgramIdentity() - no shader name is ever matched; a program that never received an identity
125 // (runtime-compiled .shader files) simply has no console effect and is skipped.
126 _generatedEffect = (!_programName.empty()
127 ? GsDevice::FindGeneratedEffect(_programName.data(), _variantName.data()) : nullptr);
128 _status = Status::LinkedWithIntrospection;
129 }
130 // The reflection is consumed by introspection (a copy of its layout is kept in _effectReflection)
131 _reflection = nullptr;
132 }
133
134 void GsShaderProgram::ImportReflection()
135 {
136 const ShaderCompiler::ProgramVariant& reflection = *_reflection;
137 std::int32_t nextLocation = 0;
138
139 // Loose uniforms - samplers are kept in a separate reflection list but treated as loose uniforms here
140 for (std::size_t i = 0; i < reflection.UniformCount; i++) {
141 const ShaderCompiler::Uniform& u = reflection.Uniforms[i];
142 _uniforms.emplace_back(this, u.Name, u.Type, std::int32_t(u.ArraySize), nextLocation++);
143 _uniformsSize += _uniforms.back().GetMemorySize();
144 }
145 for (std::size_t i = 0; i < reflection.TextureCount; i++) {
146 const ShaderCompiler::TextureBinding& t = reflection.Textures[i];
147 _uniforms.emplace_back(this, t.Name, ShaderCompiler::UniformType::Sampler2D, 1, nextLocation++);
148 _uniformsSize += _uniforms.back().GetMemorySize();
149 }
150
151 _uniformBlocks.reserve(reflection.BlockCount);
152 for (std::size_t i = 0; i < reflection.BlockCount; i++) {
153 const ShaderCompiler::UniformBlock& b = reflection.Blocks[i];
154
155 // A BATCH_SIZE-sized instance array uses the explicitly set batch size, or the same 64 KB-based
156 // fallback the in-shader "#ifndef BATCH_SIZE" defaults assume when no size is injected
157 std::uint32_t effectiveBatchSize = 0;
158 std::uint32_t dataSize = b.BaseSize;
159 if (b.InstanceStride > 0) {
160 effectiveBatchSize = (_batchSize != std::uint32_t(DefaultBatchSize) && _batchSize > 0)
161 ? _batchSize : (64u * 1024u) / b.InstanceStride;
162 dataSize += b.InstanceStride * effectiveBatchSize;
163 }
164
165 const std::uint32_t blockIndex = std::uint32_t(_uniformBlocks.size());
166 _uniformBlocks.emplace_back(blockIndex, b.Name, std::int32_t(dataSize));
167 GsUniformBlock& block = _uniformBlocks.back();
168 _uniformBlocksSize += block.GetSize();
169
170 if (_introspection != Introspection::NoUniformsInBlocks) {
171 block._members.reserve(b.MemberCount);
172 for (std::size_t j = 0; j < b.MemberCount; j++) {
173 const ShaderCompiler::BlockMember& m = b.Members[j];
174 if (m.Type == ShaderCompiler::UniformType::Struct) {
175 // Struct aggregates are never read by name; only flat leaf members matter
176 continue;
177 }
178 GsUniform member;
179 member.SetName(m.Name);
180 member._type = m.Type;
181 member._size = (m.ArraySize == ShaderCompiler::SymbolicArraySize)
182 ? std::int32_t(effectiveBatchSize)
183 : (m.ArraySize > 0 ? std::int32_t(m.ArraySize) : 1);
184 member._blockIndex = std::int32_t(blockIndex);
185 member._offset = std::int32_t(m.Offset);
186 member._owner = this;
187 block._members.push_back(member);
188 }
189 }
190 }
191
192 for (std::size_t i = 0; i < reflection.AttributeCount; i++) {
193 const ShaderCompiler::Attribute& a = reflection.Attributes[i];
194 const std::int32_t location = (a.Location >= 0 ? a.Location : std::int32_t(i));
195 _attributes.emplace_back(a.Name, a.Type, location);
196 _vertexFormat[std::uint32_t(location)].Init(std::uint32_t(location), std::int32_t(UniformTypeInfo::ComponentCount(a.Type)), 0);
197 }
198 }
199
200 bool GsShaderProgram::HasAttribute(const char* name) const
201 {
202 for (const GsAttribute& a : _attributes) {
203 if (std::strcmp(a.GetName(), name) == 0) {
204 return true;
205 }
206 }
207 return false;
208 }
209
210 GsVertexFormat::Attribute* GsShaderProgram::GetAttribute(const char* name)
211 {
212 for (const GsAttribute& a : _attributes) {
213 if (std::strcmp(a.GetName(), name) == 0 && a.GetLocation() >= 0) {
214 return &_vertexFormat[std::uint32_t(a.GetLocation())];
215 }
216 }
217 return nullptr;
218 }
219
220 void GsShaderProgram::DefineVertexFormat(const GsBuffer* vbo, const GsBuffer* ibo, std::uint32_t vboOffset)
221 {
222 _boundVbo = vbo;
223 _boundVboOffset = vboOffset;
224 _boundIbo = ibo;
225 if (vbo != nullptr) {
226 for (const GsAttribute& a : _attributes) {
227 if (a.GetLocation() >= 0) {
228 GsVertexFormat::Attribute& attr = _vertexFormat[std::uint32_t(a.GetLocation())];
229 attr.setVbo(vbo);
230 attr.SetBaseOffset(vboOffset);
231 }
232 }
233 _vertexFormat.SetIbo(ibo);
234 }
235 }
236
237 void GsShaderProgram::Reset()
238 {
239 _uniforms.clear();
240 _uniformBlocks.clear();
241 _attributes.clear();
242 _resolvedUniforms.clear();
243 _vertexFormat.Reset();
244 _status = Status::NotLinked;
245 _batchSize = DefaultBatchSize;
246 _reflection = nullptr;
247 _effectReflection = nullptr;
248 // A reloaded program gets a fresh identity from its loader (SetProgramIdentity), so nothing stale can
249 // leak into the effect resolution of the next PerformIntrospection()
250 _programName = {};
251 _variantName = {};
252 _generatedEffect = nullptr;
253 _ditherVariant = false;
254 _usesPalette = false;
255 }
256
257 void GsShaderProgram::SetObjectLabel(StringView label)
258 {
259 // The label is kept for log messages only - effect identity comes from SetProgramIdentity()
260 _label = label;
261 }
262
263 void GsShaderProgram::SetProgramIdentity(const char* programName, const char* variantName)
264 {
265 // The true (program, variant) identity the loader compiled this program from: the .shader program name
266 // and the variant define (both baked into the generated tables). Stored as copies because
267 // runtime-compiled programs hand in transient strings; the generated-table lookup itself runs in
268 // PerformIntrospection(), after the reflection is set alongside.
269 _programName = (programName != nullptr ? programName : "");
270 _variantName = (variantName != nullptr ? variantName : "");
271 // The dithering variant is a variant of the SAME program (TexturedBackground and its circle twin
272 // declare "variant DITHER;"), so the flag is exactly the variant name
273 _ditherVariant = (_variantName == "DITHER");
274 }
275
276 const GsUniformBlock* GsShaderProgram::FindBlock(const char* name) const
277 {
278 for (const GsUniformBlock& block : _uniformBlocks) {
279 if (std::strcmp(block.GetName(), name) == 0) {
280 return &block;
281 }
282 }
283 return nullptr;
284 }
285
286 void GsShaderProgram::SetResolvedUniform(const char* name, const std::uint8_t* data)
287 {
288 // The two names every dispatch reads get direct slots, so the draw path never scans by name
289 if (std::strcmp(name, "uProjectionMatrix") == 0) {
290 _resolvedProjection = data;
291 } else if (std::strcmp(name, "uViewMatrix") == 0) {
292 _resolvedView = data;
293 }
294 for (ResolvedUniform& r : _resolvedUniforms) {
295 if (r.Name == name) {
296 r.Data = data;
297 return;
298 }
299 }
300 _resolvedUniforms.push_back({name, data});
301 }
302
303 const std::uint8_t* GsShaderProgram::ResolveUniform(const char* name) const
304 {
305 for (const ResolvedUniform& r : _resolvedUniforms) {
306 if (r.Name == name) {
307 return r.Data;
308 }
309 }
310 return nullptr;
311 }
312 }