My OpenGL programming (1) (Introduction, image rendering, 3D observation, and illumination)

Source: Internet
Author: User

This is my second learning of OpenGL. My first learning was in the sophomore computer graphics class. It was just a careless look at OpenGL. Now, after two years, I plan to make a complete and systematic learning of OpenGL for three purposes: 1. familiar with OpenGL programming. 2. Learn more about the entire system of the computer graphics rendering pipeline from the opegl system. make beautiful CG works.

Here is the entire learning notes from the beginning to the end of my learning OpenGL programming guide Fifth Edition. Here, I will give myself a reference and want to share with you. There are many typos. Please forgive me ~~

 

Front: OpenGL is an open industrial standard for drawing 2D/3D images. It is just a standard, so OpenGL managers do not have a so-called SDK, all the sdks that developers can use are compiled by members of the khronos group (OpenGL standard administrator). (members of the SDK can obtain this standard ), for example, OpenGL in Microsoft Visual Studio is compiled by Microsoft Based on opengl1.1.
More features of OpenGL versions are called OpenGL extensions. Different graphics cards support different extension functions in these extensions. Therefore, you must have these extension libraries when using more advanced features, and your video card supports your features.

Glew is a very good extension library, which includes the latest OpenGL core library and a large number of extension libraries, and can automatically identify which extensions are available based on hardware. In addition, NVIDIA will have the latest opengl_sdk_guide, which shows developers The Latest Core libraries and extended libraries supported by their graphics cards in various demo forms, their demos are basically written using glew.

To support later OpenGL versions and new extensions, NVIDIA will also frequently release new hardware drivers to support OpenGL development. NVIDIA's developer websites can be followed at any time.
0. Configure the development environment:
In vs2005, Win32 console programs are generally used, and then <window. h>
1. The general composition of the glut program:
Gluinit
Gluinitdisplaymode
Gluinitwindowposition
Gluinitwindowsize
Glucreatewindow
The window does not appear until you call the glumainloop () function.
Every time the window content needs to be re-painted, it will call gludisplayfunc (void (* func) (void). When you want to force re-paint some content, you can call glupostredisplay (void) send a signal
2 glut's four Time Response Return Functions
Glureshapefunc (void (* func) (int w, int H ))
Glukeyboardfunc (void (* func) (unsigned char key, int X, int y ))
Glumousefunc (void (* func) (INT button, int state, int X, int y ))
Glumotionfunc (void (* func) (int x, int y ))
3. dual cache, one display, and the other prepare to draw the next frame. Now one frame is ready to be drawn and switched to another cache. This is so alternating that no one can see the painting process, only when the results are drawn will the results be seen, there will be no black screen (flash ).
In a program that writes a motion, in addition to using the gluinitdisplaymode (glu_single | glu_rgb) during initialization, The gluswapbuffers () must be added at the end of the function, because after the dual cache is enabled, the program will not automatically swap the cache to be displayed, but will always display a cached content. In this way, when a frame ends, the cache will clear the screen and repaint it, this process is also displayed. Generally, we can see that the program is like a card call, because most of the time this cache is being used for the drawing operation, it is only a moment when the drawing result is displayed, therefore, you need to call gluswapbuffers () to immediately display the results of another cache.
4. Three basic operations for OpenGL: clearing the window, drawing a geometric object, and drawing a raster object)
Clearing the window: Why clear first, because the data in the cache is usually retained last time and should be cleared
The graphic hardware has many caches. The cache to be cleared is in the brackets behind glclear, and there are four types of cache: Color buffer depth buffer accumulation buffer stencel buffer.
Glclear (gl_color_buffer_bit | gl_depth_buffer_bit );
Ratio
Glclear (gl_color_buffer_bit );
Glclear (gl_depth_buffer_bit) is faster
The basic primitive for drawing: the point-to-line triangle quadrilateral polygon, in addition to a special point glrect function to draw a rectangle (on the advanced point GPU, using a vector as a parameter makes it better to set a vertex than using four locations as a parameter)
 
Draw the dotted line: first set the type of gllinestipple (1, 0x3f07), and then enable the dotted line switch (gl_line_stipple). In this way, all the other draw line statements will be painted with dotted lines.
Polygon;
Glpolygonmode (glenum face, glenum mode) is used to set the fill style and linearity of the polygon outside and inside.
Inside and outside of a multilateral row, the area in the clockwise direction of the vertex is outside (visible) by default, and the other is inside, glfrontface (glenum mode) can be used) which is the outer direction of the hour hand. When a polygon is used to form a space.
Glcullface can be used to delete an external or a side. For example, you can never see a side. You need to enable the delete switch here.
Stippling polygons, you can use a bitmap data Filling Method to draw a polygon, as long as the first gl_polygon_stipple switch on, then glpolygonstipple () load the bitmap data, then the polygon drawn is filled with the bitmap.
Add:
Glflush () ensures that all the preceding draw commands are forcibly executed, and the painting is not executed immediately due to some optimizations or other reasons during the priority period, call this function to make sure that it is drawn immediately.
Glfinish () is also forced to draw, but unlike glflush, the process is temporarily blocked after it is called until the painting is complete. For example, after some user interactions, your keyboard and mouse input will respond normally.
Draw a polygon. Only simple convex polygon can be drawn.

