# OpenGL核心技术之法线贴图

3D引擎 同时被 3 个专栏收录
154 篇文章 15 订阅
97 篇文章 10 订阅
16 篇文章 85 订阅

CSDN视频网址：http://edu.csdn.net/lecturer/144

vec3 rgb_normal = normal * 0.5 + 0.5; // 从 [-1,1] 转换至 [0,1]

uniform sampler2D normalMap;

void main()
{
// 从法线贴图范围[0,1]获取法线
normal = texture(normalMap, fs_in.TexCoords).rgb;
// 将法线向量转换为范围[-1,1]
normal = normalize(normal * 2.0 - 1.0);

[...]
// 像往常那样处理光照
}

#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texCoords;

// Declare an interface block; see 'Advanced GLSL' for what these are.
out VS_OUT {
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
} vs_out;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main()
{
gl_Position = projection * view * model * vec4(position, 1.0f);
vs_out.FragPos = vec3(model * vec4(position, 1.0));
vs_out.TexCoords = texCoords;

mat3 normalMatrix = transpose(inverse(mat3(model)));
vs_out.Normal = normalMatrix * normal;
}

#version 330 core
out vec4 FragColor;

in VS_OUT {
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
} fs_in;

uniform sampler2D diffuseMap;
uniform sampler2D normalMap;

uniform vec3 lightPos;
uniform vec3 viewPos;
uniform bool normalMapping;

void main()
{
vec3 normal = normalize(fs_in.Normal);
if(normalMapping)
{
// Obtain normal from normal map in range [0,1]
normal = texture(normalMap, fs_in.TexCoords).rgb;
// Transform normal vector to range [-1,1]
normal = normalize(normal * 2.0 - 1.0);
}
// Get diffuse color
vec3 color = texture(diffuseMap, fs_in.TexCoords).rgb;
// Ambient
vec3 ambient = 0.1 * color;
// Diffuse
vec3 lightDir = normalize(lightPos - fs_in.FragPos);
float diff = max(dot(lightDir, normal), 0.0);
vec3 diffuse = diff * color;
// Specular
vec3 viewDir = normalize(viewPos - fs_in.FragPos);
vec3 reflectDir = reflect(-lightDir, normal);
vec3 halfwayDir = normalize(lightDir + viewDir);
float spec = pow(max(dot(normal, halfwayDir), 0.0), 32.0);
vec3 specular = vec3(0.2) * spec;

FragColor = vec4(ambient + diffuse + specular, 1.0f);
}

• 3
点赞
• 0
评论
• 13
收藏
• 一键三连
• 扫一扫，分享海报

11-11 1665

04-08 1万+
10-09 495
10-10 3643
01-25 130
02-10 6058
11-11 2964
09-28 2896
03-15 2万+
05-03 354
03-19 362