LearnOpenGL 光照—基础光照—练习题

文章目录

初始代码

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;

uniform mat4 model;	//模型
uniform mat4 view;	//观察
uniform mat4 projection;	//投影

out vec3 Normal;
out vec3 FragPos;

void main()
{
	// 注意乘法要从右向左读
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    Normal = mat3(transpose(inverse(model))) * aNormal;
    FragPos = vec3(model * vec4(aPos, 1.0));
}
#version 330 core

in vec3 Normal;
in vec3 FragPos;

out vec4 FragColor;  

uniform vec3 objectColor;
uniform vec3 lightColor;
uniform vec3 lightPos;
uniform vec3 viewPos;

void main()
{
	//环境光
	float ambientStrength=0.1;
	vec3 ambient=ambientStrength*lightColor;
	//漫反射
	vec3 norm=normalize(Normal);
	vec3 lightDir=normalize(lightPos-FragPos);
	float diff=max(dot(norm,lightDir),0.0);
	vec3 diffuse=diff*lightColor;
	//镜面反射
	float specularStrength=0.5;
	vec3 viewDir=normalize(viewPos-FragPos);
	vec3 reflectDir=reflect(-lightDir,norm);
	float spec=pow(max(dot(reflectDir,viewDir),0.0),32);
	vec3 specular=specularStrength*spec*lightColor;
	//最终结果
	vec3 result=(ambient+diffuse+specular)*objectColor;
	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"
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.vs";
const char* fShaderPath = "ShaderFiles/shader.fs";
//光源着色器
const char* lightvShaderPath = "ShaderFiles/shader.vs";
const char* lightfShaderPath = "ShaderFiles/light_shader.fs";

//混合颜色的插值
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[] = {
		-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
	};

	//顶点缓冲对象 VBO
	//顶点数组对象 VAO
	unsigned int VBO, VAO;
	//渲染物体
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);

	glBindVertexArray(VAO);

	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	//设置顶点属性
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
	glEnableVertexAttribArray(0);
	
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
	glEnableVertexAttribArray(1);

	//光源
	unsigned int lightVAO;
	glGenVertexArrays(1, &lightVAO);
	glBindVertexArray(lightVAO);

	glBindBuffer(GL_ARRAY_BUFFER, VBO);

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
	glEnableVertexAttribArray(0);

	//线框模式
	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	//这些uniform不会更新 可以放到循环外面
	shaderProgram.use();
	shaderProgram.setVec3("objectColor", 1.0f, 0.5f, 0.31f);
	shaderProgram.setVec3("lightColor", 1.0f, 1.0f, 1.0f);
	shaderProgram.setVec3("lightPos", 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);
		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);
}

练习一

目前,我们的光源是静止的,你可以尝试使用sin或cos函数让光源在场景中来回移动。观察光照随时间的改变能让你更容易理解冯氏光照模型。

思路:设当前时间为 t t t,自定义半径 r r r,得到 x = r ∗ c o s t , z = − r ∗ s i n t , y = r / 2 ∗ ( s i n t + c o s t ) x=r*cost,z=-r*sint,y=r/2*(sint+cost) x=r∗cost,z=−r∗sint,y=r/2∗(sint+cost)。

结果:
LearnOpenGL 光照—基础光照—练习题
代码:在循环中增加以下语句,修改一下同名变量的位置即可:

float t = glfwGetTime(), r = 1.5f;
float sint = sinf(t), cost = cosf(t);
glm::vec3 lightPos(r * cost, -r * sint, r / 2 * (sint + cost));

练习二

尝试使用不同的环境光、漫反射和镜面强度,观察它们怎么是影响光照效果的。同样,尝试实验一下镜面光照的反光度因子。尝试理解为什么某一个值能够有着某一种视觉输出。

结果:设 K a 、 K d 、 K s K_a、K_d、K_s Ka​、Kd​、Ks​分别代表环境光、漫反射、镜面反射的强度。

K a = 0.1 , K d = 1.0 , K s = 0.5 K_a=0.1,K_d=1.0,K_s=0.5 Ka​=0.1,Kd​=1.0,Ks​=0.5
LearnOpenGL 光照—基础光照—练习题
K a = 0.8 , K d = 1.0 , K s = 0.5 K_a=0.8,K_d=1.0,K_s=0.5 Ka​=0.8,Kd​=1.0,Ks​=0.5
LearnOpenGL 光照—基础光照—练习题
感觉 K a K_a Ka​增大,物体整体都会变量,和光源的位置无关。

