问题
I wrote a small program to display a simple triangle using vertex buffer. For the windowing i'm using glfw, my environment is Mac 10.9, XCode 5.
The window appears black but the triangle isn't paint.
Here the code:
#include <GLFW/glfw3.h>
#include <OpenGL/gl.h>
#include <iostream>
int main(int argc, const char * argv[])
{
GLFWwindow* window;
if (!glfwInit())
{
return -1;
}
glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(640, 480, "Hello Triangle", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
GLfloat verts[] =
{
0.0f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f
};
//Generate a buffer id
GLuint vboID;
//Create a buffer on GPU memory
glGenBuffers(1, &vboID);
//Bind an arraybuffer to the ID
glBindBuffer(GL_ARRAY_BUFFER, vboID);
// Fill that buffer with the client vertex
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
//Enable attributes
glEnableVertexAttribArray(0);
// Setup a pointer to the attributes
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
while (!glfwWindowShouldClose(window))
{
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwPollEvents();
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
回答1:
You're choosing the OpenGL Core Profile for your rendering:
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
Your code is missing a number of things to be Core Profile compliant:
- You need to implement shader programs. The Core Profile does not support the old fixed pipeline anymore, and requires you to implement your own shaders in GLSL. Explaining how to do this in detail is beyond the scope of an answer, but you will be using calls like
glCreateProgram
,glCreateShader
,glShaderSource
,glCompileShader
,glAttachShader
,glLinkProgram
. You should be able to find material online and in books. - You need to use Vertex Array Objects (VAO). Look up
glGenVertexArrays
andglBindVertexArray
.
来源:https://stackoverflow.com/questions/24797999/simple-triangle-using-opengl-and-glfw