Jubjub
Jubjub

Reputation: 55

Ray-Box intersection normal

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.

Upvotes: 2

Views: 5993

Answers (1)

Jubjub
Jubjub

Reputation: 55

I found a way to do it:

v3 Box::normalAt(const v3 &point) {
    v3 normal;
    v3 localPoint = point - center;
    float min = std::numeric_limits<float>::max();
    float distance = std::abs(size.x - std::abs(localPoint.x));
    if (distance < min) {
        min = distance;
        normal.set(1, 0, 0);
        normal *= SIGN(localPoint.x);
    }
    distance = std::abs(size.y - std::abs(localPoint.y));
    if (distance < min) {
        min = distance;
        normal.set(0, 1, 0);
        normal *= SIGN(localPoint.y);
    }
    distance = std::abs(size.z - std::abs(localPoint.z));
    if (distance < min) { 
        min = distance; 
        normal.set(0, 0, 1);
        normal *= SIGN(localPoint.z);
    } 
    return normal;
}

It produces wrong results at the box's edges, but it's acceptable for now.

sample

Upvotes: 3

Related Questions