Debian Codegraph @

avogadro/rendering/shaderprogram.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "shaderprogram.h"
7
8 #include "avogadrogl.h"
9 #include "shader.h"
10 #include "texture2d.h"
11
12 #include <avogadro/core/types.h>
13
14 #include <algorithm>
15
16 namespace Avogadro::Rendering {
17
18 namespace {
19 inline GLenum convertType(Type type)
20 {
21 switch (type) {
22 default:
23 case UCharType:
24 return GL_UNSIGNED_BYTE;
25 case CharType:
26 return GL_BYTE;
27 case ShortType:
28 return GL_SHORT;
29 case UShortType:
30 return GL_UNSIGNED_SHORT;
31 case IntType:
32 return GL_INT;
33 case UIntType:
34 return GL_UNSIGNED_INT;
35 case FloatType:
36 return GL_FLOAT;
37 case DoubleType:
38 return GL_DOUBLE;
39 }
40 }
41
42 inline GLenum lookupTextureUnit(GLint index)
43 {
44 #define MAKE_TEXTURE_UNIT_CASE(i) \
45 case i: \
46 return GL_TEXTURE##i;
47 switch (index) {
48 MAKE_TEXTURE_UNIT_CASE(0)
49 MAKE_TEXTURE_UNIT_CASE(1)
50 MAKE_TEXTURE_UNIT_CASE(2)
51 MAKE_TEXTURE_UNIT_CASE(3)
52 MAKE_TEXTURE_UNIT_CASE(4)
53 MAKE_TEXTURE_UNIT_CASE(5)
54 MAKE_TEXTURE_UNIT_CASE(6)
55 MAKE_TEXTURE_UNIT_CASE(7)
56 MAKE_TEXTURE_UNIT_CASE(8)
57 MAKE_TEXTURE_UNIT_CASE(9)
58 MAKE_TEXTURE_UNIT_CASE(10)
59 MAKE_TEXTURE_UNIT_CASE(11)
60 MAKE_TEXTURE_UNIT_CASE(12)
61 MAKE_TEXTURE_UNIT_CASE(13)
62 MAKE_TEXTURE_UNIT_CASE(14)
63 MAKE_TEXTURE_UNIT_CASE(15)
64 MAKE_TEXTURE_UNIT_CASE(16)
65 MAKE_TEXTURE_UNIT_CASE(17)
66 MAKE_TEXTURE_UNIT_CASE(18)
67 MAKE_TEXTURE_UNIT_CASE(19)
68 MAKE_TEXTURE_UNIT_CASE(20)
69 MAKE_TEXTURE_UNIT_CASE(21)
70 MAKE_TEXTURE_UNIT_CASE(22)
71 MAKE_TEXTURE_UNIT_CASE(23)
72 MAKE_TEXTURE_UNIT_CASE(24)
73 MAKE_TEXTURE_UNIT_CASE(25)
74 MAKE_TEXTURE_UNIT_CASE(26)
75 MAKE_TEXTURE_UNIT_CASE(27)
76 MAKE_TEXTURE_UNIT_CASE(28)
77 MAKE_TEXTURE_UNIT_CASE(29)
78 MAKE_TEXTURE_UNIT_CASE(30)
79 MAKE_TEXTURE_UNIT_CASE(31)
80 default:
81 return 0;
82 }
83 }
84 } // namespace
85
86 ShaderProgram::ShaderProgram()
87 : m_handle(0), m_vertexShader(0), m_fragmentShader(0), m_linked(false)
88 {
89 initializeTextureUnits();
90 }
91
92 ShaderProgram::~ShaderProgram()
93 {
94 if (m_handle != 0) {
95 glDeleteProgram(static_cast<GLuint>(m_handle));
96 }
97 }
98
99 bool ShaderProgram::attachShader(const Shader& shader)
100 {
101 if (shader.handle() == 0) {
102 m_error = "Shader object was not initialized, cannot attach it.";
103 return false;
104 }
105 if (shader.type() == Shader::Unknown) {
106 m_error = "Shader object is of type Unknown and cannot be used.";
107 return false;
108 }
109
110 if (m_handle == 0) {
111 GLuint handle_ = glCreateProgram();
112 if (handle_ == 0) {
113 m_error = "Could not create shader program.";
114 return false;
115 }
116 m_handle = static_cast<Index>(handle_);
117 m_linked = false;
118 }
119
120 if (shader.type() == Shader::Vertex) {
121 if (m_vertexShader != 0) {
122 glDetachShader(static_cast<GLuint>(m_handle),
123 static_cast<GLuint>(m_vertexShader));
124 }
125 m_vertexShader = shader.handle();
126 } else if (shader.type() == Shader::Fragment) {
127 if (m_fragmentShader != 0) {
128 glDetachShader(static_cast<GLuint>(m_handle),
129 static_cast<GLuint>(m_fragmentShader));
130 }
131 m_fragmentShader = shader.handle();
132 } else {
133 m_error = "Unknown shader type encountered - this should not happen.";
134 return false;
135 }
136
137 glAttachShader(static_cast<GLuint>(m_handle),
138 static_cast<GLuint>(shader.handle()));
139 m_linked = false;
140 return true;
141 }
142
143 bool ShaderProgram::detachShader(const Shader& shader)
144 {
145 if (shader.handle() == 0) {
146 m_error = "Shader object was not initialized, cannot attach it.";
147 return false;
148 }
149 if (shader.type() == Shader::Unknown) {
150 m_error = "Shader object is of type Unknown and cannot be used.";
151 return false;
152 }
153 if (m_handle == 0) {
154 m_error = "This shader prorgram has not been initialized yet.";
155 }
156
157 switch (shader.type()) {
158 case Shader::Vertex:
159 if (m_vertexShader != shader.handle()) {
160 m_error = "The supplied shader was not attached to this program.";
161 return false;
162 } else {
163 glDetachShader(static_cast<GLuint>(m_handle),
164 static_cast<GLuint>(shader.handle()));
165 m_vertexShader = 0;
166 return true;
167 }
168 case Shader::Fragment:
169 if (m_fragmentShader != shader.handle()) {
170 m_error = "The supplied shader was not attached to this program.";
171 return false;
172 } else {
173 glDetachShader(static_cast<GLuint>(m_handle),
174 static_cast<GLuint>(shader.handle()));
175 m_fragmentShader = 0;
176 return true;
177 }
178 default:
179 return false;
180 }
181 }
182
183 bool ShaderProgram::link()
184 {
185 if (m_linked)
186 return true;
187
188 if (m_handle == 0) {
189 m_error = "Program has not been initialized, and/or does not have shaders.";
190 return false;
191 }
192
193 GLint isCompiled;
194 glLinkProgram(static_cast<GLuint>(m_handle));
195 glGetProgramiv(static_cast<GLuint>(m_handle), GL_LINK_STATUS, &isCompiled);
196 if (isCompiled == 0) {
197 GLint length(0);
198 glGetShaderiv(static_cast<GLuint>(m_handle), GL_INFO_LOG_LENGTH, &length);
199 if (length > 1) {
200 char* logMessage = new char[length];
201 glGetShaderInfoLog(static_cast<GLuint>(m_handle), length, nullptr,
202 logMessage);
203 m_error = logMessage;
204 delete[] logMessage;
205 }
206 return false;
207 }
208 m_linked = true;
209 m_attributes.clear();
210 return true;
211 }
212
213 bool ShaderProgram::bind()
214 {
215 if (!m_linked && !link())
216 return false;
217
218 glUseProgram(static_cast<GLuint>(m_handle));
219 return true;
220 }
221
222 void ShaderProgram::release()
223 {
224 glUseProgram(0);
225 releaseAllTextureUnits();
226 }
227
228 bool ShaderProgram::enableAttributeArray(const std::string& name)
229 {
230 auto location = static_cast<GLint>(findAttributeArray(name));
231 if (location == -1) {
232 m_error = "Could not enable attribute " + name + ". No such attribute.";
233 return false;
234 }
235 glEnableVertexAttribArray(location);
236 return true;
237 }
238
239 bool ShaderProgram::disableAttributeArray(const std::string& name)
240 {
241 auto location = static_cast<GLint>(findAttributeArray(name));
242 if (location == -1) {
243 m_error = "Could not disable attribute " + name + ". No such attribute.";
244 return false;
245 }
246 glDisableVertexAttribArray(location);
247 return true;
248 }
249
250 #define BUFFER_OFFSET(i) ((char*)nullptr + (i))
251
252 bool ShaderProgram::useAttributeArray(const std::string& name, int offset,
253 size_t stride, Type elementType,
254 int elementTupleSize,
255 NormalizeOption normalize)
256 {
257 auto location = static_cast<GLint>(findAttributeArray(name));
258 if (location == -1) {
259 m_error = "Could not use attribute " + name + ". No such attribute.";
260 return false;
261 }
262 glVertexAttribPointer(location, elementTupleSize, convertType(elementType),
263 normalize == Normalize ? GL_TRUE : GL_FALSE,
264 static_cast<GLsizei>(stride), BUFFER_OFFSET(offset));
265 return true;
266 }
267
268 bool ShaderProgram::setTextureSampler(const std::string& name,
269 const Texture2D& texture)
270 {
271 // Look up sampler location:
272 auto location = static_cast<GLint>(findUniform(name));
273 if (location == -1) {
274 m_error = "Could not set sampler " + name + ". No uniform with that name.";
275 return false;
276 }
277
278 // Check if the texture is already bound:
279 GLint textureUnitId = 0;
280 auto result = m_textureUnitBindings.find(&texture);
281 if (result == m_textureUnitBindings.end()) {
282 // Not bound. Attempt to bind the texture to an available texture unit.
283 // We'll leave GL_TEXTURE0 unbound, as it is used for manipulating
284 // textures.
285 auto begin = m_boundTextureUnits.begin() + 1;
286 auto end = m_boundTextureUnits.end();
287 auto available = std::find(begin, end, false);
288
289 if (available == end) {
290 m_error = "Could not set sampler " + name +
291 ". No remaining texture units available.";
292 return false;
293 }
294
295 textureUnitId = static_cast<GLint>(available - begin);
296
297 GLenum textureUnit = lookupTextureUnit(textureUnitId);
298 if (textureUnit == 0) {
299 m_error =
300 "Could not set sampler " + name + ". Texture unit lookup failed.";
301 return false;
302 }
303
304 glActiveTexture(textureUnit);
305 if (!texture.bind()) {
306 m_error = "Could not set sampler " + name +
307 ": Error while binding texture: '" + texture.error() + "'.";
308 glActiveTexture(GL_TEXTURE0);
309 return false;
310 }
311 glActiveTexture(GL_TEXTURE0);
312
313 // Mark texture unit as in-use.
314 m_textureUnitBindings.insert(std::make_pair(&texture, textureUnitId));
315 *available = true;
316 } else {
317 // Texture is already bound.
318 textureUnitId = result->second;
319 }
320
321 // Set the texture unit uniform
322 glUniform1i(location, textureUnitId);
323
324 return true;
325 }
326
327 bool ShaderProgram::setUniformValue(const std::string& name, int i)
328 {
329 auto location = static_cast<GLint>(findUniform(name));
330 if (location == -1) {
331 m_error = "Could not set uniform " + name + ". No such uniform.";
332 return false;
333 }
334 glUniform1i(location, static_cast<GLint>(i));
335 return true;
336 }
337
338 bool ShaderProgram::setUniformValue(const std::string& name, float f)
339 {
340 auto location = static_cast<GLint>(findUniform(name));
341 if (location == -1) {
342 m_error = "Could not set uniform " + name + ". No such uniform.";
343 return false;
344 }
345 glUniform1f(location, static_cast<GLfloat>(f));
346 return true;
347 }
348
349 bool ShaderProgram::setUniformValue(const std::string& name,
350 const Eigen::Matrix3f& matrix)
351 {
352 auto location = static_cast<GLint>(findUniform(name));
353 if (location == -1) {
354 m_error = "Could not set uniform " + name + ". No such uniform.";
355 return false;
356 }
357 glUniformMatrix3fv(location, 1, GL_FALSE,
358 static_cast<const GLfloat*>(matrix.data()));
359 return true;
360 }
361
362 bool ShaderProgram::setUniformValue(const std::string& name,
363 const Eigen::Matrix4f& matrix)
364 {
365 auto location = static_cast<GLint>(findUniform(name));
366 if (location == -1) {
367 m_error = "Could not set uniform " + name + ". No such uniform.";
368 return false;
369 }
370 glUniformMatrix4fv(location, 1, GL_FALSE,
371 static_cast<const GLfloat*>(matrix.data()));
372 return true;
373 }
374
375 bool ShaderProgram::setUniformValue(const std::string& name, const Vector3f& v)
376 {
377 auto location = static_cast<GLint>(findUniform(name));
378 if (location == -1) {
379 m_error = "Could not set uniform " + name + ". No such uniform.";
380 return false;
381 }
382 glUniform3fv(location, 1, v.data());
383 return true;
384 }
385
386 bool ShaderProgram::setUniformValue(const std::string& name, const Vector2i& v)
387 {
388 auto location = static_cast<GLint>(findUniform(name));
389 if (location == -1) {
390 m_error = "Could not set uniform " + name + ". No such uniform.";
391 return false;
392 }
393 glUniform2iv(location, 1, v.data());
394 return true;
395 }
396
397 bool ShaderProgram::setUniformValue(const std::string& name, const Vector3ub& v)
398 {
399 auto location = static_cast<GLint>(findUniform(name));
400 if (location == -1) {
401 m_error = "Could not set uniform " + name + ". No such uniform.";
402 return false;
403 }
404 Vector3f colorf(v.cast<float>() * (1.0f / 255.0f));
405 glUniform3fv(location, 1, colorf.data());
406 return true;
407 }
408
409 bool ShaderProgram::setAttributeArrayInternal(
410 const std::string& name, void* buffer, Avogadro::Type type, int tupleSize,
411 ShaderProgram::NormalizeOption normalize)
412 {
413 if (type == Avogadro::UnknownType) {
414 m_error = "Unrecognized data type for attribute " + name + ".";
415 return false;
416 }
417 auto location = static_cast<GLint>(findAttributeArray(name));
418 if (location == -1) {
419 m_error = "Could not set attribute " + name + ". No such attribute.";
420 return false;
421 }
422 const auto* data = static_cast<const GLvoid*>(buffer);
423 glVertexAttribPointer(location, tupleSize, convertType(type),
424 normalize == Normalize ? GL_TRUE : GL_FALSE, 0, data);
425 return true;
426 }
427
428 void ShaderProgram::initializeTextureUnits()
429 {
430 GLint numTextureUnits = 0;
431 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &numTextureUnits);
432
433 // We'll impose a hard limit of 32 texture units for symbolic lookups.
434 // This seems to be about the maximum available on current hardware.
435 // If increasing this limit, modify the lookupTextureUnit method
436 // appropriately.
437 numTextureUnits = std::clamp(numTextureUnits, 0, 32);
438
439 m_boundTextureUnits.clear();
440 m_boundTextureUnits.resize(numTextureUnits, false);
441 m_textureUnitBindings.clear();
442 }
443
444 void ShaderProgram::releaseAllTextureUnits()
445 {
446 std::fill(m_boundTextureUnits.begin(), m_boundTextureUnits.end(), false);
447 m_textureUnitBindings.clear();
448 }
449
450 inline int ShaderProgram::findAttributeArray(const std::string& name)
451 {
452 if (name.empty() || !m_linked)
453 return -1;
454 const auto* namePtr = static_cast<const GLchar*>(name.c_str());
455 auto location = static_cast<int>(
456 glGetAttribLocation(static_cast<GLuint>(m_handle), namePtr));
457 if (location == -1) {
458 m_error = "Specified attribute not found in current shader program: ";
459 m_error += name;
460 }
461
462 return location;
463 }
464
465 inline int ShaderProgram::findUniform(const std::string& name)
466 {
467 if (name.empty() || !m_linked)
468 return -1;
469 const auto* namePtr = static_cast<const GLchar*>(name.c_str());
470 auto location = static_cast<int>(
471 glGetUniformLocation(static_cast<GLuint>(m_handle), namePtr));
472 if (location == -1)
473 m_error = "Uniform " + name + " not found in current shader program.";
474
475 return location;
476 }
477
478 } // namespace Avogadro::Rendering