gambit20088
gambit20088

Reputation: 321

OpenGL - getting a weird results working with a fragment shader

I created a very simple 2D star shape that i want to paint in red. I created 2 VBOs for it and one VAO. One VBO is for the star's vertices and one is for the color values i wish to pass to the shader.

Here is how i created the color data: (let's say i'm interested in red)

struct CArray {
    static const GLuint numColor = 1;
    glm::vec4 color[numColor];
    CArray() {
        color[0] = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);
    }
};

CArray starColor;

This is my buffer binding process:

  glEnableVertexAttribArray(12);
  glGenBuffers(1, &g_bufferObject3);
  glBindBuffer(GL_ARRAY_BUFFER, g_bufferObject3);
  glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4), starColor.color, GL_STATIC_DRAW);
  glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, 0, 0);

This is my vertex shader:

layout (location=0) in vec4 position;
layout(location=12) in vec4 color;

out vec4 colorVertFrag; 

uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;

void main() {
  gl_Position = ProjectionMatrix * ModelViewMatrix * position;
  colorVertFrag = color;
}

This is my fragment shader:

in vec4 colorVertFrag;
out vec4 color;

void main() {
  color = colorVertFrag;
}

And here is the result i get: (ignore the dots that form the star's eyes, nose and smile, they're supposed to be black)

enter image description here

As you can see, instead of getting a solid red color, i'm getting some sort of a weird black-red gradient. If i put the following line in my vertex shader:

colorVertFrag = vec4(1.0, 0.0, 0.0, 1.0);

The star comes out perfectly red.

What could be the problem? Thanks!

Upvotes: 1

Views: 104

Answers (1)

Wagner Patriota
Wagner Patriota

Reputation: 5674

the line

glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4), starColor.color, GL_STATIC_DRAW);

should be

glBufferData(GL_ARRAY_BUFFER, numberOfElements * sizeof(glm::vec4), starColor.color, GL_STATIC_DRAW);

where numberOfElements is supposed to be number of vertices you have. You must send 1 color per vertex.

Upvotes: 2

Related Questions