You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

677 lines
18 KiB

  1. #![allow(dead_code)]
  2. use std::borrow::Borrow;
  3. use std::convert::{AsMut, AsRef};
  4. use std::fmt::{Debug, Formatter, Result as FmtResult};
  5. use std::ops::{Deref, DerefMut, Mul};
  6. #[cfg(feature = "serde")]
  7. use serde::{
  8. de::{Deserializer, Error, MapAccess, SeqAccess, Visitor},
  9. ser::{SerializeStruct, Serializer},
  10. Deserialize, Serialize,
  11. };
  12. use super::vector::{Vector2, Vector3, Vector4};
  13. pub use super::{
  14. angle::Angle,
  15. numeric::{Float, Numeric},
  16. };
  17. macro_rules! first_ptr {
  18. ($this:ident, $first:ident $(, $other:ident)*) => {
  19. unsafe { $this.$first.as_ptr() }
  20. };
  21. }
  22. macro_rules! define_mat {
  23. ($Name:ident, $Vector:ident, $size:tt, $($T:ident => $i:tt => $f:ident),*) => {
  24. #[repr(C, packed)]
  25. pub struct $Name<T> {
  26. $(pub $f: $Vector<T>,)+
  27. }
  28. impl<T> $Name<T> {
  29. #[inline]
  30. pub fn new($($f: $Vector<T>,)+) -> Self {
  31. Self { $($f,)+ }
  32. }
  33. pub fn as_ptr(&self) -> * const T {
  34. first_ptr!(self $(,$f)+)
  35. }
  36. }
  37. impl<T> Default for $Name<T>
  38. where
  39. T: Numeric
  40. {
  41. #[inline]
  42. fn default() -> Self {
  43. Self::identity()
  44. }
  45. }
  46. impl<T> Debug for $Name<T>
  47. where
  48. T: Debug
  49. {
  50. fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
  51. fmt.debug_list().entries(self.as_ref().iter()).finish()
  52. }
  53. }
  54. impl<T, S> PartialEq<$Name<S>> for $Name<T>
  55. where
  56. $Vector<S>: PartialEq<$Vector<T>>,
  57. {
  58. fn eq(&self, other: &$Name<S>) -> bool {
  59. unsafe { true $(&& other.$f.eq(&self.$f))+ }
  60. }
  61. }
  62. impl<T> Eq for $Name<T>
  63. where
  64. T: Eq
  65. { }
  66. impl<T> Deref for $Name<T> {
  67. type Target = [$Vector<T>; $size];
  68. #[inline]
  69. fn deref(&self) -> &Self::Target {
  70. self.as_ref()
  71. }
  72. }
  73. impl<T> DerefMut for $Name<T> {
  74. #[inline]
  75. fn deref_mut(&mut self) -> &mut Self::Target {
  76. self.as_mut()
  77. }
  78. }
  79. impl<T> AsRef<[$Vector<T>; $size]> for $Name<T> {
  80. #[inline]
  81. fn as_ref(&self) -> &[$Vector<T>; $size] {
  82. unsafe {
  83. let raw: * const _ = self;
  84. let raw = raw as * const [$Vector<T>; $size];
  85. &*raw
  86. }
  87. }
  88. }
  89. impl<T> AsMut<[$Vector<T>; $size]> for $Name<T> {
  90. #[inline]
  91. fn as_mut(&mut self) -> &mut [$Vector<T>; $size] {
  92. unsafe {
  93. let raw: * mut _ = self;
  94. let raw = raw as * mut [$Vector<T>; $size];
  95. &mut *raw
  96. }
  97. }
  98. }
  99. impl<T> Clone for $Name<T>
  100. where
  101. T: Clone
  102. {
  103. #[inline]
  104. fn clone(&self) -> Self {
  105. unsafe {
  106. Self {
  107. $($f: self.$f.clone(),)+
  108. }
  109. }
  110. }
  111. }
  112. impl<T> Copy for $Name<T>
  113. where
  114. T: Copy
  115. { }
  116. impl<T> From<[$Vector<T>; $size]> for $Name<T>
  117. where
  118. T: Copy,
  119. {
  120. #[inline]
  121. fn from(arr: [$Vector<T>; $size]) -> Self {
  122. Self {
  123. $($f: arr[$i],)+
  124. }
  125. }
  126. }
  127. impl<T> From<($($Vector<$T>,)+)> for $Name<T> {
  128. #[inline]
  129. fn from(($($f,)+): ($($Vector<$T>,)+)) -> Self {
  130. Self {
  131. $($f,)+
  132. }
  133. }
  134. }
  135. #[cfg(feature = "serde")]
  136. impl<T> Serialize for $Name<T>
  137. where
  138. T: Serialize,
  139. {
  140. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  141. where
  142. S: Serializer
  143. {
  144. let mut s = serializer.serialize_struct(stringify!($Name), $size)?;
  145. unsafe { $(s.serialize_field(stringify!($f), &self.$f)?;)+ }
  146. s.end()
  147. }
  148. }
  149. #[cfg(feature = "serde")]
  150. impl<'de, T> Deserialize<'de> for $Name<T>
  151. where
  152. T: Deserialize<'de>,
  153. {
  154. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  155. where
  156. D: Deserializer<'de>
  157. {
  158. struct MatrixVisitor<T>(std::marker::PhantomData<T>);
  159. impl<'de, X> Visitor<'de> for MatrixVisitor<X>
  160. where X: Deserialize<'de>,
  161. {
  162. type Value = $Name<X>;
  163. fn expecting(&self, formatter: &mut Formatter) -> FmtResult {
  164. formatter.write_fmt(format_args!("struct {}", stringify!($Name)))
  165. }
  166. fn visit_seq<V>(self, mut seq: V) -> Result<$Name<X>, V::Error>
  167. where
  168. V: SeqAccess<'de>,
  169. {
  170. Ok($Name {
  171. $($f: seq.next_element()?.ok_or_else(|| Error::invalid_length($i, &self))?,)+
  172. })
  173. }
  174. fn visit_map<V>(self, mut map: V) -> Result<$Name<X>, V::Error>
  175. where
  176. V: MapAccess<'de>,
  177. {
  178. $(let mut $f = None;)+
  179. while let Some(key) = map.next_key()? {
  180. match key {
  181. $(
  182. stringify!($f) => {
  183. if $f.is_some() {
  184. return Err(Error::duplicate_field(stringify!($f)));
  185. }
  186. $f = Some(map.next_value()?);
  187. }
  188. )+
  189. value => return Err(Error::unknown_field(value, FIELDS)),
  190. }
  191. }
  192. Ok($Name {
  193. $($f: $f.ok_or_else(|| Error::missing_field(stringify!($f)))?,)+
  194. })
  195. }
  196. }
  197. const FIELDS: &'static [&'static str] = &[$(stringify!($f),)+];
  198. deserializer.deserialize_struct(stringify!($Name), FIELDS, MatrixVisitor::<T>(std::marker::PhantomData))
  199. }
  200. }
  201. };
  202. }
  203. define_mat!(Matrix2, Vector2, 2, T => 0 => axis_x, T => 1 => axis_y);
  204. define_mat!(Matrix3, Vector3, 3, T => 0 => axis_x, T => 1 => axis_y, T => 2 => axis_z);
  205. define_mat!(Matrix4, Vector4, 4, T => 0 => axis_x, T => 1 => axis_y, T => 2 => axis_z, T => 3 => position);
  206. pub type Matrix2f = Matrix2<gl::GLfloat>;
  207. pub type Matrix3f = Matrix3<gl::GLfloat>;
  208. pub type Matrix4f = Matrix4<gl::GLfloat>;
  209. pub type Matrix2d = Matrix2<gl::GLdouble>;
  210. pub type Matrix3d = Matrix3<gl::GLdouble>;
  211. pub type Matrix4d = Matrix4<gl::GLdouble>;
  212. pub type Matrix2i = Matrix2<gl::GLint>;
  213. pub type Matrix3i = Matrix3<gl::GLint>;
  214. pub type Matrix4i = Matrix4<gl::GLint>;
  215. /* Matrix2 */
  216. impl<T> Matrix2<T>
  217. where
  218. T: Numeric,
  219. {
  220. #[inline]
  221. pub fn identity() -> Self {
  222. let one = T::one();
  223. let zero = T::zero();
  224. Self::new(Vector2::new(one, zero), Vector2::new(zero, one))
  225. }
  226. }
  227. /* Matrix3 */
  228. impl<T> Matrix3<T>
  229. where
  230. T: Numeric,
  231. {
  232. #[inline]
  233. pub fn identity() -> Self {
  234. let one = T::one();
  235. let zero = T::zero();
  236. Self::new(
  237. Vector3::new(one, zero, zero),
  238. Vector3::new(zero, one, zero),
  239. Vector3::new(zero, zero, one),
  240. )
  241. }
  242. #[inline]
  243. pub fn translate(v: Vector2<T>) -> Self {
  244. let one = T::one();
  245. let zro = T::zero();
  246. Self::new(
  247. Vector3::new(one, zro, zro),
  248. Vector3::new(zro, one, zro),
  249. Vector3::new(v.x, v.y, one),
  250. )
  251. }
  252. #[inline]
  253. pub fn determinant(&self) -> T {
  254. let m = self;
  255. m[0][0] * m[1][1] * m[2][2] + m[1][0] * m[2][1] * m[0][2] + m[2][0] * m[0][1] * m[1][2]
  256. - m[2][0] * m[1][1] * m[0][2]
  257. - m[1][0] * m[0][1] * m[2][2]
  258. - m[0][0] * m[2][1] * m[1][2]
  259. }
  260. #[inline]
  261. pub fn multiply(&self, other: &Self) -> Self {
  262. let m1 = self;
  263. let m2 = other;
  264. macro_rules! mul {
  265. ($x:tt, $y:tt) => {
  266. m1[0][$y] * m2[$x][0] + m1[1][$y] * m2[$x][1] + m1[2][$y] * m2[$x][2]
  267. };
  268. }
  269. Self::new(
  270. Vector3::new(mul!(0, 0), mul!(0, 1), mul!(0, 2)),
  271. Vector3::new(mul!(1, 0), mul!(1, 1), mul!(1, 2)),
  272. Vector3::new(mul!(2, 0), mul!(2, 1), mul!(2, 2)),
  273. )
  274. }
  275. }
  276. impl<T> Matrix3<T>
  277. where
  278. T: Float,
  279. {
  280. #[inline]
  281. pub fn rotate(a: Angle<T>) -> Self {
  282. let one = T::one();
  283. let zro = T::zero();
  284. Self::new(
  285. Vector3::new(a.cos(), -a.sin(), zro),
  286. Vector3::new(a.sin(), a.cos(), zro),
  287. Vector3::new(zro, zro, one),
  288. )
  289. }
  290. }
  291. impl<T, M> Mul<M> for Matrix3<T>
  292. where
  293. T: Float,
  294. M: Borrow<Matrix3<T>>,
  295. {
  296. type Output = Self;
  297. fn mul(self, rhs: M) -> Self::Output {
  298. self.multiply(rhs.borrow())
  299. }
  300. }
  301. /* Matrix4 */
  302. impl<T> Matrix4<T>
  303. where
  304. T: Numeric,
  305. {
  306. #[inline]
  307. pub fn identity() -> Self {
  308. let one = T::one();
  309. let zero = T::zero();
  310. Self::new(
  311. Vector4::new(one, zero, zero, zero),
  312. Vector4::new(zero, one, zero, zero),
  313. Vector4::new(zero, zero, one, zero),
  314. Vector4::new(zero, zero, zero, one),
  315. )
  316. }
  317. }
  318. impl<T> Matrix4<T>
  319. where
  320. T: Float,
  321. {
  322. #[inline]
  323. pub fn translate(v: Vector3<T>) -> Self {
  324. let one = T::one();
  325. let zero = T::zero();
  326. Self::new(
  327. Vector4::new(one, zero, zero, zero),
  328. Vector4::new(zero, one, zero, zero),
  329. Vector4::new(zero, zero, one, zero),
  330. Vector4::new(v.x, v.y, v.z, one),
  331. )
  332. }
  333. #[inline]
  334. pub fn scale(v: Vector3<T>) -> Self {
  335. let one = T::one();
  336. let zero = T::zero();
  337. Self::new(
  338. Vector4::new(v.x, zero, zero, zero),
  339. Vector4::new(zero, v.y, zero, zero),
  340. Vector4::new(zero, zero, v.z, zero),
  341. Vector4::new(zero, zero, zero, one),
  342. )
  343. }
  344. #[inline]
  345. #[allow(clippy::many_single_char_names)]
  346. pub fn rotate(axis: Vector3<T>, angle: Angle<T>) -> Self {
  347. let axis = axis.normalize();
  348. let x = axis.x;
  349. let y = axis.y;
  350. let z = axis.z;
  351. let angle = angle.into_rad().into_inner();
  352. let s = T::sin(angle);
  353. let c = T::cos(angle);
  354. let one = T::one();
  355. let zero = T::zero();
  356. Self::new(
  357. Vector4::new(
  358. x * x + (one - y * y) * c,
  359. x * y * (one - c) + z * s,
  360. x * z * (one - c) - y * s,
  361. zero,
  362. ),
  363. Vector4::new(
  364. x * y * (one - c) - z * s,
  365. y * y + (one - y * y) * c,
  366. y * z * (one - c) + x * s,
  367. zero,
  368. ),
  369. Vector4::new(
  370. x * z * (one - c) + y * s,
  371. y * z * (one - c) - x * s,
  372. z * z + (one - z * z) * c,
  373. zero,
  374. ),
  375. Vector4::new(zero, zero, zero, one),
  376. )
  377. }
  378. #[inline]
  379. pub fn multiply(&self, other: &Self) -> Self {
  380. let m1 = self;
  381. let m2 = other;
  382. macro_rules! mul {
  383. ($x:tt, $y:tt) => {
  384. m1[0][$y] * m2[$x][0]
  385. + m1[1][$y] * m2[$x][1]
  386. + m1[2][$y] * m2[$x][2]
  387. + m1[3][$y] * m2[$x][3]
  388. };
  389. }
  390. Self::new(
  391. Vector4::new(mul!(0, 0), mul!(0, 1), mul!(0, 2), mul!(0, 3)),
  392. Vector4::new(mul!(1, 0), mul!(1, 1), mul!(1, 2), mul!(1, 3)),
  393. Vector4::new(mul!(2, 0), mul!(2, 1), mul!(2, 2), mul!(2, 3)),
  394. Vector4::new(mul!(3, 0), mul!(3, 1), mul!(3, 2), mul!(3, 3)),
  395. )
  396. }
  397. #[inline]
  398. pub fn transform(&self, v: &Vector4<T>) -> Vector4<T> {
  399. let m = self;
  400. macro_rules! mul {
  401. ($i:tt) => {
  402. m[0][$i] * v[0] + m[1][$i] * v[1] + m[2][$i] * v[2] + m[3][$i] * v[3]
  403. };
  404. }
  405. Vector4::new(mul!(0), mul!(1), mul!(2), mul!(3))
  406. }
  407. #[inline]
  408. pub fn transpose(&self) -> Self {
  409. let m = self;
  410. Self::new(
  411. Vector4::new(m[0][0], m[1][0], m[2][0], m[3][0]),
  412. Vector4::new(m[0][1], m[1][1], m[2][1], m[3][1]),
  413. Vector4::new(m[0][2], m[1][2], m[2][2], m[3][2]),
  414. Vector4::new(m[0][3], m[1][3], m[2][3], m[3][3]),
  415. )
  416. }
  417. #[inline]
  418. pub fn submatrix(&self, s: usize, z: usize) -> Matrix3<T> {
  419. let mut ret = Matrix3::identity();
  420. for i in 0..=2 {
  421. for j in 0..=2 {
  422. let x = if i >= s { i + 1 } else { i };
  423. let y = if j >= z { j + 1 } else { j };
  424. ret[i][j] = self[x][y];
  425. }
  426. }
  427. ret
  428. }
  429. #[inline]
  430. pub fn determinant(&self) -> T {
  431. let m = self;
  432. m[0][0] * m.submatrix(0, 0).determinant() - m[1][0] * m.submatrix(1, 0).determinant()
  433. + m[2][0] * m.submatrix(2, 0).determinant()
  434. + m[3][0] * m.submatrix(3, 0).determinant()
  435. }
  436. #[inline]
  437. pub fn adjoint(&self) -> Self {
  438. let m = self;
  439. Self::new(
  440. Vector4::new(
  441. m.submatrix(0, 0).determinant(),
  442. -m.submatrix(1, 0).determinant(),
  443. m.submatrix(2, 0).determinant(),
  444. -m.submatrix(3, 0).determinant(),
  445. ),
  446. Vector4::new(
  447. -m.submatrix(0, 1).determinant(),
  448. m.submatrix(1, 1).determinant(),
  449. -m.submatrix(2, 1).determinant(),
  450. m.submatrix(3, 1).determinant(),
  451. ),
  452. Vector4::new(
  453. m.submatrix(0, 2).determinant(),
  454. -m.submatrix(1, 2).determinant(),
  455. m.submatrix(2, 2).determinant(),
  456. -m.submatrix(3, 2).determinant(),
  457. ),
  458. Vector4::new(
  459. -m.submatrix(0, 3).determinant(),
  460. m.submatrix(1, 3).determinant(),
  461. -m.submatrix(2, 3).determinant(),
  462. m.submatrix(3, 3).determinant(),
  463. ),
  464. )
  465. }
  466. #[inline]
  467. pub fn invert(&self) -> Self {
  468. let d = self.determinant();
  469. let mut ret = self.adjoint();
  470. ret[0][0] = ret[0][0] / d;
  471. ret[0][1] = ret[0][1] / d;
  472. ret[0][2] = ret[0][2] / d;
  473. ret[0][3] = ret[0][3] / d;
  474. ret[1][0] = ret[1][0] / d;
  475. ret[1][1] = ret[1][1] / d;
  476. ret[1][2] = ret[1][2] / d;
  477. ret[1][3] = ret[1][3] / d;
  478. ret[2][0] = ret[2][0] / d;
  479. ret[2][1] = ret[2][1] / d;
  480. ret[2][2] = ret[2][2] / d;
  481. ret[2][3] = ret[2][3] / d;
  482. ret[3][0] = ret[3][0] / d;
  483. ret[3][1] = ret[3][1] / d;
  484. ret[3][2] = ret[3][2] / d;
  485. ret[3][3] = ret[3][3] / d;
  486. ret
  487. }
  488. }
  489. impl<T> Matrix4<T>
  490. where
  491. T: Float,
  492. {
  493. #[inline]
  494. pub fn ortho(left: T, right: T, bottom: T, top: T, near: T, far: T) -> Self {
  495. let one = T::one();
  496. let two = one + one;
  497. let zero = T::zero();
  498. Matrix4::new(
  499. Vector4::new(two / (right - left), zero, zero, zero),
  500. Vector4::new(zero, two / (top - bottom), zero, zero),
  501. Vector4::new(zero, zero, -two / (far - near), zero),
  502. Vector4::new(
  503. -(right + left) / (right - left),
  504. -(top + bottom) / (top - bottom),
  505. -(far + near) / (far - near),
  506. one,
  507. ),
  508. )
  509. }
  510. #[inline]
  511. pub fn perspective(fov: Angle<T>, ratio: T, near: T, far: T) -> Self {
  512. let one = T::one();
  513. let two = one + one;
  514. let zero = T::zero();
  515. let top = near * fov.into_rad().into_inner().tan();
  516. let bottom = -top;
  517. let right = ratio * top;
  518. let left = -right;
  519. Matrix4::new(
  520. Vector4::new(two * near / (right - left), zero, zero, zero),
  521. Vector4::new(zero, two * near / (top - bottom), zero, zero),
  522. Vector4::new(
  523. (right + left) / (right - left),
  524. (top + bottom) / (top - bottom),
  525. -(far + near) / (far - near),
  526. -one,
  527. ),
  528. Vector4::new(zero, zero, -two * far * near / (far - near), zero),
  529. )
  530. }
  531. }
  532. impl<T, M> Mul<M> for Matrix4<T>
  533. where
  534. T: Float,
  535. M: Borrow<Matrix4<T>>,
  536. {
  537. type Output = Self;
  538. fn mul(self, rhs: M) -> Self::Output {
  539. self.multiply(rhs.borrow())
  540. }
  541. }
  542. #[cfg(test)]
  543. mod tests {
  544. use super::*;
  545. #[test]
  546. fn invert() {
  547. let m = Matrix4d::identity()
  548. * Matrix4::translate(Vector3::new(1.0, 2.0, 3.0))
  549. * Matrix4::scale(Vector3::new(30.0, 20.0, 10.0))
  550. * Matrix4::rotate(Vector3::new(1.0, 0.0, 0.0), Angle::Deg(45.0));
  551. let m = m.invert();
  552. let e = Matrix4d::new(
  553. Vector4::new(
  554. 0.019526214587563498,
  555. -0.000000000000000000,
  556. 0.000000000000000000,
  557. -0.000000000000000000,
  558. ),
  559. Vector4::new(
  560. -0.000000000000000000,
  561. 0.035355339059327376,
  562. -0.035355339059327376,
  563. 0.000000000000000000,
  564. ),
  565. Vector4::new(
  566. 0.00000000000000000,
  567. 0.07071067811865475,
  568. 0.07071067811865475,
  569. -0.00000000000000000,
  570. ),
  571. Vector4::new(
  572. -0.019526214587563498,
  573. -0.282842712474619000,
  574. -0.141421356237309560,
  575. 1.000000000000000000,
  576. ),
  577. );
  578. assert_eq!(e, m);
  579. }
  580. }