Matrix.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // This code is in the public domain -- [email protected]
  2. #include "Matrix.inl"
  3. #include "Vector.inl"
  4. #include <float.h>
  5. #if !NV_CC_MSVC && !NV_OS_ORBIS
  6. #include <alloca.h>
  7. #endif
  8. using namespace nv;
  9. // Given a matrix a[1..n][1..n], this routine replaces it by the LU decomposition of a rowwise
  10. // permutation of itself. a and n are input. a is output, arranged as in equation (2.3.14) above;
  11. // indx[1..n] is an output vector that records the row permutation effected by the partial
  12. // pivoting; d is output as -1 depending on whether the number of row interchanges was even
  13. // or odd, respectively. This routine is used in combination with lubksb to solve linear equations
  14. // or invert a matrix.
  15. static bool ludcmp(float **a, int n, int *indx, float *d)
  16. {
  17. const float TINY = 1.0e-20f;
  18. float * vv = (float*)alloca(sizeof(float) * n); // vv stores the implicit scaling of each row.
  19. *d = 1.0; // No row interchanges yet.
  20. for (int i = 0; i < n; i++) { // Loop over rows to get the implicit scaling information.
  21. float big = 0.0;
  22. for (int j = 0; j < n; j++) {
  23. big = max(big, fabsf(a[i][j]));
  24. }
  25. if (big == 0) {
  26. return false; // Singular matrix
  27. }
  28. // No nonzero largest element.
  29. vv[i] = 1.0f / big; // Save the scaling.
  30. }
  31. for (int j = 0; j < n; j++) { // This is the loop over columns of Crout's method.
  32. for (int i = 0; i < j; i++) { // This is equation (2.3.12) except for i = j.
  33. float sum = a[i][j];
  34. for (int k = 0; k < i; k++) sum -= a[i][k]*a[k][j];
  35. a[i][j] = sum;
  36. }
  37. int imax = -1;
  38. float big = 0.0; // Initialize for the search for largest pivot element.
  39. for (int i = j; i < n; i++) { // This is i = j of equation (2.3.12) and i = j+ 1 : : : N
  40. float sum = a[i][j]; // of equation (2.3.13).
  41. for (int k = 0; k < j; k++) {
  42. sum -= a[i][k]*a[k][j];
  43. }
  44. a[i][j]=sum;
  45. float dum = vv[i]*fabs(sum);
  46. if (dum >= big) {
  47. // Is the figure of merit for the pivot better than the best so far?
  48. big = dum;
  49. imax = i;
  50. }
  51. }
  52. nvDebugCheck(imax != -1);
  53. if (j != imax) { // Do we need to interchange rows?
  54. for (int k = 0; k < n; k++) { // Yes, do so...
  55. swap(a[imax][k], a[j][k]);
  56. }
  57. *d = -(*d); // ...and change the parity of d.
  58. vv[imax]=vv[j]; // Also interchange the scale factor.
  59. }
  60. indx[j]=imax;
  61. if (a[j][j] == 0.0) a[j][j] = TINY;
  62. // If the pivot element is zero the matrix is singular (at least to the precision of the
  63. // algorithm). For some applications on singular matrices, it is desirable to substitute
  64. // TINY for zero.
  65. if (j != n-1) { // Now, finally, divide by the pivot element.
  66. float dum = 1.0f / a[j][j];
  67. for (int i = j+1; i < n; i++) a[i][j] *= dum;
  68. }
  69. } // Go back for the next column in the reduction.
  70. return true;
  71. }
  72. // Solves the set of n linear equations Ax = b. Here a[1..n][1..n] is input, not as the matrix
  73. // A but rather as its LU decomposition, determined by the routine ludcmp. indx[1..n] is input
  74. // as the permutation vector returned by ludcmp. b[1..n] is input as the right-hand side vector
  75. // B, and returns with the solution vector X. a, n, and indx are not modified by this routine
  76. // and can be left in place for successive calls with different right-hand sides b. This routine takes
  77. // into account the possibility that b will begin with many zero elements, so it is efficient for use
  78. // in matrix inversion.
  79. static void lubksb(float **a, int n, int *indx, float b[])
  80. {
  81. int ii = 0;
  82. for (int i=0; i<n; i++) { // When ii is set to a positive value, it will become
  83. int ip = indx[i]; // the index of the first nonvanishing element of b. We now
  84. float sum = b[ip]; // do the forward substitution, equation (2.3.6). The
  85. b[ip] = b[i]; // only new wrinkle is to unscramble the permutation as we go.
  86. if (ii != 0) {
  87. for (int j = ii-1; j < i; j++) sum -= a[i][j]*b[j];
  88. }
  89. else if (sum != 0.0f) {
  90. ii = i+1; // A nonzero element was encountered, so from now on we
  91. }
  92. b[i] = sum; // will have to do the sums in the loop above.
  93. }
  94. for (int i=n-1; i>=0; i--) { // Now we do the backsubstitution, equation (2.3.7).
  95. float sum = b[i];
  96. for (int j = i+1; j < n; j++) {
  97. sum -= a[i][j]*b[j];
  98. }
  99. b[i] = sum/a[i][i]; // Store a component of the solution vector X.
  100. } // All done!
  101. }
  102. bool nv::solveLU(const Matrix & A, const Vector4 & b, Vector4 * x)
  103. {
  104. nvDebugCheck(x != NULL);
  105. float m[4][4];
  106. float *a[4] = {m[0], m[1], m[2], m[3]};
  107. int idx[4];
  108. float d;
  109. for (int y = 0; y < 4; y++) {
  110. for (int x = 0; x < 4; x++) {
  111. a[x][y] = A(x, y);
  112. }
  113. }
  114. // Create LU decomposition.
  115. if (!ludcmp(a, 4, idx, &d)) {
  116. // Singular matrix.
  117. return false;
  118. }
  119. // Init solution.
  120. *x = b;
  121. // Do back substitution.
  122. lubksb(a, 4, idx, x->component);
  123. return true;
  124. }
  125. bool nv::solveLU(const Matrix3 & A, const Vector3 & b, Vector3 * x)
  126. {
  127. nvDebugCheck(x != NULL);
  128. float m[3][3];
  129. float *a[3] = {m[0], m[1], m[2]};
  130. int idx[3];
  131. float d;
  132. for (int y = 0; y < 3; y++) {
  133. for (int x = 0; x < 3; x++) {
  134. a[x][y] = A(x, y);
  135. }
  136. }
  137. // Create LU decomposition.
  138. if (!ludcmp(a, 3, idx, &d)) {
  139. // Singular matrix.
  140. return false;
  141. }
  142. // Init solution.
  143. *x = b;
  144. // Do back substitution.
  145. lubksb(a, 3, idx, x->component);
  146. return true;
  147. }
  148. bool nv::solveCramer(const Matrix & A, const Vector4 & b, Vector4 * x)
  149. {
  150. nvDebugCheck(x != NULL);
  151. *x = transform(inverse(A), b);
  152. return true; // @@ Return false if determinant(A) == 0 !
  153. }
  154. bool nv::solveCramer(const Matrix3 & A, const Vector3 & b, Vector3 * x)
  155. {
  156. nvDebugCheck(x != NULL);
  157. const float det = A.determinant();
  158. if (equal(det, 0.0f)) { // @@ Use input epsilon.
  159. return false;
  160. }
  161. Matrix3 Ai = inverse(A);
  162. *x = transform(Ai, b);
  163. return true;
  164. }
  165. #if 0
  166. // Copyright (C) 1999-2004 Michael Garland.
  167. //
  168. // Permission is hereby granted, free of charge, to any person obtaining a
  169. // copy of this software and associated documentation files (the
  170. // "Software"), to deal in the Software without restriction, including
  171. // without limitation the rights to use, copy, modify, merge, publish,
  172. // distribute, and/or sell copies of the Software, and to permit persons
  173. // to whom the Software is furnished to do so, provided that the above
  174. // copyright notice(s) and this permission notice appear in all copies of
  175. // the Software and that both the above copyright notice(s) and this
  176. // permission notice appear in supporting documentation.
  177. //
  178. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  179. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  180. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
  181. // OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  182. // HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
  183. // INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
  184. // FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  185. // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  186. // WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  187. //
  188. // Except as contained in this notice, the name of a copyright holder
  189. // shall not be used in advertising or otherwise to promote the sale, use
  190. // or other dealings in this Software without prior written authorization
  191. // of the copyright holder.
  192. // Matrix inversion code for 4x4 matrices using Gaussian elimination
  193. // with partial pivoting. This is a specialized version of a
  194. // procedure originally due to Paul Heckbert <[email protected]>.
  195. //
  196. // Returns determinant of A, and B=inverse(A)
  197. // If matrix A is singular, returns 0 and leaves trash in B.
  198. //
  199. #define SWAP(a, b, t) {t = a; a = b; b = t;}
  200. double invert(Mat4& B, const Mat4& m)
  201. {
  202. Mat4 A = m;
  203. int i, j, k;
  204. double max, t, det, pivot;
  205. /*---------- forward elimination ----------*/
  206. for (i=0; i<4; i++) /* put identity matrix in B */
  207. for (j=0; j<4; j++)
  208. B(i, j) = (double)(i==j);
  209. det = 1.0;
  210. for (i=0; i<4; i++) { /* eliminate in column i, below diag */
  211. max = -1.;
  212. for (k=i; k<4; k++) /* find pivot for column i */
  213. if (fabs(A(k, i)) > max) {
  214. max = fabs(A(k, i));
  215. j = k;
  216. }
  217. if (max<=0.) return 0.; /* if no nonzero pivot, PUNT */
  218. if (j!=i) { /* swap rows i and j */
  219. for (k=i; k<4; k++)
  220. SWAP(A(i, k), A(j, k), t);
  221. for (k=0; k<4; k++)
  222. SWAP(B(i, k), B(j, k), t);
  223. det = -det;
  224. }
  225. pivot = A(i, i);
  226. det *= pivot;
  227. for (k=i+1; k<4; k++) /* only do elems to right of pivot */
  228. A(i, k) /= pivot;
  229. for (k=0; k<4; k++)
  230. B(i, k) /= pivot;
  231. /* we know that A(i, i) will be set to 1, so don't bother to do it */
  232. for (j=i+1; j<4; j++) { /* eliminate in rows below i */
  233. t = A(j, i); /* we're gonna zero this guy */
  234. for (k=i+1; k<4; k++) /* subtract scaled row i from row j */
  235. A(j, k) -= A(i, k)*t; /* (ignore k<=i, we know they're 0) */
  236. for (k=0; k<4; k++)
  237. B(j, k) -= B(i, k)*t;
  238. }
  239. }
  240. /*---------- backward elimination ----------*/
  241. for (i=4-1; i>0; i--) { /* eliminate in column i, above diag */
  242. for (j=0; j<i; j++) { /* eliminate in rows above i */
  243. t = A(j, i); /* we're gonna zero this guy */
  244. for (k=0; k<4; k++) /* subtract scaled row i from row j */
  245. B(j, k) -= B(i, k)*t;
  246. }
  247. }
  248. return det;
  249. }
  250. #endif // 0