OpenGL學習筆記:GLAD和第一個視窗
阿新 • • 發佈:2018-11-02
環境
系統:Windows10 64位 家庭中文版
IDE:Visual Studio 2017 專業版
參考教程:https://learnopengl-cn.github.io/01 Getting started/03 Hello Window/
步驟
1.獲取GLAD:
a.開啟GLAD提供的線上服務;
b.將Language設定為C/C++、將Specification設定為OpenGL、API中的gl選項選擇Version 3.3(或以上)、Profile設定為Core,並且選中Generate a loader,暫時忽略其他內容,如下圖所示,最後點選GENERATE按鈕來生成庫檔案;
c.在跳轉後的網頁中選擇glad.zip下載下來,如下圖所示:
d.把下載下來的glad.zip檔案解壓,就可以得到我們需要的include\glad\glad.h、include\KHR\khrplatform.h和src\glad.c這3個檔案。
2.新建Visual Studio專案,把步驟1得到的3個檔案都新增到專案中,同時在專案中新增一個main.cpp檔案,然後把以下程式碼複製到main.cpp檔案中:
#include <glad\glad.h> //這個必須放在GLFW之前 #include <GLFW\glfw3.h> #include <iostream> //這個是為了使用列印語句 //函式宣告 void framebuffer_size_callback(GLFWwindow* window, int width, int height); //視窗大小設定回撥函式 void processInput(GLFWwindow* window); //輸入處理函式 //常量定義 const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; //主函式 int main() { glfwInit(); //glfw 初始化 //設定OpenGL版本等資訊 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //建立GLFW視窗 GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } //設定當前上下文 glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); //把OpenGL的函式指標匯入給GLAD if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } //迴圈渲染 while (!glfwWindowShouldClose(window)) { processInput(window); //交換快取 glfwSwapBuffers(window); //事件處理 glfwPollEvents(); } //停止 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); } }
3.編譯執行程式碼,可以得到1個視窗,如下圖: