02. OpenGL窗口

窗口显示和鼠标点击事件绑定
#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <cstdio>

void framebuffer_size_callback(GLFWwindow * window, int width, int height);
void processInput(GLFWwindow * window);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void mouse_button_callback(GLFWwindow* window, int action, int state, int mods);

const int WIDTH = 800;
const int HEIGHT = 600;
const char* TITLE = "Learn OpenGL";


int main()
{
    // GLFW init
    glfwInit();
    // 设置OpenGL版本为3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    // 设置模式为核心模式
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);


    // 创建窗口
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, nullptr, nullptr);
    if (window == nullptr)
    {
        printf("Failed to create GLFW window\n");
        glfwTerminate();
        return -1;
    }

    // 绑定window为当前线程上下文对象
    glfwMakeContextCurrent(window);


    // GLAD init
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        printf("Failed to initialize GLAD\n");
        return -1;
    }

    // 渲染窗口的位置和大小
    // glViewport(0, 0, WIDTH, HEIGHT);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // 循环渲染
    while (!glfwWindowShouldClose(window))
    {
        // 输入
        processInput(window);

        // 绑定鼠标点击事件
        glfwSetMouseButtonCallback(window, mouse_button_callback);
        // glfwSetCursorPosCallback(window, mouse_callback);

        // 清除颜色缓存
        glClearColor(0.2f, 0.3f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);


        // 检查并调用事件,交换渲染
        glfwPollEvents();
        glfwSwapBuffers(window);
    }

    // 释放资源
    glfwTerminate();
    return 0;
}

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);
    }
}


void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
    // 获取鼠标当前坐标
    printf("(%.3f, %.3f)\n", xpos, ypos);
}


void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
    // 鼠标点击后获取坐标
    double xpos, ypos;
    if (action == GLFW_PRESS)
    {
        // glfwSetCursorPosCallback(window, mouse_callback);

        // 获取当前坐标
        glfwGetCursorPos(window, &xpos, &ypos);
        printf("(%.3f, %.3f)\n", xpos, ypos);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容