我正在实现 OpenGL 4.0 Shading Language Cookbook 中的每个顶点的漫反射着色器,但为了适合我的项目进行了轻微修改。
这是我的顶点着色器代码:
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);
}
我正在渲染一个盒子,我有所有法线的值。然而,盒子只是黑色的。假设我的制服在渲染时设置正确,我的着色器代码有什么明显错误吗?
与书中的代码相比,我所做的更改是我将模型矩阵用作普通矩阵,并且我在模型空间中传递了我的光照位置,但在着色器中将其转换为相机空间。
渲染图像,不要被作为纹理的阴影背景混淆:
FragColor = vec4(f_vertexNormal, 1.0);
使用片段着色器
渲染时的图片:
在眼睛空间建议中使用 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;
}