Opengl GLSL法线贴图问题

时间:2015-01-26 23:31:02

标签: opengl glsl

我的法线贴图存在问题,而且我遇到了错误的地方。地图似乎位于模型上,但不在正确的空间中。可变眼睛只是摄像机位置。切线在程序中计算,它们是正确的。

顶点着色器:

void main() 
{     

    vec3 EyeSpaceNormal = normalize(vec3(NormalMatrix * VertexNormal));
    vec3 EyeSpaceTangent = normalize(vec3(NormalMatrix * vec3(VertexTangent)));

    TexCoord = VertexUV;
    vec3 bitangent = normalize(cross( EyeSpaceNormal, EyeSpaceTangent)) * VertexTangent.w;

    mat3 TBN = mat3(EyeSpaceTangent, bitangent, EyeSpaceNormal);

    TangentLightDirection = vec3( normalize(LightDirection) * TBN );
    TangentEye = vec3(normalize( eye) * TBN );

    Normal = EyeSpaceNormal;   
    VertPosition = vec3( ModelViewMatrix * vec4(VertexPosition,1.0));     

    gl_Position = MVP * vec4(VertexPosition,1.0); 
}

Frag Shader:

void main() 
{    
    vec3 ReturnColour;
    vec3 TextureNormal_tangentspace = normalize(texture2D( NormalMap, TexCoord ).rgb * 2.0 - 1.0);

    vec3 diffuse =  intensity * vec3(0.0,1.0,0.0) * max(0,dot(normalize(TextureNormal_tangentspace), normalize(-TangentLightDirection)));
    vec3 specular;

    //Specular
    vec3 VertexToEye = normalize(TangentEye - VertPosition);
    vec3 LightReflect = normalize(reflect(normalize(TangentLightDirection), TextureNormal_tangentspace));
    float SpecularFactor = dot(VertexToEye, LightReflect);
    SpecularFactor = pow(SpecularFactor, Shininess);

    if(SpecularFactor > 0)
    {
        specular = intensity * vec3(0.0,1.0,0.0) * SpecularFactor;  
    }

    ReturnColour = diffuse + specular;       

    FragColor = vec4(ReturnColour, 1.0); 
}

enter image description here

1 个答案:

答案 0 :(得分:0)

我的最后一个获奖者:Normal mapping and phong shading with incorrect specular component 看,如何计算镜面反射因子。

1)您的代码:

dot(VertexToEye, LightReflect)

必须:

max(dot(VertexToEye, LightReflect), 0.0)

钳位负值需要为零,因为在镜面计算中我们有指数(如何说Reto Koradi)!

2)如果在编译着色器时没有看到错误,请尝试使用 glGetProgramInfoLog 功能。看到它:

vec3 specular;
...
if(SpecularFactor > 0)
{
    specular = intensity * vec3(0.0,1.0,0.0) * SpecularFactor;  
}

如果高光等于 0 ,我们变量未定义错误。

替换:

vec3 specular;

由:

vec3 specular = vec3(0.0);

P.S。最好使用浮点值(0.0)来表示float变量,例如float,vec2,vec3 ......这就是:

if(SpecularFactor > 0) -> if(SpecularFactor > 0.0)