# How to assign/calculate triangle texture coordinates

Below is a triangle with its vertices and uv coordinates. These are read from the input model file.

I don't understand why the texture comes in different orientation than the image.

here is the method to calculate uv coordinate for the hit point(ray-triangle code from Moller, Trumbore):

     public bool GetIntersection(Vector rayOrigin, Vector rayDirection, ref
float hitDistance, out Vector uv)
{
uv = null;

// begin calculating determinant - also used to calculate U parameter
Vector pvec = rayDirection.Cross(edge2);

// if determinant is near zero, ray lies in plane of triangle
float det = edge1.Dot(pvec);

const float EPSILON = 0.000001f;
if ((det > -EPSILON) && (det < EPSILON))
return false;

float inv_det = 1.0f / det;

// calculate distance from vertex 0 to ray origin
Vector tvec = rayOrigin - verts;

// calculate U parameter and test bounds
float u = tvec.Dot(pvec) * inv_det;
if ((u < 0.0f) || (u > 1.0f))
return false;

// prepare to test V parameter
Vector qvec = tvec.Cross(edge1);

// calculate V parameter and test bounds
float v = rayDirection.Dot(qvec) * inv_det;
if ((v < 0.0f) || (u + v > 1.0f))
return false;

Vector uvHit = uvVectors * u + uvVectors * v + uvVectors * (1 - u - v);
uv = new Vector(uvHit, uvHit, 0);

// calculate t, ray intersects triangle
hitDistance = edge2.Dot(qvec) * inv_det;

// only allow intersections in the forward ray direction
return hitDistance >= 0.0f;
}


And here is the method in ImageTexture class to convert the hit point uv coordinate:

    public Vector Interpolate(Vector uv)
{
float u = uv - (float)Math.Floor(uv);
float v = uv - (float)Math.Floor(uv);
u *= bmp.Width - 1;
v *= bmp.Height - 1;

Color cuv = bmp.GetPixel((int)u, (int)v);

return new Vector(cuv.R, cuv.G, cuv.B);
}


Also how are the uv coordinates that come from the input model are supposed to be calculated? If this is a big mesh(a terrain) with many triangles how is the uv coordinates for each triangle vertex is calculated?

Thanks.