-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
modify nalgebra sphere-ray intersection
- Loading branch information
1 parent
ab37099
commit 9a75d78
Showing
2 changed files
with
35 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,28 @@ | ||
pub fn intersection_ray( | ||
center: &nalgebra::Vector3<f32>, | ||
rad: f32, | ||
ray_src: &nalgebra::Vector3<f32>, | ||
ray_dir: &nalgebra::Vector3<f32>, | ||
) -> Option<(nalgebra::Vector3<f32>, nalgebra::Vector3<f32>, f32)> { | ||
let depth0 = (center - ray_src).dot(ray_dir); | ||
if depth0 < 0f32 { | ||
return None; | ||
|
||
/// ray_dir is not always a unit vector | ||
pub fn intersection_ray<T>( | ||
center: &nalgebra::Vector3<T>, | ||
rad: T, | ||
ray_src: &nalgebra::Vector3<T>, | ||
ray_dir: &nalgebra::Vector3<T>, | ||
) -> Option<T> | ||
where T: nalgebra::RealField + Copy | ||
{ | ||
// Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0 | ||
let op = ray_src - center; | ||
let a = ray_dir.dot(&ray_dir); | ||
let b = op.dot(&ray_dir); | ||
let c = op.dot(&op) - rad * rad; | ||
let det: T = b * b - c * a; | ||
if det < T::zero() { | ||
None | ||
} else { | ||
let det = det.sqrt(); | ||
if -b - det >= T::zero() { | ||
return Some((-b - det)/a); | ||
} else if -b + det >= T::zero() { | ||
return Some((-b + det)/a); | ||
} | ||
None | ||
} | ||
let sqdist = (ray_src + depth0 * ray_dir - center).norm_squared(); | ||
if rad * rad - sqdist < 0f32 { | ||
return None; | ||
} | ||
let depth1 = depth0 - (rad * rad - sqdist).sqrt(); | ||
if depth1 < 0f32 { | ||
return None; | ||
} | ||
let hit_pos = ray_src + depth1 * ray_dir; | ||
let hit_normal = (hit_pos - center).normalize(); | ||
Some((hit_pos, hit_normal, depth1)) | ||
} |