Reputation: 1482
I have read a code which rotates a cube like this (only the key part):
static GLfloat theta[] = {0.0,0.0,0.0};
static GLint axis = 2;
void display(void)
{
/* display callback, clear frame buffer and z buffer,
rotate cube and draw, swap buffers */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
colorcube();
glFlush();
glutSwapBuffers();
}
void spinCube()
{
/* Idle callback, spin cube 2 degrees about selected axis */
theta[axis] += 2.0;
if( theta[axis] > 360.0 ) theta[axis] -= 360.0;
/* display(); */
glutPostRedisplay();
}
void mouse(int btn, int state, int x, int y)
{
/* mouse callback, selects an axis about which to rotate */
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;
if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;
if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;
}
It keeps a variable theta
outside the display
function to trace the
change of the angle. And every time it just redefines the transformation
matrix then it just looks like the new transformation was based on the
last one.
However, this is just the case for only rotation. When both rotation and translation are considered. I find it hard to use a similar method which keeps some variables outside to track transformations and redefines the matrix every time, since rotation and translation are not interchangeable
One of my ideas is to use glPushMatrix
and glPopMatrix
. But I wonder
whether this is the standard way to deal with such a thing.
Can you please help? Thank you.
Upvotes: 1
Views: 285
Reputation: 2001
Yes it's the standard method to go about when you want to change your Model-View Matrix, that's what glPushMatrix()
and glPopMatrix()
do, saves your current model-view matrix on the matrix stack.
Let's say you have a second object, a sphere, which has different changes for it's coordinates, sake of argument just a translation by -5 on the OX axis.
If you try:
//for spehere
glTranslatef(-5.0f,0.0f,0.0f):
drawSphere();
//for cube
glTranslatef(-1.0f,0.0f,0.0f)
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
drawCube();
You will be actually translating your cube by -6.0 on the Ox axis instead of -5.0.
To fix this you just need to use glPushMatrix(), glPopMatrix()
.
//for spehere
glPushMatrix();
glTranslatef(-5.0f,0.0f,0.0f):
drawSphere();
glPopMatrix();
//for cube
glPushMatrix();
glTranslatef(-1.0f,0.0f,0.0f)
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
drawCube();
glPopMatrix();
This way you save your original Model-View matrix so you can apply the correct transformations for each object.
Upvotes: 1