I'm writing an iPhone app which uses GLSL shaders to perform transformations on textures, but one point that I'm having a little hard time with is passing variables to my GLSL shader.
I've read that it's possible to have a shader read part of the OpenGL state (and I would only need read-only access to this variable), but I'm not sure how that exchange would happen.
In short, I'm trying to get a float value created outside of a fragment shader to be accessible to the fragment shader (whether it's passed in or read from inside the shader).
Thanks for any help/pointers you can provide, it's very appreciated!
One option is to pass information via uniform variables.
After
glUseProgram(myShaderProgram);
you can use
GLint myUniformLocation = glGetUniformLocation(myShaderProgram, "myUniform");
and for example
glUniform1f(myUniformLocation, /* some floating point value here */);
In your vertex or fragment shader, you need to add the following declaration:
uniform float myUniform;
That's it, in your shader you can now access (read-only) the value you passed earlier on via glUniform1f
.
Of course uniform variables can be any valid GLSL type including complex types such
as arrays, structures or matrices. OpenGL provides a glUniform
function with the usual suffixes,
appropriate for each type. For example, to assign to a variable of type vec3
, one would
use glUniform3f
or glUniform3fv
.
Note: the value can't be modified during execution of the shader, i.e. in a glBegin
/glEnd
block. It is read-only and the same for every fragment/vertex processed.
There are also several tutorials using uniforms, you can find them by googling "glsl uniform variable".
I hope that helps.