Search code examples
copenglglut

OpenGL/glut background polygons appear to overlap foreground plygons


I am new to OpenGL, and I am having trouble displaying a simple cube on my screen. The problem is that sides of the cube that should be hidden in the background still appear. I feel that the answer should be that I have to enable GL_DEPTH_TEST, but this causes the screen to display a complete white canvas with nothing on it. Here's a sample from a run I have done:

example

Each side is just a random color.

Here is a snippet of my code:

glutInit(&argc, argv);
glutInitWindowSize(600, 400);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);


glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(50.0, 1.5, 1.0f, 100.0);
gluLookAt(10.0, 5.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
//glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_MODELVIEW);

glClearColor(1.0, 1.0, 1.0, 1.0);  /* white */

I have commented out glEnable(GL_DEPTH_TEST) for now.

What else should I be doing so that there is no overlapping on this cube?

Thank you for any help!


Solution

  • Enable GL_DEPTH_TEST, and clear the depth buffer before rendering with glClear(GL_DEPTH_BUFFER_BIT);. This can be combined with glClear(GL_COLOR_BUFFER_BIT); if you're using that, as glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);