matrix3.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. const Matrix3 IDENT_MATRIX3 = {{
  2. 1, 0, 0,
  3. 0, 1, 0,
  4. 0, 0, 1,
  5. }};
  6. void mIdent3(Matrix3* m) {
  7. *m = IDENT_MATRIX3;
  8. }
  9. // out cannot overlap with a or b
  10. // with restrict and -O2, this vectorizes nicely.
  11. void mFastMul3(Matrix3* restrict a, Matrix3* restrict b, Matrix3* restrict out) {
  12. int r, c;
  13. for(r = 0; r < 3; r++) {
  14. for(c = 0; c < 3; c++) {
  15. out->m[c + r * 3] =
  16. (a->m[r * 3 + 0] * b->m[c + 0]) +
  17. (a->m[r * 3 + 1] * b->m[c + 3]) +
  18. (a->m[r * 3 + 2] * b->m[c + 6]);
  19. }
  20. }
  21. }
  22. void mMul3(Matrix3* a, Matrix3* out) {
  23. Matrix3 b = *out;
  24. mFastMul3(a, &b, out);
  25. }
  26. Vector3 vMatrix3Mul(Vector3 v, Matrix3* restrict m) {
  27. return (Vector3){
  28. .x = v.x * m->m[0+0] + v.y * m->m[3+0] + v.z * m->m[6+0],
  29. .y = v.x * m->m[0+1] + v.y * m->m[3+1] + v.z * m->m[6+1],
  30. .z = v.x * m->m[0+2] + v.y * m->m[3+2] + v.z * m->m[6+2]
  31. };
  32. }
  33. float mDeterminate3(Matrix3* m) {
  34. // computes the inverse of a matrix m
  35. return m->m[0+0] * (m->m[3+1] * m->m[6+2] - m->m[6+1] * m->m[3+2]) -
  36. m->m[0+1] * (m->m[3+0] * m->m[6+2] - m->m[3+2] * m->m[6+0]) +
  37. m->m[0+2] * (m->m[3+0] * m->m[6+1] - m->m[3+1] * m->m[6+0]);
  38. }
  39. void mInverse3(Matrix3* m, Matrix3* out) {
  40. double id = 1.0 / mDeterminate3(m);
  41. out->m[0+0] = (m->m[3+1] * m->m[6+2] - m->m[6+1] * m->m[3+2]) * id;
  42. out->m[0+1] = (m->m[0+2] * m->m[6+1] - m->m[0+1] * m->m[6+2]) * id;
  43. out->m[0+2] = (m->m[0+1] * m->m[3+2] - m->m[0+2] * m->m[3+1]) * id;
  44. out->m[3+0] = (m->m[3+2] * m->m[6+0] - m->m[3+0] * m->m[6+2]) * id;
  45. out->m[3+1] = (m->m[0+0] * m->m[6+2] - m->m[0+2] * m->m[6+0]) * id;
  46. out->m[3+2] = (m->m[3+0] * m->m[0+2] - m->m[0+0] * m->m[3+2]) * id;
  47. out->m[6+0] = (m->m[3+0] * m->m[6+1] - m->m[6+0] * m->m[3+1]) * id;
  48. out->m[6+1] = (m->m[6+0] * m->m[0+1] - m->m[0+0] * m->m[6+1]) * id;
  49. out->m[6+2] = (m->m[0+0] * m->m[3+1] - m->m[3+0] * m->m[0+1]) * id;
  50. }
  51. void mScalarMul3(Matrix3* m, float scalar, Matrix3* out) {
  52. for(int i = 0; i < 9; i++) out->m[i] = m->m[i] * scalar;
  53. }
  54. void mTranspose3(Matrix3* m, Matrix3* out) {
  55. float tmp;
  56. out->m[0+0*3] = m->m[0+0*3];
  57. out->m[1+1*3] = m->m[1+1*3];
  58. out->m[2+2*3] = m->m[2+2*3];
  59. tmp = m->m[0+1*3];
  60. out->m[0+1*3] = m->m[1+0*3];
  61. out->m[1+0*3] = tmp;
  62. tmp = m->m[0+2*3];
  63. out->m[0+2*3] = m->m[2+0*3];
  64. out->m[2+0*3] = tmp;
  65. tmp = m->m[2+1*3];
  66. out->m[2+1*3] = m->m[1+2*3];
  67. out->m[1+2*3] = tmp;
  68. }
  69. float mTrace3(Matrix3* m) {
  70. return m->m[0+0*3] + m->m[1+1*3] + m->m[2+2*3];
  71. }