本文参考LearnOpenGL CN
在现实世界中,每个物体会对光产生不同的反应。比如:钢看起来通常会比陶瓷瓶更闪闪发光,木头箱子也不会像钢制箱子那样对光产生很强的反射。每个梧桐对镜面高光也有不同的反应。有些物体反射光的时候不会有太多的散射,因而产生一个较小的高光点,而有些物体则会散射很多,产生一个有着更大半径的高光点。如果我们想要在OPenGL中模拟多种类型的物体,我们必须为每个物体分别定义一个材质属性。
上一节指定了一个物体和光的颜色,以及结合环境光和镜面强度分量,来定义物体的视觉输出。当描述一个物体的时候,我们可以定义一个材质颜色(Material Color):环境光照(Ambient Lighting),漫反射光照(Diffuse Lighting)和镜面光照(Specular Lighting).通过为每个分量指定一个颜色,再加上高光系数shininess,我们就能够对物体的颜色输出有着精细的控制了。整个材质在片元着色器中的定义为如下所示的结构体:
#version 330 core
struct Material{
vec3 ambient;
vec3 diffuse;
vec3 specular;
float shininess;
};
uniform Material material;
上述结构体中,ambient材质向量定义了在环境光照下这个物体反射得什么颜色,通常这是和物体颜色相同的颜色。
diffuse材质向量定义了在漫反射光照下物体的颜色。(和环境光照一样)蛮烦设颜色也要设置为我们需要的物体颜色。
specualr材质向量设置的是镜面光照对物体的颜色影响(或者甚至可能反射一个物体特定的镜面高光颜色)
shininess影响镜面高光的散射/半径。
设置材质
void main()
{
// 环境光
vec3 ambient = lightColor * material.ambient;
// 漫反射
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = lightColor * (diff * material.diffuse);
// 镜面光
vec3 viewDir = normalize(viewPos - FragPos);
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;
FragColor = vec4(result, 1.0);
}
在main函数中使用分量来设置属性各个部分的实现:
glUniform3f(glGetUniformLocation(ourShader->ID, "material.ambient"), 0.2f,0.1f,0.0f);
glUniform3f(glGetUniformLocation(ourShader->ID, "material.diffuse"), 10.0f, 10.0f, -5.0f);
glUniform3f(glGetUniformLocation(ourShader->ID, "material.specular"), 1.0f, 0.5f, 0.31f);
glUniform1f(glGetUniformLocation(ourShader->ID, "material.shininess"), 32,0f);
将环境光和漫反射分量设置成我们想让物体拥有的颜色,而将镜面分量设置为一个中等亮度的颜色,我们不希望镜面分量在这个物体上过于强烈。我们将反光度保持为32。
材质类
Material.h
#include "Material.h"
Material::Material(Shader * _shader, glm::vec3 _diffuse, glm::vec3 _specular, glm::vec3 _ambient, float _shininess)
:shader(_shader),
diffuse(_diffuse),
specular(_specular),
ambient(_ambient),
shininess(_shininess)
{
}
Material::~Material()
{
}
Material.cpp
#pragma once
#include"Shader.h"
#include
#include
#include
class Material
{
public:
Shader *shader;
glm::vec3 diffuse;
glm::vec3 specular;
glm::vec3 ambient;
float shininess;
Material(Shader* _shader,glm::vec3 _diffuse,glm::vec3 _specular,glm::vec3 _ambient,float _shininess);
~Material();
};
在shader.h中添加函数
void SetUniform3f(const char* paramNameString, glm::vec3 param);
void SetUniform1f(const char* paraNameString, float param);
shader.cpp中
void Shader::SetUniform3f(const char * paramNameString, glm::vec3 param)
{
glUniform3f(glGetUniformLocation(ID, paramNameString), param.x,param.y,param.z);
}
void Shader::SetUniform1f(const char * paraNameString, float param)
{
glUniform1f(glGetUniformLocation(ID, paraNameString), param);
}
fragmentSource.txt
#version 330 core
struct Material{
vec3 ambient;
vec3 diffuse;
vec3 specular;
float shininess;
};
in vec3 FragPos;
in vec3 Normal;
uniform vec3 objColor;
uniform vec3 ambientColor;
uniform vec3 lightPos;
uniform vec3 lightColor;
uniform vec3 CameraPos;
uniform Material material;
out vec4 FragColor;
void main()
{
vec3 lightDir = normalize(lightPos-FragPos);
vec3 reflectVec = reflect(-lightDir,Normal);
vec3 CameraVec = normalize(CameraPos-FragPos);
//specular
float specularAmount = pow(max(dot(reflectVec,CameraVec),0),material.shininess);
vec3 specular = material.specular * specularAmount * lightColor;
//diffuse
vec3 diffuse =material.diffuse * max( dot(lightDir,Normal),0) * lightColor;
//ambient
vec3 ambient = material.ambient*ambientColor;
FragColor = vec4((diffuse + ambient + specular) * objColor,1.0);
}
VertexSource.txt
#version 330 core
layout (location = 0) in vec3 aPos;
layout(location = 3) in vec3 aNormal;
uniform mat4 modelMat;
uniform mat4 viewMat;
uniform mat4 projMat;
//out vec2 TexCoord;
//out vec4 vertexColor;
out vec3 FragPos;
out vec3 Normal;
void main()
{
gl_Position = projMat * viewMat * modelMat * vec4(aPos, 1.0);
FragPos= (modelMat * vec4(aPos.xyz,1.0)).xyz;
Normal = mat3(transpose(inverse(modelMat)))* aNormal;
}
main函数
#include
#include
#include
#include"Shader.h"
#include"Camera.h"
#include
#include
#include
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include"Material.h"
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT =600;
#pragma region Camera Declare
Camera camera(glm::vec3(0, 0, 3.0f), glm::radians(-15.0f), glm::radians(180.0f), glm::vec3(0, 1.0f, 0));
#pragma endregion
#pragma region Input Declare
float lastX;
float lastY;
bool firstMouse = true;
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
camera.speedZ = 0.1f;
}
else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
camera.speedZ = -0.1f;
}
else
{
camera.speedZ = 0;
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
camera.speedX = 0.1f;
}
else if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
camera.speedX = -0.1f;
}
else
{
camera.speedX = 0;
}
}
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
{
camera.speedY = -0.1f;
}
else if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
{
camera.speedY = 0.1f;
}
else
{
camera.speedY = 0;
}
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse == true)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float deltaX, deltaY;
deltaX = xpos - lastX;
deltaY = ypos - lastY;
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(deltaX, deltaY);
}
#pragma endregion
unsigned int LoadImageToGPU(const char*filename, GLint internalformat, GLenum format, int textureSlot)
{
unsigned int texBuffer;
glGenTextures(1, &texBuffer);
glActiveTexture(GL_TEXTURE0 + textureSlot);
glBindTexture(GL_TEXTURE_2D, texBuffer);
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
unsigned char *data = stbi_load(filename, &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, internalformat, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
return texBuffer;
}
int main()
{
#pragma region Open a window
// 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(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// configure global opengl state
// -----------------------------
glEnable(GL_DEPTH_TEST);
#pragma endregion
#pragma region Model Data
GLfloat vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.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,
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
};
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
#pragma endregion
#pragma region Init Shader Pragram
Shader *ourShader = new Shader("VertexSource.vert", "fragmentSource.frag");
#pragma region Init Material
Material* myMaterial = new Material(ourShader,
glm::vec3(1.0f, 0.5f, 0.31f),
glm::vec3(1.0f, 0.5f, 0.31f),
glm::vec3(0, 1.0f, 0),
32.0f);
#pragma endregion
#pragma endregion
#pragma region Init and Load Models to VAO,VBO
unsigned int VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
unsigned int VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(3);
#pragma endregion
#pragma region Init and Load Texture
unsigned int texBufferA;
texBufferA = LoadImageToGPU("container.jpg",GL_RGB,GL_RGB,0);
unsigned int texBufferB;
texBufferB = LoadImageToGPU("awesomeface.png",GL_RGBA, GL_RGBA, 1);
#pragma endregion
// tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
// -------------------------------------------------------------------------------------------
#pragma region Prepare MVP matrices
glm::mat4 modelMat;
glm::mat4 viewMat;
glm::mat4 projMat;
projMat = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
#pragma endregion
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
processInput(window);
// clear srceen
glClearColor(0, 0, 0, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now!
viewMat = camera.GetViewMatrix();
for (unsigned int i = 0; i < 10; i++)
{
//set Model Matrix
modelMat = glm::translate(glm::mat4(1.0f), cubePositions[i]);
//set View and Project Matrices here
//set Material->shader program
ourShader->use();
//set Material->textures
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texBufferA);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texBufferB);
//set material->uniforms
/* glUniform1i(glGetUniformLocation(ourShader.ID, "ourTexture"), 0);
glUniform1i(glGetUniformLocation(ourShader.ID, "ourFace"), 1);*/
unsigned int modelLoc = glGetUniformLocation(ourShader->ID, "modelMat");
unsigned int viewLoc = glGetUniformLocation(ourShader->ID, "viewMat");
unsigned int projectLoc = glGetUniformLocation(ourShader->ID, "projMat");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(modelMat));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(viewMat));
glUniformMatrix4fv(projectLoc, 1, GL_FALSE, glm::value_ptr(projMat));
glUniform3f(glGetUniformLocation(ourShader->ID, "objColor"), 1.0f, 0.5f, 0.31f);
glUniform3f(glGetUniformLocation(ourShader->ID, "ambientColor"), 0.2f,0.1f,0.0f);
glUniform3f(glGetUniformLocation(ourShader->ID, "lightPos"), 10.0f, 10.0f, -5.0f);
glUniform3f(glGetUniformLocation(ourShader->ID, "lightColor"), 1.0f, 1.0f, 1.0f);
glUniform3f(glGetUniformLocation(ourShader->ID, "CameraPos"), camera.Position.x, camera.Position.y, camera.Position.z);
myMaterial->shader->SetUniform3f("material.ambient", myMaterial->ambient);
myMaterial->shader->SetUniform3f("material.diffuse", myMaterial->diffuse);
myMaterial->shader->SetUniform1f("material.shininess", myMaterial->shininess);
// set Model
glBindVertexArray(VAO);
//Drawcall
glDrawArrays(GL_TRIANGLES, 0, 36);
}
//Clean up,prepare for next render loop
glfwSwapBuffers(window);
glfwPollEvents();
camera.UpdataCameraPos();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}