I have a ray, going outwards from a camera, I need to find the length of the ray inside the cube. Note that the camera could be inside the cube, in which case it should return the distance to the edge of the cube.
It’s for a shader, so it should be relatively small and involve a minimum of branching.
Any ideas?
To intersect a ray with a convex polyhedron, intersect the ray with the planes containing each face.
Suppose the ray starts at q and has direction r. Then any point on the ray can be represented as q + t r for a scalar parameter t. Now suppose we want to intersect this ray with the plane given by the equation p · n = k (where n is an outward-pointing unit normal to the face). The ray intersects the plane when
That is, when
and so
The ray enters the face when r · n is negative and exits when r · n is positive. When r · n is zero, the ray is parallel to the face. You need to check for this case to avoid division by zero; and in this case, if q · n > k, the ray misses the polyhedron completely.
So find t for all the faces of your polyhedron and let tin be the maximum t for the the points where the ray enters a face, and tout be the minimum t for the points where the ray exits a face. Then the length of the ray within the polyhedron is
If r is a unit vector you can avoid the division here. The two inner max(t, 0) are necessary to handle the case where the camera is inside the cube or the cube is behind the camera. The outer max(…, 0) is there to handle the case where the ray misses the cube entirely (in which case tin will be greater than tout).
I’m afraid I have no idea how to represent this computation in your shader language, let alone how to do so branchlessly.