I'm trying to light up a rotating model, however when trying to apply specular lighting, it appears to be incorrect and moves around the object and will disappear at certain angles.
This is part of the vertex shader:
void main() {
frag_vertex = vec3(mvpMatrix * vec4(position, 1.0));
frag_textureCoord = textureCoord;
frag_colour = colour;
mat3 normalMatrix = transpose(inverse(mat3(mMatrix)));
frag_normal = normalize(normal * normalMatrix);
frag_worldPosition = (vec4(position, 1.0) * mvpMatrix).xyz;
gl_Position = mvpMatrix * vec4(position, 1.0);
}
And this is the fragment shader:
vec4 calculateLight(BaseLight base, vec3 direction, vec3 normal) {
float diffuseFactor = max(dot(normal, -direction), 0.0);
vec4 diffuseColour = vec4(0.0, 0.0, 0.0, 0.0);
vec4 specularColour = vec4(0.0, 0.0, 0.0, 0.0);
if (diffuseFactor > 0.0) {
diffuseColour = vec4(base.colour, 1.0) * base.intensity * diffuseFactor;
vec3 directionToEye = normalize(eyePosition - frag_worldPosition);
vec3 halfDirection = normalize(directionToEye - direction);
float specularFactor = max(dot(frag_normal, halfDirection), 0.0);
specularFactor = pow(specularFactor, specularPower);
if (specularFactor > 0.0) {
specularColour = vec4(base.colour, 1.0) * specularIntensity * specularFactor;
}
}
return (ambientLight + diffuseColour + specularColour);
}
void main() {
gl_FragColor = frag_colour * material.diffuseColour * texture2D(material.diffuseTexture, frag_textureCoord) * calculateDirectionalLight(directionalLight, frag_normal);
}
In this, the direction is (0, 0, 1), and the eyePosition represents the position of the camera.
Using this without rotating the object gives:
Then rotating it 80 degrees moves the highlight to the left:
What am I doing wrong?
Thank you.