Intersection Math & Algorithms - Learn to Derive

By Vilem Otte

math, intersection, ray, plane, sphere, box, triangle, aabb, tracing

One of the most important group of algorithms inside game engines are intersection algorithms. Even though there are plenty of sites showing code for intersection algorithms, there are only a few describing the math backround behind this, and algorithm derivation. To understand this article you need to know just a bit about linear algebra.

Primitive description

Let's start with a mathematical description of primitives we're going to intersect. For this article I've used just ray (line), plane, sphere, axis-aligned bounding box and triangle ... these should be enough for a basic game engine.

Ray

This is the simplest (and very useful) primitive you can think about. Let us define it with two 4-component numbers, point (further referred as origin) and direction. Mathematically the definition is: $$x = o + t \cdot d$$ Where:

  • x represents any point on a line
  • o represents some exact specified point on line (e.g. origin)
  • d represents direction vector of line
  • t is parameter within some specified range

The range specifies whether our line is infinite in both directions (+d and -d), whether it's just in a single direction, or whether it's finite. Writing a ray object in some programming language is straight-forward of course, you should end up with something like this:

class Ray 
{ 
public: 
    float4 origin; 
    float4 direction; 

    ... 
};

Constructor and methods are straight-forward (and should be also inline for performance reasons).

Plane

Another basic primitive. There are more ways to define a plane, but we will derive one that is well known and used. What is a plane? It's a point set that contains every such point in space, that when we create vector from that point to our known point on a plane, that vector has to be perpendicular to plane normal. And we know that perpendicular vectors are those whose dot product is equal to zero. So: $$n \cdot (x - p) = 0$$ Where:

  • n is unit vector in the plane normal direction
  • x is every point on the plane
  • p is our specified point on the plane

Expanding this yields: $$n_x \cdot (x - p_x) + n_y \cdot (y - p_y) + n_z \cdot (z - p_z) = 0$$ $$n_x \cdot x + n_y \cdot y + n_z \cdot z - (n_x \cdot p_x + n_y \cdot p_y + n_z \cdot p_z) = 0$$ Substitute: $$- (n_x \cdot p_x + n_y \cdot p_y + n_z \cdot p_z) = -n \cdot p = d, n_x = a, n_y = b, n_z = c$$ Yields something very familiar: $$a \cdot x + b \cdot y + c \cdot z + d = 0$$ Which is a plane equation (so we proved that the definition we use is actually a plane). Definition in programming language could be like this:

class Plane 
{ 
public: 
    float4 point; 
    float4 normal; 

    ... 
};

A very simple definition. Let's jump ahead.

Sphere

Yet another basic primitive, that is widely used. The definition is surface containing all points in distance from sphere's center less-or-equal to sphere's radius. We will define it using an analytic equation: $$(x-p_x)^2+(y-p_y)^2+(z-p_z)^2=r^2$$ Where:

  • x, y and z are coordinates of point on sphere
  • p represents sphere's center
  • r represents sphere's radius

A sphere class is again very trivial:

class Sphere 
{ 
public: 
    float4 center; 
    float radius; 

    ...
};

So much for sphere; simple, yet very useful primitive.

Axis-Aligned Bounding Box

From here on I'll call this one just AABB (which stands for Axis-Aligned Bounding Box). Definition is very simple, as we work in Cartesian coordinate system, we have perpendicular axes X, Y and Z - AABB is defined as volume between minimum and maximum point in this system, the sides are made by planes orthogonal to planes formed by all 3 combinations of 2 base axis (XY, XZ and YZ). Mathematically we can define it as: $$min_p \leq x \leq max_p$$ Where:

  • min_p stands for AABB minimum point
  • max_p stands for AABB maximum point
  • x represents point inside AABB

In programming language it can look like:

class AABB 
{ 
public: 
    float4 min_p; 
    float4 max_p;

    ...
}; 

Let's jump ahead to last object we're going to use.

Triangle

The first and only primitive in this article that is going to be defined by more than 2 values, yet very important. Most of the game worlds are described by triangles, most of the simulation use objects described as triangles, and every more (or less) complex 3D object can be decomposed into triangles. They're awesome; as opposed to other boring N-gons, triangles are never concave!

