Reference Video Basics of Computer Graphics – Implementation of OpenGL_bilibili_bilibiliT
Graphics drawing
Point
GL_POINTS
#define FREEGLUT_STATIC // Define a static library for calling functions #include <GL/freeglut.h> // Include the header file void myPoints() { //show three points in screen glClear(GL_COLOR_BUFFER_BIT); glPointSize(3); glBegin(GL_POINTS); //show what to draw,here we draw points glColor3f(1.0, 0.0, 0.0); //color:red glVertex2i(-3, 3);//coordinate glColor3f(0.0, 1.0, 0.0); //color:green glVertex2i(10, 20);//coordinate glColor3f(0.0, 0.0, 1.0); //color:blue glVertex2i(0, -15);//coordinate glEnd(); glFlush(); //Push the drawing buffer to the screen } void init() { glClearColor(1.0, 1.0, 1.0, 1.0); //black background glMatrixMode(GL_PROJECTION); glLoadIdentity; gluOrtho2D(-100, 100, -100, 100); //The range that can be displayed } int main(int argc, char* argv[]) { glutInit( & argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(200, 300); //Position on the screen glutInitWindowSize(300, 300); glutCreateWindow("Display Points"); init(); glutDisplayFunc(myPoints); //Callback function glutMainLoop(); return 0; }
result:
?
Note: Change the color every time (nonsense). If you don’t change it, it will always be the same color.
glFlush() is important! It’s about pushing pictures to the screen!
Line segment
GL_LINES
Two by two pairing connection
void lines() { int p1[] = { 6,4 }; int p2[] = { 1,1 }; int p3[] = { 3,7 }; int p4[] = { 5,1 }; int p5[] = { 0,4 }; glClear(GL_COLOR_BUFFER_BIT);//clear glColor3f(0.3, 0.1, 0.8); glPointSize(3); glBegin(GL_LINES); //This and the following changes are here glVertex2iv(p1); glVertex2iv(p2); glVertex2iv(p3); glVertex2iv(p4); glVertex2iv(p5); //Draw two line segments because P5 does not match glEnd(); glFlush(); }
?
GL_LINE
?
GL_LINE_LOOP
?
Polygon POLYGON
GL_POLYGON
void polygonTraingle() { int p1[] = { 1,3 }; int p2[] = { 3,0 }; int p3[] = { 6,0 }; int p4[] = { 7,3 }; int p5[] = { 6,6 }; int p6[] = { 3,6 }; glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.6, 0.5, 0.2); glPointSize(3); glBegin(GL_POLYGON); //point first glVertex2iv(p1); glVertex2iv(p2); glVertex2iv(p3); glVertex2iv(p4); glVertex2iv(p5); glVertex2iv(p6); glEnd(); glFlush(); }
result
?
GL_TRIANGLES
?
GL_QUADS
?
Keyboard and mouse interaction
Keyboard
glutKeyboardFunc()
Here we focus on glutkeyboardfuc() in mykeyboard and mian.
#define FREEGLUT_STATIC // Define a static library for calling functions #include <GL/freeglut.h> // Include the header file int xd=0, yd = 0; void myDisplay() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.8,0.5,0.6); glPointSize(5); glBegin(GL_POLYGON); glVertex2i(10 + xd,10 + yd); glVertex2i(20 + xd,10 + yd); glVertex2i(20 + xd,0 + yd); glVertex2i(10 + xd,0 + yd); glEnd(); glFlush(); } void myKeyBoard(unsigned char key, int x, int y) { switch (key) { case 'w':yd + + ; break; case 's':yd--; break; case 'a':xd--; break; case 'd':xd + + ; break; } glutPostRedisplay(); //Requires the contents of the window to be redrawn } void init() { glClearColor(1.0, 1.0, 1.0, 1.0); //black background glMatrixMode(GL_PROJECTION); glLoadIdentity; gluOrtho2D(-20, 30, -20, 30); //The range that can be displayed } void main(int argc, char* argv[]) { glutInit( & argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(300, 100); //Position on the screen glutInitWindowSize(600, 500); glutCreateWindow("Key interaction"); init(); glutDisplayFunc(myDisplay); //Callback function glutKeyboardFunc(myKeyBoard); glutMainLoop(); }
Effect
?
The cute pink square tuotuo will move up, down, left and right with your wasd keys
Mouse
glutMouseFunc
Focus on the mouseMotion function
#define FREEGLUT_STATIC // Define a static library for calling functions #include <GL/freeglut.h> // Include the header file GLint xd=0, yd = 0; //GLint is mainly used to process integer data in OpenGL and is used to configure and represent various parameters and information related to graphics rendering. GLint w = 600, h = 500; void myDisplay() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.8, 0.5, 0.6); glPointSize(5); glBegin(GL_POLYGON); glVertex2i(10 + xd, 10 + yd); glVertex2i(20 + xd, 10 + yd); glVertex2i(20 + xd, 0 + yd); glVertex2i(10 + xd, 0 + yd); glEnd(); glFlush(); } void mouseMotion(GLint button,GLint state, GLint x,GLint y) { //Mouse button, whether the mouse is pressed or bounced, x, y if (button == GLUT_LEFT_BUTTON & amp; & amp; state == GLUT_DOWN) { //Left mouse button and press xd = x; yd = h-y; glutPostRedisplay(); } } void init() { glClearColor(1.0, 1.0, 1.0, 1.0); //black background glMatrixMode(GL_PROJECTION); glLoadIdentity; gluOrtho2D(0, w, 0, h); //The range that can be displayed } void main(int argc, char* argv[]) { glutInit( & argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(300, 100); //Position on the screen glutInitWindowSize(w, h); glutCreateWindow("Mouse Motion"); init(); glutDisplayFunc(myDisplay); //Callback function glutMouseFunc(mouseMotion); glutMainLoop(); }
result
?
The cute pink square tuotuo will move with your mouse
Graphic transformation
Pan
x = x + tx
y = y + ty
This is quite simple so I won’t write more.
Rotate
x,y
Rotate around the origin θ
x’ = xcosθ – ysinθ
y’ = xsinθ + ycosθ
Rotate θ around xr yr
x’ = xr + (x-xr)cosθ – (y-yr)sinθ
y’ = yr + (x-xr)sinθ + (y-yr)cosθ
Zoom
x’ = x*Sx
y’ = y*Sy
glPushMatrix()
glPushMatrix()
is a function in OpenGL, which is used to push the current Model-View Matrix onto the stack and save a copy of the current matrix. This function is typically used in conjunction with glPopMatrix()
.
The main purpose of glPushMatrix()
is to save the current transformation state, allowing you to modify the transformation in subsequent drawing operations, and then use glPopMatrix()
to restore the previous transformation state. This is useful for applying different transforms between different objects or when drawing nested objects.
Animation
glTimerFunc()
It is a function used to register a timer callback function to perform an action within a specified interval. This function is usually used to implement animations, periodic updates, or other tasks that need to be triggered regularly in OpenGL applications.
Here is its basic syntax:
void glutTimerFunc(unsigned int millis, void (*callback)(int value), int value);
millis
: Indicates how many milliseconds the timer callback function should be executed.callback
: is a function pointer used to specify the callback function to be executed when the timer fires.value
: is an integer value that can be passed to the callback function, usually used to identify different timers.
Texture map
-
glTexImage2D()
:- Use: Defines the image as a texture.
- Parameters: Specify the type of texture (2D, cube mapped, etc.), levels (different levels of detail used for texture mapping), color format, etc.
- Remember to glEnable(GL_TEXTURE_2D) before using
-
glTexParameter*()
:- Function: Specifies the filtering and packaging method of textures.
- Parameters: Includes
GL_TEXTURE_MIN_FILTER
andGL_TEXTURE_MAG_FILTER
, which are used to set the texture’s minification and amplification filters respectively, andGL_TEXTURE_WRAP_S
andGL_TEXTURE_WRAP_T
, used to set the wrapping method of texture coordinates.
-
glTexEnv{fi}[v]()
:- Action: Specifies how the texture is used, such as modulating, blending, or mapping.
- Parameters: Includes
GL_TEXTURE_ENV_MODE
, which defines the texture’s grading mode.
-
glTexCoord{1234}{sifd}{v}()
:- Use: Specify texture coordinates.
- Parameters: Set the s, t, r, q components of texture coordinates, usually used to specify the position of texture coordinates.
-
glTexGen{ifd}[v]()
:- Function: Texture coordinates are automatically generated by OpenGL.
- Parameters: Specify the coordinates and generation method of generating texture coordinates.
-
glHint()
:- Use: Define perspective correction prompts.
- Parameters: Specifies hints for perspective correction, affecting OpenGL’s accuracy and speed tradeoff when generating perspective textures.
-
glBindTexture()
:- Use: Bind a named texture to the texture target.
- Parameters: Specify the target texture and the texture object to be bound.
- glHnit()
- Function: used as a prompt when rendering
Parameters: The target
parameter specifies the target to set the prompt, and themode
parameter specifies the prompt mode to be set.
glTexImage2D()
glTexImage2D(target, level, components, w, h, border, format, type, texels);
Is an OpenGL function used to specify a two-dimensional texture image. The following is the parameter description of this function:
-
target
: Specifies the type of texture, which can be one of the following:GL_TEXTURE_1D
: One-dimensional textureGL_TEXTURE_2D
: two-dimensional textureGL_TEXTURE_3D
: three-dimensional textureGL_TEXTURE_CUBE_MAP_POSITIVE_X
toGL_TEXTURE_CUBE_MAP_NEGATIVE_Z
: six sides of the cube map- etc.
-
level
: Specifies the texture’s level of detail. Level 0 is the most detailed level, with progressively higher levels indicating lower-resolution versions. -
components
: Specifies the number of color components of the texture, which can be one of the following:GL_RED
: red componentGL_GREEN
: green componentGL_BLUE
: blue componentGL_ALPHA
: transparency componentGL_RGB
: RGB colorGL_RGBA
: RGBA color
-
w
andh
: Specify the width and height of the texture image. -
border
: Specifies the width of the border, usually set to 0. -
format
: Specify the format oftexels
data, for example:GL_RED
GL_RG
GL_RGB
GL_RGBA
-
type
: Specify the data type oftexels
data, for example:GL_UNSIGNED_BYTE
: 8-bit unsigned integerGL_UNSIGNED_SHORT
: 16-bit unsigned integerGL_FLOAT
: 32-bit floating point number
-
texels
: Specifies the data of the texture image, which is a pointer to the stored texture data.
glTexParameteri()
1. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
2. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1This function call is used to set the magnification filter of the two-dimensional texture object. The following is a description of each parameter of this function call:
-
GL_TEXTURE_2D
: Specifies that the target texture is a two-dimensional texture. This is a texture target, indicating that subsequent operations will affect the texture object bound toGL_TEXTURE_2D
. -
GL_TEXTURE_MAG_FILTER
: The filter specified in the setting is a magnification filter for the texture. -
GL_NEAREST
: Specifies the use of nearest neighbor interpolation method for texture amplification filtering. Nearest neighbor interpolation selects the color of the texel closest to the sample point.
glTexXCoord() — glVertex()
Sets the two-dimensional texture coordinates and accepts two parameters s
and t
, which represent the horizontal (usually called s coordinate) and vertical (usually called t) texture coordinates respectively. coordinates) component. These coordinates are usually in the range [0, 1] and represent relative positions on the texture.
glvertex is where it is mapped
Display
OpenGL transformation and projection matrices
glViewport()
Function for setting the viewport. The viewport is a rectangular area that determines the position and size of the final image rendered by OpenGL on the screen.
void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);
x
andy
: Specify the coordinates of the lower left corner of the viewport in the window.width
andheight
: Specify the width and height of the viewport.
The glViewport()
function is usually called during the initialization process of OpenGL and is used to set the initial size and position of the viewport. It defines which part of the window will be covered by the final image rendered by OpenGL.
glMatrixMode()
- Function: Select the current matrix mode.
- Parameters:
mode
can be one ofGL_MODELVIEW
,GL_PROJECTION
orGL_TEXTURE
, respectively Represents a model view matrix, projection matrix, or texture matrix. - Example:
glMatrixMode(GL_MODELVIEW);
Selects the model view matrix.
glLoadIdentity()
- Function: Reset the currently selected matrix to the identity matrix.
- Example:
glLoadIdentity();
Resets the currently selected matrix to the identity matrix, usually called before starting a new drawing operation.
gluOrtho2D()
- Function: Set the two-dimensional orthogonal projection matrix.
- Parameters:
left
,right
,bottom
,top
respectively define the clipping space Left, right, bottom, top borders. - Example:
gluOrtho2D(0, windowWidth, 0, windowHeight);
Set an orthographic projection with the upper left corner at (0, 0) and the lower right corner at (windowWidth, windowHeight) matrix.
glOrtho()
- Function: Set the three-dimensional orthogonal projection matrix.
- Parameters:
left
,right
,bottom
,top
,near
,far
respectively define the positions of the left, right, bottom, top, near clipping plane and far clipping plane of the clipping space. - Example:
glOrtho(-1, 1, -1, 1, 0.1, 100);
Sets an orthogonal projection matrix between the near and far clipping planes .
gluPerspective()
- Function: Set the perspective projection matrix.
- Parameters:
fovy
is the vertical field of view angle,aspect
is the aspect ratio,zNear
andzFar
code> are the distances between the near clipping plane and the far clipping plane respectively. - Example:
gluPerspective(45, windowWidth / windowHeight, 0.1, 100);
Set a perspective projection matrix, the vertical field of view angle is 45 degrees, and the aspect ratio is the window aspect ratio .
glFrustum()
- Use: Sets a perspective projection matrix for asymmetry.
- Parameters:
left
,right
,bottom
,top
,near
,far
respectively define the positions of the left, right, bottom, top, near clipping plane and far clipping plane of the clipping space. - Example:
glFrustum(-1, 1, -1, 1, 1, 100);
Sets an asymmetric perspective projection matrix between the near and far clipping planes .
Remove hidden surface
Place it in the main function
glutInitDisplayMode()
Specifies some properties and characteristics of the graphics window, such as color mode, buffer properties, etc. It is necessary to call this function before creating the GLUT window.
Place it in the initialization function
glEnable(GL_DEPTH_TEST)
- Use: Enables depth testing.
- Explanation: Depth testing is a technique used to resolve object occlusion relationships. When depth testing is enabled, OpenGL will consider the depth value when drawing each pixel, and only the pixel with the smallest depth value will be drawn. This ensures that near objects obscure far objects.
glClear(GL_COLOR_BUFFER_BIT |GL_DEPTH_BUFFER_BIT)
- Use: Clear the color buffer and depth buffer.
- Explanation: Before each frame of rendering starts, it is usually necessary to clear the color buffer and depth buffer to ensure that previously rendered images will not affect the rendering of the current frame.
GL_COLOR_BUFFER_BIT
means clearing the color buffer, andGL_DEPTH_BUFFER_BIT
means clearing the depth buffer. This operation will cause the entire window’s render target to go blank.
backface removal backside removal
glEnable(GL_CULL_FACE);
- Use: Enables backface culling of polygons.
- Explanation: Backface culling is an optimization technology that detects the normal vector direction of polygons and eliminates invisible back faces, thereby improving rendering efficiency. When enabled, OpenGL will not draw polygons that are considered back faces.
glCullFace(GLenum);
- Function: Set the direction of polygons to be culled during back surface culling.
- Parameters:
mode
can be one ofGL_FRONT
,GL_BACK
orGL_FRONT_AND_BACK
, respectively It means to remove the front, remove the back or remove both the front and the back. - Explanation: This function defines which side of the polygon should be culled. Typically, you’ll choose to cull the side that won’t be seen by the observer to improve performance. For example, if backface culling is enabled and
glCullFace(GL_BACK)
is set, only polygons facing away from the viewer will be culled.
depth buffer function
glClear(GL_DEPTH_BUFFER_BIT);
- Use: Clear the depth buffer.
- Explanation: This function is used to clear the depth buffer before rendering a new frame.
GL_DEPTH_BUFFER_BIT
means clearing the depth buffer. This is to ensure that the depth information is clean when rendering the next frame.
glEnable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
Enable/disable depth testing
glClearDepth(maxDepth);
- Function: Set the clearing value of the depth buffer.
- Parameters:
maxDepth
is a floating point number that represents the depth value when the depth buffer is cleared. The default is 1.0. - Explanation: This function can be used to set the initial value of the depth buffer. When testing for depth, depth values usually range from 0.0 (near clipping plane) to 1.0 (far clipping plane).
glClearDepth(maxDepth)
can be used to set the depth value used when clearing the depth buffer, ensuring that the depth value is within this range.
Adjust the clipping plane
glDepthRange(nearNormDepth, farNormDepth);
glDepthFunc(testCondition);
glPolygonMode()
Color
glClearColor()
void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
This function is used to set the color when clearing the color buffer
glClear()
Function to clear the color buffer
glFlush()
/ glutSwapBuffers()
Display the image to the screen. This ensures that the background color is the cleared color at the beginning of each frame.