OpenGL Shading Language Tutorials

Tutorial 4: Varying Variables


Varying variables provide an interface between Vertex and Fragment Shader. Vertex Shaders compute values per vertex and fragment shaders compute values per fragment. If you define a varying variable in a vertex shader, its value will be interpolated (perspective-correct) over the primitve being rendered and you can access the interpolated value in the fragment shader.

Varying can be used only with the data types float, vec2, vec3, vec4, mat2, mat3, mat4. (arrays of them too.)

OGLSL Example

 

 

Vertex Shader

varying float xpos;
varying float ypos;
varying float zpos;
void main(void)
{
  xpos = clamp(gl_Vertex.x,0.0,1.0);
  ypos = clamp(gl_Vertex.y,0.0,1.0);
  zpos = clamp(gl_Vertex.z,0.0,1.0);
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}


I get the incoming vertex position and clamp it to 0.0 ... 1.0 and save x, y and z value in 3 varying variables

Fragment Shader

varying float xpos;
varying float ypos;
varying float zpos;
void main (void)
{
   gl_FragColor = vec4 (xpos, ypos, zpos, 1.0);
}

I set the interpolated value as output color, this results in the color cube.

 

Exercise:

Using 3 varying float variables is bad design. Change it so it uses one vec3.
Hint: In OGLSL * is component wise multiplication.


Go to Tutorial 5

 


Author: Martin Christen, christen@clockworkcoders.com
(source code is included in Tutorial Version 0.1 and higher)

 

 

© 2003 by Martin Christen. All Rights Reserved.
christen@clockworkcoders.com