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!
Data is passed from shader to shader by using the in and out keywords. You create an output shader variable by using the out keyword. The out variable in one shader provides the input data to the next shader declared as an in variable. The only condition is that both of these variables must have the same name.
gl_Position is a special variable that holds the position of the vertex in clip space. Since a vertex shader's main output is the position in clip space, it must always set gl_Position. This vertex shader just transforms each vertex position (by the VP matrix).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With