【三】创建窗口

Mac上搭建开发环境

搭建环境是参考的这篇文章,在这里记录一下。

创建窗口

基本步骤:

  1. 初始化GLFW库,函数:glfwInit
  2. 设置GLFW参数, 函数:glfwWindowHint
  3. 创建窗口,函数:glfwCreateWindow
  4. 将创建的窗口设置为上下文环境, 函数:glfwMakeContextCurrent
  5. 使用GLAD库中的函数绑定OpenGL函数, 函数:gladLoadGLLoader
  6. 设置视图大小,函数:glViewport
  7. 渲染屏幕,在本例中简单的把屏幕填充为一个颜色,函数:glClearColorglClear
  8. 展示屏幕,函数:glfwSwapBuffers
  9. 监听键盘事件,函数:glfwPollEvents
  10. 释放资源,退出窗口,函数:glfwTerminate

关键函数

  • glfwInit
    这个函数用来初始化GLFW库;
  • glfwWindowHint
    这个函数用来设置GLFW相关参数
  • glfwCreatWindow

代码

//
//  main.cpp
//  firstOpenGL
//
//  Created by woodlouse on 2019/10/25.
//  Copyright © 2019年 woodlouse. All rights reserved.
//

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

int main() {
    using std::cout;
    using std::endl;
    
    glfwInit();
    //    主版本
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    // 次版本
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    //
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //向前兼容
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    GLFWwindow *window = glfwCreateWindow(800, 600, "LearOpenGL", NULL, NULL);
    if (window == NULL) {
        std::cout<<"Failed to creat GLFW window"<<std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
        std::cout<<"Failed to initalize GLAD"<<std::endl;
        return -1;
    }
    glViewport(0, 0, 800, 600);
    void framebuffer_size_callback(GLFWwindow *window, int width, int height);
    
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    
    void processInput(GLFWwindow *window);
    
    while (!glfwWindowShouldClose(window)) {
        processInput(window);
        glClearColor(0.5f, 0.1f, 0.0f, 0.1f);
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    
//    printf("%s", "Hello world");
    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);
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容