Matrix4x4.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Math.h>
  8. #include <LibGfx/Matrix.h>
  9. #include <LibGfx/Vector3.h>
  10. #include <LibGfx/Vector4.h>
  11. namespace Gfx {
  12. template<typename T>
  13. using Matrix4x4 = Matrix<4, T>;
  14. template<typename T>
  15. constexpr static Vector4<T> operator*(Matrix4x4<T> const& m, Vector4<T> const& v)
  16. {
  17. auto const& elements = m.elements();
  18. return Vector4<T>(
  19. v.x() * elements[0][0] + v.y() * elements[0][1] + v.z() * elements[0][2] + v.w() * elements[0][3],
  20. v.x() * elements[1][0] + v.y() * elements[1][1] + v.z() * elements[1][2] + v.w() * elements[1][3],
  21. v.x() * elements[2][0] + v.y() * elements[2][1] + v.z() * elements[2][2] + v.w() * elements[2][3],
  22. v.x() * elements[3][0] + v.y() * elements[3][1] + v.z() * elements[3][2] + v.w() * elements[3][3]);
  23. }
  24. // FIXME: this is a specific Matrix4x4 * Vector3 interaction that implies W=1; maybe move this out of LibGfx
  25. // or replace a Matrix4x4 * Vector4 operation?
  26. template<typename T>
  27. constexpr static Vector3<T> transform_point(Matrix4x4<T> const& m, Vector3<T> const& p)
  28. {
  29. auto const& elements = m.elements();
  30. return Vector3<T>(
  31. p.x() * elements[0][0] + p.y() * elements[0][1] + p.z() * elements[0][2] + elements[0][3],
  32. p.x() * elements[1][0] + p.y() * elements[1][1] + p.z() * elements[1][2] + elements[1][3],
  33. p.x() * elements[2][0] + p.y() * elements[2][1] + p.z() * elements[2][2] + elements[2][3]);
  34. }
  35. template<typename T>
  36. constexpr static Matrix4x4<T> translation_matrix(Vector3<T> const& p)
  37. {
  38. return Matrix4x4<T>(
  39. 1, 0, 0, p.x(),
  40. 0, 1, 0, p.y(),
  41. 0, 0, 1, p.z(),
  42. 0, 0, 0, 1);
  43. }
  44. template<typename T>
  45. constexpr static Matrix4x4<T> scale_matrix(Vector3<T> const& s)
  46. {
  47. return Matrix4x4<T>(
  48. s.x(), 0, 0, 0,
  49. 0, s.y(), 0, 0,
  50. 0, 0, s.z(), 0,
  51. 0, 0, 0, 1);
  52. }
  53. template<typename T>
  54. constexpr static Matrix4x4<T> rotation_matrix(Vector3<T> const& axis, T angle)
  55. {
  56. T c, s;
  57. AK::sincos(angle, s, c);
  58. T t = 1 - c;
  59. T x = axis.x();
  60. T y = axis.y();
  61. T z = axis.z();
  62. return Matrix4x4<T>(
  63. t * x * x + c, t * x * y - z * s, t * x * z + y * s, 0,
  64. t * x * y + z * s, t * y * y + c, t * y * z - x * s, 0,
  65. t * x * z - y * s, t * y * z + x * s, t * z * z + c, 0,
  66. 0, 0, 0, 1);
  67. }
  68. typedef Matrix4x4<float> FloatMatrix4x4;
  69. typedef Matrix4x4<double> DoubleMatrix4x4;
  70. }
  71. using Gfx::DoubleMatrix4x4;
  72. using Gfx::FloatMatrix4x4;
  73. using Gfx::Matrix4x4;