Skip to content

Commit

Permalink
mat2.determinant, mat2.inverse
Browse files Browse the repository at this point in the history
  • Loading branch information
sinisterchipmunk committed May 3, 2012
1 parent 5198b9b commit 99a6ced
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
33 changes: 33 additions & 0 deletions gl-matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -2610,6 +2610,39 @@
return dest;
};

/**
* Calculates the determinant of a mat2
*
* @param {mat2} mat mat2 to calculate determinant of
*
* @returns {Number} determinant of mat
*/
mat2.determinant = function (mat) {
return mat[0] * mat[3] - mat[2] * mat[1];
};

/**
* Calculates the inverse matrix of a mat2
*
* @param {mat2} mat mat2 to calculate inverse of
* @param {mat2} [dest] mat2 receiving inverse matrix. If not specified result is written to mat
*
* @param {mat2} dest is specified, mat otherwise, null if matrix cannot be inverted
*/
mat2.inverse = function (mat, dest) {
if (!dest) { dest = mat; }
var a0 = mat[0], a1 = mat[1], a2 = mat[2], a3 = mat[3];
var det = a0 * a3 - a2 * a1;
if (!det) return null;

det = 1.0 / det;
dest[0] = a3 * det;
dest[1] = -a1 * det;
dest[2] = -a2 * det;
dest[3] = a0 * det;
return dest;
}

/*
* Exports
*/
Expand Down
28 changes: 27 additions & 1 deletion spec/javascripts/mat2_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,31 @@ describe("mat2", function() {
it("should return a", function() { expect(result).toBe(a); });
});
});


describe("determinant", function() {
it("should produce the correct result", function() {
expect(mat2.determinant(a)).toBeEqualish(-2);
});
});

describe("inverse", function() {
describe("when no inverse exists", function() {
it("should be null", function() {
expect(mat2.inverse([3, 4, 6, 8])).toBeNull();
});
});

describe("with dest", function() {
beforeEach(function() { result = mat2.inverse(a = [4, 7, 2, 6], dest); });
it("should set dest", function() { expect(dest).toBeEqualish([0.6, -0.7, -0.2, 0.4]); });
it("should return dest", function() { expect(result).toBe(dest); });
it("should not modify a", function() { expect(a).toBeEqualish([4, 7, 2, 6]); });
});

describe("without dest", function() {
beforeEach(function() { result = mat2.inverse(a = [4, 7, 2, 6]); });
it("should set a", function() { expect(a).toBeEqualish([0.6, -0.7, -0.2, 0.4]); });
it("should return a", function() { expect(result).toBe(a); });
});
});
});

0 comments on commit 99a6ced

Please sign in to comment.