Every time I try and do something like this (lighting with shaders), it never quite works out the first time.

This is probably causes by some little thing I overlooked or haven't noticed yet, but I also never seem to figure anything out myself untill I've posted something about it here.

Anyway, for some reason my lighting is messed up, even though these shaders worked on my old engine framework (causing me to think I screwed up my tangent space calculations like I usually do). The bump effect isn't there, and the lighting shows up in odd places (on other faces of the object, not facing the light).

The shot below shows what i'm talking about. the light is between the two cubes, but it lights the corners of two of the other visible faces.

My tangent/bitangent calculation:

Code:

void CObject::CalculateTB(){
float t1[2];
float t2[2];
float t3[2];
float tan[3];
float bitan[3];
for(int i=0; i<numMeshes; i++){
for(int j=0; j<mesh[i].numTriangles; j++){
int triangleIndex = mesh[i].triangleIndices[j];
const Triangle *triPtr = &triangle[triangleIndex];
int index[3];
index[0] = triPtr->vertexIndices[0];
index[1] = triPtr->vertexIndices[1];
index[2] = triPtr->vertexIndices[2];
t1[0] = triPtr->s[0];
t1[1] = triPtr->t[0];
t2[0] = triPtr->s[1];
t2[1] = triPtr->t[1];
t3[0] = triPtr->s[2];
t3[1] = triPtr->t[2];
// -- TANGENT BASIS -- //
Vec3 V1, V2, V3;
V1 = V1.FromArray(vertex[index[0]].location);
V2 = V2.FromArray(vertex[index[1]].location);
V3 = V3.FromArray(vertex[index[2]].location);
Vec3 cp;
Vec3 e0(V2.x-V1.x, t2[0]-t1[0], t2[1]-t1[1]);
Vec3 e1(V3.x-V1.x, t3[0]-t1[0], t3[1]-t1[1]);
cp.Cross(e0, e1);
if(fabs(cp.x) > 0.000001f){
tan[0] = -cp.y/cp.x;
bitan[0] = -cp.z/cp.x;
}
e0.x = V2.y-V1.y;
e1.x = V3.y-V1.y;
cp.Cross(e0, e1);
if(fabs(cp.x) > 0.000001f){
tan[1] = -cp.y/cp.x;
bitan[1] = cp.z/cp.x;
}
e0.x = V2.z-V1.z;
e1.x = V3.z-V1.z;
cp.Cross(e0, e1);
if(fabs(cp.x) > 0.000001f){
tan[2] = -cp.y/cp.x;
bitan[2] = -cp.z/cp.x;
}
// -- TANGENT BASIS -- //
Vec3 tangent, bitangent;
tangent = tangent.FromArray(tan);
bitangent = bitangent.FromArray(bitan);
tangent.Normalize();
bitangent.Normalize();
for(int k=0; k<3; k++){
vertex[index[k]].tangent[0] = tangent.x;
vertex[index[k]].tangent[1] = tangent.y;
vertex[index[k]].tangent[2] = tangent.z;
vertex[index[k]].bitangent[0] = bitangent.x;
vertex[index[k]].bitangent[1] = bitangent.y;
vertex[index[k]].bitangent[2] = bitangent.z;
}
}
}
}

Is there something really obviously wrong with that code?

Thanks.