matrix.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. * 3D Engine
  3. * matrice.c:
  4. * Based on pikuma.com 3D software renderer in C
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 06/03/2021.
  8. */
  9. #include <math.h>
  10. #include <matrix.h>
  11. /* Matrix operations */
  12. vec4_t mat4ProdVec4(matrix4_t mat, vec4_t v)
  13. {
  14. vec4_t ret =
  15. {
  16. .x = FastGet4(mat, 0, 0) * v.x +
  17. FastGet4(mat, 0, 1) * v.y +
  18. FastGet4(mat, 0, 2) * v.z +
  19. FastGet4(mat, 0, 3) * v.w,
  20. .y = FastGet4(mat, 1, 0) * v.x +
  21. FastGet4(mat, 1, 1) * v.y +
  22. FastGet4(mat, 1, 2) * v.z +
  23. FastGet4(mat, 1, 3) * v.w,
  24. .z = FastGet4(mat, 2, 0) * v.x +
  25. FastGet4(mat, 2, 1) * v.y +
  26. FastGet4(mat, 2, 2) * v.z +
  27. FastGet4(mat, 2, 3) * v.w,
  28. .w = FastGet4(mat, 3, 0) * v.x +
  29. FastGet4(mat, 3, 1) * v.y +
  30. FastGet4(mat, 3, 2) * v.z +
  31. FastGet4(mat, 3, 3) * v.w,
  32. };
  33. return ret;
  34. }
  35. /* Matrix creations */
  36. matrix4_t mat4Scale(double scaleX, double scaleY, double scaleZ)
  37. {
  38. matrix4_t ret =
  39. {
  40. .v =
  41. {
  42. scaleX, 0, 0, 0,
  43. 0, scaleY, 0, 0,
  44. 0, 0, scaleZ, 0,
  45. 0, 0, 0, 1
  46. }
  47. };
  48. return ret;
  49. }
  50. matrix4_t mat4Translate(double tX, double tY, double tZ)
  51. {
  52. matrix4_t ret =
  53. {
  54. .v =
  55. {
  56. 1, 0, 0, tX,
  57. 0, 1, 0, tY,
  58. 0, 0, 1, tZ,
  59. 0, 0, 0, 1
  60. }
  61. };
  62. return ret;
  63. }
  64. matrix4_t mat4RotationX(double angle)
  65. {
  66. matrix4_t ret =
  67. {
  68. .v =
  69. {
  70. 1, 0, 0, 0,
  71. 0, cos(angle), -sin(angle), 0,
  72. 0, sin(angle), cos(angle), 0,
  73. 0, 0, 0, 1
  74. }
  75. };
  76. return ret;
  77. }
  78. matrix4_t mat4RotationY(double angle)
  79. {
  80. matrix4_t ret =
  81. {
  82. .v =
  83. {
  84. cos(angle), 0, sin(angle), 0,
  85. 0, 1, 0, 0,
  86. -sin(angle), 0, cos(angle), 0,
  87. 0, 0, 0, 1
  88. }
  89. };
  90. return ret;
  91. }
  92. matrix4_t mat4RotationZ(double angle)
  93. {
  94. matrix4_t ret =
  95. {
  96. .v =
  97. {
  98. cos(angle), -sin(angle), 0, 0,
  99. sin(angle), cos(angle), 0, 0,
  100. 0, 0, 1, 0,
  101. 0, 0, 0, 1
  102. }
  103. };
  104. return ret;
  105. }