opengle 创建窗口

// OpenglTemplate.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
//这里包含顺序很重要  需要先包含glad 后glfw
#include <glad/glad.h>
#include <GLFW/glfw3.h>

//窗口大小发生变化时的回调
void framebuffer_size_callback(GLFWwindow* Window, int width, int height)
{
    glViewport(0, 0, width, height);
}

//处理输入
void processInput(GLFWwindow* Window)
{
    if (glfwGetKey(Window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
    {
        glfwSetWindowShouldClose(Window, true);
    }
}
int main()
{
    //初始化glfw
    glfwInit();
    //使用opengl3.3版本
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    //使用opengl核心模式
    glfwWindowHint(GLFW_OPENGL_CORE_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //macos 需要添加 表示启用不支持的opengl功能
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    //创建窗口
    GLFWwindow* Window = glfwCreateWindow(800, 600, "Create Window", NULL, NULL);
    if (Window == NULL)
    {
        std::cout << "Failed to Create GLFW window" << std::endl;
        glfwTerminate(); //销毁所有相关资源
        return -1;
    }
    glfwMakeContextCurrent(Window); //指定opengl opengles 的context到当前程序

    //初始化glad
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initalize Glad" << std::endl;
        return -1;
    }

    //创建opengl视口大小
    glViewport(0, 0, 200, 600);
    //注册窗口回调函数
    glfwSetFramebufferSizeCallback(Window, framebuffer_size_callback);
   
    //渲染循环
    while (!glfwWindowShouldClose(Window))
    {
        //处理输入
        processInput(Window);
        //处理渲染
        glClearColor(0.2, 0, 0, 1);
        glClear(GL_COLOR_BUFFER_BIT); //清空上一帧的颜色缓冲
        //交换缓冲
        glfwSwapBuffers(Window); //交换前后颜色缓冲
        glfwPollEvents(); //触发窗口输入
    }

    glfwTerminate();
    return 0;
}


发布了144 篇原创文章 · 获赞 15 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/maxiaosheng521/article/details/103967037