我正在尝试使用 GLSL 3.3 实现 Phong 反射模型。我已经按照教程进行了操作,尽管我已经更改了代码以匹配教程的内容,但我仍然无法创建效果。我有一个奇怪的聚光灯效果,从原点到光源所在的地方,而不是任何 Phong 反射。这是顶点着色器:
#version 330
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 normal;
out vec3 Color;
out vec3 NormalCamSpace;
out vec3 EyeDir;
out vec3 PositionWorldSpace;
out vec3 LightDirCamSpace;
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform vec3 lightPos;
void main() {
NormalCamSpace =(V*M *vec4(normal,0.0)).xyz;
PositionWorldSpace = (M * vec4(position,1.0)).xyz;
vec3 PositionCamSpace = (V*M*vec4(position, 1.0)).xyz;
EyeDir = -PositionCamSpace;
LightDirCamSpace = (V*vec4(lightPos, 1.0)).xyz + EyeDir;
Color = vec3(0.0, 1.0, 1.0);
gl_Position = MVP * vec4(position, 1.0 );
}
这是碎片着色器:
#version 330
in vec3 Color;
in vec3 NormalCamSpace;
in vec3 PositionWorldSpace;
in vec3 EyeDir;
in vec3 LightDirCamSpace;
uniform vec3 lightPos;
uniform float ambientIntensity;
out vec3 outColor;
void main() {
vec3 n = normalize(NormalCamSpace);
vec3 l = normalize (LightDirCamSpace);
float cosTheta = clamp(dot(n, l),0,1);
vec3 E = normalize(EyeDir);
vec3 R = reflect(-l, n);
float cosAlpha = clamp(dot(E, R),0,1);
cosAlpha = pow(cosAlpha, 5);
float attenIntensity = 1.0 + 0.01*distance(lightPos, PositionWorldSpace)*distance(lightPos, PositionWorldSpace);
outColor = Color*cosTheta /attenIntensity+
Color* vec3(0.3, 0.3, 0.3) * cosAlpha/attenIntensity+
vec3(0.8, 0.8, 0.8) * ambientIntensity;
}
lightPos 在世界空间中。
这是相关的教程。除了镜面光照外,一切正常。