1 gledgeflag (glboolean flag); to specify a property of the following vertex. If it is false, This vertex will not lead to draw a line. The default value is true, this function is used to draw polygon that do not require the shape of internal lines or are not convex.
2. Set the sending vector of a vertex: glnormal3fv (N0); glvertex3fv (v0 );
Gl_normalize (gl_normalize) is usually used to turn on the automatic normalization trigger vector (making it a unit vector) in some less common geometric operations (such as multiplying a matrix. by default, OpenGL does not automatically unit this vector During computation.
4. array data,
Glarrayelemernt
When drawing a graph with a large number of vertices, vectors, and colors, you can define the array data to reduce code,
Static glint vertices [] = {25, 25,
100,325,
175, 25,
175,325,
250, 25,
325,325 };
Glableclientstate (gl_vertex_array); Enable vertex Array
Glvertexpointer (2, gl_int, 4 * sizeof (glint), vertices); // specify the structure. The two elements in the table are a group, and the first four are selected;
Glinterleavedarrays (gl_c3f_v3f, 0, intertwined)

Then use
Glbegin (gl_triangles );
Glarrayelement (2) to access the third element.
Glend ()
In addition, other arrays such as vectors can be defined at the same time, and can be called at the same time when the above sentence is called.
Gldrawelements
Used to draw a group
Static glubyte allindices = {4, 5, 6, 7, 1, 2, 6, 5,
0, 1, 5, 4, 0, 3, 2, 1,
0, 4, 7, 3, 2, 3, 7, 6 };

Gldrawelements (gl_quads, 24, gl_unsigned_byte, allindices); draw a square with 24 points (that is, draw 6)
This function cannot be used between glbegin and glend.

Gldrawarrays (glenum mode, glint first, glsizei count );
Use the number between first and first + count-1 as the value to draw the mode (A ry)

5. status Management and query. Most statuses are disabled by default to achieve high root rendering speeds. Void glable (glenum cap) and void gldisable (glenum cap) are used to enable or disable status management and query,
To query the current status, you can use glisenabled (glenum capability) to query the shutdown of a status, or use a more powerful void glgetbooleanv (glenum pname, glboolean * Params );
Void glgetintegerv (glenum pname, glint * Params );
Void glgetfloatv (glenum pname, glfloat * Params );
Void glgetdoublev( glenum pname, gldouble * Params );
Void glgetpointerv (glenum pname, glvoid ** Params); these can query all the data (such as the current color );
6. Transformation Matrix
Viewing and modeling Transformations-convert an object coordinate system to a horizon coordinate system (for example, the coordinate of a vertex P of an object in its own coordinate system is (, 1 ), after the translated model matrix is changed to (1, 2, 1), and the person is in the four or five degrees of observation in front of the source oblique, So multiply by the view matrix to transform to the human's horizon coordinate system, after the point is changed, the point is taken as the origin point by the human eye, and the coordinate system with the observation direction as the Z negative direction is not (, 1), but changed,
Projection Matrix-in your horizon coordinate system, divide XYZ by W to normalize and determine the projection form, perspective transform or orthogonal transformation
Viewport transformation-converts three-dimensional location information to the location of a two-dimensional screen

In glloadidentity () and OpenGL, all conversions multiply the conversion matrix by the current matrix, and then the results are pseudo-current matrix. Therefore, you may need to call this function to clear the current matrix before performing some transformations.
Gllookat glscale (rotate...) <modelview matrix>
Glfrustum <projection matrix> and so on
Glloadmatrix * () loads a specified matrix as a pseudo current Matrix
In OpenGL, the matrix is stored in the form that a 16-element ancestor can be defined to represent this matrix;

Perspective Projection is used to generate the real world, and orthogonal projection is used to generate situations that require strict consideration of the real size.

In OpenGL, A modelview matrix and a projection matrix exist at the same time. When you want to change the projection matrix, use glmatrixmode (gl_projection) to switch and multiply. After switching, when you call glfrustum again, you multiply the value on the projection matrix without changing the modelview matrix.
Generally, modelview and other transformations are written in the drawing function. The view transformation statement must always be written before the model transformation, the projection and viewport transformations are written in the reshape function (because the projection and viewport changes with the window size)
The order of multiplication of the transformation matrix. The order of occurrence of the matrix is opposite to that of the actual transformation order. For example, the Code for first rotation and then translation should be
Glloadidentity ();
Glmultmatrixf (t);/* translation */
Glmultmatrixf (r);/* rotation */
Draw_the_object ()
If the glscale parameter is a negative value, it indicates the opposite direction. If you want to create an image on the xz plane, as long as the glscale (1.-1.1), glscale will reduce the performance.
Two Perspective Projection functions: gluperspective glfrustum
The aspect ratio of the viewport must be the same as that of the projection.
Glpushmatrix () glpopmatrix (): Write the conversion code in the middle. You can reset the Matrix to push after the end, but the matrix stack of OpenGL is limited, you can use glgetintegerv (gl_max_modelview_stack_depth, glint * Params ). queries the number of matrices currently available
7. Custom cropping plane: In addition to using glperspective to crop four boundaries, you can also customize any plane to crop the visible cone. You can define the size of 6 planes, use glclipplane to define and crop the cropping surface. Enable and enable the interface with glenable later.
8. inversion matrix transformation, that is, converting two-dimensional information from the screen to 3D space when modeling an object, is equivalent to reversing the entire rendering pipeline, using gluunproject (gldouble winx, gldouble winy, gldouble WINZ, const gldouble modelmatrix [16], const gldouble projmatrix [16], const glint viewport [4], gldouble * objx, gldouble * objy, gldouble * objz) Function
Among them, WINZ refers to the depth cache. The default value is 0-1. From the 0-1 Depth cache, a line corresponding to the modeling space of the object will be taken out, and each matrix in the rendering pipeline process will also be formulated.
Gluproject () is the opposite of it, imitating the normal geometric rendering pipeline to obtain three-dimensional corresponding two-dimensional data
9. The color cache is composed of Bit Planes. Each bit plane provides storage for pixels. Several planes store several bits.
Dithering creates more colors that are not supported by hardware with a reasonable board layout. In addition, when dual-cache is used, because the bit plane is reduced by half, it may be used sometimes. Enable it with gl_dither.

You can use the uchar type (0-255) with glcolor3ub when specifying the color)

When the color index table mode is used, set the screen color to glclearindex (), and set the color to glindex (). Set the color table with the help of glusetcolor ()

Use glshademodel to set the color rendering model. Only gl_smooth and gl_flat. Smooth are default values.
10. Steps for using light in OpenGL:
Define its normal vectors for each fixed point (the default normal vectors have been defined for such functions as the glusolidsphere)
I create a light source (use gllight () to set various properties of the light source, position/attribute/participate in various types of light color, by default, the ambient light is 0.0.0, indicating that the light is not contributed to the ambient light. The first light source has a reflected light of 1.1.1, and the rest are white light)
Ii. Create a illumination model (the distance between a person and an object is considered infinite by default. In this way, the line between a person and an object is not considered as the angle between the line between the person and the object, but only the light outside the object is considered as calculated by default)
The function that defines the caring model is gllightmodel, which has three parameters:
Gl_light_model_ambient, which is used to define a basic ambient light. This ambient light is not the ambient light contributed by any actual light source.
Gl_light_model_local_viewer (gl_ture or Fale) is used to define whether the viewpoint is infinitely far from the object. That is to say, if it is true, the angle of the light source is not considered at each vertex, and each vertex is the same, if it is incorrect, it is more realistic. The default value is infinitely far.
Gl_light_model_two_side defines whether two-sided illumination is enabled.
III define the surface illumination material of an object (glmaterialfv () is used to define attributes of various reflections)
Glmaterialfv (gl_front, gl_emission, mat_emission) can define a simulated light source.
Note: After glmaterialfv is set, this attribute will always affect the status of all subsequent drawn objects.
A Method to simplify the setting of lighting material attributes. It is used in combination with glcolormaterial () and glcolor.
After glcolormaterial () and enable the glable (gl_color_material) switch, each time glcolor is changed, the color defined in glcolormaterial () is changed.
You also need to use gl_lighting to enable the Care Function and use gl_light0 to open the corresponding light source.
The name of the light source is gl_light0, gl_light1, gl_light2, gl_light3...
11. light source type. OpenGL consists of a direction light source (the sun, only the direction and no position) and a position light source (only the position). When the gl_position parameter is specified, if the matrix W is 0, it is the direction light source, XYZ represents the direction, if W is not zero, it is the location light source, XYZ is the second Location Coordinate

The light intensity attenuation can be set for the position light source (imitating natural light), and the parameters for its attenuation can be set with gllightf (gl_light0, gl_constant_attenuation, 2.0 );
Gllightf (gl_light0, gl_linear_attenuation, 1.0 );
Gllightf (gl_light0, gl_quadratic_attenuation, 0.5 );
Because the actual light intensity is X, the default KC is 1, and the remaining is 0;

All position light sources can be shot into a spotlight. gllightf (gl_light0, gl_spot_cutoff, 45.0) is used to define the angle. gllightfv (gl_light0, gl_spot_direction, spot_direction) is used to define the direction.

The position of the light source is also affected by the modelview matrix, so sometimes the pop push stack is used.

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.