OpenGL学习笔记(三)OpenGL新建窗口

//
// Created by czh on 18-6-25.
//

#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);

int main()
{
    glfwInit();//glfw初始化
    //告诉GLFW我们要使用的OpenGL版本是3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);//主版本号(Major)
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);//次版本号(Minor)
    //明确告诉GLFW我们需要使用核心模式意味着我们只能使用OpenGL功能的一个子集
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(800, 600, "title", NULL, NULL);//设置窗口对象的宽度,高度,名称
    if (window == NULL)//空指针
    {
        glfwTerminate();//释放/删除之前的分配的所有资源
        return -1;
    }
    glfwMakeContextCurrent(window);//创建一个窗口对象
    //回调函数(Callback Function),它会在每次窗口大小被调整的时候被调用
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    //GLAD是用来管理OpenGL的函数指针的,所以在调用任何OpenGL的函数之前我们需要初始化GLAD。
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        glfwTerminate();
        return -1;
    }

    while (!glfwWindowShouldClose(window))//渲染循环(Render Loop),它能在我们让GLFW退出前一直保持运行。
    {
        processInput(window);//获取按键输入
        glClearColor(0.0f, 0.0f, 1.0f, 0.0f);//设置清空屏幕所用的颜色,前三个参数设置RGB,最后一个透明度
        glClear(GL_COLOR_BUFFER_BIT);//清空屏幕
        glfwPollEvents();// 检查并调用事件,交换缓冲
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}

void processInput(GLFWwindow *window)
{
    if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)//如果检测到按键输入Esc,关闭窗口
        glfwSetWindowShouldClose(window, true);
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

运行效果

猜你喜欢

转载自blog.csdn.net/czhzasui/article/details/80802344