質問

I'm making a per pixel lighting shader in GLSL. Pictured is a grid of cubes where, depending on the order they're drawn, sides that should be obscured are rendered on top of others. This is not a problem when I switch to my fixed function opengl lighting setup. What is causing it, how do I fix it?

what it looks like

vertex shader:

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();

} 

fragment shader:

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;
}

The shaders are mostly modified versions of these http://www.lighthouse3d.com/tutorials/glsl-tutorial/point-light-per-pixel/

役に立ちましたか?

解決

Well you've probably forgot to enable the GL_DEPTH_TEST.

You need to call glEnable(GL_DEPTH_TEST); this enabled OpenGL, to test the depth of different primitives. So when OpenGL is rendering it won't randomly render things on top of other things which actually needs to be behind!

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top