I'm writing a simple raytracer and I've hit a wall while trying to get the normal vector for an axis-aligned box, given the intersection point.
I'm using this intersection algorithm:
float tmin, tmax, tymin, tymax, tzmin, tzmax;
if (ray.direction.x >= 0) {
tmin = (min.x - ray.origin.x) / ray.direction.x;
tmax = (max.x - ray.origin.x) / ray.direction.x;
}
else {
tmin = (max.x - ray.origin.x) / ray.direction.x;
tmax = (min.x - ray.origin.x) / ray.direction.x;
}
if (ray.direction.y >= 0) {
tymin = (min.y - ray.origin.y) / ray.direction.y;
tymax = (max.y - ray.origin.y) / ray.direction.y;
} else {
tymin = (max.y - ray.origin.y) / ray.direction.y;
tymax = (min.y - ray.origin.y) / ray.direction.y;
}
if ((tmin > tymax) || (tymin > tmax)) {
return -1;
}
if (tymin > tmin) {
tmin = tymin;
}
if (tymax < tmax) {
tmax = tymax;
}
if (ray.direction.z >= 0) {
tzmin = (min.z - ray.origin.z) / ray.direction.z;
tzmax = (max.z - ray.origin.z) / ray.direction.z;
} else {
tzmin = (max.z - ray.origin.z) / ray.direction.z;
tzmax = (min.z - ray.origin.z) / ray.direction.z;
}
if ((tmin > tzmax) || (tzmin > tmax)) {
return -1;
}
if (tzmin > tmin) {
tmin = tzmin;
}
if (tzmax < tmax) {
tmax = tzmax;
}
return tmin;
While I'm sure I could decompose the box into planes instead of treating it as a separate primitive, making computing the normal trivial, I'd like to keep this optimized intersection code and somehow calculate the normal from the intersection point.
