| |
How to Pop and Push Matrices with the OpenGL API
Back to OpenGL Tutorial Index
In OpenGl, when you call a command, it then effects everything
created afterwards. Often this leads to unwanted problems, such
as extra colours added to objects, or transformations in wrong
directions.
To fix this we can set starting and ending points for commands
that we call, so that it only effects the items within this set
point.
To set a starting point, all you need to call is:
glPushMatrix();
Then to set an ending point, call
glPopMatrix();
You will see inside the cube1 function:
This calls the start of the current transformation
glPushMatrix();
Here I am setting the colour of the current cube to red
glColor3f(1, 0, 0);
Here I am translating the cube right 1 unit
glTranslatef(1, 0, 0);
Now I am rotating it according to angle
glRotatef(angle, 1, 1, 1);
Then I am drawing the cube
glutWireCube(2);
And finally I am ending the current set of commands
glPopMatrix();
Then you can see with cube2, I have set it up with its own
colour, translation and rotation.
If you have any queries, feel free to email me at swiftless@gmail.com
#include <GL/gl.h>
#include <GL/glut.h>
GLfloat angle = 0.0; //angle for cube1
GLfloat tangle = 0.0; //angle for cube2
void cube (void) {
glPushMatrix(); //set where to start the current object transformations
glColor3f(1.0, 0.0, 0.0); //change cube1 to red
glTranslatef(1, 0, 0); //move cube1 to the right
glRotatef(angle, 1.0, 0.0, 0.0);
glRotatef(angle, 0.0, 1.0, 0.0);
glRotatef(angle, 0.0, 0.0, 1.0);
glutWireCube(2);
glPopMatrix(); //end the current object transformations
}
void cube2 (void) {
glPushMatrix(); //set where to start the current object transformations
glColor3f(0.0, 1.0, 0.0); //change cube2 to green
glTranslatef(-1, 0, 0); //move cube2 to the left
glRotatef(tangle, 1.0, 0.0, 0.0);
glRotatef(tangle, 0.0, 1.0, 0.0);
glRotatef(tangle, 0.0, 0.0, 1.0);
glutWireCube(2);
glPopMatrix(); //end the current object transformations
}
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();
cube2();
glutSwapBuffers();
angle+= 1.0;
tangle+= 2.0;
}
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);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("A basic OpenGL Window");
glutDisplayFunc (display);
glutIdleFunc (display);
glutReshapeFunc (reshape);
glutMainLoop ();
return 0;
}
Download C++ Source Code for this Tutorial
Download Visual Basic Source Code for this Tutorial |
 |