Trying to do a simple point light shader in GLSL

Started by
4 comments, last by Alberto Garc 9 years, 6 months ago

Hi there, I'm triyng to do a simple point entity light shader where the light position is harcoded in the shader ( 0, 0, 0 ). The problem is that when I move my ball, it always recives the light in the same direction.

This is my vertex shader:


vec4 lightPos;
vec3 vertexPos, normal, s;
varying float i;

void main()
{
    normal = normalize( gl_NormalMatrix * gl_Normal );
    vertexPos = vec3( gl_ModelViewMatrix * gl_Vertex );
    lightPos = vec4( 0, 0, 0, 1 );

    s = normalize( lightPos - vertexPos );
    // The diffuse shading equation
    i = dot( normal, s );

    gl_Position = ftransform();
}

And this my fragment shader:


varying float i;

void main (void)
{
    gl_FragColor = vec4( i, i, i, 1.0);
}

In the picture attach you can see the result. Allways is the same result when I move it arroun the 0,0,0 position.

Any help is welcome,

thaks in advance.

Advertisement

Your lightPos variable is in world space e.g. a position in the global world, while your normal and vertexPos are in view space e.g. as seen from the viewer. Because you're doing calculations on variables that are in different spaces you get wrong results. You should transform your lightPos vector to view space as well by multiplying this with the view matrix of your scene to get it to the view space.

Hello,
you may want to have a look at this: http://www.lighthouse3d.com/tutorials/glsl-core-tutorial/point-lights/
The names are a little different there because its OpenGL 3.3 and there you dont have gl_NormalMatrix and so on by default.
And the shader there also uses ambient and specular light but the basics for the diffuse part are what you want to do.
I am sorry right now I dont have the time to look
deeper into your problem. If nobody will tell you what exactly the problem is, I will look into this after work.

Thanks for your response I have tried multiply my lightPos * gl_ModelViewMatrix and I have the same result, in addition I have follow the tutorial in lighthouse3d and I have the same result.

You need to multiply your light position with only the view matrix. Multiplying it with gl_ModelViewMatrix multiplies it with both the model and view matrix, which is not correct. Unfortunately I'm not too familiar with pre 3.3 OpenGL. I searched it up and it seems you can't retrieve just the view matrix in GLSL which makes doing lighting calculations like this quite cumbersome if I'm honest. Maybe someone else knows how to retrieve the view matrix pre 3.3?

If definitions like world space, view/camera space sounds confusing to you I suggest you look up a tutorial or article about OpenGL's coordinate systems; once you get the hang of the different spaces, lighting becomes much eassier to understand :)

Thanks for your response. :)

This topic is closed to new replies.

Advertisement