2013-08-26 64 views
0

我正在GLSL中創建每像素點亮着色器。圖爲一個立方體的網格,根據它們的順序,應該被遮擋的邊被渲染在其他邊上。當我切換到我的固定功能opengl燈光設置時,這不是問題。是什麼導致它,我該如何解決它?GLSL - 如何避免多邊形重疊?

what it looks like

頂點着色器:

varying vec4 ecPos; 
varying vec3 normal; 

void main() 
{ 

gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; 

/* first transform the normal into eye space and normalize the result */ 
normal = normalize(gl_NormalMatrix * gl_Normal); 

/* compute the vertex position in camera space. */ 
ecPos = gl_ModelViewMatrix * gl_Vertex; 


gl_Position = ftransform(); 

} 

片段着色器:

varying vec4 ecPos; 
varying vec3 normal; 

uniform sampler2D tex; 
uniform vec2 resolution; 

void main() 
{ 
vec3 n,halfV,lightDir; 
float NdotL,NdotHV; 

vec4 color = gl_LightModel.ambient; 
vec4 texC = texture2D(tex,gl_TexCoord[0].st) * gl_LightSource[0].diffuse; 

float att, dist; 

/* a fragment shader can't write a verying variable, hence we need 
a new variable to store the normalized interpolated normal */ 
n = normalize(normal); 

// Compute the ligt direction 
lightDir = vec3(gl_LightSource[0].position-ecPos); 

/* compute the distance to the light source to a varying variable*/ 
dist = length(lightDir); 


/* compute the dot product between normal and ldir */ 
NdotL = max(dot(n,normalize(lightDir)),0.0); 

if (NdotL > 0.0) { 

    att = 1.0/(gl_LightSource[0].constantAttenuation + 
      gl_LightSource[0].linearAttenuation * dist + 
      gl_LightSource[0].quadraticAttenuation * dist * dist); 
    color += att * (texC * NdotL + gl_LightSource[0].ambient); 


    halfV = normalize(gl_LightSource[0].halfVector.xyz); 
    NdotHV = max(dot(n,halfV),0.0); 
    color += att * gl_FrontMaterial.specular * gl_LightSource[0].specular * pow(NdotHV,gl_FrontMaterial.shininess); 

} 


gl_FragColor = color; 
} 

着色器大多是修改版本這些http://www.lighthouse3d.com/tutorials/glsl-tutorial/point-light-per-pixel/

+0

對不起,「每像素照明」。 – everling

回答

5

那麼你可能已經忘記,使GL_DEPTH_TEST

你需要調用glEnable(GL_DEPTH_TEST);這啓用了OpenGL,來測試不同基元的深度。所以當OpenGL渲染它時,它不會隨意將事物渲染到實際需要落後的其他事物之上!

http://www.opengl.org/sdk/docs/man/xhtml/glEnable.xml

+2

或OP忘記分配深度緩衝區,結果相同。 – Bahbar