All vector variables are marked bold.
Given:
R0 - start point of the ray,
Dir - direction of the ray,
|Dir| = 1 - direction is normalized to be of length 1
A, B, C - the triangle points
Specific point P at ray may be expressed as:
P = R0 + t * Dir
From another side specific P may be expressed in terms of triangle. Let's introduce new coordinate system (U, V, W, A), where
U = B - A, first axis
V = C - A, second eaxis
W = U x V, third axis is calculated to be prependicular to both U and V. Dot product makes the job.
A, is our central point
Then point P in general case is equal:
P = U * u + V * v + W * w + A,
So what we need to find the intersection is just find these u, v, w
As our intersection must be in triangle plane we can say that
w = 0
We need to find u, v values. They may be also used as point to triangle texture material.
Let's introduce vector D which will be our point P but relative to our new coordinate system:
D = P - A
Or
Dx = Ux * u + Vx * v + Wx * w
Dy = Uy * u + Vy * v + Wy * w
Dz = Uz * u + Vz * v + Wz * w
These linear equations can be solved as
u = detu / det
v = detv / det
w = detw / det
Ux | Vx | Wx | |
det = | Uy | Vy | Wy |
Uz | Vz | Wz |
Dx | Vx | Wx | |
detu = | Dy | Vy | Wy |
Dz | Vz | Wz |
Ux | Dx | Wx | |
detv = | Uy | Dy | Wy |
Uz | Dz | Wz |
Ux | Vx | Dx | |
detw = | Uy | Vy | Dy |
Uz | Vz | Dz |
Or
detu = D * (V x W)
detv = D * (W x U)
detw = D * (U x V)= D * W
u = detu / det = D * (V x W) / det = D * Tu
v = detv / det = D * (W x U) / det = D * Tv
w = detw / det = D * (U x V) / det = D * Tw
w = 0
D * Tw = 0
(P - A) * Tw = 0
P * Tw = A * Tw
(R0 + t * Dir) * Tw = A * Tw
R0 * Tw + t * Dir * Tw = A * Tw
t * Dir * Tw = A * Tw - R0 * Tw
t * Dir * Tw = (A - R0) * Tw
t = (A - R0) * Tw / (Dir * Tw)