Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why glClear doesn't clear my screen?

Tags:

c

opengl

Here is a simple opengl program by me. I'm trying to clear the screen before I draw a triangle. I've called glClear() in my init() function, however, it seemed that it failed to clear the screen.

#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

void myIdleFunc()
{
    glBegin(GL_TRIANGLES);
    {
        glColor3f(1.0f, 1.0f, 1.0f);
        glVertex2f(0.0f, 1.0f);
        glVertex2f(-1.0f, -1.0f);
        glVertex2f(1.0f, -1.0f);
    }
    glEnd();

    glFlush();

    usleep(1000000);
}

void init()
{
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glFlush();
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutCreateWindow("Hello, World!");

    init();

    glutIdleFunc(myIdleFunc);
    glutMainLoop();
    return 1;
}

Here is a screen-shot, the text is from the gnome terminal in the back ground.

enter image description here

like image 257
xzhu Avatar asked May 22 '11 03:05

xzhu


2 Answers

Where's your display callback? You shouldn't use the idle function for drawing.

All drawing needs to take place in the appropriate callbacks, the GL context might not be active until glutMainLoop starts running, and with no active context, your commands simply get ignored (without a context, there might not even be a place to store errors for retrieval with glGetError).

NOTE: Usually you want to clear the buffer at the beginning of every frame. You might get away with clearing just once with single-buffering, but double-buffering is better and requires you to somehow render the entire area between each swap.

like image 160
Ben Voigt Avatar answered Sep 30 '22 15:09

Ben Voigt


Your problem is, that you do clear the screen in your initialization code. But you need to clear it every frame, so right at the start of your display (or in your case idle) function.

like image 36
Christian Rau Avatar answered Sep 30 '22 15:09

Christian Rau