PDA

View Full Version : How to pass the color data to vertex shader(GLSL)



sc20184
06-13-2017, 12:04 AM
For example, I'd like to draw two triangles, here are their vertex data:


GLfloat vertices[NumVertices][2] = {
{-0.90, -0.90},
{ 0.85, -0.90},
{-0.90, 0.85},
{ 0.90, -0.85},
{ 0.90, 0.90},
{-0.85, 0.90},
};

GLfloat colors[NumVertices][3] = {
{1.0,0.0,0.0},
{1.0,0.0,0.0},
{1.0,0.0,0.0},
{1.0,0.0,0.0},
{1.0,0.0,0.0},
{1.0,0.0,0.0},
};


I used the following code to pass the data to vertex shader:


glGenVertexArrays(NumVAOs,VAOs);
glBindVertexArray(VAOs[Triangles]);
glGenBuffers(NumBuffers,Buffers);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vert ices,GL_DYNAMIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0,0);
glEnableVertexAttribArray(0);


glGenVertexArrays(1,ColorObj);
glBindVertexArray(ColorObj[0]);
glGenBuffers(1,ColorBuf);
glBindBuffer(GL_ARRAY_BUFFER,ColorBuf[0]);
glBufferData(GL_ARRAY_BUFFER,sizeof(colors),colors ,GL_DYNAMIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0,0);
glEnableVertexAttribArray(1);


and the GLSL code of shaders are:


#version 330
layout(location = 0) in vec4 vPosition;
layout(location = 1) in vec3 vColor11;
out vec3 vColorOut;
void main()
{
gl_Position = vPosition;
vColorOut = vColor11;
}


#version 330
in vec3 vColorOut;
out vec3 fColor;
void main()
{
fColor = vColorOut;
}


However, the program is failed of drawing triangles. But, if I use the static color data (like using: vColorOut = vec3(1.0,0.0,0.0)), there are two red triangles can be shown correctly.

Am I wrong in using "glVertexAttribPointer"?

Silence
06-13-2017, 01:06 AM
https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glEnableVertexAttribArray.xhtml

sc20184
06-13-2017, 06:32 AM
https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glEnableVertexAttribArray.xhtml

Thanks for your reply. Could you give me more detail, because I did write the code of glEnableVertexAttribArray(0); and glEnableVertexAttribArray(1);

larryl
06-13-2017, 01:54 PM
I'm very much a newbie like you.

I'd recommend this (https://learnopengl.com/#!Getting-started/Shaders) series of tutorials. They're well regarded in this forum.

The particular lesson in the link addresses your question.

Your code examples demonstrate several gaps in your understanding of OpenGL. I suggest you start at the first lesson. In an hour or two you'll understand what you need to do.