我试图在OpenGL中绘制一个彩色正方形,但我只是看到了一些奇怪的彩色线条。它在我在着色器中手动设置颜色时有效,但在我将其作为属性发送时则无效。
这是我的最小,完整和可验证的例子。
#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
void glfw_framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main()
{
glfwInit();
GLFWwindow *window = glfwCreateWindow(640, 480, "test", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, glfw_framebuffer_size_callback);
glfwSwapInterval(0);
glewExperimental = GL_TRUE;
glewInit();
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLfloat verts[] = {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f};
GLfloat color[] = {
255.0f, 0.0f, 0.0f, 1.0f,
0.0f, 255.0f, 0.0f, 1.0f,
0.0f, 0.0f, 255.0f, 1.0f,
255.0f, 255.0f, 0.0f, 1.0f
};
GLuint verts_vbo;
glGenBuffers(1, &verts_vbo);
glBindBuffer(GL_ARRAY_BUFFER, verts_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
GLuint color_vbo;
glGenBuffers(1, &color_vbo);
glBindBuffer(GL_ARRAY_BUFFER, color_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(color), color, GL_STATIC_DRAW);
const GLchar *v_shader_source =
"#version 330 core\n"
"in vec4 vcoords;"
"in vec4 color;"
"out vec4 frag_color;"
"uniform mat4 model, view, projection;"
"void main() { gl_Position = vcoords;"
"frag_color = color; }";
const GLchar *f_shader_source =
"#version 330 core\n"
"in vec4 frag_color;"
"out vec4 final_color;"
"void main() { final_color = frag_color; }";
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vs, 1, &v_shader_source, NULL);
glShaderSource(fs, 1, &f_shader_source, NULL);
glCompileShader(vs);
glCompileShader(fs);
GLuint shader = glCreateProgram();
glAttachShader(shader, vs);
glAttachShader(shader, fs);
glLinkProgram(shader);
glDeleteShader(vs);
glDeleteShader(fs);
glUseProgram(shader);
GLuint verts_index = glGetAttribLocation(shader, "vcoords");
glEnableVertexAttribArray(verts_index);
glBindBuffer(GL_ARRAY_BUFFER, verts_vbo);
glVertexAttribPointer(verts_index, 2, GL_FLOAT, GL_FALSE, 0, NULL);
GLuint color_index = glGetAttribLocation(shader, "color");
glEnableVertexAttribArray(color_index);
glBindBuffer(GL_ARRAY_BUFFER, color_vbo);
glVertexAttribPointer(color_index, 4, GL_FLOAT, GL_FALSE, 0, NULL);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glfwSwapBuffers(window);
glfwWaitEvents();
}
glDeleteProgram(shader);
return 0;
}
这就是结果:
我做错了什么?
代码仍然太长而无法添加更多文字但我不知道还有什么要说的。