K a = 0.1 , K d = 2.0 , K s = 0.5 K_a=0.1,K_d=2.0,K_s=0.5 Ka​=0.1,Kd​=2.0,Ks​=0.5
LearnOpenGL 光照—基础光照—练习题
感觉 K d K_d Kd​增大,法线和光源夹角<90°的部分会更亮,和光源位置有关。

K a = 0.1 , K d = 1.0 , K s = 1.0 K_a=0.1,K_d=1.0,K_s=1.0 Ka​=0.1,Kd​=1.0,Ks​=1.0
LearnOpenGL 光照—基础光照—练习题

感觉 K s K_s Ks​增大,从反射视角看的部分会更亮,和光源位置、观察位置都有关。

强度不变,反光度因子由32增大到256:
LearnOpenGL 光照—基础光照—练习题
明显看到高光点更加聚集。

练习三

在观察空间(而不是世界空间)中计算冯氏光照。

思路:修改着色器代码即可,注意传递给片段着色器的法向量、位置都要转换到观察坐标。而且光源位置也不能直接传递给uniform变量了(世界坐标系),需要转换到观察坐标系。

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;

uniform mat4 model;	//模型
uniform mat4 view;	//观察
uniform mat4 projection;	//投影
uniform vec3 lightPos;

out vec3 Normal;
out vec3 FragPos;
out vec3 LightPos;

void main()
{
	// 注意乘法要从右向左读
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    Normal = mat3(transpose(inverse(view*model))) * aNormal;
    FragPos = vec3(view * model * vec4(aPos, 1.0));
    LightPos = vec3(view * vec4(lightPos,1.0));
}
#version 330 core

in vec3 Normal;
in vec3 FragPos;
in vec3 LightPos;

out vec4 FragColor;  

uniform vec3 objectColor;
uniform vec3 lightColor;

void main()
{
	//观察空间下
	vec3 viewPos=vec3(0.0,0.0,0.0);
	//环境光
	float ambientStrength=0.1;
	vec3 ambient=ambientStrength*lightColor;
	//漫反射
	float diffuseStrength=1.0;
	vec3 norm=normalize(Normal);
	vec3 lightDir=normalize(LightPos-FragPos);
	float diff=max(dot(norm,lightDir),0.0);
	vec3 diffuse=diffuseStrength*diff*lightColor;
	//镜面反射
	float specularStrength=0.5;
	vec3 viewDir=normalize(viewPos-FragPos);
	vec3 reflectDir=reflect(-lightDir,norm);
	float spec=pow(max(dot(reflectDir,viewDir),0.0),32);
	vec3 specular=specularStrength*spec*lightColor;
	//最终结果
	vec3 result=(ambient+diffuse+specular)*objectColor;
	FragColor=vec4(result,1.0);
}

练习四

尝试实现一个Gouraud着色(而不是冯氏着色)。如果你做对了话,立方体的光照应该会看起来有些奇怪,尝试推理为什么它会看起来这么奇怪。
LearnOpenGL 光照—基础光照—练习题

能较为明显地看到条纹(两个三角形中间的那条线)。

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;

uniform mat4 model;	//模型
uniform mat4 view;	//观察
uniform mat4 projection;	//投影
uniform vec3 lightPos;
uniform vec3 objectColor;
uniform vec3 lightColor;

out vec4 fragColor;

void main()
{
	// 注意乘法要从右向左读
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    vec3 Normal = mat3(transpose(inverse(view*model))) * aNormal;
    vec3 FragPos = vec3(view * model * vec4(aPos, 1.0));
    vec3 LightPos = vec3(view * vec4(lightPos,1.0));
    //观察空间下
	vec3 viewPos=vec3(0.0,0.0,0.0);
	//环境光
	float ambientStrength=0.1;
	vec3 ambient=ambientStrength*lightColor;
	//漫反射
	float diffuseStrength=1.0;
	vec3 norm=normalize(Normal);
	vec3 lightDir=normalize(LightPos-FragPos);
	float diff=max(dot(norm,lightDir),0.0);
	vec3 diffuse=diffuseStrength*diff*lightColor;
	//镜面反射
	float specularStrength=0.5;
	vec3 viewDir=normalize(viewPos-FragPos);
	vec3 reflectDir=reflect(-lightDir,norm);
	float spec=pow(max(dot(reflectDir,viewDir),0.0),32);
	vec3 specular=specularStrength*spec*lightColor;
	//最终结果
	vec3 result=(ambient+diffuse+specular)*objectColor;
	fragColor=vec4(result,1.0);
}
#version 330 core

in vec4 fragColor;
out vec4 FragColor;  

void main()
{
	FragColor=fragColor;
}
上一篇:elasticsearch 6.2.4和elasticsearch-head环境搭建 使用docker-compose方式


下一篇:从0开始的技美实战(十)