OpenGL experiment one drawing simple graph

Keywords: Windows Programming less

OpenGL Experiment 1

OpenGL (English: Open Graphics Library) is a cross language, cross platform application programming interface (API) for rendering 2D, 3D vector graphics. This interface consists of nearly 350 different function calls, which are used to draw from simple graphics bits to complex 3D scenes. Another program interface system is Direct3D on Microsoft Windows only. OpenGL is commonly used in CAD, virtual reality, scientific visualization programs and video game development.
Development environment: win10, VS-2015

1, Preparation in advance

1.1 installation VS2015

1.2 create project directory and copy GLIB to project directory


The documents in GLIB are as follows:



2, Create project

2.1 creating a command line program

Open vs and click file - > New - > Project
Open the dialog box to select: template - > VC + ± > Win32 - > Win32 console application
Click OK to enter the command line program Wizard

2.2 Win32 Application Wizard

Click next to open the application settings
Application type: select console application
Additional options: None
Click Finish to generate the project

2.3 specifying the OpenGL header file path

2.4 add OpenGL static library and dynamic library


2.5 include header file: in main.cpp, add and overwrite main function:

2.6 Click: vs - > generate - > regenerate the solution. If the compilation is successful, it indicates that the compilation connection configuration is correct

2.7 debugging run click F5 to run the program successfully

3, Draw a 2D drawing

3.1 rewrite main.cpp

// exp_1.cpp: defines the entry point for the console application.
//
#include "stdafx.h"
#include<windows.h>
#define GLUT_DISABLE_ATEXIT_HACK
#include "GL/glut.h"
void myDisplay();
void myInit();
int main(int argc,char **argv)
{
	glutInit(&argc, argv);   //Initialize GLUT function callings
	//Set window size (width,height)in number of pixels
	glutInitWindowSize(400, 400);
	//Set window position,form the left and top of the screen
	glutInitWindowPosition(200, 100);//in numbers of pixels
	//Specify a window creation event
	glutCreateWindow("Green Triangle");
	//Specify the drawing function that is called when the window is created or re-drew
	glutDisplayFunc(myDisplay);   
	myInit();  //Invoke this function for initialization
	glutMainLoop();  //Enter the event processing loop
	return 0; //Indicate normal termination
}
void myDisplay() {
	
	glClear(GL_COLOR_BUFFER_BIT); //Clear the frame buffer
	glColor3f(0.0, 1.0, 0.0);  //Set current color to green
	glBegin(GL_POLYGON);   //Draw the triangle
	glVertex2f(-0.7, -0.7);
	glVertex2f(0.7, -0.7);
	glVertex2f(0, 0.7);
	glEnd();
	glFlush();   //Force to display the new drawings immediately
}
void myInit() {
	
	glClearColor(0.0, 0.0, 0.0, 0.0);  //Set the clear color to black
	//Specify the boundaries of the view window
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();//Restore initial coordinates
	gluOrtho2D(-1.0, 1.0, -1.0, 1.0);  //Specify world window
	glMatrixMode(GL_MODELVIEW);
}

3.2 compile and run

4, Drawing 3D graphics

4.1 rewrite main.cpp

