简体   繁体   中英

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)

在此处输入图片说明

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM