選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

713 行
19 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: Into<Vector2<T>>>(v: V) -> Self {
  244. let v = V::into(v);
  245. let one = T::one();
  246. let zro = T::zero();
  247. Self::new(
  248. Vector3::new(one, zro, zro),
  249. Vector3::new(zro, one, zro),
  250. Vector3::new(v.x, v.y, one),
  251. )
  252. }
  253. #[inline]
  254. pub fn determinant(&self) -> T {
  255. let m = self;
  256. 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]
  257. - m[2][0] * m[1][1] * m[0][2]
  258. - m[1][0] * m[0][1] * m[2][2]
  259. - m[0][0] * m[2][1] * m[1][2]
  260. }
  261. #[inline]
  262. pub fn multiply<M: Borrow<Self>>(&self, other: M) -> Self {
  263. let m1 = self;
  264. let m2 = other.borrow();
  265. macro_rules! mul {
  266. ($x:tt, $y:tt) => {
  267. m1[0][$y] * m2[$x][0] + m1[1][$y] * m2[$x][1] + m1[2][$y] * m2[$x][2]
  268. };
  269. }
  270. Self::new(
  271. Vector3::new(mul!(0, 0), mul!(0, 1), mul!(0, 2)),
  272. Vector3::new(mul!(1, 0), mul!(1, 1), mul!(1, 2)),
  273. Vector3::new(mul!(2, 0), mul!(2, 1), mul!(2, 2)),
  274. )
  275. }
  276. #[inline]
  277. pub fn transform<V: Into<Vector2<T>>>(&self, v: V) -> Vector2<T> {
  278. let m = self;
  279. let v = V::into(v);
  280. macro_rules! mul {
  281. ($i:tt) => {
  282. m[0][$i] * v[0] + m[1][$i] * v[1] + m[2][$i] * T::one()
  283. };
  284. }
  285. Vector2::new(mul!(0), mul!(1))
  286. }
  287. }
  288. impl<T> Matrix3<T>
  289. where
  290. T: Float,
  291. {
  292. #[inline]
  293. pub fn rotate(a: Angle<T>) -> Self {
  294. let one = T::one();
  295. let zro = T::zero();
  296. Self::new(
  297. Vector3::new(a.cos(), -a.sin(), zro),
  298. Vector3::new(a.sin(), a.cos(), zro),
  299. Vector3::new(zro, zro, one),
  300. )
  301. }
  302. }
  303. impl<T, M> Mul<M> for Matrix3<T>
  304. where
  305. T: Float,
  306. M: Borrow<Matrix3<T>>,
  307. {
  308. type Output = Self;
  309. fn mul(self, rhs: M) -> Self::Output {
  310. self.multiply(rhs.borrow())
  311. }
  312. }
  313. /* Matrix4 */
  314. impl<T> Matrix4<T>
  315. where
  316. T: Numeric,
  317. {
  318. #[inline]
  319. pub fn identity() -> Self {
  320. let one = T::one();
  321. let zero = T::zero();
  322. Self::new(
  323. Vector4::new(one, zero, zero, zero),
  324. Vector4::new(zero, one, zero, zero),
  325. Vector4::new(zero, zero, one, zero),
  326. Vector4::new(zero, zero, zero, one),
  327. )
  328. }
  329. }
  330. impl<T> Matrix4<T>
  331. where
  332. T: Float,
  333. {
  334. #[inline]
  335. pub fn translate<V: Into<Vector3<T>>>(v: V) -> Self {
  336. let v = V::into(v);
  337. let one = T::one();
  338. let zero = T::zero();
  339. Self::new(
  340. Vector4::new(one, zero, zero, zero),
  341. Vector4::new(zero, one, zero, zero),
  342. Vector4::new(zero, zero, one, zero),
  343. Vector4::new(v.x, v.y, v.z, one),
  344. )
  345. }
  346. #[inline]
  347. pub fn scale<V: Into<Vector3<T>>>(v: V) -> Self {
  348. let v = V::into(v);
  349. let one = T::one();
  350. let zero = T::zero();
  351. Self::new(
  352. Vector4::new(v.x, zero, zero, zero),
  353. Vector4::new(zero, v.y, zero, zero),
  354. Vector4::new(zero, zero, v.z, zero),
  355. Vector4::new(zero, zero, zero, one),
  356. )
  357. }
  358. #[inline]
  359. #[allow(clippy::many_single_char_names)]
  360. pub fn rotate<V: Into<Vector3<T>>>(axis: V, angle: Angle<T>) -> Self {
  361. let axis = V::into(axis).normalize();
  362. let x = axis.x;
  363. let y = axis.y;
  364. let z = axis.z;
  365. let angle = angle.into_rad().into_inner();
  366. let s = T::sin(angle);
  367. let c = T::cos(angle);
  368. let one = T::one();
  369. let zero = T::zero();
  370. Self::new(
  371. Vector4::new(
  372. x * x + (one - y * y) * c,
  373. x * y * (one - c) + z * s,
  374. x * z * (one - c) - y * s,
  375. zero,
  376. ),
  377. Vector4::new(
  378. x * y * (one - c) - z * s,
  379. y * y + (one - y * y) * c,
  380. y * z * (one - c) + x * s,
  381. zero,
  382. ),
  383. Vector4::new(
  384. x * z * (one - c) + y * s,
  385. y * z * (one - c) - x * s,
  386. z * z + (one - z * z) * c,
  387. zero,
  388. ),
  389. Vector4::new(zero, zero, zero, one),
  390. )
  391. }
  392. #[inline]
  393. pub fn multiply<M: Borrow<Self>>(&self, other: M) -> Self {
  394. let m1 = self;
  395. let m2 = other.borrow();
  396. macro_rules! mul {
  397. ($x:tt, $y:tt) => {
  398. m1[0][$y] * m2[$x][0]
  399. + m1[1][$y] * m2[$x][1]
  400. + m1[2][$y] * m2[$x][2]
  401. + m1[3][$y] * m2[$x][3]
  402. };
  403. }
  404. Self::new(
  405. Vector4::new(mul!(0, 0), mul!(0, 1), mul!(0, 2), mul!(0, 3)),
  406. Vector4::new(mul!(1, 0), mul!(1, 1), mul!(1, 2), mul!(1, 3)),
  407. Vector4::new(mul!(2, 0), mul!(2, 1), mul!(2, 2), mul!(2, 3)),
  408. Vector4::new(mul!(3, 0), mul!(3, 1), mul!(3, 2), mul!(3, 3)),
  409. )
  410. }
  411. #[inline]
  412. pub fn transform<V: Into<Vector4<T>>>(&self, v: V) -> Vector4<T> {
  413. let m = self;
  414. let v = V::into(v);
  415. macro_rules! mul {
  416. ($i:tt) => {
  417. m[0][$i] * v[0] + m[1][$i] * v[1] + m[2][$i] * v[2] + m[3][$i] * v[3]
  418. };
  419. }
  420. Vector4::new(mul!(0), mul!(1), mul!(2), mul!(3))
  421. }
  422. #[inline]
  423. pub fn transpose(&self) -> Self {
  424. let m = self;
  425. Self::new(
  426. Vector4::new(m[0][0], m[1][0], m[2][0], m[3][0]),
  427. Vector4::new(m[0][1], m[1][1], m[2][1], m[3][1]),
  428. Vector4::new(m[0][2], m[1][2], m[2][2], m[3][2]),
  429. Vector4::new(m[0][3], m[1][3], m[2][3], m[3][3]),
  430. )
  431. }
  432. #[inline]
  433. pub fn submatrix(&self, s: usize, z: usize) -> Matrix3<T> {
  434. let mut ret = Matrix3::identity();
  435. for i in 0..=2 {
  436. for j in 0..=2 {
  437. let x = if i >= s { i + 1 } else { i };
  438. let y = if j >= z { j + 1 } else { j };
  439. ret[i][j] = self[x][y];
  440. }
  441. }
  442. ret
  443. }
  444. #[inline]
  445. pub fn determinant(&self) -> T {
  446. let m = self;
  447. m[0][0] * m.submatrix(0, 0).determinant() - m[1][0] * m.submatrix(1, 0).determinant()
  448. + m[2][0] * m.submatrix(2, 0).determinant()
  449. + m[3][0] * m.submatrix(3, 0).determinant()
  450. }
  451. #[inline]
  452. pub fn adjoint(&self) -> Self {
  453. let m = self;
  454. Self::new(
  455. Vector4::new(
  456. m.submatrix(0, 0).determinant(),
  457. -m.submatrix(1, 0).determinant(),
  458. m.submatrix(2, 0).determinant(),
  459. -m.submatrix(3, 0).determinant(),
  460. ),
  461. Vector4::new(
  462. -m.submatrix(0, 1).determinant(),
  463. m.submatrix(1, 1).determinant(),
  464. -m.submatrix(2, 1).determinant(),
  465. m.submatrix(3, 1).determinant(),
  466. ),
  467. Vector4::new(
  468. m.submatrix(0, 2).determinant(),
  469. -m.submatrix(1, 2).determinant(),
  470. m.submatrix(2, 2).determinant(),
  471. -m.submatrix(3, 2).determinant(),
  472. ),
  473. Vector4::new(
  474. -m.submatrix(0, 3).determinant(),
  475. m.submatrix(1, 3).determinant(),
  476. -m.submatrix(2, 3).determinant(),
  477. m.submatrix(3, 3).determinant(),
  478. ),
  479. )
  480. }
  481. #[inline]
  482. pub fn invert(&self) -> Self {
  483. let d = self.determinant();
  484. let mut ret = self.adjoint();
  485. ret[0][0] = ret[0][0] / d;
  486. ret[0][1] = ret[0][1] / d;
  487. ret[0][2] = ret[0][2] / d;
  488. ret[0][3] = ret[0][3] / d;
  489. ret[1][0] = ret[1][0] / d;
  490. ret[1][1] = ret[1][1] / d;
  491. ret[1][2] = ret[1][2] / d;
  492. ret[1][3] = ret[1][3] / d;
  493. ret[2][0] = ret[2][0] / d;
  494. ret[2][1] = ret[2][1] / d;
  495. ret[2][2] = ret[2][2] / d;
  496. ret[2][3] = ret[2][3] / d;
  497. ret[3][0] = ret[3][0] / d;
  498. ret[3][1] = ret[3][1] / d;
  499. ret[3][2] = ret[3][2] / d;
  500. ret[3][3] = ret[3][3] / d;
  501. ret
  502. }
  503. }
  504. impl<T> Matrix4<T>
  505. where
  506. T: Float,
  507. {
  508. #[inline]
  509. pub fn ortho(left: T, right: T, bottom: T, top: T, near: T, far: T) -> Self {
  510. let one = T::one();
  511. let two = one + one;
  512. let zero = T::zero();
  513. Matrix4::new(
  514. Vector4::new(two / (right - left), zero, zero, zero),
  515. Vector4::new(zero, two / (top - bottom), zero, zero),
  516. Vector4::new(zero, zero, -two / (far - near), zero),
  517. Vector4::new(
  518. -(right + left) / (right - left),
  519. -(top + bottom) / (top - bottom),
  520. -(far + near) / (far - near),
  521. one,
  522. ),
  523. )
  524. }
  525. #[inline]
  526. pub fn perspective(fov: Angle<T>, ratio: T, near: T, far: T) -> Self {
  527. let one = T::one();
  528. let two = one + one;
  529. let zero = T::zero();
  530. let top = near * fov.into_rad().into_inner().tan();
  531. let bottom = -top;
  532. let right = ratio * top;
  533. let left = -right;
  534. Matrix4::new(
  535. Vector4::new(two * near / (right - left), zero, zero, zero),
  536. Vector4::new(zero, two * near / (top - bottom), zero, zero),
  537. Vector4::new(
  538. (right + left) / (right - left),
  539. (top + bottom) / (top - bottom),
  540. -(far + near) / (far - near),
  541. -one,
  542. ),
  543. Vector4::new(zero, zero, -two * far * near / (far - near), zero),
  544. )
  545. }
  546. }
  547. macro_rules! impl_mul_mat4 {
  548. ($input:ty, $output:ty, $func:ident) => {
  549. impl<T> Mul<$input> for Matrix4<T>
  550. where
  551. T: Float,
  552. {
  553. type Output = $output;
  554. fn mul(self, rhs: $input) -> Self::Output {
  555. self.$func(rhs)
  556. }
  557. }
  558. impl<T> Mul<$input> for &Matrix4<T>
  559. where
  560. T: Float,
  561. {
  562. type Output = $output;
  563. fn mul(self, rhs: $input) -> Self::Output {
  564. self.$func(rhs)
  565. }
  566. }
  567. };
  568. }
  569. impl_mul_mat4!(Matrix4<T>, Matrix4<T>, multiply);
  570. impl_mul_mat4!(&Matrix4<T>, Matrix4<T>, multiply);
  571. impl_mul_mat4!(Vector4<T>, Vector4<T>, transform);
  572. #[cfg(test)]
  573. mod tests {
  574. use super::*;
  575. #[test]
  576. fn invert() {
  577. let m = Matrix4d::identity()
  578. * Matrix4::translate(Vector3::new(1.0, 2.0, 3.0))
  579. * Matrix4::scale(Vector3::new(30.0, 20.0, 10.0))
  580. * Matrix4::rotate(Vector3::new(1.0, 0.0, 0.0), Angle::Deg(45.0));
  581. let m = m.invert();
  582. let e = Matrix4d::new(
  583. Vector4::new(
  584. 0.019526214587563498,
  585. -0.000000000000000000,
  586. 0.000000000000000000,
  587. -0.000000000000000000,
  588. ),
  589. Vector4::new(
  590. -0.000000000000000000,
  591. 0.035355339059327376,
  592. -0.035355339059327376,
  593. 0.000000000000000000,
  594. ),
  595. Vector4::new(
  596. 0.00000000000000000,
  597. 0.07071067811865475,
  598. 0.07071067811865475,
  599. -0.00000000000000000,
  600. ),
  601. Vector4::new(
  602. -0.019526214587563498,
  603. -0.282842712474619000,
  604. -0.141421356237309560,
  605. 1.000000000000000000,
  606. ),
  607. );
  608. assert_eq!(e, m);
  609. }
  610. }