Sandundhammika's Blog











{July 12, 2010}   glRotatef

let’s write a simple program to demonstrate the glRotatef function.

here is the documentation from OpenGL SDK.

http://www.opengl.org/sdk/docs/man/xhtml/glRotate.xml

study the source code bellow.Remember that every time that you draw again should need to load the identity matrix into the GL_MODELVIEW matrix stack.There are three matrix stacks that internally maintained by the OpenGL.the glRotatef() function will apply the rotation to the current matrix stack.But we didn’t use the glMatrixMode() to select appropriate matrix stack.So all the changes will be applied to the initial matrix stack which is GL_MODELVIEW.But as a practice try to check what matrix stack that we are going to apply some change to the current matrix mode.


#define GLUT_DISABLE_ATEXIT_HACK ;; this is a dirty hack,but we have to do this.
#include <GL/gl.h>

#include <GL/glut.h>
#include <stdio.h>

/* This variable will keep the state of the rotation information. */
double rotation = 0;

 /* The Display Function */
void display_func()
{

 // clear the buffer
 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
 // load the identity matrix
 glLoadIdentity();
 // do rotation around the vector k/root(3)
 glRotatef(rotation,0,0,1);
 glBegin(GL_LINES);
 // we are drawing a square that spans -0.5,-0.5 to 0.5,0.5
 glVertex3f(-0.5,-0.5,0.0);
 glVertex3f(0.5,-0.5,0.0);

 // right vertical line
 glVertex3f(0.5,-0.5,0.0);
 glVertex3f(0.5,0.5,0.0);

 // the top horizontal line
 glVertex3f(0.5,0.5,0.0);
 glVertex3f(-0.5,0.5,0.0);

 // the left vertical line.
 glVertex3f(-0.5,0.5,0.0);
 glVertex3f(-0.5,-0.5,0.0);
 glEnd();
 glutSwapBuffers();     // at the end,we are swapping the buffers because
 // we enabled the double buffering.

}
/* The keyboard function */
void keyboard_func(unsigned char key ,int x,int y)
{
 if( key == 'q' || key=='Q')    {
 printf("Exit from the OpenGL program.......\n");
 exit(0);

 }

 if ( key == 'a')
 {
 printf("rotation =%f \n",rotation);
 rotation = rotation +1 ;
 if (rotation >360)
 rotation =0;
 glutPostRedisplay();

 }
}

/* The main function of this program */
int main(int argc,char** argv)
{
 // initialize the glut
 glutInit(&argc,argv);
 glutInitWindowPosition(100,100);
 glutInitWindowSize(500,500);
 glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH |GLUT_RGBA);

 // Enable some appropriate modes in the gl
 glEnable(GL_DEPTH_TEST);

 // create the window
 glutCreateWindow("Ch10");
 // set up the display function.
 glutDisplayFunc(display_func);
 // set up the keyboard function
 glutKeyboardFunc(keyboard_func);
 glutMainLoop();

 return 0;
}

–press the ‘a’ key on the keyboard to experience the rotation effect of the rectangle.

Happy Coding.



Leave a comment

et cetera