纹理和纹理坐标是两个东西
texture(material.diffuse, TexCoords)这个方法,是从纹理中根据对应的纹理坐标取出对应的颜色值
texture(material.emission, TexCoords).rgb等同于vec3(texture(material.emission,TexCoords))其实就是把vec4转成vec3
vec3 result = ambient + diffuse + specular + emission;也就是说,你可以针对一个物体,对应不同的位置进行专门贴图,只要找到那个对应的纹理的对应的区域的颜色值即可
这个demo中使用的是同一个纹理坐标,其实也可以给各个纹理单独指定坐标
opengl_color_light_picture.cpp
#include <iostream>
#include <cmath>
#include "glad/glad.h"
#include "GLFW/glfw3.h"
#include "utils/Shader.h"
//图片工具库
#include "utils/stb_image.h"
//矩阵工具库
#include "utils/glm/glm.hpp"
#include "utils/glm/gtc/matrix_transform.hpp"
#include "utils/glm/gtc/type_ptr.hpp"
#include "utils/Camera.h"
void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void processInput(GLFWwindow *window);
void loadTexture(unsigned int *texture, const char *path);
unsigned int loadTextureReal(char const * path);
void mouse_callback(GLFWwindow *window, double xpos, double ypos);
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);//相机位置
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);//面对的方向,以这个为尺度更改观看的,其实就是单位速度
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);//头顶的方向
float deltaTime = 0.0f; //当前帧与上一帧的时间差
float lastFrameTime = 0.0f;//上一帧的时间
float lastX = 300;
float lastY = 300;
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
/**
* 顶点数组对象:Vertex Array Object,VAO
* 顶点缓冲对象:Vertex Buffer Object,VBO
* 索引缓冲对象:Element Buffer Object,EBO或Index Buffer Object,IBO
* @return
*/
int main() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_OPENGL_CORE_PROFILE);
//第三个参数是标题
GLFWwindow *window = glfwCreateWindow(600, 600, "LearnOpengl", NULL, NULL);
if (window == NULL) {
std::cout << "Fail to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
//奇特的写法,本应是个函数,写出来却像个变量,连参数都不需要传了
if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
std::cout << "File to initialize GLAD" << std::endl;
return -1;
}
//使窗口隐藏光标并且捕捉它
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
//使用回调
glfwSetCursorPosCallback(window, mouse_callback);
glViewport(0, 0, 600, 600);//指定视口大小,跟java一样
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetScrollCallback(window, scroll_callback);
//加载纹理
unsigned int diffuseMap, diffuse_specular_Map, matrixMap;
const char *path1 = "D:\\cl_workspace\\TestOpengl\\resource\\container2.jpg";
const char *path2 = "D:\\cl_workspace\\TestOpengl\\resource\\container2_specular.png";
const char *path3 = "D:\\cl_workspace\\TestOpengl\\resource\\matrix.jpg";
// //两个都要传递引用,这样函数更改的值才是上面的值
// loadTexture(&diffuseMap, path1);
// loadTexture(&diffuse_specular_Map, path2);
// loadTexture(&matrixMap, path3);
diffuseMap = loadTextureReal(path1);
diffuse_specular_Map = loadTextureReal(path2);
matrixMap = loadTextureReal(path3);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffuseMap);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, diffuse_specular_Map);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, matrixMap);
//箱子
Shader lightingShader("D:\\cl_workspace\\TestOpengl\\shader\\vertex_shader_6.glsl",
"D:\\cl_workspace\\TestOpengl\\shader\\fragment_shader_6.glsl");
//光源
Shader lampShader("D:\\cl_workspace\\TestOpengl\\shader\\vertex_shader_4.glsl",
"D:\\cl_workspace\\TestOpengl\\shader\\fragment_shader_4.glsl");
//立方体
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, 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, 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, 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, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
//创建VBO,绑定数据,绑定VAO
//明白了,VBO顶点缓冲区,是用来存放数据的,而VAO是调用数据的索引
unsigned int cubeVAO;
glGenVertexArrays(1, &cubeVAO);
glBindVertexArray(cubeVAO);
unsigned int VBO;
glGenBuffers(1, &VBO);//&符号应该是传引用对象的意思,不然会传值进去
glBindBuffer(GL_ARRAY_BUFFER, VBO);//这一步就是给GL_ARRAY_BUFFER绑定数据了
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//做的时间长,反而忘了。。。这是给着色器里面的某个location设置值的
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);
//当调用glBindVertexArray(lightVAO)后,再调用glBindBuffer(GL_ARRAY_BUFFER, VBO)
//相当于把缓冲区中的数据设置给了lightVAO,上面的顺序一定不能变
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);
//循环绘制
while (!glfwWindowShouldClose(window)) {//判断界面是否关闭,没关闭就循环绘制
processInput(window);
//记录deltaTime
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrameTime;
lastFrameTime = currentFrame;
//同java
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//如果开启了深度测试,这里就要把GL_DEPTH_BUFFER_BIT也清空
//让光源随着时间的变化而改变位置
// lightPos = glm::vec3(1.2f * sin(glfwGetTime()), 1.0f * sin(glfwGetTime()), 2.0f);
glm::vec3 lightColor;
lightColor.x = sin(glfwGetTime() * 2.0f);
lightColor.y = sin(glfwGetTime() * 0.7f);
lightColor.z = sin(glfwGetTime() * 1.3f);
glm::vec3 diffuseColor = lightColor * glm::vec3(0.5f);//降低影响
glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f);//环境光,更低
//开启深度测试
glEnable(GL_DEPTH_TEST);
//lighting其实是物体。。。
lightingShader.use();
lightingShader.setVec3("lightPos", lightPos);//光源位置
lightingShader.setVec3("viewPos", camera.Position);//观察位置
//设置各个光照的强度
// lightingShader.setVec3("light.ambient", ambientColor);
// lightingShader.setVec3("light.diffuse", diffuseColor);
lightingShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
lightingShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);//镜面反射
lightingShader.setInt("material.diffuse", 0);//绑定纹理?用0即可,0对应GL_TEXTURE0
lightingShader.setInt("material.specular", 1);//绑定纹理?用1即可,1对应GL_TEXTURE1
lightingShader.setInt("material.emission", 2);
// lightingShader.setVec3("material.specular", 0.5f, 0.5f, 0.5f);
lightingShader.setFloat("material.shininess", 64.0f);
glm::mat4 model = glm::mat4();
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), 1.0f, 0.1f, 100.0f);
glm::mat4 view = camera.GetViewMatrix();
lightingShader.setMat4("model", model);
lightingShader.setMat4("view", view);
lightingShader.setMat4("projection", projection);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
lampShader.use();
lampShader.setMat4("view", view);
lampShader.setMat4("projection", projection);
model = glm::mat4();
model = glm::translate(model, lightPos);
model = glm::scale(model, glm::vec3(0.2f));
lampShader.setMat4("model", model);
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
//双缓冲机制,前缓冲保存着最终输出的图像,后缓冲则进行绘制,绘制完成以后与前缓冲交换,就会立即显示
//单缓冲会存在闪烁问题
glfwSwapBuffers(window);//交换颜色缓冲
glfwPollEvents();//检查有没有什么触发事件,鼠标键盘等,并调用相关的回调
}
//回收数据
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &lightVAO);
glDeleteBuffers(1, &VBO);
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_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
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);
}
//*代表引用传递,传参数时要用&符号,而取*里的值则需要*p
void loadTexture(unsigned int *texture, const char *path) {
glGenTextures(1, texture);
// 对*p赋值,从而改变p所指的地址上说保存的值
//*textrue就能表示这个内存地址上表示的值
glBindTexture(GL_TEXTURE_2D, *texture);//GL_TEXTURE_2D同样,它也是一个目标
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);
//加载纹理,第三个参数是颜色通道的个数
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true);
//图片
unsigned char *data = stbi_load(path, &width,
&height, &nrChannels, 0);
//第二个参数为多级渐远纹理的级别,0为基本级别,第三个参数为指定纹理存储为何种格式
//第六个总是设置为0,第七第八定义源图的格式和数据类型
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
//释放图像内存
stbi_image_free(data);
}
unsigned int loadTextureReal(char const *path) {
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data) {
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
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_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
} else {
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
bool firstMouse = 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; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
//滚轮的回调
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
camera.ProcessMouseScroll(yoffset);
}
fragment_shader_6.glsl
#version 330 core
out vec4 FragColor;
uniform vec3 lightPos;
uniform vec3 viewPos;
in vec3 Normal;
in vec3 FragPos;
struct Material {
//环境光颜色几乎在所有情况下都等于漫反射颜色,所以不需要环境光,只用漫反射即可
// vec3 ambient;//环境光,一般是物体颜色
// vec3 diffuse;//漫反射光照下物体的颜色
sampler2D diffuse;
// vec3 specular;//镜面光照对物体的颜色影响
sampler2D specular;
sampler2D emission;//放射光的贴图
float shininess;//反光度
};
//一个光源对它的ambient、diffuse和specular光照有着不同的强度
struct Light {
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
//之前都是用灯光来设定环境光,漫反射光和镜面反射光,现在我们要分开设置这些材质
uniform Material material;
uniform Light light;
//上面用两个纹理,下面用一个接收?并不是,这个是纹理的坐标
//而纹理的对象,是设置给了Light结构体里的diffuse和specular
in vec2 TexCoords;
void main() {
//环境光,现在设置为与漫反射同样的值
vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));
//漫反射,先对向量进行标准化
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);//光的方向向量是光源位置与片段位置之间的向量差
//依据法向量计算光源对当前片段的漫反射影响
float diff = max(dot(norm, lightDir),0.0);//点积,算出来的是投影长度,夹角越小,越接近1,越亮
vec3 diffuse = light.diffuse * (diff * vec3(texture(material.diffuse, TexCoords)));//混合纹理
//镜面反射
vec3 viewDir = normalize(viewPos - FragPos);//片段位置到摄像机位置的向量,也就是视线方向
//反射向量,reflect函数要求第一个向量是从光源指向片段位置的向量
vec3 reflectDir = reflect(-lightDir,norm);
//点乘,避免负值,取32次幂,32是高光的反光度,这个点乘肯定小于1,32次方,那就更小了
//一个物体的反光度越高,反射光的能力越强,散射得越少,高光点就会越小,可以理解
//反光度material.shininess,必须是float类型,否则报错
//镜面光贴图我们可以可以对物体设置大量的细节,比如物体的哪些部分需要有闪闪发光的属性,我们甚至可以设置它们对应的强度。
//镜面光贴图能够在漫反射贴图之上给予我们更高一层的控制
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * (spec * vec3(texture(material.specular,TexCoords)));
//放射光贴图,这个.rgb跟前面的vec3()转是一个效果,都是把vec4转成vec3
vec3 emission = texture(material.emission, TexCoords).rgb;
//将环境光,漫反射光,镜面反射光作用于物体
vec3 result = ambient + diffuse + specular + emission;
//混合两个光照颜色
FragColor = vec4(result, 1.0);
}
vertex_shader_6.glsl
#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);
FragPos = vec3(model * vec4(aPos,1.0));
//把法向量也转换为世界空间坐标,所以需要一个法线矩阵
//由于我们只在世界空间中进行操作(不是在观察空间),我们只使用模型矩阵
//使用inverse和transpose函数修改model生成这个法线矩阵,必须是3x3的
mat3 normalMatrix = mat3(transpose(inverse(model)));
Normal = normalMatrix * aNormal;
TexCoords = aTexCoords;
}
网友评论