实现漫反射每顶点着色器,无法正常工作

时间:2012-09-21 18:28:51

标签: opengl glsl

我正在使用OpenGL 4.0着色语言手册实现漫反射每顶点着色器,但为了适合我的项目,我略微修改了它。

这是我的顶点着色器代码:

layout(location = 0) in vec4 vertexCoord;
layout(location = 1) in vec3 vertexNormal;

uniform vec4 position; // Light position, initalized to vec4(100, 100, 100, 1)
uniform vec3 diffuseReflectivity; // Initialized to vec3(0.8, 0.2, 0.7)
uniform vec3 sourceIntensity; // Initialized to vec3(0.9, 1, 0.3)

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

out vec3 LightIntensity;

void main(void) {
    // model should be the normalMatrix here in case that
    // non-uniform scaling has been applied.
    vec3 tnorm = normalize(vec3(model * vec4(vertexNormal, 0.0)));

    // Convert to eye/camera space
    vec4 eyeCoordsLightPos = view * model * position;
    vec4 eyeCoords = view * model * vertexCoord;
    vec3 s = normalize(vec3(eyeCoordsLightPos - eyeCoords));

    // Diffuse shading equation
    LightIntensity = sourceIntensity * diffuseReflectivity * max(dot(s,tnorm), 0.0);

    gl_Position = projection * view * model * vertexCoord;
}

这是我的片段着色器:

in vec3 LightIntensity;

layout(location = 0) out vec4 FragColor;

void main(){
    FragColor = vec4(LightIntensity, 1.0);
}

我正在渲染一个盒子,我有所有法线的值。然而盒子只是黑色。 假设我的制服在渲染时设置正确,我的着色器代码是否有任何明显错误?

与书中的代码相比,我所改变的是我使用模型矩阵作为普通矩阵,我在模型空间中传递了光位置,但将其转换为着色器中的相机空间。

渲染图像,不要被作为纹理的阴影背景混淆: Image of rendering, do not be confused by the shaded background which is a texture.

在片段着色器中使用FragColor = vec4(f_vertexNormal, 1.0);进行渲染时的图片: enter image description here

在眼睛空间建议中使用tnorm更新了代码:

void main(void) {
    // model should be the normalMatrix here in case that
    // non-uniform scaling has been applied.
    vec3 tnorm = normalize(vec3(model * vec4(vertexNormal, 0.0)));

    // Convert to eye/camera space
    vec3 eyeTnorm = vec3(view * vec4(tnorm, 0.0));
    vec4 eyeCoordsLightPos = view * position;
    vec4 eyeCoords = view * model * vertexCoord;
    vec3 s = normalize(vec3(eyeCoordsLightPos - eyeCoords));

    // Diffuse shading equation
    LightIntensity = sourceIntensity * diffuseReflectivity * max(dot(s,eyeTnorm), 0.0);

    gl_Position = projection * view * model * vertexCoord;
    f_vertexNormal = vertexNormal;
}

1 个答案:

答案 0 :(得分:2)

除了上面的评论之外,您还dot了一个带有眼睛空间向量tnorm的世界空间向量s。您应该只在同一空间中对矢量点。因此,您可能还需要考虑将tnorm转换为眼睛空间。