<<< Diffuse lighting, cont.     Index     Translating normal vectors into the world space >>>

10. Diffuse lighting in vertex shader


  • Vertex shader

    
    #version 130
    
    in vec4 s_vPosition;
    in vec4 s_vNormal;
    
    uniform mat4 mM;    // model matrix
    uniform mat4 mV;    // camera view matrix
    uniform mat4 mP;    // perspective matrix
    
    uniform mat4 mRotations; // all model rotations matrix
    
    uniform vec4 vLight; // direction of light
    
    smooth out vec4 interpolated_color;
    
    void main () {
        
        // Rotate the normal and use as vec3:
        // No need tp normalize after rotation since it remains a unit vector:
        vec3 normal_in_cam_space = (mRotations*s_vNormal).xyz;
        // The angle between the surface normal and the light source vector
        // is called the angle of incidence of the light:
        float cos_incidence = dot( normal_in_cam_space, vLight.xyz );
        // Note that cosine of the angle of incidence can become negative
        // for angles greater than 90 degrees, hence we use the clamp() to
        // keep it in range from zero to one:
    	cos_incidence = clamp( cos_incidence, 0, 1 );
        vec4 light_color = vec4( 1.0, 1.0, 0.0, 1.0 ); // R + G = yellow
        interpolated_color = vec4( light_color.rgb * cos_incidence, 1.0);
    
        gl_Position = mP*mV*mM*s_vPosition;
    }
    
    
  • Fragment shader

    
    #version 130
    
    smooth in vec4 interpolated_color;
    
    out vec4 fColor;
    
    void main()
    {
    	fColor = interpolated_color;
    }
    
    

<<< Diffuse lighting, cont.     Index     Translating normal vectors into the world space >>>