adamtheguy762
adamtheguy762

Reputation: 3

I am struggling to understand and something in shaders

I am watching thechernoproject tutorials on youtube for opengl and in the writing a shader in opengl episode he defines where the start of the position attribute is in the shader using the line:

layout(location = 0) in vec4 positions;

but my question is, why does he need to do this because surely when he previously used glVertexAttribPointer like this:

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

So here he specifies how to read the buffer including the first position attribute index so why does he need to also specify it in the shader like he has above?

You can see all this code at 23:22 in the video: https://www.youtube.com/watch?v=71BLZwRGUJE&index=7&list=PLlrATfBNZ98foTJPJ_Ev03o2oq3-GGOS2

Upvotes: 0

Views: 88

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473407

So here he specifies how to read the buffer including the first position attribute index so why does he need to also specify it in the shader like he has above?

Specify what in the shader, exactly? That the value is a 4-element vector? Well, there's no requirement that the corresponding type specified by the shader attribute is the exact same as that provided by the VAO. You can pass integers which can get converted to floats via normalization or just "casting". And so forth.

As you can see from your example, the number of components specified in the shader doesn't even have to match the number provided by the array. Your array sends 2 components for this attribute, but the shader takes 4. And that's fine; the last two values in the corresponding attribute will be 0 and 1.

Are you talking about that the name position maps to attribute 0? Well, how else is the system going to know that the array elements read from attribute 0 go into a variable named position. 0 means nothing to the system except an index; without the layout(location part, the system couldn't tell where to send the data read from the array.

Lastly and most importantly of all... glVertexAttribPointer modifies the vertex array object, not the shader. So how is the linked program supposed to know any of this stuff if its stored in some other object? How would you write to multiply the position from the array by a matrix if you don't assign some name in the shader to it?

No, every piece of information in that shader needs to be there. It is not redundant.

Upvotes: 4

Related Questions