#include "stdafx.h"
#include <windows.h>   //Header File For Windows
#include <GL\GL.h>     //Header File For The OpenGL32 Library
#include <GL\GLU.h>     //Header File For The GLu32 Library	
#include <GL\GLAUX.H>   //Header File For the Glaux Library
#define GLUT_DISABLE_ATEXIT_HACK
#include "GL\GLUT.H"
GLfloat rtri;   //Angle For The Triangle (NEW)
GLfloat rquad;  //Angle for the Quad (NEW)
void InitGL(int width, int height);
GLvoid DrawGLScene(GLvoid);
void myReshape(int w, int h);
void myKeyboard(int key, int x, int y);
void myMovedMouse(int x, int y);
int main(int argc, char **argv) {
	glutInit(&argc, argv);   //Intialize GLUT function callings
	glutInitWindowSize(800, 600); //Set widow size (width,height)in number of pixels
	//Set window positio, from the left and top of the screen,
	glutInitWindowPosition(200, 100);  //in numbers of pixels
	//Specify a window creation event
	glutCreateWindow("3D Graph");
	//Specify the drawing function that is called when the window
	glutDisplayFunc(DrawGLScene);
	glutReshapeFunc(myReshape);
	glutMotionFunc(myMovedMouse);
	glutSpecialFunc(myKeyboard); //New keyboard response
	InitGL(800, 600);   //Invoke this function for initialization
	glutMainLoop();     // Enter the event processing loop
	  
	return 0;           //Indicate normal termination
}
void InitGL(int width, int height) {
	myReshape(width, height);
	glShadeModel(GL_SMOOTH);   //Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f); //BlackBackground
	glClearDepth(1.0f);
	//Depth Buffer Setup
	glEnable(GL_DEPTH_TEST); //Enables Depth Testing
	glDepthFunc(GL_LEQUAL);  //The Type of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  //Really Nice Perspective Calculations
}
void myReshape(int width, int height) {
	if (height == 0)
		//Prevent A Divide By Zero By
	{
		height = 1;
		//Making Height Equal One
	}
	glViewport(0, 0, width, height);    //Reset the Cuurent Viewport
	glMatrixMode(GL_PROJECTION); //Select the Projection Matrix
	glLoadIdentity();            //Resetthe Projection Matrix
	//Calculate the Aspect Ratio of the window
	gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
	glMatrixMode(GL_MODELVIEW);        //Select The Modelview Matrix
	glLoadIdentity();                  //Reset the Modelview Matrix
}
GLvoid DrawGLScene(GLvoid)
//Here's where we do all the drawing
{
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);    //Clear Screen And Depth Buffer
	glLoadIdentity(); //Reset The cuurent Modelview Matrix
	glTranslatef(-1.5f, 0.0f, -6.0f); //Move Left 1.5 Units And Into The Screen 6.0
	glRotatef(rtri, 0.0f, 1.0f, 0.0f); //Rotate The Triangle On the Y axis(NEW)
	glBegin(GL_TRIANGLES);          //Start Drawing A Triangle
	glColor3f(1.0f, 0.0f, 0.0f);    //Red
	glVertex3f(0.0f, 1.0f, 0.0f);   //Top of Triangle (Front)
	glColor3f(0.0f, 1.0, 0.0f);     //Green
    glVertex3f(-1.0f, -1.0f, 1.0f); //Left of Triangle (Front)
	glColor3f(0.0f, 0.0f, 1.0f);    //Blue
	glVertex3f(1.0f, -1.0f, 1.0f);  //Right of Triangle (Front)
	glColor3f(1.0f, 0.0f, 0.0f);    //Red
	glVertex3f(0.0f, 1.0f,0.0f);   //Top of Triangle (Right)
	glColor3f(0.0f, 0.0f, 1.0f);    //Blue
	glVertex3f(1.0f, -1.0f, 1.0f); //Left of Triangle (Right)
	glColor3f(0.0f, 1.0f, 0.0f);    //Green
	glVertex3f(1.0f, -1.0f, -1.0f);  //Right of Triangle (Right)
	glColor3f(1.0f, 0.0f, 0.0f);	//Red
	glVertex3f(0.0f, 1.0f, 0.0f);   //Top of Triangle  (Back)
	glColor3f(0.0f, 1.0f, 0.0f);    //Green
	glVertex3f(1.0f, -1.0f, -1.0f);//Left of Triangle(Back)
	glColor3f(0.0f, 0.0f, 1.0f);    //Blue
	glVertex3f(-1.0f, -1.0f, -1.0f); //Left of Triangle (Back)
	
	glColor3f(1.0f, 0.0f, 0.0f);    //Red
	glVertex3f(0.0f, 1.0f, 0.0f);   //Top of Triangle  (Left)
	glColor3f(0.0f, 0.0f, 1.0f);    //Blue
	glVertex3f(-1.0f, -1.0f, -1.0f);//Left of Triangle (Left)
	glColor3f(0.0f, 1.0f, 0.0f);    //Green
	glVertex3f(-1.0f, -1.0f, 1.0f); //Right of Triangle(Left)
	glEnd();
	//Done Drawing the Pyramid
	glLoadIdentity();  //Reset the Current Modelview Matrix
	glTranslatef(1.5f, 0.0f, -7.0f); //Move Right 1.5 Units And Intothe screen 7.0
	glRotatef(rquad, 1.0f, 1.0f, 1.0f); //Rotate The Quad On the X axis(NEW)
	glBegin(GL_QUADS);
	//Draw A Quad
	glColor3f(0.0f, 1.0f, 0.0f);   // Set The Color to Green
	glVertex3f(1.0f, 1.0f, -1.0f); //Top Right of The Quad (Top)
	glVertex3f(-1.0f, 1.0f, -1.0f);//Top Left of The Quad (Top)
	glVertex3f(-1.0f, 1.0f, 1.0f); //Bottom Left of the Quad(Top)
	glVertex3f(1.0f, 1.0f, 1.0f);  //Bottom Right of the Quad(Top)
	glColor3f(1.0f, 0.5f, 0.0f);   //Set The Color to Orange
	glVertex3f(1.0f, -1.0f, 1.0f); //Top Right of the Quad(Bottom)
	glVertex3f(-1.0f, -1.0f, 1.0f);//Top Left of the Quad (Bottom)
	glVertex3f(-1.0f, -1.0f, -1.0f);//Bottom Left of the Quad(Bottom)
	glVertex3f(1.0f, -1.0f, -1.0f);//Bottom Right of the Quad
	glColor3f(1.0f, 0.0f, 0.0f);   //Set the Color to Red
	glVertex3f(1.0f, 1.0f, 1.0f);  //Top Right of the Quad (Front)
	glVertex3f(-1.0f, 1.0f, 1.0f); //Top Left of the Quad (Front)
	glVertex3f(-1.0f, -1.0f, 1.0f);//Bottom Left of the Quad(Front)
	glVertex3f(1.0f, -1.0f, 1.0f); //Bottom Right of the Quad(Front)
	glColor3f(1.0f, 1.0f, 0.0f);   //Set the Color to Yellow 
	glVertex3f(1.0f, -1.0f, -1.0f);//Top Right of the Quad(back)
	glVertex3f(-1.0f, -1.0f, -1.0f);//Top Left of the Quad(back)
	glVertex3f(-1.0f, 1.0f, -1.0f);//Bottom Left of the Quad (back)
	glVertex3f(1.0f, 1.0f, -1.0f); //Bottom Right of the Quad (back)
	glColor3f(0.0f, 0.0f, 1.0f);//Set the Color to Blue
	glVertex3f(-1.0f, 1.0f, 1.0f);//Top Right of the Quad(Left)
	glVertex3f(-1.0f, 1.0f, -1.0f);//Top Left of the Quad(Left)
	glVertex3f(-1.0f, -1.0f, -1.0f);//Bottom Left of the Quad (Left)
	glVertex3f(-1.0f, -1.0f, 1.0f);//Bottom Right of the Quad (Left)
	glColor3f(1.0f, 0.0f, 1.0f);   //Set the Color to Violet
	glVertex3f(1.0f, 1.0f, -1.0f); //Top right of the Quad(Right)
	glVertex3f(1.0f, 1.0f, 1.0f); //Top Left of the Quad(Right)
	glVertex3f(1.0f, -1.0f, 1.0f); //Bottom Left of the Quad(Right)
	glVertex3f(1.0f, -1.0f, -1.0f); //Bottom Right of the Quad(Right)
	glEnd();
	//Done Drawing the quad
	glFlush();  //Force to display the new drawings immediately	
}
void myKeyboard(int key, int x, int y) {
	switch (key) {
	case GLUT_KEY_LEFT:
	case GLUT_KEY_UP:
		rtri -= 0.5f;   //Decrese the Roatation Variable For The Triangle (New)
		rquad += 0.5f;  //Increse The Rotation Variable For The Quad
		DrawGLScene();
		break;
	case GLUT_KEY_RIGHT:
	case GLUT_KEY_DOWN:
	rtri += 0.5f;   //Increse the Roatation Variable For The Triangle (New)
	rquad -= 0.85f;  //Decrese The Rotation Variable For The Quad
	DrawGLScene();
	break;
	}
}
void myMovedMouse(int x, int y) {
}

