1 of 47

OpenGL

2 of 47

什麼是OpenGL?

  • 由Khronos組織所制定並維護的規範(Specification), 用於 render 2D、3D 場景的跨語言、跨平台 API
  • OpenGL的函式庫實作由顯卡的生產商提供
  • 讓電腦能透過GPU render 2D 與 3D的場景

3 of 47

OpenGL環境

  • Windows
  • OpenGL3.3
  • Visual Studio 2019: c++ IDE
  • Glfw: context/window toolkit
  • Glad: loading library

4 of 47

安裝 Visual Studio

5 of 47

安裝 cmake

6 of 47

下載 glfw

7 of 47

將glfw解壓縮,並在其中建立build資料夾

8 of 47

打開cmake,設置剛剛的路徑,並按下Configure

9 of 47

選擇你的visual studio版本,並設定為x64

10 of 47

再次按下Configure,然後點擊Generate

作業時要在編譯一次 glfw ,這裡換個 build 的資料夾例如 buildshared,並勾選 BUILD_SHARED_LIBS

用 Cmake 編作業時會用到 CMAKE_INSTALL_PREFIX 這個資料夾,這選個喜歡的資料夾像 msvc2019shared 並記住

11 of 47

進入build資料夾,用visual studio執行GLFW.sln

12 of 47

在方案名稱上點擊右鍵 > 建置方案

Debug 跟 Release 都 build

13 of 47

下載 glad

可透過工具查看最高支援的 opengl 版本

14 of 47

Visual Studio建立C++空白專案

15 of 47

在專案路徑中創建Libraries資料夾

16 of 47

在Libraries中創建lib與include

17 of 47

將include中的GLFW移到你的include中

18 of 47

將build/src/Debug中產生的glfw3.lib移到你的lib中

19 of 47

將glad解壓縮,其中include中的資料移到你的include

20 of 47

將glad解壓縮,其中include中的資料移到你的include

21 of 47

將glad/src/glad.c直接移到你的專案資料夾

22 of 47

回到你的專案,將上方的x86改為x64

23 of 47

在專案名稱點擊右鍵 > 屬性

24 of 47

屬性頁上方選擇所有平台

25 of 47

左側選擇VC++目錄,並編輯include目錄

26 of 47

加入剛剛建立的include資料夾路徑

27 of 47

編輯程式庫目錄

28 of 47

加入剛剛建立的lib資料夾路徑

29 of 47

左側選擇連結器 > 輸入,並編輯其他相依性

30 of 47

加入glfw3.lib與opengl32.lib

31 of 47

右鍵點擊來源檔案 > 加入 > 現有項目

32 of 47

選擇剛剛加入的glad.c

33 of 47

右鍵點擊來源檔案 > 加入 > 新增項目

34 of 47

創建main.cpp

35 of 47

測試-建立視窗

36 of 47

Double buffer

37 of 47

Render pipeline

38 of 47

Vertex Data

39 of 47

Vertex Buffer Object(VBO)

  • 用來將大量的資料儲存在 GPU Memory

40 of 47

Linking Vertex Attributes

  • 將 buffer object 的資料對應到 vertex shader 的 input

Vertex shader

41 of 47

Vertex Array Object(VAO)

  • VAO 讓我們可以在重複畫不同的物件時可以不需要重複進行Linking Vertex Attributes的動作
  • VAO須在VBO之前創建
  • Core OpenGL requires that we use a VAO so it knows what to do with our vertex inputs. If we fail to bind a VAO, OpenGL will most likely refuse to draw anything.

42 of 47

Shader

  • 使用 GLSL(OpenGL Shading Language)
  • gl_Position => 預設變數,輸出對應的 clip space 座標
  • Vertex shader 的 out 對應到 fragment shader 的 in
  • uniform 是 CPU 向 GPU 的 Shader 發送數據的方式, 使用 glGetUniformLocation() 以及 glUniform**()

Vertex shader

Fragment shader

43 of 47

Compile shaders and link into a program

檢查並輸出 error message

44 of 47

繪製物體

  • 設定好 shader program 和 vertex array object , 之後就根據想繪製的東西使用對應的 shader program 和 vertex array object

45 of 47

詳細流程

46 of 47

Element Buffer Object(EBO)

  • 儲存頂點索引到 GPU Memory
  • 解決使用重複的頂點, 減少空間浪費

0

1

2

3

47 of 47

Reference