32inline bool InvertMat4(
const float M[16],
float out[16]) {
34 for (
int r = 0; r < 4; ++r) {
35 for (
int c = 0; c < 4; ++c) m[r][c] = M[r * 4 + c];
36 for (
int c = 0; c < 4; ++c) m[r][4 + c] = (r == c) ? 1.0f : 0.0f;
38 for (
int col = 0; col < 4; ++col) {
39 int pivot = -1;
float maxv = 0.0f;
40 for (
int row = col; row < 4; ++row) {
41 float v = std::abs(m[row][col]);
42 if (v > maxv) { maxv = v; pivot = row; }
44 if (pivot < 0 || maxv < 1e-7f)
return false;
45 if (pivot != col) std::swap(m[col], m[pivot]);
46 float inv = 1.0f / m[col][col];
47 for (
int c = 0; c < 8; ++c) m[col][c] *= inv;
48 for (
int row = 0; row < 4; ++row) {
49 if (row == col)
continue;
50 float f = m[row][col];
51 for (
int c = 0; c < 8; ++c) m[row][c] -= f * m[col][c];
54 for (
int r = 0; r < 4; ++r)
55 for (
int c = 0; c < 4; ++c)
56 out[r * 4 + c] = m[r][4 + c];