Let's define triangle with 3 points, then any point on triangle can be described as: $$x = A \cdot \alpha + B \cdot \beta + C \cdot \gamma$$ With conditions: $$\alpha + \beta + \gamma = 1, \alpha \geq 0, \beta \geq 0, \gamma \geq 0$$ Where:

  • x is every point in triangle
  • A, B, C are points defining triangle
  • alpha, beta and gamma are so called barycentric coordinates (e.g. parameters in the equation above)

A triangle inside of a program could be defined as:

class Triangle 
{ 
    public: float4 p[3];

    ...
};

Intersections

So now that we have defined some of the basic primitives, it's time to derive intersection equation and also intersection algorithms between the primitives. As I want to keep the article short (and I don't want to storm you with zillion of equations and exhausting equation solving), I will just show you 4 derivations - Ray-Plane (analytic derivation), Ray-Sphere (geometric derivation), Ray-AABB (tricky derivation) and Ray-Triangle (more complex analytic derivation).

You should get an idea of how the intersection equation can be derived and in the end you should be able to derive the rest of them on your own.

Ray-Plane Intersection

I will derive Ray-Plane intersection analytically, as this is one of the most simple approaches to the derivation.

When we want to derive some intersection algorithm analytically, we should write equations of those 2 objects right away, so (I intentionally used commonly known plane equation, instead of our definition): $$x=o+t \cdot d$$ $$a \cdot x + b \cdot y + c \cdot z + d = 0$$

Now we're looking for a point that lies on both, the ray and the plane - so we're looking for x. So we first write the first equation in scalar form: $$x=o_x+t \cdot d_x, y=o_y+t \cdot d_y, z=o_z+t \cdot d_z$$

Let's substitute these 3 to plane equation:

$$a \cdot (o{x}+t\cdot d{x}) + b \cdot (o{y}+t\cdot d{y}) + c \cdot (o{z}+t\cdot d{z}) + d = 0$$ $$a \cdot o{x}+ a \cdot t \cdot d{x} + b \cdot o{y} + b \cdot t \cdot d{y} + c \cdot o{z} + c \cdot t \cdot d{z} + d = 0$$ $$a \cdot t \cdot d{x} + b \cdot t \cdot d{y} + c \cdot t \cdot d{z} = -(a \cdot o{x} + b \cdot o{y} + c \cdot o{z} + d)$$ $$t \cdot (a \cdot d{x} + b \cdot d{y} + c \cdot d{z}) = -(a \cdot o{x} + b \cdot o{y} + c \cdot o{z} + d)$$ $$t = -{a \cdot o{x} + b \cdot o{y} + c \cdot o{z} + d \over {a \cdot d{x} + b \cdot d{y} + c \cdot d{z}}}$$

It's time to reverse substitution we did when "deriving" plane equation, e.g.:

$$-(n{x}\cdot p{x} + n{y}\cdot p{y} + n{z}\cdot p{z})=-n\cdotp=d$$ $$t = -{{n{x} \cdot o{x} + n{y} \cdot o{y} + n{z} \cdot o{z} - (n{x}\cdot p{x} + n{y}\cdot p{y} + n{z}\cdot p{z})} \over {n{x} \cdot d{x} + n{y} \cdot d{y} + n{z} \cdot d{z}}}$$

And transformed to vector form we get:

$$t = {-{{n\cdot o-n\cdot p}\over{n\cdot d}}}$$

But we can optimize this a little bit:

$$t = {-{{n\cdot(o-p)}\over{n\cdot d}}}$$

Voila, that's what we have been looking for! So basically we need just subtraction, 2 dot products and 1 division. In program this can look like (assuming we want to intersect planes in front of ray origin in direction of ray):

bool IntrRayPlane(const Ray* r, const Plane* p, float* t) 
{ 
    float denom = dot(p->normal, r->direction); 

    // Test whether ray and plane aren't parallel 
    if(fabsf(dotND) < EPSILON) 
        return false; 

    *t = -(dot(p->normal, r->origin - p->point) / denom); 
    return ((*t) > 0.0f); 
}

