| 1 |
#![allow(clippy::float_cmp)] |
| 2 |
extern crate nalgebra as na; |
| 3 |
|
| 4 |
use na::{Unit, Vector3}; |
| 5 |
|
| 6 |
fn length_on_direction_with_unit(v: &Vector3<f32>, dir: &Unit<Vector3<f32>>) -> f32 { |
| 7 |
// No need to normalize `dir`: we know that it is non-zero and normalized. |
| 8 |
v.dot(dir.as_ref()) |
| 9 |
} |
| 10 |
|
| 11 |
fn length_on_direction_without_unit(v: &Vector3<f32>, dir: &Vector3<f32>) -> f32 { |
| 12 |
// Obligatory normalization of the direction vector (and test, for robustness). |
| 13 |
if let Some(unit_dir) = dir.try_normalize(1.0e-6) { |
| 14 |
v.dot(&unit_dir) |
| 15 |
} else { |
| 16 |
// Normalization failed because the norm was too small. |
| 17 |
panic!("Invalid input direction.") |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
fn main() { |
| 22 |
let v = Vector3::new(1.0, 2.0, 3.0); |
| 23 |
|
| 24 |
let l1 = length_on_direction_with_unit(&v, &Vector3::y_axis()); |
| 25 |
let l2 = length_on_direction_without_unit(&v, &Vector3::y()); |
| 26 |
|
| 27 |
assert_eq!(l1, l2) |
| 28 |
} |