一、材質
前面環境光、漫反射光照和鏡面光照都已經安排上了,但是物體的屬性是寫死的
在真實的世界裏,不同的物體會對光產生不同的反應,例如一顆金屬球或一塊橡木,它們在完全相同的光照下顯示出來的效果必然是不同的,前者以反射(Reflect)爲主,後者以散射(Scatter)爲主,如果想在OpenGL中模擬不同的材質,就必須爲每個物體定義材質(Material)屬性,儘管現在還是在用正方體
- ambient:定義了在環境光照下這個物體反射的是什麼顏色,通常是和物體顏色相同的顏色
- diffuse:定義了在漫反射光照下物體的顏色,通常是和物體顏色相同的顏色
- specular:設置的是物體受到的鏡面光照影響的顏色,或者是反射一個物體特定的鏡面高光顏色
- shininess:反光度,值越高,反射光的能力越強,散射得越少,高光點越小
#version 330 core
struct Material
{
vec3 ambient; //環境光
vec3 diffuse; //漫反射光色
vec3 specular; //鏡面光色
float shininess; //反光度
};
爲一個物體賦予一款正確的材質是非常困難的,這需要大量實驗和豐富的經驗,所以由於錯誤的設置材質而毀了物體的畫面質量是件經常發生的事
一樣修改片段着色器設置材質,這個時候不再寫死環境光強度、鏡面強度和反光度
void main()
{
//環境光
vec3 ambient = material.ambient * lightColor;
//漫反射光
vec3 norm = normalize(normalIn);
vec3 lightDir = normalize(lightPos - fragPosIn);
float diff = max(dot(norm, lightDir), 0.0f);
vec3 diffuse = lightColor * (diff * material.diffuse);
//鏡面光
vec3 viewDir = normalize(viewPos - fragPosIn);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = lightColor * (spec * material.specular);
//混合
vec3 result = ambient + diffuse + specular;
color = vec4(result, 1.0f);
}
接下來我們在主代碼中將 ambient 和 diffuse 元素設置成想要讓物體所呈現的顏色,設置 specular 元素爲中等亮度顏色,同樣設置 shininess 爲 32,這樣 specular 元素對這個指定物體就不會產生過於強烈的影響
GLint matAmbientLoc = glGetUniformLocation(shaderObj.Program, "material.ambient");
GLint matDiffuseLoc = glGetUniformLocation(shaderObj.Program, "material.diffuse");
GLint matSpecularLoc = glGetUniformLocation(shaderObj.Program, "material.specular");
GLint matShineLoc = glGetUniformLocation(shaderObj.Program, "material.shininess");
glUniform3f(matAmbientLoc, 1.0f, 0.5f, 0.31f);
glUniform3f(matDiffuseLoc, 1.0f, 0.5f, 0.31f);
glUniform3f(matSpecularLoc, 0.5f, 0.5f, 0.5f);
glUniform1f(matShineLoc, 32.0f);
二、光的屬性
物體有了材質後,接下來再設置光的屬性
- position:位置
- ambient:環境光常數,一般默認爲一個比較小的值,對應之前的 ambientStrength
- diffuse:總是光的顏色,影響漫反射
- specular:全強度發光,影響鏡面反射
struct Light
{
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
uniform Light light;
接下來就是和材質一樣的套路了:
vec3 ambient = light.ambient * material.ambient;
vec3 diffuse = light.diffuse * (diff * material.diffuse);
vec3 specular = light.specular * (spec * material.specular);
一個完整的效果和代碼如下(青色瓷磚材質):
#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 texture;
layout (location = 2) in vec3 normal;
out vec2 texIn;
out vec3 normalIn;
out vec3 fragPosIn;
uniform mat4 model; //模型矩陣
uniform mat4 view; //觀察矩陣
uniform mat4 projection; //投影矩陣
void main()
{
gl_Position = projection * view * model * vec4(position, 1.0);
//texIn = vec2(texture.x, 1.0f - texture.y);
fragPosIn = vec3(model * vec4(position, 1.0f));
normalIn = mat3(transpose(inverse(model))) * normal;
}
/////////////////////////////////////////////////////////////////////////
#version 330 core
struct Material
{
vec3 ambient; //環境光
vec3 diffuse; //漫反射光色
vec3 specular; //鏡面光色
float shininess; //反光度
};
struct Light
{
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
uniform Material material;
uniform Light light;
out vec4 color;
uniform vec3 viewPos;
in vec3 fragPosIn;
in vec2 texIn;
in vec3 normalIn;
uniform sampler2D texOutA;
void main()
{
//環境光
vec3 ambient = light.ambient * material.ambient;
//漫反射光
vec3 norm = normalize(normalIn);
vec3 lightDir = normalize(light.position - fragPosIn);
float diff = max(dot(norm, lightDir), 0.0f);
vec3 diffuse = light.diffuse * (diff * material.diffuse);
//鏡面光
vec3 viewDir = normalize(viewPos - fragPosIn);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * (spec * material.specular);
//混合
vec3 result = ambient + diffuse + specular;
color = vec4(result, 1.0f);
}
main.cpp:
#include<iostream>
#include<opengl/glew.h>
#define GLEW_STATIC
#include<GLFW/glfw3.h>
#include"Camera.h"
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
#include"Shader.h"
#include<opengl/freeglut.h>
#include<SOIL.h>
bool keys[1024];
Camera camera;
GLfloat lastX, lastY;
bool firstMouse = true;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void cameraMove();
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
const GLuint WIDTH = 800, HEIGHT = 600;
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glewExperimental = GL_TRUE;
glewInit();
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
Shader shaderObj("ObjVShader.txt", "ObjFShader.txt");
Shader shaderLight("LightVShader.txt", "L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, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
GLuint VBO, VAO, texture;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenTextures(1, &texture);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBindTexture(GL_TEXTURE_2D, texture);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
/*glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
int picWidth, picHeight;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
unsigned char* image = SOIL_load_image("Texture/wood.jpg", &picWidth, &picHeight, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, picWidth, picHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D, 0);*/
GLuint lightVAO;
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
//VBO數據已經綁定且我們就用之前的頂點數據,所以無需再管理VBO
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_DEPTH_BUFFER_BIT);
cameraMove();
//glBindTexture(GL_TEXTURE_2D, 0);
shaderLight.Use();
lightPos.x = 1.0f + sin(glfwGetTime()) * 2.0f;
lightPos.y = sin(glfwGetTime() / 2.0f) * 1.0f;
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
glm::mat4 model = glm::translate(glm::mat4(1.0f), lightPos);
model = glm::scale(model, glm::vec3(0.2f));
GLint modelLoc = glGetUniformLocation(shaderLight.Program, "model");
GLint viewLoc = glGetUniformLocation(shaderLight.Program, "view");
GLint projLoc = glGetUniformLocation(shaderLight.Program, "projection");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
//glBindTexture(GL_TEXTURE_2D, texture);
shaderObj.Use();
GLint matAmbientLoc = glGetUniformLocation(shaderObj.Program, "material.ambient");
GLint matDiffuseLoc = glGetUniformLocation(shaderObj.Program, "material.diffuse");
GLint matSpecularLoc = glGetUniformLocation(shaderObj.Program, "material.specular");
GLint matShineLoc = glGetUniformLocation(shaderObj.Program, "material.shininess");
glUniform3f(matAmbientLoc, 0.0f, 0.1f, 0.06f);
glUniform3f(matDiffuseLoc, 0.0f, 0.50980392f, 0.50980392f);
glUniform3f(matSpecularLoc, 0.50196078f, 0.50196078f, 0.50196078f);
glUniform1f(matShineLoc, 32.0f);
/*glUniform3f(matAmbientLoc, 1.0f, 0.5f, 0.31f);
glUniform3f(matDiffuseLoc, 1.0f, 0.5f, 0.31f);
glUniform3f(matSpecularLoc, 0.5f, 0.5f, 0.5f);
glUniform1f(matShineLoc, 32.0f);*/
GLint lightPosLoc = glGetUniformLocation(shaderObj.Program, "light.position");
GLint lightAmbientLoc = glGetUniformLocation(shaderObj.Program, "light.ambient");
GLint lightDiffuseLoc = glGetUniformLocation(shaderObj.Program, "light.diffuse");
GLint lightSpecularLoc = glGetUniformLocation(shaderObj.Program, "light.specular");
glUniform3f(lightAmbientLoc, 0.2f, 0.2f, 0.2f);
glUniform3f(lightDiffuseLoc, 1.0f, 1.0f, 1.0f);
glUniform3f(lightSpecularLoc, 1.0f, 1.0f, 1.0f);
glUniform3f(lightPosLoc, lightPos.x, lightPos.y, lightPos.z);
GLint viewPosLoc = glGetUniformLocation(shaderObj.Program, "viewPos");
glUniform3f(viewPosLoc, camera.Position.x, camera.Position.y, camera.Position.z);
model = glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(57.0f), glm::vec3(-0.5f, 1.0f, 0.0f));
modelLoc = glGetUniformLocation(shaderObj.Program, "model");
viewLoc = glGetUniformLocation(shaderObj.Program, "view");
projLoc = glGetUniformLocation(shaderObj.Program, "projection");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
GLfloat deltaTime = 0.0f;
GLfloat lastFrame = 0.0f;
void cameraMove()
{
GLfloat currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
GLfloat cameraSpeed = 1.0f * deltaTime;
if (keys[GLFW_KEY_W])
camera.ProcessKeyboard(Camera_Movement(FORWARD), deltaTime);
if (keys[GLFW_KEY_S])
camera.ProcessKeyboard(Camera_Movement(BACKWARD), deltaTime);
if (keys[GLFW_KEY_A])
camera.ProcessKeyboard(Camera_Movement(LEFT), deltaTime);
if (keys[GLFW_KEY_D])
camera.ProcessKeyboard(Camera_Movement(RIGHT), deltaTime);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (action == GLFW_PRESS) //如果當前是按下操作
keys[key] = true;
else if (action == GLFW_RELEASE) //鬆開鍵盤
keys[key] = false;
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
GLfloat xoffset = xpos - lastX;
GLfloat yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
GLfloat sensitivity = 0.05;
xoffset *= sensitivity;
yoffset *= sensitivity;
camera.ProcessMouseMovement(xoffset, yoffset);
}