Creating a GLSL Arrays of Uniforms?

ArraysOpenglGlslShader

Arrays Problem Overview


I would like to leave OpenGL's lights and make my own. I would like my shaders to allow for a variable number of lights.

Can we declare an array of uniforms in GLSL shaders? If so, how would we set the values of those uniforms?

Arrays Solutions


Solution 1 - Arrays

Yes this is possible. You declare uniform arrays similar to how you'd do it in C, e.g.

uniform float v[10];

Then you can set their values using glUniform{1,2,3,4}{f,i}v

GLfloat v[10] = {...};
glUniform1fv(glGetUniformLocation(program, "v"), 10, v);

Solution 2 - Arrays

Yes it is possible to declare an array of uniforms in GLSL shaders. Just google "glsl uniform array" for some examples (edit: or see datenwolf's example). There are however limitations on how many uniforms can be sent to different graphics cards (at least on older ones, I'm not sure about current ones (although I imagine there still would be)).

If you do decide to go down the route of uniforms, i would suggest using uniform buffers. According to http://www.opengl.org/wiki/Uniform_Buffer_Object, "Switching between uniform buffer bindings is typically faster than switching dozens of uniforms in a program".

If you have large numbers of lights and parameters, you could also send the data as float buffers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMilesView Question on Stackoverflow
Solution 1 - ArraysdatenwolfView Answer on Stackoverflow
Solution 2 - ArraysNickLHView Answer on Stackoverflow