4.2 screenshot of successful operation

4.3 control 3D object rotation and Translation

The myKeyboard in the above code implements image rotation through the keyboard. Note that in the main function, you can call it with glutSpecialFunc().

void myKeyboard(int key, int x, int y) {
	switch (key) {
	case GLUT_KEY_LEFT:
	case GLUT_KEY_UP:
		rtri -= 0.5f;   //Decrese the Roatation Variable For The Triangle (New)
		rquad += 0.5f;  //Increse The Rotation Variable For The Quad
		DrawGLScene();
		break;
	case GLUT_KEY_RIGHT:
	case GLUT_KEY_DOWN:
	rtri += 0.5f;   //Increse the Roatation Variable For The Triangle (New)
	rquad -= 0.85f;  //Decrese The Rotation Variable For The Quad
	DrawGLScene();
	break;
	}
}

5, Experience

In this experiment, we need to carefully compare each parameter when writing code. For example, for color, different values of three parameters in glColor3f function will lead to different effects. You should also pay attention to the import of header files. For example, "stdafx.h" files must be placed before other library files.
By observing the code structure, we can find that the idea of drawing a graph is roughly as follows:

  1. Drawing window
  2. Initialize GL function
  3. Writing functions for reloading images
  4. Drawing functions
  5. Functions of keyboard or mouse to manipulate graphics
    List of related functions:
  6. Main functions in the above source program:
    glutInit initialization function
    glutInitWindowSize set window size
    glutInitWindowPosition set window position
    glutCreateWindow create window
    Glutdisplayfunction (drawglscene) specifies the display function
    glutReshapeFunc(myReshape) changes the display area
    glutMotionFunc(myMovedMouse) is a function that handles mouse drag events when the mouse button is pressed. When you drag the mouse, this function is called once per frame.
    Glutspecial func (mykeyboard) is a function used to handle the pressing events of some special keys (such as F1,F2,etc). In this experiment, we mainly focus on the direction bond.
    glutMainLoop() for process loop
  7. myReshape function
    glViewport(width,height) represents the width and height of the viewport rectangle, and redraws the window according to the real-time changes of the window.
    In fact, the function of selecting projection matrix in glMatrixMode is to make a statement about what to do next. That is to say, before doing the next step, it tells the computer that I want to operate "what". There are three modes of "what" options (parameters) in "()" of glMatrixMode: GL project projection, GL modelview model view, GL text texture.
    If the parameter is GL? Project, this is the meaning of projection. It means to operate the projection correlation, that is, to project the object onto a plane, just like we take photos, to project the 3D object onto the 2D plane. In this way, the following statements can be perspective related functions, such as glFrustum() or gluPerspective();
    Before you can operate on the projection matrix, you need to call the function:
    GlMatrixMode (GL? Project); / / specifies the current matrix as a projection matrix
    Then set the matrix as unit matrix:
    glLoadIdentity();
    Then we call glFrustum() or gluPerspective(), and the matrix generated by them will multiply with the current matrix to produce the effect of perspective.
    reference material:
    https://blog.csdn.net/jiangdf/article/details/8460012
    glLoadIdentity restore initial coordinate system
    This command is a valueless function without parameters. Its function is to replace the current matrix with a 4 × 4 unit matrix. In fact, it is to initialize the current matrix. That is to say, no matter how many matrix transformations have been carried out before, after the execution of this command, the current matrix is restored to a unit matrix, that is to say, there is no matrix transformation state.
    Note: for some reasons, the elements in the current matrix may have some uncertain values, which will lead to an unexpected result when the program makes geometric deformation on the drawing object. Therefore, it is necessary to initialize the current matrix into a unit matrix, that is, to make no transformation to the graphic object. This is why the glMatrixMode() command is always called after it has been called. Because the glMatrixMode() command itself is also a matrix transformation, it changes the current matrix into the form specified by the command parameters. If the unit matrix is not used to replace it, the graph drawn under this matrix will be unpredictable.
    For a detailed explanation of this function, see the following blog:
    https://blog.csdn.net/shuaihj/article/details/7228265
    (I feel that this article is very clear ~)
    Glviewport by default, the viewport is set to occupy the entire pixel rectangle of the window, and the window size is the same as the viewport size. If you choose a smaller drawing area, you can use the glviewport function to implement this transformation, define a pixel rectangle in the window, and map the image to this rectangle.
    gluPerspective(GLdouble fovy,GLdouble aspect,GLdouble zNear,GLdouble zFar)
    fovy, this is the most difficult to understand. My understanding is that the angle of opening the eyes, that is, the size of the angle of view. If it is set to 0, you close your eyes, so you can't see anything. If it is 180, you can think of your vision as very broad
    Aspect, which is easy to understand, is the aspect ratio of the actual window, i.e. x/y
    zNear, this is the cutting surface of your proximity,
    zFar is the cutting surface in the distance

    Reference: https://blog.csdn.net/dcrmg/article/details/53106457
    glMatrixMode
  8. Functions in InitGL
    glShadeModel() sets the shading mode, which controls the transition mode of painting other point colors between two points. The parameter is GL smooth (default). If two points are different in color, GL smooth will have a transition effect. When using constant shading (that is, GL ﹣ flat), the color of a vertex in the entity is used to render the entire entity.
    When using smooth shading (that is, GL? Smooth), the color of each vertex in the entity is processed independently. For segment entities, the color of each point on the segment is obtained by the difference between the colors of the two vertices. For polygon primitives, the color of the inner region of the polygon is obtained based on the color difference of all vertices.
    Reference: original link: https://blog.csdn.net/deniece1/article/details/102133394

