"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var create_1 = require("../gl-mat4/create");
var cross_1 = require("../gl-vec3/cross");
var dot_1 = require("../gl-vec3/dot");
var length_1 = require("../gl-vec3/length");
var normalize_1 = require("../gl-vec3/normalize");
var normalize_2 = require("./normalize");
var vec3 = {
    length: length_1.default,
    normalize: normalize_1.default,
    dot: dot_1.default,
    cross: cross_1.default,
};
var tmp = create_1.default();
var row = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
var pdum3 = [0, 0, 0];
exports.roundVector = function (vector) { return vector.map(function (value) { return Number(value.toFixed(2)); }); };
function decomposeMat4(matrix) {
    if (!normalize_2.default(tmp, matrix)) {
        return false;
    }
    var translation = exports.roundVector([tmp[12], tmp[13], tmp[14]]);
    mat3from4(row, tmp);
    var scale = exports.roundVector([
        vec3.length(row[0]),
        vec3.length(row[1]),
        vec3.length(row[2]),
    ]);
    if (scale.indexOf(0) !== -1) {
        return {
            translation: [0, 0, 0],
            scale: [0, 0, 0],
            quaternion: [0, 0, 0, 0],
        };
    }
    vec3.normalize(row[0], row[0]);
    vec3.normalize(row[1], row[1]);
    vec3.normalize(row[2], row[2]);
    vec3.cross(pdum3, row[1], row[2]);
    if (vec3.dot(row[0], pdum3) < 0) {
        for (var i = 0; i < 3; i++) {
            scale[i] *= -1;
            row[i][0] *= -1;
            row[i][1] *= -1;
            row[i][2] *= -1;
        }
    }
    var quaternion = [
        0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0)),
        0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0)),
        0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0)),
        0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0)),
    ];
    if (row[2][1] > row[1][2]) {
        quaternion[0] = -quaternion[0];
    }
    if (row[0][2] > row[2][0]) {
        quaternion[1] = -quaternion[1];
    }
    if (row[1][0] > row[0][1]) {
        quaternion[2] = -quaternion[2];
    }
    return { translation: translation, scale: scale, quaternion: quaternion };
}
exports.default = decomposeMat4;
function mat3from4(out, mat4x4) {
    out[0][0] = mat4x4[0];
    out[0][1] = mat4x4[1];
    out[0][2] = mat4x4[2];
    out[1][0] = mat4x4[4];
    out[1][1] = mat4x4[5];
    out[1][2] = mat4x4[6];
    out[2][0] = mat4x4[8];
    out[2][1] = mat4x4[9];
    out[2][2] = mat4x4[10];
}
//# sourceMappingURL=index.js.map