OpenGL光线四 opengl光照贴图Lighting Maps

一、从VBO数据中读取贴图的uv坐标
//uv坐标
glVertexAttribPointer(7, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(7);

二、在Material类中添加记录贴图ID的成员变量
unsigned int diffuse;//漫反射贴图id
unsigned int specular;//镜面反射贴图id
unsigned int emission;//自发光贴图id

三、通过loadImageToGPU函数获取贴图id
unsigned int loadImageToGPU(const char* filename, GLint internalFormat, GLenum format, int textureSlot, bool flipped)
{
//上下颠倒texture贴图
stbi_set_flip_vertically_on_load(flipped);
unsigned int TexBuffer;
glGenTextures(1, &TexBuffer);
glActiveTexture(GL_TEXTURE0 + textureSlot);
glBindTexture(GL_TEXTURE_2D, TexBuffer);
int width, height, numChannel;
unsigned char* data = stbi_load(filename, &width, &height, &numChannel, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else {
std::cout << “load image failed0.” << std::endl;
}
stbi_image_free(data);
return TexBuffer;
}

四、将贴图ID绑定到GPU texture槽位上 GL_TEXTURE0 ~ GL_TEXTURE15
//Set Material ->Texture
glActiveTexture(GL_TEXTURE0+Shader::DIFFUSE);
glBindTexture(GL_TEXTURE_2D, myMaterial->diffuse);
glActiveTexture(GL_TEXTURE0+ Shader::SPECULAR);
glBindTexture(GL_TEXTURE_2D, myMaterial->specular);
glActiveTexture(GL_TEXTURE0 + Shader::EMISSION);
glBindTexture(GL_TEXTURE_2D, myMaterial->emission);

五、通过uniform将贴图信息传递到fragmentShader
myMaterial->shader->SetUniform1i(“material.diffuse”, Shader::DIFFUSE);
myMaterial->shader->SetUniform1i(“material.specular”, Shader::SPECULAR);
myMaterial->shader->SetUniform1i(“material.emission”, Shader::EMISSION);
myMaterial->shader->SetUniform1f(“material.shininess”, myMaterial->shininess);

六、在fragmentShader 根据phong lighting model 计算贴图的颜色
vec3 lightDir = normalize(lightPos - FragPos);
vec3 reflectVec =reflect(lightDir,Normal);
vec3 cameraVec = normalize(cameraPos - FragPos);
//specular 镜面反射
float specularAmount = pow(max(dot(reflectVec,cameraVec),0.0f),material.shininess);
vec3 specular = texture(material.specular,TextCoord).rgbspecularAmountlightColor;

//deffuse 漫反射
//vec3 diffuse =material.diffuse * max(dot(lightDir,Normal),0.0f)*lightColor;
vec3 diffuse = texture(material.diffuse,TextCoord).rgb* max(dot(lightDir,Normal),0.0f)*lightColor;

//ambient 环境色
vec3 ambient = texture(material.diffuse,TextCoord).rgb*ambientColor;

//emission 发光色
vec3 emission = texture(material.emission,TextCoord).rgb;

FragColor = vec4((ambient+diffuse+specular)*objColor,1.0f)+vec4(emission,1.0f);

代码Git地址.

你可能感兴趣的:(opengl)