Wednesday, June 29, 2011

Pushing and Poppin'

In OpenGL when you apply any type of transformation or apply any type of texture or property, it is applied globally to everything else below it.

So if I were to do this:

for(int i = 0; i < 5; i++)
{
     glColor3f(1.0,0.0,0.0) ;
     glTranslatef(i*3,0.0,0.0);
     glutSolidTetrahedron (); // TETRAHEDRONS!!
}

We would expect to see 5 evenly spaced tetrahedrons(think pyramids) right? Of course since I'm asking you would expect its wrong, so I know you wouldn't whip out your visa and bet with me.

See the translation is applied to the entire world and it persists. Therefore instead of this:

^   ^   ^   ^   ^

You end up with this

^   ^      ^         ^            ^

How do we solve this? Simple you push and then pop before you make the translation! By pushing into a sort of matrix buffer you tell the compiler : Only apply the changes to things inside this matrix, nothing else. So if you do this instead:

for(int i = 0; i < 5; i++)
{

     glColor3f(1.0,0.0,0.0) ;
glPushMatrix();

     glTranslatef(i*3,0.0,0.0);
     glutSolidTetrahedron (); // TETRAHEDRONS!!
glPopMatrix();
}

and with that you will get the expected result.

3 comments:

  1. Im gonna be honest,I have no idea what any of this means :P

    ReplyDelete
  2. nice tip man! Had a test about OpenGL a few days ago.
    Will follow your blog

    ReplyDelete