Clockworkcoders Tutorials

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 primitive 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.)


In the example before (Vertex Attributes) the color attribute was used to transform the vertex position, this time we actually use the color value in its correct purpose and pass it down (as varying variable) to the fragment shader. The color value is interpolated this way. If you disable the shader you should get the same result - the fixed function pipeline does the same with the color!

varying vec4 vColor;
void main(void)
   vColor = gl_Color;
   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
Vertex Shader Source Code

varying vec4 vColor;
void main (void) 
   gl_FragColor = vColor; 
Fragment Shader Source Code

Example Project

In this example project the above example shaders are used.

Download: (Visual Studio 8 Project)
(If you create a project/makefile for a different platform/compiler, please send it to: christen(at) and I will put it here.)


Previous: Vertex Attributes

(c) 2007 by Martin Christen