0

I have a sphere drawn on the screen. When I press a button I want the sphere to slowly move to the right. I am trying to accomplish this with

for (int i = 0;i<10;i++)
{
sphere.moveToRight(0.1);
glutPostRedisplay();
sleep(1000);
}

But instead of animated, it waits a few seconds and then draws the sphere in the final location. I assume it is because sleep is stopping the glutPostRediplay(). Any ideas of how to accomplish this basic annimation?

James
  • 2,951
  • 8
  • 41
  • 55

1 Answers1

2

You are using glutPostRedisplay wrong.

Check out: http://www.opengl.org/resources/libraries/glut/spec3/node20.html

glutPostRedisplay marks the normal plane of current window as needing to be redisplayed. glutPostWindowRedisplay works the specified window as needing to be redisplayed. After either call, the next iteration through glutMainLoop, the window's display callback will be called to redisplay the window's normal plane. Multiple calls to glutPostRedisplay before the next display callback opportunity generates only a single redisplay callback. glutPostRedisplay may be called within a window's display or overlay display callback to re-mark that window for redisplay.

Which means, after 10 seconds your image will get refreshed once.

KoKuToru
  • 4,055
  • 2
  • 20
  • 21
  • Perfect explanation! glutSwapBuffers still didnt do the trick, however I used to explanation and now I am just calling display(). It is working now – James Dec 12 '11 at 19:06
  • Sure it only works with double buffered rendering... `glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)` When you have `GLUT_DOUBLE` set, `glutSwapBuffers` should work. – KoKuToru Dec 12 '11 at 19:10
  • @KoKuToru: glutSwapBuffers should not be called in a inner loop, but only at the end of the rendering to make the rendered picture visible. The proper way to animate things in a GLUT programm is to take a timing beween calls of the display function and issue a glutPostRedisplay in the GLUT idle function (or just use glutPostRedisplay as idle itself). – datenwolf Dec 12 '11 at 20:52
  • @datenwolf haven't wrote with glut for years. I thought `glutSwapBuffers` is the same as `glXSwapBuffers` – KoKuToru Dec 12 '11 at 21:01
  • @KoKuToru: Indeed it is the same. But GLUT expects display to return eventually (preferrably right after glutSwapBuffers has been called) so that input events can be processed. After all pending events have been processed the idle function is called. Just keeping the display function in a loop with swapping buffers at the end will play some animation, but it will prevent the program from processing events. – datenwolf Dec 12 '11 at 21:52