opengl es 2.0 specular lighting

1.9k Views Asked by At

this is my very first post here but I'm banging my head against a wall trying to figure out this problem. The code below is my fragment shader for an incredibly simple Opengl es 2.0 app. The vertex shader is doing all the usual business. The problem is with the specular highlight, it is performing the calculations on what seems to be a per-vertex basis, not per-fragment. If anyone could explain to me why this is happening I would greatly appreciate it. Thanks.

BTW im sorry for the inefficient code, I was simply going back to the very basics of lighting to attempt to track this problem.

precision highp float;

struct DirectionLight
{
    vec4 Ambient;
    vec4 Diffuse;
    vec4 Specular;
};

struct Material
{
    vec4 Ambient;
    vec4 Diffuse;
    vec4 Specular;
    float SpecularExponent;
};

const float c_zero = 0.0;
const float c_one  = 1.0;

uniform DirectionLight   u_directionLight;
uniform Material         u_material;
uniform sampler2D        u_texture;
uniform vec3             u_lightPosition;
uniform vec3             u_eyePosition;

varying vec3             v_position;
varying vec3             v_normal;
varying vec2             v_texCoord;

void main()
{
    vec4 totalLight = vec4(c_zero, c_zero, c_zero, c_zero);
    vec4 ambient    = vec4(c_zero, c_zero, c_zero, c_zero);
    vec4 diffuse    = vec4(c_zero, c_zero, c_zero, c_zero);
    vec4 specular   = vec4(c_zero, c_zero, c_zero, c_zero);
    vec3 halfPlane  = vec3(c_zero, c_zero, c_zero);

    halfPlane = normalize(u_eyePosition + u_lightPosition);

    float distance    = length(u_lightPosition - v_position);
    float attenuation = c_one / (c_one + (0.1 * distance) + (0.01 * distance * distance));

    vec3 lightVector = normalize(u_lightPosition - v_position);

    float ndotl = max(dot(v_normal, lightVector), 0.1);
    float ndoth = max(dot(v_normal, halfPlane), 0.1);

    ambient = u_directionLight.Ambient * u_material.Ambient;
    diffuse = ndotl * u_directionLight.Diffuse * u_material.Diffuse;

    if(ndoth > c_zero)
    {
        specular = pow(ndoth, u_material.SpecularExponent) * u_directionLight.Specular * u_material.Specular;
    }

    totalLight = ambient + ((diffuse + specular) * attenuation);

    gl_FragColor = totalLight;// * (texture2D(u_texture, v_texCoord));
}
1

There are 1 best solutions below

1
On

I think this could help you with Diffuse lighting http://www.learnopengles.com/android-lesson-two-ambient-and-diffuse-lighting/