2013-05-11 166 views
0

這是我在這裏的第一篇文章,但我正在試圖解決這個問題的牆壁撞我的頭。下面的代碼是我的一個令人難以置信的簡單的Opengl ES 2.0應用程序的片段着色器。頂點着色器完成所有常見業務。問題在於高光反射,它正在對每個頂點的基礎上執行計算,而不是每個片段。如果有人能向我解釋爲什麼會發生這種情況,我將不勝感激。謝謝。opengl es 2.0鏡面照明

順便說一句,對於效率低下的代碼感到抱歉,我只是回到照明的基礎知識來試圖跟蹤這個問題。

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)); 
} 
+0

能否請您分享您的固定代碼。 – Nishant 2015-06-09 07:15:40

回答