初始代码
l i g h t s h a d e r : light\ shader: light shader:
#version 330 core
layout (location = 0) in vec3 aPos;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPos,1.0);
}
#version 330 core
out vec4 FragColor;
void main()
{
FragColor = vec4(1.0); 将向量的四个分量全部设置为1.0
}
o b j e c t s h a d e r : object\ shader: object shader:
#version 330 core
layout (location = 0) in vec3 aPos; // 位置变量的属性位置值为 0
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
uniform mat4 model; //模型
uniform mat4 view; //观察
uniform mat4 projection; //投影
out vec3 Normal;
out vec3 FragPos;
out vec2 TexCoords;
void main()
{
// 注意乘法要从右向左读
gl_Position = projection * view * model * vec4(aPos, 1.0);
Normal = mat3(transpose(inverse(model))) * aNormal;
FragPos = vec3(model * vec4(aPos, 1.0));
TexCoords = aTexCoords;
}
#version 330 core
struct Material
{
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct Light
{
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;
out vec4 FragColor;
uniform Material material;
uniform Light light;
uniform vec3 viewPos;
void main()
{
//环境光
vec3 ambient = light.ambient * vec3(texture(material.diffuse,TexCoords));
//漫反射
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(light.position - FragPos);
float diff = max(dot(norm,lightDir),0.0);
vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse,TexCoords));
//镜面反射
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir,norm);
float spec = pow(max(dot(reflectDir,viewDir),0.0),material.shininess);
vec3 specular = light.specular * spec * vec3(texture(material.specular,TexCoords));
//最终结果
vec3 result = ambient + diffuse + specular;
FragColor = vec4(result,1.0);
}
c p p : cpp: cpp:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include "shader.h"
#include "stb_image.h"
#include "camera.h"
#include "texture.h"
using std::cout;
//窗口回调函数
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
//绘图视口 3D坐标到2D坐标的转换(映射)和这些参数(宽高)有关
glViewport(0, 0, width, height);
}
//键盘回调
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
//鼠标回调
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
//滚轮回调
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
//窗口初始大小
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
//物体着色器
const char* vShaderPath = "ShaderFiles/shader.vert";
const char* fShaderPath = "ShaderFiles/shader.frag";
//光源着色器
const char* lightvShaderPath = "ShaderFiles/light_shader.vert";
const char* lightfShaderPath = "ShaderFiles/light_shader.frag";
//混合颜色的插值
float mixValue = 0.2f;
//记录鼠标坐标
float lastX, lastY;
bool firstMouse = true;
//摄像机
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
//光源位置
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
int main()
{
//glfw初始化
glfwInit();
//告诉glfw我们所使用的opengl版本 此处为3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//创建窗口
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
cout << "Failed to create GLFW window\n";
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
//设置窗口回调函数
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
//键盘回调函数
glfwSetKeyCallback(window, key_callback);
//鼠标回调
glfwSetCursorPosCallback(window, mouse_callback);
//滚轮回调
glfwSetScrollCallback(window, scroll_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
cout << "Failed to initialize GLAD\n";
return -1;
}
//开启深度测试
glEnable(GL_DEPTH_TEST);
//着色器对象
Shader shaderProgram = Shader(vShaderPath, fShaderPath);
Shader lightShaderProgram = Shader(lightvShaderPath, lightfShaderPath);
float vertices[] = {
// positions // normals // texture coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 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VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//设置顶点属性
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
//光源
unsigned int lightVAO;
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//漫反射贴图
Texture diffuseTexture("diffuseTexture", "Images/container2_diffuse.png");
//镜面光贴图
//Texture specularTexture("specuTexture", "Images/container2_specular.png");
Texture specularTexture("specuTexture", "Images/lighting_maps_specular_color.png");
//线框模式
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//这些uniform不会更新 可以放到循环外面
shaderProgram.use();
shaderProgram.setInt("material.diffuse", diffuseTexture.getTextureUnitID());
shaderProgram.setInt("material.specular", specularTexture.getTextureUnitID());
shaderProgram.setFloat("material.shininess", 64.0f);
shaderProgram.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
shaderProgram.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
shaderProgram.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
shaderProgram.setVec3("light.position", lightPos);
while (!glfwWindowShouldClose(window))
{
glClearColor(0.1f, 0.1f, 0.1f, 0.1f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//矩阵运算
glm::mat4 lightModel(1.0f);
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::perspective(glm::radians(camera.Fov), SCR_WIDTH * 1.0f / SCR_HEIGHT, 0.1f, 100.0f);
//激活着色器
shaderProgram.use();
shaderProgram.setVec3("viewPos", camera.Position);
shaderProgram.setMat4("model", lightModel);
shaderProgram.setMat4("view", view);
shaderProgram.setMat4("projection", projection);
//贴图
diffuseTexture.use();
specularTexture.use();
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
//光源着色器
lightShaderProgram.use();
lightModel = glm::translate(lightModel, lightPos);
lightModel = glm::scale(lightModel, glm::vec3(0.2f));
lightShaderProgram.setMat4("model", lightModel);
lightShaderProgram.setMat4("view", view);
lightShaderProgram.setMat4("projection", projection);
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glfwSwapBuffers(window);
glfwPollEvents();
}
//这一步是可选的
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
//glDeleteBuffers(1, &EBO);
//释放资源
glfwTerminate();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (action == GLFW_REPEAT || action == GLFW_PRESS)
{
if (key == GLFW_KEY_ESCAPE)
{
glfwSetWindowShouldClose(window, GL_TRUE);
return;
}
switch (key)
{
case GLFW_KEY_UP:
mixValue += 0.1f;
if (mixValue >= 1.0f)
mixValue = 1.0f;
break;
case GLFW_KEY_DOWN:
mixValue -= 0.1f;
if (mixValue <= 0.0f)
mixValue = 0.0f;
break;
case GLFW_KEY_W:
camera.ProcessKeyboard(FORWARD);
break;
case GLFW_KEY_S:
camera.ProcessKeyboard(BACKWARD);
break;
case GLFW_KEY_A:
camera.ProcessKeyboard(LEFT);
break;
case GLFW_KEY_D:
camera.ProcessKeyboard(RIGHT);
break;
default:
break;
}
}
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
firstMouse = false;
lastX = xpos, lastY = ypos;
}
camera.ProcessMouseMovement(xpos - lastX, lastY - ypos);
lastX = xpos;
lastY = ypos;
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
注:若要查看封装的类的代码,请看我的其他博客。
练习一
调整光源的环境光、漫反射和镜面光向量,看看它们如何影响箱子的视觉输出。
shaderProgram.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
shaderProgram.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
shaderProgram.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
增大环境光。
shaderProgram.setVec3("light.ambient", 1.0f, 1.0f, 1.0f);
shaderProgram.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
shaderProgram.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
增大漫反射光。
shaderProgram.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
shaderProgram.setVec3("light.diffuse", 1.0f, 1.0f, 1.0f);
shaderProgram.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
增大镜面反射光。
shaderProgram.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
shaderProgram.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
shaderProgram.setVec3("light.specular", 3.0f, 3.0f, 3.0f);
练习二
尝试在片段着色器中反转镜面光贴图的颜色值,让木头显示镜面高光而钢制边缘不反光(由于钢制边缘中有一些裂缝,边缘仍会显示一些镜面高光,虽然强度会小很多)。
修改object的片段着色器即可:
#version 330 core
struct Material
{
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct Light
{
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;
out vec4 FragColor;
uniform Material material;
uniform Light light;
uniform vec3 viewPos;
void main()
{
//环境光
vec3 ambient = light.ambient * vec3(texture(material.diffuse,TexCoords));
//漫反射
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(light.position - FragPos);
float diff = max(dot(norm,lightDir),0.0);
vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse,TexCoords));
//镜面反射
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir,norm);
float spec = pow(max(dot(reflectDir,viewDir),0.0),material.shininess);
//vec3 specular = light.specular * spec * vec3(texture(material.specular,TexCoords));
vec3 specular = light.specular * spec * (vec3(1.0) - vec3(texture(material.specular,TexCoords)));
//最终结果
vec3 result = ambient + diffuse + specular;
FragColor = vec4(result,1.0);
}
练习三
使用漫反射贴图创建一个彩色而不是黑白的镜面光贴图,看看结果看起来并不是那么真实了。如果你不会生成的话,可以使用这张彩色的镜面光贴图。
//镜面光贴图
//Texture specularTexture("specuTexture", "Images/container2_specular.png");
Texture specularTexture("specuTexture", "Images/lighting_maps_specular_color.png");
练习四
添加一个叫做放射光贴图(Emission Map)的东西,它是一个储存了每个片段的发光值(Emission Value)的贴图。发光值是一个包含(假设)光源的物体发光(Emit)时可能显现的颜色,这样的话物体就能够忽略光照条件进行发光(Glow)。游戏中某个物体在发光的时候,你通常看到的就是放射光贴图(比如 机器人的眼,或是箱子上的灯带)。将这个纹理(作者为 creativesam)作为放射光贴图添加到箱子上,产生这些字母都在发光的效果。
首先修改object的片段着色器:
#version 330 core
struct Material
{
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct Light
{
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;
out vec4 FragColor;
uniform Material material;
uniform Light light;
uniform vec3 viewPos;
uniform sampler2D EmissionMap;
void main()
{
//环境光
vec3 ambient = light.ambient * vec3(texture(material.diffuse,TexCoords));
//漫反射
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(light.position - FragPos);
float diff = max(dot(norm,lightDir),0.0);
vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse,TexCoords));
//镜面反射
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir,norm);
float spec = pow(max(dot(reflectDir,viewDir),0.0),material.shininess);
vec3 specular = light.specular * spec * vec3(texture(material.specular,TexCoords));
//放射光
vec3 emission = texture(EmissionMap,TexCoords).xyz;
//最终结果
vec3 result = ambient + diffuse + specular + emission;
FragColor = vec4(result,1.0);
}
然后在main.cpp中修改以下几处代码:
//放射光贴图
Texture emissionTexture("emissionTexture", "Images/emission_map.jpg");
……
shaderProgram.setInt("EmissionMap", emissionTexture.getTextureUnitID());
……
emissionTexture.use();
其实就是多了一个放射光嘛。