Almost as simple as the equation. Let's jump ahead, time for spheres!

Ray-Sphere Intersection

I could perform analytic derivation like in the Ray-Plane intersection derivation, although Ray-Sphere intersection is just one of the cases that can be easily derived using geometry.

We're now looking for 2 distances (enter and exit) - with point O being origin, point C being center, and points P and P' being enter and exit point of the sphere.

$$t{0} = |O - P|$$ $$t{1} = |O - P'|$$

Finding C-O (vector between ray origin and sphere center) is quite straightforward, it's just simple:

$$L = p - o$$

Another thing we need to find is distance along the ray to point X (Which is the point on the line from which under right angle you can reach center of sphere), but as we know ray direction, it's just simple projection of L.

$$t_x = L \cdot d$$

This forms right angle triangles inside of the sphere - one between entry point, point X and center of sphere; another between exit point, point X and center of sphere. At this point we can apply pythagorean theorem to find tPX (which is distance from point X to the entry or exit points (these distances are equivalent), as:

$$d^2 = L \cdot L + tx^2, t{PX} = \sqrt{r^2 - d^2}$$

And our 2 hit distances are:

$$t_0 - tx - t{PX}, t_1 = tx + t{PX}$$

Time for the code (searching just for nearest hit):

bool IntrRaySphere(const Ray* r, const Sphere* s, float* t) 
{ 
    float rad2 = s->radius * s->radius; 
    float4 L = s->center - r->origin; 

    float tPX = dot(L, r->direction); 
    if(tPX < 0.0) 
        return false; 

    float dsq = dot(L, L) - tPX * tPX; 
    if(dsq > rad2) 
        return false; 

    float thit = sqrt(rad2 - dsq); 
    *t = tPX - thit; 

    if(*t < 0.0f) 
        *t = tPX + thit; 

    return ((*t) < 0.0f); 
} 

Just a side note. Analytic derivation in this case is also very trivial, you will end up with quadratic equation, where determinant is negative in case of no hit, zero in case of single point hit (e.g. tangent line), and positive in case of secant. Let's jump ahead to boxes!

Ray-AABB Intersection

Another important one, although a bit tricky. If one draws down the situation, it is shortly realized that box in 2D is formed by 2 slabs, horizontal and vertical. 3D is analogous to this, but of course it's formed by 3 slabs. For each slab we want to find minimum distance and maximum distance, e.g.:

$$t{min} = {{(a - o)} \over d}$$ $$t{max} = {{(b - o)} \over d}$$

Where a and b represents minimum (respectively maximum) point of our AABB. What we get is the minimum and maximum distance to each slab. Now we have to correctly order the distances along the ray direction, this is quite simple:

$$t{near}=min(t{min}, t{max})$$ $$t{far}=max(t{min}, t{max})$$

Where min/max is defined as:

$$min(a, b) = \lbrace min(a{x}, b{x}), min(a{y}, b{y}), ... , min(a{n}, b{n}) \rbrace$$ $$max(a, b) = \lbrace max(a{x}, b{x}), max(a{y}, b{y}), ... , max(a{n}, b{n}) \rbrace$$

Entry/exit point is then defined as maximum of near distances (see the image), thus:

$$enter = hmax(t{min})$$ $$exit = hmin(t{max})$$

Where hmax/hmin function are horizontal minimum/maximum, defined as:

$$hmin(a) = min(a{x}, a{y}, ... , a{n})$$ $$hmax(a) = max(a{x}, a{y}, ... , a{n})$$

Of course a hit only occurs when the exit point is larger than zero, and the exit point is further than the entry point (if it isn't, we missed the AABB). Time to code:

bool IntrRayAABB(const Ray* r, const AABB* b, float* enter, float* exit) 
{ 
    float4 tmin = (b->minimum - r->origin) / r->direction; 
    float4 tmax = (b->maximum - r->origin) / r->direction; 

    float4 tnear = f4min(tmin, tmax); 
    float4 tfar = f4min(tmin, tmax); 

    *enter = max(max(tnear.x, 0.0f), max(tnear.y, tnear.z)); 
    *exit = min(tfar.x, min(tfar.y, tfar.z)); 

    return (*exit > 0.0f && *enter < *exit); 
}

It can be a little more optimized, although I'll leave that to reader as an exercise.

Ray-Triangle Intersection

I'd like to say, before I begin on this one, there is like a dozen of ways to intersect a ray with a triangle. Lots of them don't even use a triangle defined by 3 points, and re-define it in better suited way.

I'll show you how to derive plain good old Barycentric test with one huge advantage, you don't have to precompute a triangle in any way, just use the standard definition with 3 points.

Let's start with equations we already have:

$$x = o + t \cdot d$$ $$x = A \cdot \alpha + B \cdot \beta + C \cdot \gamma$$

The triangle equation actually is equal to this:

$$x = A \cdot (1 - \beta - \gamma) + B \cdot \beta + C \cdot \gamma$$

And let's arrange it like this:

$$x = A + (B - A) \cdot \beta + (C - A) \cdot \gamma$$

Substituting line equation for x yields:

$$o + t \cdot d = A + (B - A) \cdot \beta + (C - A) \cdot \gamma$$ $$-t \cdot d + \beta \cdot (B - A) + \gamma \cdot (C - A) = o - A$$

Those all together define a system of 3 equations with 3 unknown variables (remember, we are operating with 3D vectors).

Instead of thinking about some more clever way, let's solve it in brute force manner with Cramer's rule. First let's re-arrange it to better form:

$$\begin{pmatrix}d & B-A & C-A\end{pmatrix} \begin{pmatrix}t \\ \beta \\ \gamma \end{pmatrix} = o - A$$

For clarity let's substitute e1 for B-A, e2 for C-A and p for o-A.

$$\begin{pmatrix}d & e_1 & e_2\end{pmatrix} \begin{pmatrix}t \\ \beta \\ \gamma \end{pmatrix} = p$$

Now it's time to apply Cramer's rule, e.g.:

$$\begin{pmatrix} t \\ \beta \\ \gamma \end{pmatrix} = \frac{1}{\begin{vmatrix}-d \quad e_1 \quad e_2\end{vmatrix}} \left ( \begin{vmatrix} p & e_1 & e_2 \\ d & p & e_2 \\ d & e_1 & p \ \end{vmatrix} \right )$$

But matrix determinant can be written as scalar triple product, so:

$$\begin{pmatrix} t \\ \beta \\ \gamma \end{pmatrix} = \frac{1}{\begin{matrix}(d \times e_1) \cdot e_2\end{matrix}} \left ( \begin{matrix} (p \times e_1) \cdot e_2 \\ (d \times p) \cdot e_2 \\ (d \times e_1) \cdot p \end{matrix} \right )$$

I know this might look scary right now, but it really is simple. For those that understand code easier than math I also add code:

bool IntrRayTriangle( const Ray* r, const Triangle* t, float* thit, float* u, float* v) 
{ 
    float4 e1 = t->v[1] - t->v[0]; 
    float4 e2 = t->v[2] - t->v[0]; 

    float4 pvec = cross(r->direction, e2); 

    float det = dot(e1, pvec); 
    if(det > -EPSILON && det < EPSILON) 
        return false; 

    float inv_det = 1.0f / det; 

    float4 tvec = r->origin - t->v[0]; 

    *u = dot(tvec, pvec) * inv_det; 
    if(*u < 0.0f || *u > 1.0f) 
        return false; 

    float4 qvec = cross(tvec, e1); 

    *v = dot(r->direction, qvec) * inv_det; 
    if(*v < 0.0f || *u + *v > 1.0f) 
        return false; 

    *thit = dot(e2, qvec) * inv_det; 

    return (*thit > 0.0f); 
}

Conclusion

Intersection algorithms, as I've said, are core algorithms for practically every game engine! And not just game engines, ray-tracers, physics simulators, collision detection libraries, even some AI simulations use them, etc. If you made it here, then I have to say thanks for reading my article, and I hope you've learned something new.

Notes

Original posted on GameDev.net - https://gamedev.net/tutorials/programming/math-and-physics/intersection-math-algorithms-learn-to-derive-r3033/

v0.0.65