diff --git a/gl-matrix.js b/gl-matrix.js index 00e3edfc..4288033b 100644 --- a/gl-matrix.js +++ b/gl-matrix.js @@ -2586,6 +2586,30 @@ return dest; }; + /** + * Transposes a mat2 (flips the values over the diagonal) + * + * @param {mat2} mat mat2 to transpose + * @param {mat2} [dest] mat2 receiving transposed values. If not specified result is written to mat + * + * @param {mat2} dest if specified, mat otherwise + */ + mat2.transpose = function (mat, dest) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (!dest || mat === dest) { + var a00 = mat[1]; + mat[1] = mat[2]; + mat[2] = a00; + return mat; + } + + dest[0] = mat[0]; + dest[1] = mat[2]; + dest[2] = mat[1]; + dest[3] = mat[3]; + return dest; + }; + /* * Exports */ diff --git a/spec/javascripts/mat2_spec.js b/spec/javascripts/mat2_spec.js index d7881cd5..cc9a5843 100644 --- a/spec/javascripts/mat2_spec.js +++ b/spec/javascripts/mat2_spec.js @@ -43,4 +43,20 @@ describe("mat2", function() { it("should set result to identity", function() { expect(result).toBeEqualish([1, 0, 0, 1]); }); }); }); + + describe("transpose", function() { + describe("with dest", function() { + beforeEach(function() { result = mat2.transpose(a, dest); }); + it("should set dest to transpose", function() { expect(dest).toBeEqualish([1, 3, 2, 4]); }); + it("should return dest", function() { expect(result).toBe(dest); }); + it("should not alter a", function() { expect(a).toBeEqualish([1, 2, 3, 4]); }); + }); + + describe("without dest", function() { + beforeEach(function() { result = mat2.transpose(a); }); + it("should set a to transpose", function() { expect(a).toBeEqualish([1, 3, 2, 4]); }); + it("should return a", function() { expect(result).toBe(a); }); + }); + }); + });