Karnivaurus
Karnivaurus

Reputation: 24121

How to set the colour of a vertex in shaders with OpenGL

I am writing a simple program to render an object in OpenGL using shaders.

My fragment shader is currently:

void main()
{
    gl_FragColor = vec4(0.5, 0.5, 0.5, 1.0);
}

And my vertex shader is currently:

layout (location = 0) in vec3 position; 
uniform mat4 projection_matrix;
uniform mat4 view_matrix;

void main()
{
    gl_Position = projection_matrix * view_matrix * vec4(position, 1.0);
}

And my vertex buffer is just a list of vertices, to make up the triangles I want to render. I tell OpenGL how to interpret the buffer as follows:

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

However, this program just renders each vertex in grey. What I want to do is to give each vertex its own colour. So, there are two things I need to change which I am unsure of how to do:

  1. I need to add colour information to the vertex buffer. Do I just do this by defining each vertex with 7 elements (3 for position, 4 for colour), rather than just 3? But then how do I tell my vertex shader where to find this colour information? Would it be something like layout (location = 3) in vec4 colour?
  2. I then need to send this colour information to the fragment shader, and then assign this to gl_FragColor. How do I do this?

Upvotes: 0

Views: 1952

Answers (1)

Robinson
Robinson

Reputation: 10122

Here's a simple shader to do just what you want:

layout(location = 0) in vec3 attrib_Position;
layout(location = 1) in vec4 attrib_Colour

out vec4 attrib_Fragment_Colour;

void main()
{
    attrib_Fragment_Colour = attrib_Colour;

    gl_Position = vec4(attrib_Position.xy, 0.0, 1.0);
}

Note that location is more like "slot number" than actual physical offset. So in this case it's 1, not 3. We also define an output from the vertex shader called attrib_Fragment_Colour. This is input to the pixel shader:

in vec4 attrib_Fragment_Colour;

out vec4 Out_Colour;

void main(void)
{
    Out_Colour = attrib_Fragment_Colour;
}

Upvotes: 1

Related Questions