[英]opengl cube won't render
我正在尝试在OpenGL上绘制一个立方体。
当我编译并运行此代码时,只看到一个黑色的窗口。 我的代码的哪一部分会导致此问题? 感谢您的帮助,因为我是opengl的新手,这是我的源文件:
#include <GL/glew.h>
#include <GL/glfw.h>
#include <iostream>
#include <cmath>
void drawCube() {
//vertices of the triangle
GLfloat vertices[] = {
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f
};
//colors of the triangle
GLfloat colors[] = {
0.410f, 0.481f, 0.675f,
0.177f, 0.823f, 0.970f,
0.604f, 0.516f, 0.611f,
0.676f, 0.779f, 0.331f,
0.179f, 0.275f, 0.338f,
0.041f, 0.616f, 0.984f,
0.799f, 0.315f, 0.460f,
0.945f, 0.719f, 0.295f
};
static float alpha = 0;
//attempt to rotate cube
glRotatef(alpha, 0, 1, 0);
/* We have a color array and a vertex array */
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3, GL_FLOAT, 0, colors);
/* Send data : 24 vertices */
glDrawArrays(GL_TRIANGLES, 0, 24);
/* Cleanup states */
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
alpha += 1;
};
int main() {
if (!glfwInit()) {
std::cerr << "Unable to initialize OpenGL!\n";
return -1;
}
if (!glfwOpenWindow(1024, 768, //width and height of the screen
8, 8, 8, 0, //Red, Green, Blue and Alpha bits
0, 0, //Depth and Stencil bits
GLFW_WINDOW)) {
std::cerr << "Unable to create OpenGL window.\n";
glfwTerminate();
return -1;
}
glfwSetWindowTitle("GLFW Simple Example");
// Ensure we can capture the escape key being pressed below
glfwEnable(GLFW_STICKY_KEYS);
do {
GLint width, height;
// Get window size (may be different than the requested size)
//we do this every frame to accommodate window resizing.
glfwGetWindowSize(&width, &height);
glViewport(0, 0, width, height);
glEnable(GL_DEPTH_TEST); // Depth Testing
glDepthFunc(GL_LEQUAL);
glDisable(GL_CULL_FACE);
glCullFace(GL_BACK);
glfwSwapInterval(1);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW_MATRIX);
glTranslatef(0, 0, -5);
gluPerspective(60, (double)width / (double)height, 0.1, 100);
drawCube();
//VERY IMPORTANT: displays the buffer to the screen
glfwSwapBuffers();
} while (glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS &&
glfwGetWindowParam(GLFW_OPENED));
glfwTerminate();
return 0;
}
问题在于您不使用透视投影,因此基本上可以在正交视图中看到立方体的一个面。
要使用透视图,可以使用gluPerspective
:
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
gluPerspective(60, (double)width / (double)height, 0.1, 100); // Set up perspective matrix.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.