# Calculating Tangent Space

This topic is 4498 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm trying to add bumpmapping to my deferred shading engine and im having trouble calculating the per-vertex tangents to pass into it. I have adapted the code from here but it doesnt always work, when ever the vertex has a normal with a negative value, the tangent isnt calculated. Could someone explain to me (in simple terms) why this is happening? Here is my code in case it helps:
void KMesh::CalculatePerVertexTangents()
{
KPolygon* ptr = polygons;
tangents = new KVec3[numVertices];

KVec3 *tan1 = new KVec3[numVertices];

memset(tan1, 0, sizeof(KVec3) * numVertices);

for (int i = 0; i < numPolygons; i++)
{
int numTris = ptr->GetNumTriangles();
for (int j = 0; j < numTris; j++)
{
int idx[3];
ptr->GetTriangle(j, idx[0], idx[1], idx[2]);

KVec3 v1 = vertices[idx[0]];
KVec3 v2 = vertices[idx[1]];
KVec3 v3 = vertices[idx[2]];

KVec2 w1 = texCoords[idx[0]];
KVec2 w2 = texCoords[idx[1]];
KVec2 w3 = texCoords[idx[2]];

float x1 = v2.X() - v1.X();
float x2 = v3.X() - v1.X();
float y1 = v2.Y() - v1.Y();
float y2 = v3.Y() - v1.Y();
float z1 = v2.Z() - v1.Z();
float z2 = v3.Z() - v1.Z();

float s1 = w2.X() - w1.X();
float s2 = w3.X() - w1.X();
float t1 = w2.Y() - w1.Y();
float t2 = w3.Y() - w1.Y();

float r = 1.0F / (s1 * t2 - s2 * t1);
KVec3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r);

tan1[idx[0]] += sdir;
tan1[idx[1]] += sdir;
tan1[idx[2]] += sdir;
}
}

KVec3 n, t;

for (int a = 0; a < numVertices; a++)
{
n = normals[a];
t = tan1[a];

// Gram-Schmidt orthogonalize
tangents[a] = (t - (n * n.Dot(t))).Normalise();
}

delete [] tan1;
}


Thanks, Luke.

##### Share on other sites
Your code looks correct to me. It should work fine as long as your input data doesn't include triangles with degenerate texture mapping or left-handed texture spaces (since you removed the handedness calculation). I'm not sure what you mean by a tangent not being calculated when the normal has a negative value.

1. 1
Rutin
26
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 10
• 9
• 9
• 46
• 41
• ### Forum Statistics

• Total Topics
631751
• Total Posts
3002076
×