glClearColor() with glClearDepth
Parameters: GL? Color? Buffer? Bit, color buffer
GL? Depth? Buffer? Bit
GL? Stencil? Buffer? Bit, template buffer
The value prefabrication is mainly completed by glclearcolor,glcleardepth,glclearstencil. It sets the value in advance. OpenGL is a state machine, which is equivalent to setting a state value of context.
Reference: https://blog.csdn.net/qq_/article/details/85115585
So the background of my program window is black~

glEnable() is used to enable various functions. The function is determined by the parameters.
The parameter GL? Depth? Test in the program enables the depth test, and automatically hides the hidden figures (materials) according to the distance of coordinates

glDepthFunc() specifies a function to compare the value size of the target pixel and the current pixel in the z direction.
If the entered depth value is less than or equal to the reference value, then the

Application of glint(): glint (GL ﹣ performance ﹣ correction ﹣ hint, GL ﹣ nicest); if OpenGL cannot effectively support the perspective correction parameter difference, GL ﹣ dot ﹣ care and GL ﹣ fastest can perform simple linear difference calculation of color and texture coordinates.
GL? Specific? Correction? Hint: Specifies the quality of the difference between color and texture coordinates. If OpenGL can not effectively support the perspective correction parameter difference, then GL? Dot? Care and GL? Fast can perform simple linear difference calculation of color and texture coordinates.
GL ﹣ nicest can generate more pixel segments during rasterization. Select the highest quality option.
Reference: https://blog.csdn.net/blues1021/article/details/48769797

  1. DrawGLScene()
    glTranslatef() translates x units along the positive x axis (x is the signed number) translates y units along the positive Y axis (y is the signed number) translates Z units along the positive Z axis (z is the signed number)
    glRotatef()
    First, explain the direction of rotation, do the vector from (0,0,0) to (x,y,z), hold this vector with your right hand, point your thumb to the positive direction of the vector, and the direction around your four fingers is the direction of rotation;
    Function function: take point (0,0,0) to point (x,y,z) as axis, rotate angle;

glBegin() mode: creates the type of the element
The glBegin and glEnd functions limit the fixed-point definitions of one or more groups of graph elements.
GL? Triangles takes each vertex as an independent triangle. Vertices 3n-2, 3n-1 and 3N define the nth triangle and draw N/3 triangles.

glColor3f()
It should be noted that if the color function is called consecutively multiple times between glBegin() and glEnd() functions, only the last color will be displayed. It should have three parameters, and the type is float. Another point is that its parameter value range is [0.0,1.0] "background color: rgb (255, 255, 255).

This experiment has come to a successful end. Welcome to share.

Published 6 original articles, won praise 0, visited 75
Private letter follow

Posted by CrimsonSoul on Mon, 13 Jan 2020 02:52:18 -0800