畫立方體和畫2D平面沒有本質的區別,因為頂點坐標里面本身就包含了Z軸坐標。唯一不同的是,需要打開OpenGL的深度測試
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
通常在OpenGL里顯示3D模型,會經過3個矩陣的轉換
- Model 模型矩陣用了確定物體的位置。一般的紋理坐標都是已原點為中心、坐標范圍(-1, 1),稱之為局部空間而生成的,Model矩陣就是用來定位物體實際的位置(世界空間)
- View 觀察者的位置。不同地方觀察物體,看到的效果也是不同的(觀察空間)
- Projection 投影矩陣可以產生近大遠小大效果,并且定義了視野大范圍(裁減空間)
舉個例子,下面代碼就定義了3個矩陣
// Create transformations
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
model = glm::rotate(model, (GLfloat)glfwGetTime() * 50.0f, glm::vec3(0.5f, 1.0f, 0.0f));
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
// Get their uniform location
GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");
// Pass them to the shaders
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
// Note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once.
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
model定義了一個旋轉角、view是在Z軸正3的位置(View和實際坐標系相反)、projection是一個45度的透視投影。
把這3個矩陣傳給Shader就可以了。