模型加載主程序:
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <fstream>
#include <sstream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Shader.h"
#include "Camera.h"
#include "Model.h"
#define _USE_MATH_DEFINES
#include<math.h>
void framebuffer_size_callback(GLFWwindow* windows, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void processInput(GLFWwindow *windows);
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);
unsigned int loadCubemap(vector<std::string> faces);
#define ambient_light 0.1 //定義四個點光源的環境光影響
#define specular_light 0.05 // 定義四個點光源鏡面反射的影響
#define screenWidth 800
#define screenHeight 600
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = screenWidth / 2.0f;
float lastY = screenHeight / 2.0f;
bool firstMouse = true;
//timing
float deltaTime = 0.2f;
float lastFrame = 0.0f;
glm::vec3 pointLightPositions[] = {
glm::vec3(0.7f, 0.2f, 2.0f),
glm::vec3(2.3f, -3.3f, -4.0f),
glm::vec3(-4.0f, 2.0f, -12.0f),
glm::vec3(0.0f, 0.0f, -3.0f)
};
vector<std::string>faces
{
"D:/opengltask/LearnOpenGL_master/resources/textures/skybox/right.jpg",
"D:/opengltask/LearnOpenGL_master/resources/textures/skybox/left.jpg",
"D:/opengltask/LearnOpenGL_master/resources/textures/skybox/top.jpg",
"D:/opengltask/LearnOpenGL_master/resources/textures/skybox/bottom.jpg",
"D:/opengltask/LearnOpenGL_master/resources/textures/skybox/back.jpg",
"D:/opengltask/LearnOpenGL_master/resources/textures/skybox/front.jpg"
};
//立方體貼圖頂點座標數據
float skyboxVertices[] = {
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
glm::mat4 model = glm::mat4(1.0f);
unsigned int cubemapVAO, cubemapVBO;
int main()
{
//glfw:initialize and configure
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, "model_loading", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
model = glm::translate(model, glm::vec3(0.0f, -1.75f, 0.0f)); // 使其處於場景的中心
model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f));
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glEnable(GL_DEPTH_TEST);
unsigned int cubemapTexture = loadCubemap(faces);
//對於立方體貼圖的VAO
glGenVertexArrays(1, &cubemapVAO);
glGenBuffers(1, &cubemapVBO);
glBindVertexArray(cubemapVAO);
glBindBuffer(GL_ARRAY_BUFFER, cubemapVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glBindVertexArray(0);
Shader ourShader("1.model_loading.vs", "1.model_loading.fs");
Shader skyboxShader = Shader("cubemap.vs", "cubemap.fs"); //天空盒對應頂點着色器和片段着色器
Model ourModel("D:/opengltask/LearnOpenGL_master/resources/objects/nanosuit/nanosuit.obj");
while (!glfwWindowShouldClose(window))
{
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
processInput(window);
ourShader.setVec3("viewPos", camera.Position);
glClearColor(0.05f, 0.05f, 0.05f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ourShader.use();
// point light 1
ourShader.setVec3("pointLights[0].position", pointLightPositions[0]);
ourShader.setVec3("pointLights[0].ambient", ambient_light, ambient_light, ambient_light);
ourShader.setVec3("pointLights[0].diffuse", 1.0f, 1.0f, 1.0f);
ourShader.setVec3("pointLights[0].specular", specular_light, specular_light, specular_light);
ourShader.setFloat("pointLights[0].constant", 1.0f);
ourShader.setFloat("pointLights[0].linear", 0.09);
ourShader.setFloat("pointLights[0].quadratic", 0.032);
// point light 2
ourShader.setVec3("pointLights[1].position", pointLightPositions[1]);
ourShader.setVec3("pointLights[1].ambient", ambient_light, ambient_light, ambient_light);
ourShader.setVec3("pointLights[1].diffuse", 0.8f, 0.8f, 0.8f);
ourShader.setVec3("pointLights[1].specular", specular_light, specular_light, specular_light);
ourShader.setFloat("pointLights[1].constant", 1.0f);
ourShader.setFloat("pointLights[1].linear", 0.09);
ourShader.setFloat("pointLights[1].quadratic", 0.032);
// point light 3
ourShader.setVec3("pointLights[2].position", pointLightPositions[2]);
ourShader.setVec3("pointLights[2].ambient", ambient_light, ambient_light, ambient_light);
ourShader.setVec3("pointLights[2].diffuse", 0.8f, 0.8f, 0.8f);
ourShader.setVec3("pointLights[2].specular", specular_light, specular_light, specular_light);
ourShader.setFloat("pointLights[2].constant", 1.0f);
ourShader.setFloat("pointLights[2].linear", 0.09);
ourShader.setFloat("pointLights[2].quadratic", 0.032);
// point light 4
ourShader.setVec3("pointLights[3].position", pointLightPositions[3]);
ourShader.setVec3("pointLights[3].ambient", ambient_light, ambient_light, ambient_light);
ourShader.setVec3("pointLights[3].diffuse", 0.8f, 0.8f, 0.8f);
ourShader.setVec3("pointLights[3].specular", specular_light, specular_light, specular_light);
ourShader.setFloat("pointLights[3].constant", 1.0f);
ourShader.setFloat("pointLights[3].linear", 0.09);
ourShader.setFloat("pointLights[3].quadratic", 0.032);
ourShader.setInt("material.skybox", 3);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
//ourShader.setVec3("material.specular", 0.5f, 0.5f, 0.5f);
ourShader.setFloat("material.shininess", 128.0f);
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)screenWidth/ (float)screenHeight, 0.1f, 100.0f);
glm::mat4 view = camera.GetViewMatrix();
ourShader.setMat4("projection", projection);
ourShader.setMat4("view", view);
ourShader.setMat4("model", model);
ourModel.Draw(ourShader);
glBindVertexArray(0);
glDepthFunc(GL_LEQUAL); //深度緩衝將會填充上天空盒的1.0,所以需要保證天空盒在值小於或等於深度緩衝時通過深度測試
skyboxShader.use();
view = glm::mat4(glm::mat3(camera.GetViewMatrix())); //取矩陣左上角得3*3矩陣來移除變換矩陣的位移部分
skyboxShader.setMat4("view", view);
skyboxShader.setMat4("projection", projection);
glBindVertexArray(cubemapVAO);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS);
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_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS)
model = glm::rotate(model, (float)(M_PI/ 360.0), glm::vec3(0.0f, 1.0f, 0.0f));
if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS)
model = glm::rotate(model, (float)(-M_PI / 360.0), glm::vec3(0.0f, 1.0f, 0.0f));
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) // glfwGetKey函數需要一個窗口以及一個按鍵作爲輸入,函數將會返回這個按鍵是否正在被按下
glfwSetWindowShouldClose(window, true);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos) //鼠標回調函數
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; //相反的,因爲y座標是從底部往頂部依次增大的
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) //鼠標滾輪的回調函數
{
camera.ProcessMouseScroll(yoffset);
}
unsigned int loadCubemap(vector<std::string> faces) //創建立方體貼圖
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
模型對應頂點着色器:
#version 330 core
layout(location=0) in vec3 aPos;
layout(location=1) in vec3 aNormal;
layout(location=2) in vec2 aTexCoords;
out vec2 TexCoords;
out vec3 FragPos;
out vec3 Normal;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
TexCoords=aTexCoords;
gl_Position=projection*view*model*vec4(aPos,1.0);
FragPos=vec3(model*vec4(aPos,1.0));
Normal=mat3(transpose(inverse(model)))*aNormal;
}
模型對應片段着色器:
#version 330 core
out vec4 FragColor;
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;
uniform vec3 viewPos;
struct Material{
sampler2D texture_diffuse1;
sampler2D texture_specular1;
sampler2D texture_ambient1;
samplerCube skybox;
float shininess;
};
struct PointLight{
vec3 position;
float constant;
float linear;
float quadratic;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
vec3 CalcPointLight(PointLight light ,vec3 normal,vec3 fragPos,vec3 viewDir);
//uniform Light light;
#define NR_POINT_LIGHTS 4
uniform PointLight pointLights[NR_POINT_LIGHTS];
uniform Material material;
void main()
{
vec3 norm=normalize(Normal);
vec3 viewDir=normalize(viewPos-FragPos);
vec3 R=reflect(-viewDir,norm);
vec3 result=vec3(0.0);
for (int i=0;i<NR_POINT_LIGHTS;i++)
{
result+=CalcPointLight(pointLights[i],norm,FragPos,viewDir);
}
result+=texture(material.skybox,R).rgb*texture(material.texture_ambient1,TexCoords).rgb;
FragColor=vec4(result,1.0);
}
vec3 CalcPointLight(PointLight light,vec3 normal,vec3 fragPos,vec3 viewDir)
{
vec3 lightDir = normalize(light.position - fragPos);
// 漫反射着色
float diff = max(dot(normal, lightDir), 0.0);
// 鏡面光着色
vec3 reflectDir = reflect(-lightDir, normal);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
// 衰減
float distance = length(light.position - fragPos);
float attenuation = 1.0 / (light.constant + light.linear * distance +
light.quadratic * (distance * distance));
// 合併結果
vec3 ambient = light.ambient * vec3(texture(material.texture_diffuse1, TexCoords));
vec3 diffuse = light.diffuse * diff * vec3(texture(material.texture_diffuse1, TexCoords));
vec3 specular=light.specular*spec*vec3(texture(material.texture_specular1,TexCoords));
//vec3 specular=light.specular*spec*vec3(0.5);
ambient *= attenuation;
diffuse *= attenuation;
specular *= attenuation;
return (ambient + diffuse + specular);
}
天空盒頂點着色器:
#version 330 core
layout(location=0)in vec3 aPos;
out vec3 TexCoords;
uniform mat4 projection;
uniform mat4 view;
void main()
{
TexCoords=aPos;
gl_Position=projection*view*vec4(aPos,1.0);
gl_Position=gl_Position.xyww;
}
天空盒片段着色器:
#version 330 core
in vec3 TexCoords;
uniform samplerCube skybox;
out vec4 FragColor;
void main()
{
FragColor=texture(skybox,TexCoords);
}