views:

416

answers:

2

Is it possible to set the color of a single vertex using a GLSL vertex shader program, in the same way that gl_Position changes the position of a vertex ?

+1  A: 

I guess I assumed too much about your experience with GLSL. My apologies.

For the versions of GLSL prior version 1.30, you want to write to the gl_FrontColor or gl_BackColor built-ins, which are varyings accessible in the vertex shader. Read about varyings in the GLSL 1.10 specification to learn more about them, or the GL_ARB_vertex_shader extension specification.

gl_FrontColor and gl_BackColor are 4D RGBA vectors which take normalized floating point scalars.

But this will set all the vertices to red, not just one vertex. This is because the same vertex shader is run for all the vertices. If you want to set individual colours, use glColorPointer together with glDrawArrays,glDrawElements,glDrawRangeElements or glMultiDrawElements. The vertex color set by glColorPointer can be read as gl_Color in the vertex shader. gl_Color in the vertex shader is a per-vertex attribute.

To read the color you wrote in the vertex shader, in the fragment shader, read the built-in varying gl_Color. Finished fragments should be written to gl_FragColor.

Vertex shader example:

void main()
{
    gl_FrontColor = gl_Color;
    gl_Position = gl_ModelviewProjectionMatrix * gl_Vertex;
}

Fragment shader example:

void main()
{
    gl_FragColor = glColor;
}

Also, to make the vertex shader set the varyings just like the OpenGL fixed-function pipeline, call the function ftransform().

void main()
{
    ftransform();
}
Mads Elvheim
Thanks for the reply. BTW, it seems that the definition of the fragment shader (with at least gl_FragColor = glColor) is mandatory to when gl_FrontColor is used in a vertex shader.
Soubok
err, gl_Position set in fragment shader ? glColor rather than gl_Color ? ftransform by itself, without setting to gl_Position ?
Bahbar
That's fixed now :)
Mads Elvheim
A: 

In the fragment shader, it should be:

gl_FragColor = gl_Color;

not

gl_FragColor = glColor;

Rex Guo