Basic OpenGL knowledge

Source: Internet
Author: User

OpenGL is a large state machine. We implement scene rendering by changing its State.

1. Basic matrix transformation:

Model Transformation: Models in mobile and transform scenarios;

Projection Transformation: Crop and distort the visual space;

View Angle conversion: scales the final output.

Matrix Transformation

Through the first three chapters, we learned how to use OpenGL to draw basic elements in 3D space and form a model using elements. However, after drawing an object or scene, we always want to observe the object from multiple angles or walk around in the scene. At this time, we need another function of OpenGL: transformation.

OpenGL provides us with many types and transformations. You can transform the projection method or the object/model. You can change your position and direction, or the object size and angle. Learn more about this chapter:

Types of OpenGL Transformations

Describe a transformation using a Matrix

Basic Transformation

Define and use your own Transformations

4.1 transformation in OpenGL

Transform (Transform) allows objects in 3D space to be projected onto a 2D plane. With transformations, you can move, rotate, scale, or even bend an object. However, the transformation does not directly modify vertex data. Instead, the transformation modifies the coordinate system. If you rotate a coordinate system, and then draw in the coordinate system after the rotation, the drawn image is like being rotated. In the Basic OpenGL rendering process, the following transformations are performed:

View Transformation: used to specify the position and direction of the observer;

Model View Transformation: Models in mobile and transform scenarios;

Projection Transformation: Crop and distort the visual space;

View area Transformation: scales the final output.

4.1.1 view Transformation

In a scenario, we want to change the observer's position and observation angle. It is used to change the orientation and angle of the observer, that is, view transformation. By default (when no transformation is performed), the observer is at (0, 0, 0) and the line of sight is in the-z direction. That is to say, drawing can only be observed at the position of z <0.

4.1.2 Model View Transformation

This transform is used to move and rotate objects in a scenario. Using Model View transformation can replace view transformation. The principle is very simple: for example, if you want to use the view transformation to move the observer to the-Z axis by 10 units, all the objects in the scene are moved to the + z axis by 10 units. This is exactly the same as moving all objects in the scenario to 10 units in the + z direction using the model view transformation.

4.1.3 Projection Transformation

To project a 3D scene to a 2D plane, you must perform a projection transformation. There are two forms of Projection Transformation: Parallel Projection Transformation and Perspective Projection Transformation. Parallel projection and Perspective Projection have been introduced in section 3rd. We will not repeat them here. Now, we need to emphasize that projection is also a kind of transformation. To implement projection, it is essentially a special transformation of all objects in the scene so that they can be painted on a plane. For example, the perspective projection transformation will scale and distort all objects in the scene according to the distance, so that they look three-dimensional.

4.1.4 view zone transformation

Here we go back to the theme in Chapter 2. The view area transformation is to scale and crop the projected 2D image so that it can be correctly displayed in the window. You can go back to Chapter 2 to learn the concept of the view area.

4.2 Matrix

Matrix is so powerful that almost all transformations can be expressed by matrices. A matrix is an array consisting of n rows of M columns (m, n ≥ 1 ). Various transformations can be used through matrix multiplication. In OpenGL, a matrix with a size of 4x4 is used.

The matrix calculation rules and specific mathematical content have little to do with the OpenGL topic (OpenGL does not need to know how the matrix is operated, Because OpenGL will help you complete everything ), so we will not introduce it here. However, this does not mean that these mathematical knowledge is not important. Using matrices flexibly, we can create many transformations not provided by OpenGL and increase the computing speed. For more information, see linear algebra.

During OpenGL transformation, the vertex is first converted to a matrix of 1 × 4 (rows 1-3 store the x, y, and z coordinates of the vertex, and rows 1 and 3 respectively store the W coordinates, that is, the scaling factor, usually 1.0), and multiply the point by the model view transformation matrix, projection matrix, and view area transformation matrix ...... finally, the 2D screen coordinates displayed on the screen are obtained to complete the transformation. Fortunately, you don't need any mathematical foundation, even if you have no idea about the Matrix, you can complete this process smoothly. Because OpenGL has encapsulated advanced functions, you can complete all the basic transformations without having to write the matrix yourself. These basic functions will be introduced later.

4.3 basic transformation

For each transformation, OpenGL has its own functions used to generate the transformation matrices and apply them. The following is a one-to-one introduction.

4.3.1 model transformation matrix

This is the most important part of this chapter. With model transformation, you can rotate and move an object and produce the effect of moving the observer. This is the topic of this chapter. To complete our example, we define the following function to draw a sphere at the origin. The following function involves the content of the quadratic surface. This is another advanced topic of OpenGL. We will explain it in future chapters. Now we only use it to draw a sphere:

Procedure drawsphere (r: single); // R indicates the sphere radius

VaR spobj: gluquadricobj;

Begin

