我遇到了每像素照明的问题,因为光越接近物体,它开始做像http://imgur.com/NbZxvAT这样奇怪的事情。
当相机距离太近时,我会得到像http://imgur.com/vDoQlj0这样的文物。
VertShader:
#version 330 core
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec4 vertexColor;
layout(location = 2) in vec2 vertexTexCord;
layout(location = 3) in vec3 vertexNormal;
uniform mat4 MVP;
uniform mat4 V;
uniform mat4 P;
uniform mat4 M;
uniform vec3 PointLight1_Position;
out vec4 fragmentColor;
out vec2 UV;
out vec3 Position_worldspace;
out vec3 Normal_cameraspace;
out vec3 EyeDirection_cameraspace;
out vec3 LightDirection_cameraspace;
void main(){
gl_Position = MVP * vec4(vertexPosition_modelspace,1);
Position_worldspace = ( M * vec4(vertexPosition_modelspace,1)).xyz;
vec3 vertexPosition_cameraspace = ( V * M * vec4(vertexPosition_modelspace,1)).xyz;
EyeDirection_cameraspace = - vertexPosition_cameraspace;
vec3 LightPosition_cameraspace = ( V * vec4(PointLight1_Position,1)).xyz;
LightDirection_cameraspace = LightPosition_cameraspace + EyeDirection_cameraspace;
vec3 NormalPosition_cameraspace = ( V * M * vec4(vertexNormal,1)).xyz;
Normal_cameraspace = -NormalPosition_cameraspace;
fragmentColor = vertexColor;
UV = vertexTexCord;
}
Fragment Shader:
#version 330 core
in vec4 fragmentColor;
in vec2 UV;
in vec3 Position_worldspace;
in vec3 Normal_cameraspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace;
out vec3 color;
uniform sampler2D TextureSampler1;
uniform vec3 PointLight1_Position;
void main()
{
vec3 LightColor = vec3(1,1,1);
float LightPower = 10.0f;
vec3 MaterialDiffuseColor = texture2D(TextureSampler1, UV).rgb * fragmentColor.rgb;
vec3 MaterialAmbientColor = vec3(0.1,0.1,0.1) * MaterialDiffuseColor;
vec3 MaterialSpecularColor = vec3(0.3,0.3,0.3);
float distance = length( PointLight1_Position - Position_worldspace );
vec3 n = normalize( Normal_cameraspace );
vec3 l = normalize( LightDirection_cameraspace );
float cosTheta = clamp( dot( n,l ), 0,1 );
vec3 E = normalize(EyeDirection_cameraspace);
vec3 R = reflect(-l,n);
float cosAlpha = clamp( dot( E,R ), 0,1 );
color =
MaterialAmbientColor +
MaterialDiffuseColor * LightColor * LightPower * cosTheta / (distance*distance) +
MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5) / (distance*distance);
}
答案 0 :(得分:5)
我认为你在这里有错误:
vec3 NormalPosition_cameraspace = ( V * M * vec4(vertexNormal,1)).xyz;
Normal_cameraspace = -NormalPosition_cameraspace;
你应该使用0作为第四个组件(而不是1)从vertexNormal构造一个vec4。这实际上意味着在乘以模型/视图矩阵时忽略任何转换。这就是你想要的,因为法线代表一个方向,而不是一个位置。
另外,我不理解这个计算:
LightDirection_cameraspace = LightPosition_cameraspace + EyeDirection_cameraspace;
不应该是这样的:
LightDirection_cameraspace = LightPosition_cameraspace - vertexPosition_cameraspace;