I was working on learning OpenGL and I was tasked with creating the figure below:
This is what my intention was, but the first time I wrote it I buffered the colors as floats from 0 - 255 instead of 0.0 - 1.0. Clearly that was wrong, but this is what was displayed:
Only the center triangle is displayed, only with outlines and the colors are the first three vertex colors. Why did this happen? What does OpenGL do when I buffer colors that aren't in the range [0.0, 1.0]? I couldn't find documentation on this.
My shaders are as follows:
vertex:
layout (location = 0) in vec3 Position;
layout (location = 2) in vec4 vertexColor;
out vec4 vertexColor0;
void main() {
gl_Position = vec4(Position, 1.0f);
vertexColor0 = vertexColor;
}
fragment:
in vec4 vertexColor0;
void main() {
gl_FragColor = vertexColor0;
}
And here's the code I use for buffering data and drawing data:
static const int npoints = 9;
static const glm::vec3 points[npoints] = {
glm::vec3(-0.5, 0.5, 0.0),
glm::vec3(-0.7, 0.0, 0.0),
glm::vec3(-0.3, 0.0, 0.0),
glm::vec3(0.2, 0.0, 0.0),
glm::vec3(-0.2, 0.0, 0.0),
glm::vec3(0.0, -0.5, 0.0),
glm::vec3(0.5, 0.5, 0.0),
glm::vec3(0.3, 0.0, 0.0),
glm::vec3(0.7, 0.0, 0.0)
};
//the incorrect version, in the correct version 255 is replaced with 1.0f and 127 with 0.5f
static const glm::vec4 colors[npoints] = {
glm::vec4(0, 255, 255, 255),
glm::vec4(255, 0, 255, 255),
glm::vec4(255, 255, 0, 255),
glm::vec4(255, 0, 0, 255),
glm::vec4(0, 255, 0, 255),
glm::vec4(0, 0, 255, 255),
glm::vec4(0, 0, 0, 255),
glm::vec4(255, 255, 255, 255),
glm::vec4(127, 127, 127, 255)
};
//Create the VAO and the buffer data
void Figure::initialize() {
glUseProgram(shaderProgram); //shaderProgram is a member set to the built shader above
glGenVertexArrays(1, &vertexArrayObject); //vertexArrayObject is also a member
glBindVertexArray(vertexArrayObject);
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER,
npoints * sizeof(glm::vec3),
points,
GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
GLuint CBO;
glGenBuffers(1, &CBO);
glBindBuffer(GL_ARRAY_BUFFER, CBO);
glBufferData(GL_ARRAY_BUFFER,
npoints * sizeof(glm::vec4),
colors,
GL_STATIC_DRAW);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(2);
}
//draw the figure
void Figure::draw() {
glUseProgram(shaderProgram);
glBindVertexArray(vertexArrayObject);
glDrawArrays(GL_TRIANGLES, 0, npoints);
}