47 lines
758 B
Plaintext
47 lines
758 B
Plaintext
#ifndef INTERSECTION_SLANG
|
|
#define INTERSECTION_SLANG
|
|
|
|
namespace rt {
|
|
|
|
struct hit_data {
|
|
float t;
|
|
float3 n;
|
|
};
|
|
|
|
Optional<hit_data> intersect_sphere(
|
|
in const float3 r_o,
|
|
in const float3 r_d,
|
|
in const float3 s_o,
|
|
in const float s_r) {
|
|
let oc = r_o - s_o;
|
|
let a = dot(r_d, r_d);
|
|
let b = 2.0 * dot(oc, r_d);
|
|
let c = dot(oc, oc) - s_r * s_r;
|
|
let discriminant = b * b - 4.0 * a * c;
|
|
|
|
if (discriminant < 0.0) {
|
|
return none;
|
|
}
|
|
|
|
let sqrt_d = sqrt(discriminant);
|
|
let t1 = (-b - sqrt_d) / (2.0 * a);
|
|
let t2 = (-b + sqrt_d) / (2.0 * a);
|
|
|
|
if (t1 > 0.0) {
|
|
let p = r_o + r_d * t1;
|
|
return hit_data(t1, normalize(p - s_o));
|
|
}
|
|
|
|
if (t2 > 0.0) {
|
|
let p = r_o + r_d * t2;
|
|
return hit_data(t2, normalize(p - s_o));
|
|
}
|
|
|
|
return none;
|
|
}
|
|
|
|
}
|
|
|
|
#endif
|
|
|