Spobj: = glunewquadric;

Gluquadricnormals (spobj, glu_smooth );

Gluquadricorientation (spobj, glu_outside );

Glusphere (spobj, R, 50, 50 );

Gludeletequadric (spobj );

End;

4.3.1.1 Translation

When drawsphere is called, a sphere is drawn at the origin. Now we want to draw this sphere on the point (, 0), we must translate 10 units of the coordinate system along the + y direction before drawing. So we will write this Code:

// Create a matrix that translates 10 units in the coordinate system along the + y direction:

....

// Multiply the current model view matrix by the matrix:

...

Drawsphere (5); // draw a sphere with a radius of 5

But in fact, we don't need to be so troublesome. OpenGL provides us with such a function:

Gltranslatef (x, y, z: single );

X, Y, and Z indicate the translation amount on the X, Y, and Z axes respectively. After this function is called, OpenGL automatically generates a translation matrix and then applies this matrix. Therefore, we can write the code as follows:

Gltranslatef (0, 10, 0 );

Drawsphere (5 );

In this way, you can draw a sphere on (0, 10, 0.

4.3.1.2 Rotation

Similar to translation, OpenGL also provides an advanced function for us to rotate objects:

Glrotatef (angle, x, y, z: single );

This function will generate and apply a matrix that rotates angle angles in the coordinate system using the vector (x, y, z) as the axis. If we want to rotate a sphere to 50 degrees on the Y axis, we can call:

Glrotatef (50, 0, 1, 0 );

Drawsphere (5 );

4.3.1.3 Scaling

In fact, the scaling transformation expands the X, Y, and Z axes of the coordinate system according to different scaling factors to achieve the scaling effect. Function

Glscalef (x, y, z: single );

Scale the X, Y, and Z axes of the coordinate system to x, y, and z. For example:

Glscalef (2, 2 );

Drawsphere (5 );

A sphere with a radius of 10 is drawn.

4.3.1.4 superposition of transformations

When using transform, we should note that the transformation is superimposed on the basis of the previous transformation. That is to say, the effect of the transformation will accumulate. Each time a transform function is called, a new function is generated to multiply the current model view matrix. Then, the new matrix becomes the current model transformation matrix. When the next transformation is executed, will be multiplied by the new matrix, so the effect will continue to accumulate. For example, we can clearly illustrate this point.

For example, if you want to draw a sphere on (4.3, 0) and draw another sphere on (, 0, 0), you can get the image shown in-1:

Figure 4.3-1
You may write the following code:

// Pan up to 10 units along the Y axis

Gltranslatef (0, 10, 0 );

// Draw the first sphere

Drawsphere (5 );

// Translate 10 units to the left along the X axis

Gltranslatef (10, 0, 0 );

// Draw the second sphere

Drawsphere (5 );

However, you should not forget that the effect of transformation is cumulative. When drawing the second sphere, since the coordinate system has moved 10 units to the Y axis, and then moved 10 units to the X direction, the origin of the new coordinate system should be the point (10, 10) in the absolute coordinate system ). Therefore, the above program will plot the image shown in 4.3-2.

Figure 4.3-2
You may call gltranslatef (0,-10, 0) before drawing the second sphere; move the coordinate system back to 10 units. However, this will reduce the readability of the code and add additional operations to the CPU. In this case, we can use the unit matrix.

We can call glloadidentity (); the function resets the transformation matrix of the current Model View to the initial state, and then creates a new drawing:

Procedure renderscene ();

Begin

Glmatrixmode (gl_modelview );

// Pan up to 10 units along the Y axis

Gltranslatef (0, 10, 0 );

// Draw the first sphere

Drawsphere (5 );

// Load the Unit Matrix

Glloadidentity;

// Pan up to 10 units along the X axis

Gltranslatef (10, 0, 0 );

// Draw the second sphere

Drawsphere (5 );

End;

See the first line of code. The glmatrixmode function is called here. This function notifies OpenGL that we will operate the Model View transformation matrix. That is, you need to transform the model view. The available parameters of glmatrixmode are as follows:

Gl_projection: used to modify the Projection Matrix

Gl_modelview: used to modify the Model View Transformation Matrix

4.3.1.5 matrix Stack

It is also troublesome to restore the current matrix to the unit matrix before each transformation. More often, we want to save the current matrix. After performing some transformations, we can restore the current matrix to the state we saved last time.

OpenGL provides us with a "Matrix stack" to meet our requirements. We can press the current matrix into the stack, execute some transformations, and then pop up the matrix just pushed in, so as to restore the current matrix to the status before the last transformation. We call

Glpushmatrix ();

Press the current matrix into the matrix stack and call

Glpopmatrix ();

The matrix is displayed. We can also call

Glget (gl_max_modelview_stack_depth );

Glget (gl_max_projection_stack_depth );

