MrSnoopy's picture

GLSL per-pixel not working

Hi! This is my first post on this forum unfortunately its going to be about a problem I have encountered.

I´m doing my first shader and I was able to achieve per-vertex lighting with it but when I try to make per-pixel lighting it either shades as per-vertex or it does not work altogether. I have tried many tutorials but to no avail. Here is my shader code:

Vertex shader:

varying vec3 normal;
varying vec3 position;
 
void main()
{
        gl_TexCoord[0] = gl_MultiTexCoord0;
 
  	normal = normalize(gl_NormalMatrix * gl_Normal);
 
 	position = normalize(gl_NormalMatrix * gl_Vertex.xyz);
 
        gl_Position = ftransform();
}

Fragment shader:

uniform sampler2D Texture;
 
varying vec3 normal;
varying vec3 position;
 
void main()
{
	vec3 n = normalize(normal);
        vec3 p = normalize(position);
 
	vec3 light_direction = normalize(gl_LightSource[0].position.xyz - p);
 
	float intensity = max(dot(normal, light_direction), 0.0);
 
	vec4 diffuse = texture2D(Texture, gl_TexCoord[0].st) * gl_LightSource[0].diffuse * intensity;
 
	vec3 V = normalize(-p);
        vec3 H = normalize(light_direction + V);
        float specularLight = pow(max(dot(n, H),0), gl_FrontMaterial.shininess);
        if(intensity <= 0)
        specularLight = 0;
        vec4 specular = gl_FrontMaterial.specular * gl_LightSource[0].diffuse * specularLight;
 
	gl_FragColor = (gl_LightSource[0].ambient * gl_FrontMaterial.ambient) + diffuse + specular;
}

Now the way I understand this is that the vertex shader needs to send the vertex normal as well as vertex position to the fragment shader and then do the calculating in the fragment shader. I made the code from several tutorials explaining per-pixel lightning however those tutorials did not include textures they only used materials and colors. Could it be that my alterations for mapping textures somehow impaired per-pixel lighting?

Thank you in advance for your replies.


Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
MrSnoopy's picture

Hello.

Ive fixed the per pixel shading , however a new problem has occurred. The shading works fine when I use a single surface like a quad whit normals pointing on the positive z axis (0.0f, 0.0f, 1.0f). However when I add a new surface with different normals, one vertex per surface(quad) is always lit differently than the others (its dark when the other three are lit and lit when the other three are dark). Any suggestions on how to fix this will be greatly appreciative.

Thank you.

MrSnoopy's picture

Fixed! My order of adding normals to vertex points was just mixed up, made the switch and it works.