Configure OpenGL (win10 + vs2019 + glad + glfw) and create your first OpenGL project

Time:2022-4-28

Before drawing a good effect, the first thing to do is to create an OpenGL context and an explicit window.
Some function libraries have provided such functions, which can provide developers with a window and context to render.
Glut, SDL, sfml and glfw are popular. Here we use glfw

OpenGL related libraries

Introduction to OpenGL related libraries

  • Glew encapsulates the interface of the underlying OpenGL, allowing developers to code across platforms
  • Glad and glew have basically the same functions and can be regarded as its upgraded version
  • Freeglut is mainly used to create OpenGL context, accept some mouse and keyboard events, and so on
  • Glfw is basically the same as freeglut and can be regarded as its upgraded version

Glad is usually used with glfw; Glew is usually used with freeglut.

GLFW

  • brief introduction
    Glfw is a special C language library for OpenGL, which provides some minimal interfaces required to render objects. It allows users to create OpenGL context, define window parameters and process user input.

  • Download from official website
    Glfw needs fromGlfw official websiteDownload.

    You can download the source file and then generate the corresponding binary version and header file with cmake tool. For details, see the link:LearnOpenGL CN
    You can also directly download the binary version compiled on the official website. It is recommended to download the 32-bit version.

  • Baidu cloud Download
    https://pan.baidu.com/s/1CCtc0sy1WpkScIkP3GZD8AExtraction code9hjy

GLAD

Due to the large number of OpenGL driver versions, the location of most of its functions cannot be determined at compile time and needs to be queried at run time. Therefore, the task falls on the developer. The developer needs to obtain the function address at runtime and save it in a function pointer for later use. However, this process is complicated and cumbersome, and the glad library can simplify this process.

  • Download from official website
    Open gladonline service, select the following configuration to generate, and select the compressed file glad Zip download.

    • Set language toC/C++
    • Set OpenGL API Version (API GL) toLatest version(downward compatibility);
    • Set the profile toCore;
    • CheckGenerate a loader option.

  • Baidu cloud Download
    https://pan.baidu.com/s/1LlBCLbRNDSUNUKz4kzw_owExtraction code54xk

Configure glad & glaf

Decompress the obtained compressed package.
For convenience, you can put the files you need in the specified directory. Here I choose to put it in the folder C: \ program files \ OpenGL.

  • In the unzipped glfw folderincludeandlib-vc2019(if it is a vs of other version, remember to change it to another version) copy it to the folderC:\Program Files\OpenGLMedium;
  • The contents in the include folder in the extracted glad foldergladandKHRCopy folder to folderC:\Program Files\OpenGL\includeMedium;
  • In the extracted glad foldersrcCopy folder to folderC:\Program Files\OpenGLMedium;

The file structure after moving is as follows:

td { width: 200px; text-align: center }

OpenGL include glad
GLFW
KHR
vc2019
src glad.c

Create project and configuration

  • Open vs2019 and create a new blank project;
  • Right clickSolution namechoiceattribute
  • clickVC + + ProjectMediumInclude directory, add the include directory of OpenGL, here is C: \ program files \ OpenGL \ include;
  • clickVC + + ProjectMediumLibrary file, add the project library directory of OpenGL, here is C: \ program files \ OpenGL \ lib-vc2019;
  • clickLinkerMediuminputMediumAdditional dependencies, add the library file glfw lib ;
  • Add the source file under the C: \ program files \ OpenGL \ SRC folder to the new projectglad.c(to be added for each new project);

