Sign in to follow this  
flyslasher

Unexpected problems with OpenGL lights

Recommended Posts

After spending much time on google, I finally got lights to somewhat work! It was the right code in the wrong places but anyways to the problem. The lights only seem to work when I am using my shader which is suppose to be a per-pixel lighting shader.
[code]//Vertex Shader
varying vec3 lightDir,normal;

void main()
{
normal = normalize(gl_NormalMatrix * gl_Normal);

lightDir = normalize(vec3(gl_LightSource[0].position));
gl_TexCoord[0] = gl_MultiTexCoord0;

gl_Position = ftransform();
}[/code]

[code]//Fragment Shader
varying vec3 lightDir,normal;
uniform sampler2D tex;

void main()
{
vec3 ct,cf;
vec4 texel;
float intensity,at,af;
intensity = max(dot(lightDir,normalize(normal)),0.0);

cf = intensity * (gl_FrontMaterial.diffuse).rgb +
gl_FrontMaterial.ambient.rgb;
af = gl_FrontMaterial.diffuse.a;
texel = texture2D(tex,gl_TexCoord[0].st);

ct = texel.rgb;
at = texel.a;
gl_FragColor = vec4(ct * cf, at * af);

}[/code]

And without the shaders enabled, my 3DS loaded appears as bright as it can be. The second problem is even if I have my shaders on, if I change the position of light0, they stop working, as in my object gets an ambient shade of light. It might be a problem with how I calculate normals which I borrowed from an example but I am not sure...
[code]typedef struct{
float x,y,z;
}vertex_type;

vertex_type CalcNormal(vertex_type v1, vertex_type v2, vertex_type v3)
{
double v1x,v1y,v1z,v2x,v2y,v2z;
double nx,ny,nz;
double vLen;

vertex_type Result;

// Calculate vectors
v1x = v1.x - v2.x;
v1y = v1.y - v2.y;
v1z = v1.z - v2.z;

v2x = v2.x - v3.x;
v2y = v2.y - v3.y;
v2z = v2.z - v3.z;

// Get cross product of vectors
nx = (v1y * v2z) - (v1z * v2y);
ny = (v1z * v2x) - (v1x * v2z);
nz = (v1x * v2y) - (v1y * v2x);

// Normalise final vector
vLen = sqrt( (nx * nx) + (ny * ny) + (nz * nz) );

Result.x = (float)(nx / vLen);
Result.y = (float)(ny / vLen);
Result.z = (float)(nz / vLen);

return Result;
}[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this