Remembering the past to build the future

" Remembering the past to build the future "

Saturday, 29 March 2014

OpenGL Transformations

In this post I want to show 3D affine trasformations using OpenGL functions like glTranslate(), glRotate() ,glPushMatrix and glPopMatrix(). Here the final result:






You can download the c++ sources from the url: OpenGL Demo Use left mouse button to rotate the scene and middle plus right button for zoom. In the sources you will find some classes:
  • Geometry class allows you  boxes and spheres rendering with different colors
  • Scene class allows you to make a complete scene using Geometry
  • Main class starts the application
You can use Visual C++ Express Edition to build the demo but it's important to have OpenGL well configured in your environment, you can use this url to see how configure OpenGL: OpenGL configuration
Now open the sources and the Scene class. In this class we have several methods, for now we want to focus on draw() method. This method draws the scene and here we find the OpenGL code trasformations:

Geometry geo;

 int colors1[]={ 255,153,51, 0,127,255, 255,153,51, 
        0,127,255, 0,127,255, 0,127,255};
 
 int colors2[]={ 0,127,255, 102,255,0};
 int colors3[]={ 255,0,0, 255,0,0, 255,0,0, 
        255,0,0, 255,0,0, 255,0,0};
 
 int colors4[]={ 0,255,0, 0,255,0};
 int colors5[]={ 255,255,0, 255,255,0};
 
 /*Sphere in (0,1,0) 90 degree rotated around x axes
   Note:First trasformation is the rotation
        Second trasformation is the translation
        So you have to read the trasformations 
        from down to up in your code
  */
 glPushMatrix();
  glTranslatef(0,1,0);//Second
  glRotatef(90,1,0,0);//First
  geo.sphere(1,20,20,colors2);
 glPopMatrix();

 /*Box in (2,0.75,2)*/
 glPushMatrix();
  glTranslatef(2,0.75,2);
  geo.box(1.5,1.5,1.5,colors1);
 glPopMatrix();

 /*Box in (-2,0.75,-2)*/
 glPushMatrix();
  glTranslatef(-2,0.75,-2);
  geo.box(1.5,1.5,1.5,colors3);
 glPopMatrix();

 /*Sphere in (3,1,-3)  90 degree rotated around x axes*/
 glPushMatrix();
  glTranslatef(3,1,-3);
  glRotatef(90,1,0,0);
  geo.sphere(1,20,20,colors4);
 glPopMatrix();
 
 /*Sphere in (-4,1,4)  90 degree rotated around x axes*/
 glPushMatrix();
  glTranslatef(-4,1,4);
  glRotatef(90,1,0,0);
  geo.sphere(1,20,20,colors5);
 glPopMatrix();

 /* */
The glPushMatrix() save the current ModelView matrix, the glPopMatrix() restore the matrix saved. So we have used this methods to save current trasformation matrix before to apply our trasformations for a box or a sphere and then restore the initial trasformation matrix. If you note the code for a sphere, you can see a trasformation composition. The sphere is first rotated and then translated. Use this fragment code to play with trasformations and understand how OpenGL works with them.Well I have finished for now. I hope this post is useful.
Thanks for reading.

My Android Games, much are free