欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

材质

程序员文章站 2022-06-10 21:12:43
...

描述物体的时候,我们可以使用3种光照元素:环境光照(Ambient Lighting)、漫反射光照(Diffuse Lighting)、镜面光照(Specular Lighting)定义一个材质颜色。通过为每个元素指定一个颜色,我们已经对物体的颜色输出有了精密的控制。现在把一个镜面高光元素添加到这三个颜色里
1.片段着色器中添加材质结构体

struct Materail
{
	vec3 ambient;
	vec3 diffuse;
	vec3 specular;
	float shininess;
};

uniform Materail materail;

2.用材质的属性对之前计算的光照进行运算

vec3 lightDir = normalize(lightPos-FragPos);
float diff = max(dot(lightDir,Normal),0);
vec3 diffuse = materail.diffuse*diff*lightColor;

vec3 reflrctVec = reflect(-lightDir,Normal);
vec3 cameraVec = normalize(cameraPos-FragPos);
float specularAmount = pow(max(dot(reflrctVec,cameraVec),0),materail.shininess);
vec3 specular = materail.specular*specularAmount*lightColor;

vec3 ambient = materail.ambient*ambientColor;

  //FragColor = vec4(objColor*ambientColor,1.0f);
FragColor = vec4((diffuse+ambientColor+specular)*objColor,1.0f);

3.封装材质类

#include "Shader.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

class Material
{
public:
	glm::vec3 ambient;
	glm::vec3 diffuse;
	glm::vec3 specular;
	float shininess;
	Shader *shader;

	Material(Shader* _shader, glm::vec3 _ambient,glm::vec3 _diffuse,glm::vec3 _specualr,float _shininess);
	~Material();
};
#include "Material.h"



Material::Material(Shader * _shader, glm::vec3 _ambient, glm::vec3 _diffuse, glm::vec3 _specualr, float _shininess)
{
	shader = _shader;
	ambient = _ambient;
	diffuse = _diffuse;
	specular = _specualr;
	shininess = _shininess;
}

Material::~Material()
{
}

4.shader类增加设置uniform参数方法

void Shader::SetUniform3f(const char* paramNameString, glm::vec3 param)
{
	glUniform3f(glGetUniformLocation(ID, paramNameString), param.x, param.y, param.z);
}

void Shader::SetUniform1f(const char* paramNameString, float param)
{
	glUniform1f(glGetUniformLocation(ID, paramNameString), param);
}

5.传入gpu操作

Material material =  Material(&shader, glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f),32);
material.shader->SetUniform3f("material.ambient", material.ambient);
material.shader->SetUniform3f("material.diffuse", material.diffuse);
material.shader->SetUniform3f("material.specular", material.specular);
material.shader->SetUniform1f("material.shininess", material.shininess);
相关标签: opengl