To obtain the maximum stack depth of the model view matrix stack and projection matrix stack. Generally (on Windows), the maximum stack depth of the model view is 32, while that of the projection stack is 2.

Using the matrix stack, the program in section 4.3.1.4 can be rewritten:

Procedure renderscene ();

Begin

Glmatrixmode (gl_modelview );

// Push into the matrix Stack

Glpushmatrix;

// Pan up to 10 units along the Y axis

Gltranslatef (0, 10, 0 );

// Draw the first sphere

Drawsphere (5 );

// Restore to the last saved status

Glpopmatrix;

// Translate 10 units to the left along the X axis

Gltranslatef (10, 0, 0 );

// Draw the second sphere

Drawsphere (5 );

End;

4.3.2 Projection Matrix

The projection matrix is usually set before OpenGL drawing and Model View transformation. Normally, we call

Glmatrixmode (gl_projection );

Set the current matrix to a projection matrix. Call again

Glortho or gluperspective to create parallel or perspective projection. Call

Glmatrixmode (gl_modelview );

Set the current transformation matrix to the model view transformation matrix.

So far, you should be able to understand the significance of the setview process in the sample program in the previous chapter. Let's take another look at the setview process:

Procedure tfrmmain. setview;

Begin

Glclearcolor (,); // sets the background color to black.

Glviewport (, clientwidth, clientheight); // specify OpenGL for plotting in this area.

Glmatrixmode (gl_projection); // sets the view projection transformation matrix.

Glloadidentity; // load the unit matrix.

Glortho (0, clientwidth, clientheight,-1); // create a parallel projection.

Glmatrixmode (gl_modelview); // you can convert a matrix object to a model view.

End;

4.4 define and use your own Transformations

In addition to the several advanced transformation functions provided by OpenGL, we can also create a matrix by ourselves and multiply the current matrix to perform special transformations. You can create a 4 × 4 two-dimensional array to describe a matrix. For example:

M: array [1 .. 4] of array [1 .. 4] of single;

M [J, I] indicates the row J of matrix m and the data in column I.

You can also create a one-dimensional array:

M: array [1 .. 16] of single;

Both a two-dimensional array and a one-dimensional array are saved in the column priority order.

After the matrix is defined, call

Glloadmatrix (m );

You can use matrix m to replace the current matrix and call

Glmultmatrix (m );

Multiply the current matrix by M.

It should be noted that the speed of using glloadmatrix or glmultmatrix is faster than that of OpenGL's advanced transformation function. Therefore, do not use glloadmatrix or glmultmatrix if it is not a transformation that cannot be completed by an advanced transform function.

4.5 sample program

This is a classic sample program. It demonstrates the relationship between the Earth and the Sun in the Solar System: The moon grao the earth, the whole Earth and the moon grao the sun, and all the planets rotate. This example shows the nature of matrix transformation and the role of matrix stack. In order to increase the visual effect, the program adds light rendering. At the same time, we also added texture maps to view the rotation of the planet. For more information about illumination and texture pasters, see the following sections.

The code for the rendering process is as follows:

Procedure tfrmmain. renderscene;

Begin

Glable (gl_cull_face );

Glclear (gl_color_buffer_bit or gl_depth_buffer_bit );

Glloadidentity;

Gltranslatef (110 );

Glrotatef (ydeg, 0, 0 );

Glrotatef (xdeg, 1, 0, 1 );

Renderlights; // illumination Processing

// Draw the sun

Glcolor3ub (255,100, 64 );

Glpushmatrix;

Glrotate (sunselfang, 0, 0 );

Drawsphere (10 );

Glpopmatrix;

Glpushmatrix; // push to the current Matrix

// Plot the geographic and month System

Glrotatef (earthcommonang, 0, 0 );

Gltranslatef (50, 0, 0 );

Glpushmatrix; // draws the earth

Glrotatef (earthselfang, 0, 0 );

Glcolor3ub (20, 50, 255 );

Drawsphere (5 );

Glpopmatrix;

Glpushmatrix; // draw the moon

Glcolor3ub (200,200,200 );

Glrotatef (moonang, 0, 0 );

Gltranslatef (10, 0, 0 );

Glrotatef (moonselfang, 0, 0 );

Drawsphere (2 );

Glpopmatrix;

Glpopmatrix; // the pop-up matrix.

Swapbuffers (wglgetcurrentdc );

End;

2. OpenGL is divided into three materials: ambient light, diffuse light, and mirror light.

Set ambient light intensity:

Glfloat lightambient [] = {0.5f, 0.5f, 0.5f, 1.0f };

Assign ambient light properties to the gl_light1 light source:

Gllightfv (gl_light1, gl_ambient, lightambient );

Set the position for the light source gl_light1:

Gllightfv (gl_light1, gl_position, lightposition );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.