New window

  • Create a new source file that contains the following header files

    #include 
    #include
  • establishmainFunction to instantiate glfw window

    int main() {
        //Initialize glfw
        glfwInit();
        //Configure glfw
        //The first parameter is the enum type, representing the option name
        //The second parameter is of type int, which is used to set the value of the first parameter
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);                  //  Set major version number
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);                  //  Set minor version number
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  //  Use core mode
        //The following statement is required only for Mac OS X systems
        //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    
        return 0;
    }
  • Create a window object

    //The glfwcreatewindow function is used to create the window object glfwcreatewindow
    //The first, second and third parameters are the width, height and title of the window
    //The last two parameters are ignored for the time being
    //Returns a pointer to the glfwwindow object
    GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
    if (window == NULL) {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    
    //After the window is created successfully, notify glfw to set the context of the window as the main context of the current thread 
    glfwMakeContextCurrent(window);
  • Load the pointer address of OpenGL function related to system storage
    Glad is used to manage the function pointer of OpenGL, so glad must be initialized before any function calling OpenGL.

    //Gladloadglloader: gladloader
    //Glfwgetprocaddress: glfw defines the correct function according to the compiled system
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }
  • Viewport
    Before you start rendering, you must tell opengl the size of the rendered rectangular area, that is, the viewport.
    The viewport can be the same size as the window, or larger or smaller than the size of the window.
    Only graphics drawn in the viewport area can be explicit,

    //Glviewport: sets the anchor point and size of the viewport
    //The first and second parameters control the position of the lower left corner of the viewport, and the lower left corner of the window is (0, 0)
    //The third and fourth parameters control the size of the viewport in pixels
    glViewport(0, 0, 800, 600);

    When the user changes the size of the window, the viewport should also be adjusted.
    You can register a callback function for the window, which will be called every time the window size is adjusted.

    //The first parameter of the callback function is the window object pointer
    //The last two parameters of the callback function are the width and height of the window after it is changed
    void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
        glViewport(0, 0, width, height);
    }

    In addition, you need to register this callback function to tell glfw developers that they want to call this function whenever the window is resized.

    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
  • Render Loop
    Add a in the programwhileLoop is used to continuously draw images and accept user input before glfw launch.

    while(!glfwWindowShouldClose(window)) { 
        glfwSwapBuffers(window);
        glfwPollEvents();    
    }
    • glfwWindowShouldCloseThe function checks whether glfw is required to exit at the beginning of each cycle.
    • glfwPollEventsThe function detects whether an event is triggered, updates the window state, and calls the corresponding callback function.
    • glfwSwapBuffersThe function swaps the color cache, which is used to draw in this iteration, and is displayed on the screen as output.

    Double buffer
    When an application uses single buffer drawing, the problem of image flicker can occur, because the generated image is not drawn at once, but generated step by step, which leads to the unreal rendering result.
    To avoid this problem, we use a double buffered configuration window application. Among them,Front bufferThe final output image is saved in the;Punch backUsed to draw all rendering instructions. When all rendering instructions are completed, swap the front and back buffers, and the image will be displayed immediately.

  • Correctly release / delete all previously allocated resources

    //Correctly release / delete all previously allocated resources
    glfwTerminate();

input

Take getting a key input as an example: close the window when you press the escape key.

//Create a processinput to process the input
void processInput(GLFWwindow *window) {
    //Glfwgetkey is used to check whether the key escape is pressed (if pressed, return to gldfw_release)
    //Glfwsetwindowshouldclose is used to set the windowshouldclose property to true when escape is pressed
    if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);         //  The next cycle will turn off glfw
}

//Processinput is called in each iteration of the loop rendering
while (!glfwWindowShouldClose(window)) {
    processInput(window);

    glfwSwapBuffers(window);
    glfwPollEvents();
}

Render

We need to put all the rendering operations into the rendering cycle, so as to ensure that the rendering instructions can be executed at each iteration of the rendering cycle.

//Render loop
while(!glfwWindowShouldClose(window)) {
    //Input
    processInput(window);

    //Rendering instructions
    ...

    //Check and call events, swap buffers
    glfwPollEvents();
    glfwSwapBuffers(window);
}

Recommended Today

Plan task

Through task planning, the system can automatically execute tasks according to time or periodic tasks   Environmental preparation [[email protected] ~]#yum -y install postfix [[email protected] ~]#systemctl enable –now postfix   Perform a task at a certain point in the future At specifies a point in time to perform a one-time task The batch system chooses its […]