Tuesday, June 28, 2011

Model Transformation in OpenGL

If you are new to transformations and OpenGl concepts then I would like you to run though my previous artile listed here
The following are the OpenGL functions for Model transformations:
glRotate()
glScale()
glTranslate()

It will be helpful if you understand Matrices/Vectors and basic Trignometry along the 4 Quadrants around a circle.
For our use here we will use an Identity Matrix.

In mathematical terms if we were to represent this following transformation then
glTranslatef( 4.0, 2.0, 0.0 );
glRotatef( 90.0, 0.0, 0.0, 1.0 );
glVertex3f( 1.0, 2.0, 3.0 );

would be represented as(1st Quad rule applied)
|1 0 0 4.0| |Cos90 -Sin90 0 0| |1.0|      |x|
|0 1 0 2.0| |Sin90 Cos90 0 0| |2.0|   = |y|
|0 0 0 0.0| |0 0 1 0| |3.0|      |z|
|0 0 0 0 | |0 0 0 1| |1.0|      |y| Transformed vertex



The most important thing to remember about Model transformation is that it effects the co-ordinate system.As a result all models appear to be transformed because they are drawn relative to the new co-ordinates.
Also the current co-ordinate system is represented by the current matrix.

The final position or layout of the object will depend on the order the functions are called and there by the co-ordinate system is re-aligned.

Example 1: Let us see how a cube/rectangle will render itself if we were to follow the transformation given in the order below.

1. glPushMatrix() : this will create a new matrix of co-ordinates as the original axes layout and any further changes/transformation will happen to the new Matrix on the stack while the original Matrix is saved.




2. glTranslatef( 4.0, 2.0, 0.0 )
: This moves the co-ordinate system origin to the new location





3. glScalef( 1.0, 0.5, 1.0 ) : The co-ordinate system for y-axis is scaled down by half




4. glRotatef( 45.0, 0.0, 0.0, 1.0 ) : Rotates the co-ordinate system 45 degrees around the z-axis



5. Any custom function to draw a rectangle will result in the model being drawn wrt to the new matrix co-ordinate system.



6. glPopMatrix() : After drawing we want to reset our co-ordinate system to the original layout



If you visualize(as shown above), any model drawn is transformed according to the co-ordinate system layout changes.

No comments:

Post a Comment