8. OpenGL Double Buffering




Last time we looked at rotation the cube looked ‘broken’ now it
looked like this because we had a single buffer running. This
means that the program is automatically drawing straight to the
window. To fix this we add a second buffer, by changing the:
glutInitDisplayMode (GLUT_SINGLE);
to:
glutInitDisplayMode (GLUT_DOUBLE);
this is giving the programa buffer to draw what it has to, then transfer
what is acctually needed to the screen.
You may notice that alot of games these days even have a triple
buffer, this is pretty redundant in OpenGL, in fact it doesn’t even exist in OpenGL.

When changing the buffer from Single to Double we also have to
tell the program to swap the buffers, so we acctually see what
is on the second, and not just what we saw before.

To do this, change the line in the ‘display’ function that says:
glFlush();
to:
glutSwapBuffers();

And your done, the cube should be rotating perfectly.

If you have any questions, please email me at swiftless@gmail.com

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
    #include <GL/gl.h>
#include <GL/glut.h>

GLfloat angle = 0.0; //set the angle of rotation

void cube (void) {
    glRotatef(angle, 1.0, 0.0, 0.0); //rotate on the x axis
    glRotatef(angle, 0.0, 1.0, 0.0); //rotate on the y axis
    glRotatef(angle, 0.0, 0.0, 1.0); //rotate on the z axis
    glColor3f(1.0, 0.0, 0.0);
    glutWireCube(2);
}

void display (void) {
    glClearColor (0.0,0.0,0.0,1.0);
    glClear (GL_COLOR_BUFFER_BIT);
    glLoadIdentity();  
    gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    cube();
    glutSwapBuffers();
    angle ++;
}

void reshape (int w, int h) {
    glViewport (0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0)
;
    glMatrixMode (GL_MODELVIEW);
}

int main (int argc, char **argv) {
    glutInit (&argc, argv);
    glutInitDisplayMode (GLUT_DOUBLE); //set up the double 
buffering

    glutInitWindowSize (500, 500);
    glutInitWindowPosition (100, 100);
    glutCreateWindow (“A basic OpenGL Window);
    glutDisplayFunc (display);
    glutIdleFunc (display);
    glutReshapeFunc (reshape);
    glutMainLoop ();
    return 0;
}

Related posts:

  1. 6. OpenGL Cube (Version 2.0)
  2. 36. OpenGL Framebuffers
  3. 10. OpenGL Scaling
  4. 9. OpenGL Blending
  5. 7. OpenGL Rotation and Translation (Version 2.0)

Tags: , , , , ,


9 Responses to "8. OpenGL Double Buffering"

  • oldnewbie says:
  • Dhiraj says:
  • prabhakar says:
  • Mark says:
  • Imrn says:
  • SiUnit says:
  • Khalladay says:
Leave a Comment

Improve the web with Nofollow Reciprocity.