2012-05-14 14 views
0

我試圖在照明http://www.learnopengles.com/android-lesson-two-ambient-and-diffuse-lighting/OpenGLES2着色器:照明位置和相機移動?

添加到下面的教程我OpenGLES2應用不同於上面的教程中,我在世界FPS相機movements.In頂點着色器我有硬編碼的攝像頭位置(u_LightPos)coodinates.But其當我移動相機時會產生奇怪的照明效果。我是否必須使用投影/視圖矩陣來轉換此位置?

uniform mat4 u_MVPMatrix;   
uniform mat4 u_MVMatrix;  


attribute vec4 a_Position;  
attribute vec4 a_Color;  
attribute vec3 a_Normal;  

varying vec4 v_Color; 

void main()   
{       
vec3 u_LightPos=vec3(0,0,-20.0); 
vec3 modelViewVertex = vec3(u_MVMatrix * a_Position); 
vec3 modelViewNormal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));  

float distance = length(u_LightPos - modelViewVertex);   

    // Get a lighting direction vector from the light to the vertex. 
    vec3 lightVector = normalize(u_LightPos - modelViewVertex); 

    // Calculate the dot product of the light vector and vertex normal. If the normal and light vector are 
    // pointing in the same direction then it will get max illumination. 
    float diffuse = max(dot(modelViewNormal, lightVector), 0.1);  

    // Attenuate the light based on distance. 
    diffuse = diffuse * (1.0/(1.0 + (0.25 * distance * distance))); 

    // Multiply the color by the illumination level. It will be interpolated across the triangle. 
    v_Color = a_Color * diffuse; 

    // gl_Position is a special variable used to store the final position. 
    // Multiply the vertex by the matrix to get the final point in normalized screen coordinates. 
gl_Position = u_MVPMatrix * a_Position;       
} 

回答

1

在對向量執行算術運算時,它們必須位於相同的座標空間中。你從u_LightPos(世界空間)中減去modelViewVertex(視圖空間),這會給你一個虛假的結果。

您需要決定是否要在世界空間或視圖空間中進行光照計算(或者應該是有效的),但是您必須將所有輸入轉換爲相同的空間。

這意味着要麼獲取世界空間中的頂點/普通/ lightpos,要麼在視圖空間中獲得頂點/普通/ lightpos。

嘗試乘以你的lightpos的查看矩陣(而不是模型視圖),然後用你的計算而不是u_Lightpos,我認爲它應該工作。