nalgebra_glm/gtx/
rotate_vector.rs

1use na::{Rotation3, Unit, UnitComplex};
2
3use crate::aliases::{TMat4, TVec2, TVec3, TVec4};
4use crate::RealNumber;
5
6/// Build the rotation matrix needed to align `normal` and `up`.
7pub fn orientation<T: RealNumber>(normal: &TVec3<T>, up: &TVec3<T>) -> TMat4<T> {
8    if let Some(r) = Rotation3::rotation_between(normal, up) {
9        r.to_homogeneous()
10    } else {
11        TMat4::identity()
12    }
13}
14
15/// Rotate a two dimensional vector.
16pub fn rotate_vec2<T: RealNumber>(v: &TVec2<T>, angle: T) -> TVec2<T> {
17    UnitComplex::new(angle) * v
18}
19
20/// Rotate a three dimensional vector around an axis.
21pub fn rotate_vec3<T: RealNumber>(v: &TVec3<T>, angle: T, normal: &TVec3<T>) -> TVec3<T> {
22    Rotation3::from_axis_angle(&Unit::new_normalize(*normal), angle) * v
23}
24
25/// Rotate a thee dimensional vector in homogeneous coordinates around an axis.
26pub fn rotate_vec4<T: RealNumber>(v: &TVec4<T>, angle: T, normal: &TVec3<T>) -> TVec4<T> {
27    Rotation3::from_axis_angle(&Unit::new_normalize(*normal), angle).to_homogeneous() * v
28}
29
30/// Rotate a three dimensional vector around the `X` axis.
31pub fn rotate_x_vec3<T: RealNumber>(v: &TVec3<T>, angle: T) -> TVec3<T> {
32    Rotation3::from_axis_angle(&TVec3::x_axis(), angle) * v
33}
34
35/// Rotate a three dimensional vector in homogeneous coordinates around the `X` axis.
36pub fn rotate_x_vec4<T: RealNumber>(v: &TVec4<T>, angle: T) -> TVec4<T> {
37    Rotation3::from_axis_angle(&TVec3::x_axis(), angle).to_homogeneous() * v
38}
39
40/// Rotate a three dimensional vector around the `Y` axis.
41pub fn rotate_y_vec3<T: RealNumber>(v: &TVec3<T>, angle: T) -> TVec3<T> {
42    Rotation3::from_axis_angle(&TVec3::y_axis(), angle) * v
43}
44
45/// Rotate a three dimensional vector in homogeneous coordinates around the `Y` axis.
46pub fn rotate_y_vec4<T: RealNumber>(v: &TVec4<T>, angle: T) -> TVec4<T> {
47    Rotation3::from_axis_angle(&TVec3::y_axis(), angle).to_homogeneous() * v
48}
49
50/// Rotate a three dimensional vector around the `Z` axis.
51pub fn rotate_z_vec3<T: RealNumber>(v: &TVec3<T>, angle: T) -> TVec3<T> {
52    Rotation3::from_axis_angle(&TVec3::z_axis(), angle) * v
53}
54
55/// Rotate a three dimensional vector in homogeneous coordinates around the `Z` axis.
56pub fn rotate_z_vec4<T: RealNumber>(v: &TVec4<T>, angle: T) -> TVec4<T> {
57    Rotation3::from_axis_angle(&TVec3::z_axis(), angle).to_homogeneous() * v
58}
59
60/// Computes a spherical linear interpolation between the vectors `x` and `y` assumed to be normalized.
61pub fn slerp<T: RealNumber>(x: &TVec3<T>, y: &TVec3<T>, a: T) -> TVec3<T> {
62    Unit::new_unchecked(*x)
63        .slerp(&Unit::new_unchecked(*y), a)
64        .into_inner()
65}