I want to display random colors in the GL_POLYGON.
But the colors changes only on minimize and maximize.It picks a different color on maximization and a different color on minimization.But it randomizes the colors as long as i continue minimizing and maximizing
#include <GL/gl.h>
#include <GL/glut.h>
#include <cstdlib>
void display( void )
{
glClear( GL_COLOR_BUFFER_BIT );
glBegin( GL_POLYGON );
for( int i = 0; i < 255; i++ )
{
glColor3ub( rand(), rand(), rand() );
}
glVertex3f( 0.25, 0.25, 0.0 );
glVertex3f( 0.75, 0.25, 0.0 );
glVertex3f( 0.75, 0.75, 0.0 );
glVertex3f( 0.25, 0.75, 0.0 );
glEnd();
glColor3f( 0.0, 0.0, 0.0 );
glRectf( 0.45, 0.25, 0.55, 0.05 );
glRectf( 0.35, 0.08, 0.65, 0.02 );
glFlush();
}
void init( void )
{
glClearColor( 1.0, 1.0, 1.0, 1.0 );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0, 1.0, 0.0, 1.0, -1.0, 1.0 );
}
int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
glutInitWindowSize( 250, 250 );
glutInitWindowPosition( 100, 100 );
glutCreateWindow( "Assignment" );
init();
glutDisplayFunc( display );
glutMainLoop();
return 0;
}
glutDisplayFunc()
only calls your callback when the OS needs your window re-drawn. If you want more regular calls you need to trigger them yourself via glutPostRedisplay()
:
... When GLUT determines that the normal plane for the window needs to be redisplayed, the display callback for the window is called. ...
...
GLUT determines when the display callback should be triggered based on the window's redisplay state. The redisplay state for a window can be either set explicitly by calling
glutPostRedisplay
or implicitly as the result of window damage reported by the window system. Multiple posted redisplays for a window are coalesced by GLUT to minimize the number of display callbacks called.
I like to use glutTimerFunc()
to call glutPostRedisplay()
periodically:
#include <GL/glut.h>
#include <cstdlib>
void timer( int value )
{
glutPostRedisplay();
glutTimerFunc( 16, timer, 0 );
}
void display()
{
glClearColor( 0.2, 0.2, 0.2, 1 );
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glBegin( GL_POLYGON );
glColor3ub( rand(), rand(), rand() );
glVertex3f( 0.25, 0.25, 0.0 );
glVertex3f( 0.75, 0.25, 0.0 );
glVertex3f( 0.75, 0.75, 0.0 );
glVertex3f( 0.25, 0.75, 0.0 );
glEnd();
glColor3f( 0.0, 0.0, 0.0 );
glRectf( 0.45, 0.25, 0.55, 0.05 );
glRectf( 0.35, 0.08, 0.65, 0.02 );
glutSwapBuffers();
}
int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 250, 250 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}