/**
* Creates a invert copy of the given matrix.
* @author Julian Lloyd
* code from https://github.com/jlmakes/rematrix/blob/master/src/index.js
*
* @param {mat4} out - receiving matrix
* @param {mat4} matrix - matrix to invert
* @returns {mat4} out
* @alias module:modeling/maths/mat4.invert
*/
const invert = (out, matrix) => {
const a00 = matrix[0]
const a01 = matrix[1]
const a02 = matrix[2]
const a03 = matrix[3]
const a10 = matrix[4]
const a11 = matrix[5]
const a12 = matrix[6]
const a13 = matrix[7]
const a20 = matrix[8]
const a21 = matrix[9]
const a22 = matrix[10]
const a23 = matrix[11]
const a30 = matrix[12]
const a31 = matrix[13]
const a32 = matrix[14]
const a33 = matrix[15]
const b00 = a00 * a11 - a01 * a10
const b01 = a00 * a12 - a02 * a10
const b02 = a00 * a13 - a03 * a10
const b03 = a01 * a12 - a02 * a11
const b04 = a01 * a13 - a03 * a11
const b05 = a02 * a13 - a03 * a12
const b06 = a20 * a31 - a21 * a30
const b07 = a20 * a32 - a22 * a30
const b08 = a20 * a33 - a23 * a30
const b09 = a21 * a32 - a22 * a31
const b10 = a21 * a33 - a23 * a31
const b11 = a22 * a33 - a23 * a32
// Calculate the determinant
let det =
b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06
if (!det) {
return null
}
det = 1.0 / det
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det
out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det
out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det
out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det
out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det
out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det
out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det
out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det
out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det
out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det
out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det
out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det
out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det
out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det
out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det
out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det
return out
}
module.exports = invert