法线是倒置的

时间:2015-01-26 23:33:45

标签: opengl glsl shader opentk

我在我的主程序中计算我的模型视图矩阵和普通矩阵:

private void setMV() 
        {
            modelViewMat = Matrix4.Mult(modelMat,viewMat); // model * view because opentk is row major order
            GL.UniformMatrix4(uModelViewIndex, false, ref modelViewMat);

            // normal matrix = transpose(inverse(modelView))
            normalMat = Matrix4.Invert(modelViewMat); 
            normalMat = Matrix4.Transpose(normalMat);
            GL.UniformMatrix4(uNormalIndex, false, ref normalMat);
        }

在我的顶点着色器中:

void main() 
{
    texcoord = VertexTexcoord;
        Normal = normalize( (uNormalMatrix * vec4(VertexNormal,0.0)).xyz);
    Position = (uModelViewMatrix * vec4(VertexPosition,1.0)).xyz;

    gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(VertexPosition,1.0);
}

片段着色器:

vec3 phong(vec3 n, vec3 s, vec3 v, vec3 r)
{
    vec3 diffC = texture2D(diff, texcoord.st).rgb;
    vec3 specC = texture2D(spec, texcoord.st).rgb;
    return uKa + uKd*max(dot(s,n),0.0)*diffC + uKs*pow(max(dot(r,v),0.0),uShininess)*specC;

}

void main() {

    vec3 n = blendNormals(Normal * 0.5 + 0.5, texture2D( ddn, texcoord.st ).rgb);
    //vec3 n = normalize(Normal);
    vec3 s = normalize(uLightPosition - Position);
    vec3 v = normalize(-Position);
    vec3 r = reflect(-s,n);

    fragColour = vec4(phong(n,s,v,r),1.0);
}

不确定我做错了什么,这是它的样子: enter image description here

1 个答案:

答案 0 :(得分:2)

如果你的目标是在相同的几何和法线的前面和后面获得相同的结果。您需要在着色器中翻转法线,以防三角形的方向与为它们计算法线的方向相反。

在片段着色器中,您可以:

if (gl_FrontFacing)
    myNormal = - myNormal;