Imagine your ray being a point travelling through space such that at
time 0 it is at position r.origin, and every 1 unit of time it moves the
vector r.d.

so pos = r.origin + (r.d * time), ie pos.x = r.origin.x + (r.d.x *
time) etc.

Your bounding box is the intersection of six halfspaces

(when a plane splits space into two, the volume each side of the plane
is called a halfspace) - these are represented by these equations

x > minB.x, x < maxB.x, y > minB.y, y < maxB.y, z > minB.z, z <
maxB.z

What this code does is calculate the “time” when x is between minB.x and
maxB.x, then calculate the time when y is between minB.y and minB.y and
ditto for z. These are calculated as the interval t1 to t2.

Then tnear and tfar are updated as the 1D intersection of these
intervals.

The if (r.origin.x == 0) bit is wrong I think, I believe it should be

if (r.d.x == 0) and so on.

This checks if the ray is not moving in the x direction, and if so it is either always inside the x halfspaces, or never. If never, we return FALSE as the test cannot be true.

I tend to remove the divide from the test and keep separate numerators and denominators for tNear and tFar until the end as it avoids math errors when elements of r.d are very close to zero.

I have written some code based on a pseudocode I saw on internet but I just couldn’t understand the algorithm well. Can anyone please explain it to me ? I specifically do not understadn the purpose of tnear and tfar. Here’s my code btw :