Skip to main content

grafix_toolbox/kit/policies/math/
la.rs

1pub use nalgebra as na; // TODO generalize and unify
2
3pub type V2 = na::Vector2<f32>;
4pub type V3 = na::Vector3<f32>;
5pub type V4 = na::Vector4<f32>;
6pub type M2 = na::Matrix2<f32>;
7pub type M3 = na::Matrix3<f32>;
8pub type M4 = na::Matrix4<f32>;
9pub type Q = na::UnitQuaternion<f32>;
10
11pub fn identity() -> M4 {
12	M4::identity()
13}
14pub fn inverse3(m: M3) -> M3 {
15	m.try_inverse().unwrap_or_else(M3::identity)
16}
17pub fn inverse4(m: M4) -> M4 {
18	m.try_inverse().unwrap_or_else(M4::identity)
19}
20pub fn crop_3x3(m: &M4) -> M3 {
21	m.fixed_resize(0.)
22}
23pub fn normal(p1: V3, p2: V3, p3: V3) -> V3 {
24	(p2 - p1).cross(&(p3 - p1)).normalize()
25}
26pub fn translate(m: M4, v: V3) -> M4 {
27	m.prepend_translation(&v)
28}
29pub fn rotate(m: M4, angle: f32, axis: na::Unit<V3>) -> M4 {
30	let r: M4 = Q::from_axis_angle(&axis, angle).to_rotation_matrix().into();
31	m * r
32}
33pub fn scale(m: M4, v: V3) -> M4 {
34	m.prepend_nonuniform_scaling(&v)
35}
36pub fn iL(pos: V3) -> M4 {
37	na::Translation3::new(-pos.x, -pos.y, -pos.z).to_homogeneous()
38}
39pub fn perspective(aspect: f32, fovy: f32, near: f32, far: f32) -> M4 {
40	ASSERT!((far - near).abs() > 0.0001, "Near and far planes are the same");
41	let (tan_half_fovy, mut mat) = ((fovy / 2.).tan(), M4::zeros());
42	mat[(0, 0)] = 1. / (aspect * tan_half_fovy);
43	mat[(1, 1)] = 1. / tan_half_fovy;
44	mat[(2, 2)] = -(far + near) / (far - near);
45	mat[(2, 3)] = -(2. * far * near) / (far - near);
46	mat[(3, 2)] = -1.;
47	mat
48}