gallery3d: Add new widget
authorWonseop Kim <wonseop.kim@samsung.com>
Thu, 7 Mar 2013 13:22:44 +0000 (22:22 +0900)
committerYoumin Ha <youmin.ha@samsung.com>
Fri, 22 Mar 2013 11:22:28 +0000 (20:22 +0900)
Gallery3D is a 3D photo gallery widget.
Images are arranged with a S-shaped curve on a 3-dimensional coordinate system.
A user can rotate images by swiping the widget area.

Change-Id: I235607abefb632bea9bc92b0b323c93d9b73094b

12 files changed:
COPYING
Makefile
demos/tizen-winsets/index.html
demos/tizen-winsets/widgets/gallery3d/gallery3d.html [new file with mode: 0644]
libs/js/gl-matrix.js [new file with mode: 0644]
src/js/widgets/components/imageloader.js [new file with mode: 0644]
src/js/widgets/components/motionpath.js [new file with mode: 0644]
src/js/widgets/components/webgl.js [new file with mode: 0644]
src/js/widgets/jquery.mobile.tizen.gallery3d.js [new file with mode: 0644]
tests/unit-tests/gallery3d/gallery3d-tests.js [new file with mode: 0644]
tests/unit-tests/gallery3d/index.html [new file with mode: 0644]
tests/unit-tests/tests.js

diff --git a/COPYING b/COPYING
index eba9399..1c2dba1 100644 (file)
--- a/COPYING
+++ b/COPYING
@@ -42,3 +42,5 @@ jQuery (http://jquery.com/) [MIT license]
 (parts of) Underscore (http://documentcloud.github.com/underscore/) [MIT license]
 
 Globalize (http://github.com/jquery/globalize/) [MIT license]
+
+glMatrix 1.3.7 (https://github.com/toji/gl-matrix) [https://github.com/toji/gl-matrix/blob/master/LICENSE.md]
index 74f0027..2f20fc4 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -55,6 +55,7 @@ LIBS_JS_FILES = jquery.easing.1.3.js \
                jquery.tmpl.js \
                jquery.mobile.js \
                globalize/lib/globalize.js \
+               gl-matrix.js \
                $(NULL)
 
 JQUERY_MOBILE_CSS = submodules/jquery-mobile/compiled/jquery.mobile.structure.css \
index 06881f8..09aa153 100644 (file)
 
 
 
+<!-- START_PROPRIETARY -->
+                               <li data-role="list-divider">Experimental</li>
+                               <li><a href="widgets/gallery3d/gallery3d.html">Gallery 3D</a></li>
+<!-- END_PROPRIETARY -->
                        </ul>
                </div>
                <div data-role="footer">
diff --git a/demos/tizen-winsets/widgets/gallery3d/gallery3d.html b/demos/tizen-winsets/widgets/gallery3d/gallery3d.html
new file mode 100644 (file)
index 0000000..325214c
--- /dev/null
@@ -0,0 +1,22 @@
+<!DOCTYPE html>\r
+<div data-role="page" data-add-back-btn="true">\r
+       <div data-role="header" data-position="fixed" >\r
+               <h1>Gallery 3D</h1>\r
+       </div><!-- /header -->\r
+\r
+       <div data-role="content">\r
+               <div id="gallery3d" data-role="gallery3d" style="width: 100%;"></div>\r
+       </div><!-- /content -->\r
+\r
+       <div data-role="footer">\r
+       </div><!-- /footer -->\r
+\r
+       <script>\r
+               $( "#gallery3d" ).bind( "gallery3dcreate", function () {\r
+                       var widget = $( "#gallery3d" );\r
+                       widget.gallery3d( "add", { src: "../test/01.jpg" } )\r
+                               .gallery3d( "add", { src: "../test/02.jpg" } )\r
+                               .gallery3d( "add", { src: "../test/03.jpg" } );\r
+               });\r
+       </script>\r
+</div><!-- /page -->\r
diff --git a/libs/js/gl-matrix.js b/libs/js/gl-matrix.js
new file mode 100644 (file)
index 0000000..5718055
--- /dev/null
@@ -0,0 +1,3456 @@
+/**
+ * @fileoverview gl-matrix - High performance matrix and vector operations for WebGL
+ * @author Brandon Jones
+ * @author Colin MacKenzie IV
+ * @version 1.3.7
+ */
+
+/*
+ * Copyright (c) 2012 Brandon Jones, Colin MacKenzie IV
+ *
+ * This software is provided 'as-is', without any express or implied
+ * warranty. In no event will the authors be held liable for any damages
+ * arising from the use of this software.
+ *
+ * Permission is granted to anyone to use this software for any purpose,
+ * including commercial applications, and to alter it and redistribute it
+ * freely, subject to the following restrictions:
+ *
+ *    1. The origin of this software must not be misrepresented; you must not
+ *    claim that you wrote the original software. If you use this software
+ *    in a product, an acknowledgment in the product documentation would be
+ *    appreciated but is not required.
+ *
+ *    2. Altered source versions must be plainly marked as such, and must not
+ *    be misrepresented as being the original software.
+ *
+ *    3. This notice may not be removed or altered from any source
+ *    distribution.
+ */
+
+// Updated to use a modification of the "returnExportsGlobal" pattern from https://github.com/umdjs/umd
+
+(function (root, factory) {
+    if (typeof exports === 'object') {
+        // Node. Does not work with strict CommonJS, but
+        // only CommonJS-like enviroments that support module.exports,
+        // like Node.
+        module.exports = factory(global);
+    } else if (typeof define === 'function' && define.amd) {
+        // AMD. Register as an anonymous module.
+        define([], function () {
+            return factory(root);
+        });
+    } else {
+        // Browser globals
+        factory(root);
+    }
+}(this, function (root) {
+    "use strict";
+
+    // Tweak to your liking
+    var FLOAT_EPSILON = 0.000001;
+
+    var glMath = {};
+    (function() {
+        if (typeof(Float32Array) != 'undefined') {
+            var y = new Float32Array(1);
+            var i = new Int32Array(y.buffer);
+
+            /**
+             * Fast way to calculate the inverse square root,
+             * see http://jsperf.com/inverse-square-root/5
+             *
+             * If typed arrays are not available, a slower
+             * implementation will be used.
+             *
+             * @param {Number} number the number
+             * @returns {Number} Inverse square root
+             */
+            glMath.invsqrt = function(number) {
+              var x2 = number * 0.5;
+              y[0] = number;
+              var threehalfs = 1.5;
+
+              i[0] = 0x5f3759df - (i[0] >> 1);
+
+              var number2 = y[0];
+
+              return number2 * (threehalfs - (x2 * number2 * number2));
+            };
+        } else {
+            glMath.invsqrt = function(number) { return 1.0 / Math.sqrt(number); };
+        }
+    })();
+
+    /**
+     * @class System-specific optimal array type
+     * @name MatrixArray
+     */
+    var MatrixArray = null;
+    
+    // explicitly sets and returns the type of array to use within glMatrix
+    function setMatrixArrayType(type) {
+        MatrixArray = type;
+        return MatrixArray;
+    }
+
+    // auto-detects and returns the best type of array to use within glMatrix, falling
+    // back to Array if typed arrays are unsupported
+    function determineMatrixArrayType() {
+        MatrixArray = (typeof Float32Array !== 'undefined') ? Float32Array : Array;
+        return MatrixArray;
+    }
+    
+    determineMatrixArrayType();
+
+    /**
+     * @class 3 Dimensional Vector
+     * @name vec3
+     */
+    var vec3 = {};
+     
+    /**
+     * Creates a new instance of a vec3 using the default array type
+     * Any javascript array-like objects containing at least 3 numeric elements can serve as a vec3
+     *
+     * @param {vec3} [vec] vec3 containing values to initialize with
+     *
+     * @returns {vec3} New vec3
+     */
+    vec3.create = function (vec) {
+        var dest = new MatrixArray(3);
+
+        if (vec) {
+            dest[0] = vec[0];
+            dest[1] = vec[1];
+            dest[2] = vec[2];
+        } else {
+            dest[0] = dest[1] = dest[2] = 0;
+        }
+
+        return dest;
+    };
+
+    /**
+     * Creates a new instance of a vec3, initializing it with the given arguments
+     *
+     * @param {number} x X value
+     * @param {number} y Y value
+     * @param {number} z Z value
+
+     * @returns {vec3} New vec3
+     */
+    vec3.createFrom = function (x, y, z) {
+        var dest = new MatrixArray(3);
+
+        dest[0] = x;
+        dest[1] = y;
+        dest[2] = z;
+
+        return dest;
+    };
+
+    /**
+     * Copies the values of one vec3 to another
+     *
+     * @param {vec3} vec vec3 containing values to copy
+     * @param {vec3} dest vec3 receiving copied values
+     *
+     * @returns {vec3} dest
+     */
+    vec3.set = function (vec, dest) {
+        dest[0] = vec[0];
+        dest[1] = vec[1];
+        dest[2] = vec[2];
+
+        return dest;
+    };
+
+    /**
+     * Compares two vectors for equality within a certain margin of error
+     *
+     * @param {vec3} a First vector
+     * @param {vec3} b Second vector
+     *
+     * @returns {Boolean} True if a is equivalent to b
+     */
+    vec3.equal = function (a, b) {
+        return a === b || (
+            Math.abs(a[0] - b[0]) < FLOAT_EPSILON &&
+            Math.abs(a[1] - b[1]) < FLOAT_EPSILON &&
+            Math.abs(a[2] - b[2]) < FLOAT_EPSILON
+        );
+    };
+
+    /**
+     * Performs a vector addition
+     *
+     * @param {vec3} vec First operand
+     * @param {vec3} vec2 Second operand
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.add = function (vec, vec2, dest) {
+        if (!dest || vec === dest) {
+            vec[0] += vec2[0];
+            vec[1] += vec2[1];
+            vec[2] += vec2[2];
+            return vec;
+        }
+
+        dest[0] = vec[0] + vec2[0];
+        dest[1] = vec[1] + vec2[1];
+        dest[2] = vec[2] + vec2[2];
+        return dest;
+    };
+
+    /**
+     * Performs a vector subtraction
+     *
+     * @param {vec3} vec First operand
+     * @param {vec3} vec2 Second operand
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.subtract = function (vec, vec2, dest) {
+        if (!dest || vec === dest) {
+            vec[0] -= vec2[0];
+            vec[1] -= vec2[1];
+            vec[2] -= vec2[2];
+            return vec;
+        }
+
+        dest[0] = vec[0] - vec2[0];
+        dest[1] = vec[1] - vec2[1];
+        dest[2] = vec[2] - vec2[2];
+        return dest;
+    };
+
+    /**
+     * Performs a vector multiplication
+     *
+     * @param {vec3} vec First operand
+     * @param {vec3} vec2 Second operand
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.multiply = function (vec, vec2, dest) {
+        if (!dest || vec === dest) {
+            vec[0] *= vec2[0];
+            vec[1] *= vec2[1];
+            vec[2] *= vec2[2];
+            return vec;
+        }
+
+        dest[0] = vec[0] * vec2[0];
+        dest[1] = vec[1] * vec2[1];
+        dest[2] = vec[2] * vec2[2];
+        return dest;
+    };
+
+    /**
+     * Negates the components of a vec3
+     *
+     * @param {vec3} vec vec3 to negate
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.negate = function (vec, dest) {
+        if (!dest) { dest = vec; }
+
+        dest[0] = -vec[0];
+        dest[1] = -vec[1];
+        dest[2] = -vec[2];
+        return dest;
+    };
+
+    /**
+     * Multiplies the components of a vec3 by a scalar value
+     *
+     * @param {vec3} vec vec3 to scale
+     * @param {number} val Value to scale by
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.scale = function (vec, val, dest) {
+        if (!dest || vec === dest) {
+            vec[0] *= val;
+            vec[1] *= val;
+            vec[2] *= val;
+            return vec;
+        }
+
+        dest[0] = vec[0] * val;
+        dest[1] = vec[1] * val;
+        dest[2] = vec[2] * val;
+        return dest;
+    };
+
+    /**
+     * Generates a unit vector of the same direction as the provided vec3
+     * If vector length is 0, returns [0, 0, 0]
+     *
+     * @param {vec3} vec vec3 to normalize
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.normalize = function (vec, dest) {
+        if (!dest) { dest = vec; }
+
+        var x = vec[0], y = vec[1], z = vec[2],
+            len = Math.sqrt(x * x + y * y + z * z);
+
+        if (!len) {
+            dest[0] = 0;
+            dest[1] = 0;
+            dest[2] = 0;
+            return dest;
+        } else if (len === 1) {
+            dest[0] = x;
+            dest[1] = y;
+            dest[2] = z;
+            return dest;
+        }
+
+        len = 1 / len;
+        dest[0] = x * len;
+        dest[1] = y * len;
+        dest[2] = z * len;
+        return dest;
+    };
+
+    /**
+     * Generates the cross product of two vec3s
+     *
+     * @param {vec3} vec First operand
+     * @param {vec3} vec2 Second operand
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.cross = function (vec, vec2, dest) {
+        if (!dest) { dest = vec; }
+
+        var x = vec[0], y = vec[1], z = vec[2],
+            x2 = vec2[0], y2 = vec2[1], z2 = vec2[2];
+
+        dest[0] = y * z2 - z * y2;
+        dest[1] = z * x2 - x * z2;
+        dest[2] = x * y2 - y * x2;
+        return dest;
+    };
+
+    /**
+     * Caclulates the length of a vec3
+     *
+     * @param {vec3} vec vec3 to calculate length of
+     *
+     * @returns {number} Length of vec
+     */
+    vec3.length = function (vec) {
+        var x = vec[0], y = vec[1], z = vec[2];
+        return Math.sqrt(x * x + y * y + z * z);
+    };
+
+    /**
+     * Caclulates the squared length of a vec3
+     *
+     * @param {vec3} vec vec3 to calculate squared length of
+     *
+     * @returns {number} Squared Length of vec
+     */
+    vec3.squaredLength = function (vec) {
+        var x = vec[0], y = vec[1], z = vec[2];
+        return x * x + y * y + z * z;
+    };
+
+    /**
+     * Caclulates the dot product of two vec3s
+     *
+     * @param {vec3} vec First operand
+     * @param {vec3} vec2 Second operand
+     *
+     * @returns {number} Dot product of vec and vec2
+     */
+    vec3.dot = function (vec, vec2) {
+        return vec[0] * vec2[0] + vec[1] * vec2[1] + vec[2] * vec2[2];
+    };
+
+    /**
+     * Generates a unit vector pointing from one vector to another
+     *
+     * @param {vec3} vec Origin vec3
+     * @param {vec3} vec2 vec3 to point to
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.direction = function (vec, vec2, dest) {
+        if (!dest) { dest = vec; }
+
+        var x = vec[0] - vec2[0],
+            y = vec[1] - vec2[1],
+            z = vec[2] - vec2[2],
+            len = Math.sqrt(x * x + y * y + z * z);
+
+        if (!len) {
+            dest[0] = 0;
+            dest[1] = 0;
+            dest[2] = 0;
+            return dest;
+        }
+
+        len = 1 / len;
+        dest[0] = x * len;
+        dest[1] = y * len;
+        dest[2] = z * len;
+        return dest;
+    };
+
+    /**
+     * Performs a linear interpolation between two vec3
+     *
+     * @param {vec3} vec First vector
+     * @param {vec3} vec2 Second vector
+     * @param {number} lerp Interpolation amount between the two inputs
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.lerp = function (vec, vec2, lerp, dest) {
+        if (!dest) { dest = vec; }
+
+        dest[0] = vec[0] + lerp * (vec2[0] - vec[0]);
+        dest[1] = vec[1] + lerp * (vec2[1] - vec[1]);
+        dest[2] = vec[2] + lerp * (vec2[2] - vec[2]);
+
+        return dest;
+    };
+
+    /**
+     * Calculates the euclidian distance between two vec3
+     *
+     * Params:
+     * @param {vec3} vec First vector
+     * @param {vec3} vec2 Second vector
+     *
+     * @returns {number} Distance between vec and vec2
+     */
+    vec3.dist = function (vec, vec2) {
+        var x = vec2[0] - vec[0],
+            y = vec2[1] - vec[1],
+            z = vec2[2] - vec[2];
+            
+        return Math.sqrt(x*x + y*y + z*z);
+    };
+
+    // Pre-allocated to prevent unecessary garbage collection
+    var unprojectMat = null;
+    var unprojectVec = new MatrixArray(4);
+    /**
+     * Projects the specified vec3 from screen space into object space
+     * Based on the <a href="http://webcvs.freedesktop.org/mesa/Mesa/src/glu/mesa/project.c?revision=1.4&view=markup">Mesa gluUnProject implementation</a>
+     *
+     * @param {vec3} vec Screen-space vector to project
+     * @param {mat4} view View matrix
+     * @param {mat4} proj Projection matrix
+     * @param {vec4} viewport Viewport as given to gl.viewport [x, y, width, height]
+     * @param {vec3} [dest] vec3 receiving unprojected result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    vec3.unproject = function (vec, view, proj, viewport, dest) {
+        if (!dest) { dest = vec; }
+
+        if(!unprojectMat) {
+            unprojectMat = mat4.create();
+        }
+
+        var m = unprojectMat;
+        var v = unprojectVec;
+        
+        v[0] = (vec[0] - viewport[0]) * 2.0 / viewport[2] - 1.0;
+        v[1] = (vec[1] - viewport[1]) * 2.0 / viewport[3] - 1.0;
+        v[2] = 2.0 * vec[2] - 1.0;
+        v[3] = 1.0;
+        
+        mat4.multiply(proj, view, m);
+        if(!mat4.inverse(m)) { return null; }
+        
+        mat4.multiplyVec4(m, v);
+        if(v[3] === 0.0) { return null; }
+
+        dest[0] = v[0] / v[3];
+        dest[1] = v[1] / v[3];
+        dest[2] = v[2] / v[3];
+        
+        return dest;
+    };
+
+    var xUnitVec3 = vec3.createFrom(1,0,0);
+    var yUnitVec3 = vec3.createFrom(0,1,0);
+    var zUnitVec3 = vec3.createFrom(0,0,1);
+
+    var tmpvec3 = vec3.create();
+    /**
+     * Generates a quaternion of rotation between two given normalized vectors
+     *
+     * @param {vec3} a Normalized source vector
+     * @param {vec3} b Normalized target vector
+     * @param {quat4} [dest] quat4 receiving operation result.
+     *
+     * @returns {quat4} dest if specified, a new quat4 otherwise
+     */
+    vec3.rotationTo = function (a, b, dest) {
+        if (!dest) { dest = quat4.create(); }
+        
+        var d = vec3.dot(a, b);
+        var axis = tmpvec3;
+        if (d >= 1.0) {
+            quat4.set(identityQuat4, dest);
+        } else if (d < (0.000001 - 1.0)) {
+            vec3.cross(xUnitVec3, a, axis);
+            if (vec3.length(axis) < 0.000001)
+                vec3.cross(yUnitVec3, a, axis);
+            if (vec3.length(axis) < 0.000001)
+                vec3.cross(zUnitVec3, a, axis);
+            vec3.normalize(axis);
+            quat4.fromAngleAxis(Math.PI, axis, dest);
+        } else {
+            var s = Math.sqrt((1.0 + d) * 2.0);
+            var sInv = 1.0 / s;
+            vec3.cross(a, b, axis);
+            dest[0] = axis[0] * sInv;
+            dest[1] = axis[1] * sInv;
+            dest[2] = axis[2] * sInv;
+            dest[3] = s * 0.5;
+            quat4.normalize(dest);
+        }
+        if (dest[3] > 1.0) dest[3] = 1.0;
+        else if (dest[3] < -1.0) dest[3] = -1.0;
+        return dest;
+    };
+
+    /**
+     * Returns a string representation of a vector
+     *
+     * @param {vec3} vec Vector to represent as a string
+     *
+     * @returns {string} String representation of vec
+     */
+    vec3.str = function (vec) {
+        return '[' + vec[0] + ', ' + vec[1] + ', ' + vec[2] + ']';
+    };
+
+    /**
+     * @class 3x3 Matrix
+     * @name mat3
+     */
+    var mat3 = {};
+
+    /**
+     * Creates a new instance of a mat3 using the default array type
+     * Any javascript array-like object containing at least 9 numeric elements can serve as a mat3
+     *
+     * @param {mat3} [mat] mat3 containing values to initialize with
+     *
+     * @returns {mat3} New mat3
+     */
+    mat3.create = function (mat) {
+        var dest = new MatrixArray(9);
+
+        if (mat) {
+            dest[0] = mat[0];
+            dest[1] = mat[1];
+            dest[2] = mat[2];
+            dest[3] = mat[3];
+            dest[4] = mat[4];
+            dest[5] = mat[5];
+            dest[6] = mat[6];
+            dest[7] = mat[7];
+            dest[8] = mat[8];
+        } else {
+            dest[0] = dest[1] =
+            dest[2] = dest[3] =
+            dest[4] = dest[5] =
+            dest[6] = dest[7] =
+            dest[8] = 0;
+        }
+
+        return dest;
+    };
+
+    /**
+     * Creates a new instance of a mat3, initializing it with the given arguments
+     *
+     * @param {number} m00
+     * @param {number} m01
+     * @param {number} m02
+     * @param {number} m10
+     * @param {number} m11
+     * @param {number} m12
+     * @param {number} m20
+     * @param {number} m21
+     * @param {number} m22
+
+     * @returns {mat3} New mat3
+     */
+    mat3.createFrom = function (m00, m01, m02, m10, m11, m12, m20, m21, m22) {
+        var dest = new MatrixArray(9);
+
+        dest[0] = m00;
+        dest[1] = m01;
+        dest[2] = m02;
+        dest[3] = m10;
+        dest[4] = m11;
+        dest[5] = m12;
+        dest[6] = m20;
+        dest[7] = m21;
+        dest[8] = m22;
+
+        return dest;
+    };
+
+    /**
+     * Calculates the determinant of a mat3
+     *
+     * @param {mat3} mat mat3 to calculate determinant of
+     *
+     * @returns {Number} determinant of mat
+     */
+    mat3.determinant = function (mat) {
+        var a00 = mat[0], a01 = mat[1], a02 = mat[2],
+            a10 = mat[3], a11 = mat[4], a12 = mat[5],
+            a20 = mat[6], a21 = mat[7], a22 = mat[8];
+
+        return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
+    };
+
+    /**
+     * Calculates the inverse matrix of a mat3
+     *
+     * @param {mat3} mat mat3 to calculate inverse of
+     * @param {mat3} [dest] mat3 receiving inverse matrix. If not specified result is written to mat
+     *
+     * @param {mat3} dest is specified, mat otherwise, null if matrix cannot be inverted
+     */
+    mat3.inverse = function (mat, dest) {
+        var a00 = mat[0], a01 = mat[1], a02 = mat[2],
+            a10 = mat[3], a11 = mat[4], a12 = mat[5],
+            a20 = mat[6], a21 = mat[7], a22 = mat[8],
+
+            b01 = a22 * a11 - a12 * a21,
+            b11 = -a22 * a10 + a12 * a20,
+            b21 = a21 * a10 - a11 * a20,
+
+            d = a00 * b01 + a01 * b11 + a02 * b21,
+            id;
+
+        if (!d) { return null; }
+        id = 1 / d;
+
+        if (!dest) { dest = mat3.create(); }
+
+        dest[0] = b01 * id;
+        dest[1] = (-a22 * a01 + a02 * a21) * id;
+        dest[2] = (a12 * a01 - a02 * a11) * id;
+        dest[3] = b11 * id;
+        dest[4] = (a22 * a00 - a02 * a20) * id;
+        dest[5] = (-a12 * a00 + a02 * a10) * id;
+        dest[6] = b21 * id;
+        dest[7] = (-a21 * a00 + a01 * a20) * id;
+        dest[8] = (a11 * a00 - a01 * a10) * id;
+        return dest;
+    };
+    
+    /**
+     * Performs a matrix multiplication
+     *
+     * @param {mat3} mat First operand
+     * @param {mat3} mat2 Second operand
+     * @param {mat3} [dest] mat3 receiving operation result. If not specified result is written to mat
+     *
+     * @returns {mat3} dest if specified, mat otherwise
+     */
+    mat3.multiply = function (mat, mat2, dest) {
+        if (!dest) { dest = mat; }
+        
+
+        // Cache the matrix values (makes for huge speed increases!)
+        var a00 = mat[0], a01 = mat[1], a02 = mat[2],
+            a10 = mat[3], a11 = mat[4], a12 = mat[5],
+            a20 = mat[6], a21 = mat[7], a22 = mat[8],
+
+            b00 = mat2[0], b01 = mat2[1], b02 = mat2[2],
+            b10 = mat2[3], b11 = mat2[4], b12 = mat2[5],
+            b20 = mat2[6], b21 = mat2[7], b22 = mat2[8];
+
+        dest[0] = b00 * a00 + b01 * a10 + b02 * a20;
+        dest[1] = b00 * a01 + b01 * a11 + b02 * a21;
+        dest[2] = b00 * a02 + b01 * a12 + b02 * a22;
+
+        dest[3] = b10 * a00 + b11 * a10 + b12 * a20;
+        dest[4] = b10 * a01 + b11 * a11 + b12 * a21;
+        dest[5] = b10 * a02 + b11 * a12 + b12 * a22;
+
+        dest[6] = b20 * a00 + b21 * a10 + b22 * a20;
+        dest[7] = b20 * a01 + b21 * a11 + b22 * a21;
+        dest[8] = b20 * a02 + b21 * a12 + b22 * a22;
+
+        return dest;
+    };
+
+    /**
+     * Transforms the vec2 according to the given mat3.
+     *
+     * @param {mat3} matrix mat3 to multiply against
+     * @param {vec2} vec    the vector to multiply
+     * @param {vec2} [dest] an optional receiving vector. If not given, vec is used.
+     *
+     * @returns {vec2} The multiplication result
+     **/
+    mat3.multiplyVec2 = function(matrix, vec, dest) {
+      if (!dest) dest = vec;
+      var x = vec[0], y = vec[1];
+      dest[0] = x * matrix[0] + y * matrix[3] + matrix[6];
+      dest[1] = x * matrix[1] + y * matrix[4] + matrix[7];
+      return dest;
+    };
+
+    /**
+     * Transforms the vec3 according to the given mat3
+     *
+     * @param {mat3} matrix mat3 to multiply against
+     * @param {vec3} vec    the vector to multiply
+     * @param {vec3} [dest] an optional receiving vector. If not given, vec is used.
+     *
+     * @returns {vec3} The multiplication result
+     **/
+    mat3.multiplyVec3 = function(matrix, vec, dest) {
+      if (!dest) dest = vec;
+      var x = vec[0], y = vec[1], z = vec[2];
+      dest[0] = x * matrix[0] + y * matrix[3] + z * matrix[6];
+      dest[1] = x * matrix[1] + y * matrix[4] + z * matrix[7];
+      dest[2] = x * matrix[2] + y * matrix[5] + z * matrix[8];
+      
+      return dest;
+    };
+
+    /**
+     * Copies the values of one mat3 to another
+     *
+     * @param {mat3} mat mat3 containing values to copy
+     * @param {mat3} dest mat3 receiving copied values
+     *
+     * @returns {mat3} dest
+     */
+    mat3.set = function (mat, dest) {
+        dest[0] = mat[0];
+        dest[1] = mat[1];
+        dest[2] = mat[2];
+        dest[3] = mat[3];
+        dest[4] = mat[4];
+        dest[5] = mat[5];
+        dest[6] = mat[6];
+        dest[7] = mat[7];
+        dest[8] = mat[8];
+        return dest;
+    };
+
+    /**
+     * Compares two matrices for equality within a certain margin of error
+     *
+     * @param {mat3} a First matrix
+     * @param {mat3} b Second matrix
+     *
+     * @returns {Boolean} True if a is equivalent to b
+     */
+    mat3.equal = function (a, b) {
+        return a === b || (
+            Math.abs(a[0] - b[0]) < FLOAT_EPSILON &&
+            Math.abs(a[1] - b[1]) < FLOAT_EPSILON &&
+            Math.abs(a[2] - b[2]) < FLOAT_EPSILON &&
+            Math.abs(a[3] - b[3]) < FLOAT_EPSILON &&
+            Math.abs(a[4] - b[4]) < FLOAT_EPSILON &&
+            Math.abs(a[5] - b[5]) < FLOAT_EPSILON &&
+            Math.abs(a[6] - b[6]) < FLOAT_EPSILON &&
+            Math.abs(a[7] - b[7]) < FLOAT_EPSILON &&
+            Math.abs(a[8] - b[8]) < FLOAT_EPSILON
+        );
+    };
+
+    /**
+     * Sets a mat3 to an identity matrix
+     *
+     * @param {mat3} dest mat3 to set
+     *
+     * @returns dest if specified, otherwise a new mat3
+     */
+    mat3.identity = function (dest) {
+        if (!dest) { dest = mat3.create(); }
+        dest[0] = 1;
+        dest[1] = 0;
+        dest[2] = 0;
+        dest[3] = 0;
+        dest[4] = 1;
+        dest[5] = 0;
+        dest[6] = 0;
+        dest[7] = 0;
+        dest[8] = 1;
+        return dest;
+    };
+
+    /**
+     * Transposes a mat3 (flips the values over the diagonal)
+     *
+     * Params:
+     * @param {mat3} mat mat3 to transpose
+     * @param {mat3} [dest] mat3 receiving transposed values. If not specified result is written to mat
+     *
+     * @returns {mat3} dest is specified, mat otherwise
+     */
+    mat3.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 a01 = mat[1], a02 = mat[2],
+                a12 = mat[5];
+
+            mat[1] = mat[3];
+            mat[2] = mat[6];
+            mat[3] = a01;
+            mat[5] = mat[7];
+            mat[6] = a02;
+            mat[7] = a12;
+            return mat;
+        }
+
+        dest[0] = mat[0];
+        dest[1] = mat[3];
+        dest[2] = mat[6];
+        dest[3] = mat[1];
+        dest[4] = mat[4];
+        dest[5] = mat[7];
+        dest[6] = mat[2];
+        dest[7] = mat[5];
+        dest[8] = mat[8];
+        return dest;
+    };
+
+    /**
+     * Copies the elements of a mat3 into the upper 3x3 elements of a mat4
+     *
+     * @param {mat3} mat mat3 containing values to copy
+     * @param {mat4} [dest] mat4 receiving copied values
+     *
+     * @returns {mat4} dest if specified, a new mat4 otherwise
+     */
+    mat3.toMat4 = function (mat, dest) {
+        if (!dest) { dest = mat4.create(); }
+
+        dest[15] = 1;
+        dest[14] = 0;
+        dest[13] = 0;
+        dest[12] = 0;
+
+        dest[11] = 0;
+        dest[10] = mat[8];
+        dest[9] = mat[7];
+        dest[8] = mat[6];
+
+        dest[7] = 0;
+        dest[6] = mat[5];
+        dest[5] = mat[4];
+        dest[4] = mat[3];
+
+        dest[3] = 0;
+        dest[2] = mat[2];
+        dest[1] = mat[1];
+        dest[0] = mat[0];
+
+        return dest;
+    };
+
+    /**
+     * Returns a string representation of a mat3
+     *
+     * @param {mat3} mat mat3 to represent as a string
+     *
+     * @param {string} String representation of mat
+     */
+    mat3.str = function (mat) {
+        return '[' + mat[0] + ', ' + mat[1] + ', ' + mat[2] +
+            ', ' + mat[3] + ', ' + mat[4] + ', ' + mat[5] +
+            ', ' + mat[6] + ', ' + mat[7] + ', ' + mat[8] + ']';
+    };
+
+    /**
+     * @class 4x4 Matrix
+     * @name mat4
+     */
+    var mat4 = {};
+
+    /**
+     * Creates a new instance of a mat4 using the default array type
+     * Any javascript array-like object containing at least 16 numeric elements can serve as a mat4
+     *
+     * @param {mat4} [mat] mat4 containing values to initialize with
+     *
+     * @returns {mat4} New mat4
+     */
+    mat4.create = function (mat) {
+        var dest = new MatrixArray(16);
+
+        if (mat) {
+            dest[0] = mat[0];
+            dest[1] = mat[1];
+            dest[2] = mat[2];
+            dest[3] = mat[3];
+            dest[4] = mat[4];
+            dest[5] = mat[5];
+            dest[6] = mat[6];
+            dest[7] = mat[7];
+            dest[8] = mat[8];
+            dest[9] = mat[9];
+            dest[10] = mat[10];
+            dest[11] = mat[11];
+            dest[12] = mat[12];
+            dest[13] = mat[13];
+            dest[14] = mat[14];
+            dest[15] = mat[15];
+        }
+
+        return dest;
+    };
+
+    /**
+     * Creates a new instance of a mat4, initializing it with the given arguments
+     *
+     * @param {number} m00
+     * @param {number} m01
+     * @param {number} m02
+     * @param {number} m03
+     * @param {number} m10
+     * @param {number} m11
+     * @param {number} m12
+     * @param {number} m13
+     * @param {number} m20
+     * @param {number} m21
+     * @param {number} m22
+     * @param {number} m23
+     * @param {number} m30
+     * @param {number} m31
+     * @param {number} m32
+     * @param {number} m33
+
+     * @returns {mat4} New mat4
+     */
+    mat4.createFrom = function (m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
+        var dest = new MatrixArray(16);
+
+        dest[0] = m00;
+        dest[1] = m01;
+        dest[2] = m02;
+        dest[3] = m03;
+        dest[4] = m10;
+        dest[5] = m11;
+        dest[6] = m12;
+        dest[7] = m13;
+        dest[8] = m20;
+        dest[9] = m21;
+        dest[10] = m22;
+        dest[11] = m23;
+        dest[12] = m30;
+        dest[13] = m31;
+        dest[14] = m32;
+        dest[15] = m33;
+
+        return dest;
+    };
+
+    /**
+     * Copies the values of one mat4 to another
+     *
+     * @param {mat4} mat mat4 containing values to copy
+     * @param {mat4} dest mat4 receiving copied values
+     *
+     * @returns {mat4} dest
+     */
+    mat4.set = function (mat, dest) {
+        dest[0] = mat[0];
+        dest[1] = mat[1];
+        dest[2] = mat[2];
+        dest[3] = mat[3];
+        dest[4] = mat[4];
+        dest[5] = mat[5];
+        dest[6] = mat[6];
+        dest[7] = mat[7];
+        dest[8] = mat[8];
+        dest[9] = mat[9];
+        dest[10] = mat[10];
+        dest[11] = mat[11];
+        dest[12] = mat[12];
+        dest[13] = mat[13];
+        dest[14] = mat[14];
+        dest[15] = mat[15];
+        return dest;
+    };
+
+    /**
+     * Compares two matrices for equality within a certain margin of error
+     *
+     * @param {mat4} a First matrix
+     * @param {mat4} b Second matrix
+     *
+     * @returns {Boolean} True if a is equivalent to b
+     */
+    mat4.equal = function (a, b) {
+        return a === b || (
+            Math.abs(a[0] - b[0]) < FLOAT_EPSILON &&
+            Math.abs(a[1] - b[1]) < FLOAT_EPSILON &&
+            Math.abs(a[2] - b[2]) < FLOAT_EPSILON &&
+            Math.abs(a[3] - b[3]) < FLOAT_EPSILON &&
+            Math.abs(a[4] - b[4]) < FLOAT_EPSILON &&
+            Math.abs(a[5] - b[5]) < FLOAT_EPSILON &&
+            Math.abs(a[6] - b[6]) < FLOAT_EPSILON &&
+            Math.abs(a[7] - b[7]) < FLOAT_EPSILON &&
+            Math.abs(a[8] - b[8]) < FLOAT_EPSILON &&
+            Math.abs(a[9] - b[9]) < FLOAT_EPSILON &&
+            Math.abs(a[10] - b[10]) < FLOAT_EPSILON &&
+            Math.abs(a[11] - b[11]) < FLOAT_EPSILON &&
+            Math.abs(a[12] - b[12]) < FLOAT_EPSILON &&
+            Math.abs(a[13] - b[13]) < FLOAT_EPSILON &&
+            Math.abs(a[14] - b[14]) < FLOAT_EPSILON &&
+            Math.abs(a[15] - b[15]) < FLOAT_EPSILON
+        );
+    };
+
+    /**
+     * Sets a mat4 to an identity matrix
+     *
+     * @param {mat4} dest mat4 to set
+     *
+     * @returns {mat4} dest
+     */
+    mat4.identity = function (dest) {
+        if (!dest) { dest = mat4.create(); }
+        dest[0] = 1;
+        dest[1] = 0;
+        dest[2] = 0;
+        dest[3] = 0;
+        dest[4] = 0;
+        dest[5] = 1;
+        dest[6] = 0;
+        dest[7] = 0;
+        dest[8] = 0;
+        dest[9] = 0;
+        dest[10] = 1;
+        dest[11] = 0;
+        dest[12] = 0;
+        dest[13] = 0;
+        dest[14] = 0;
+        dest[15] = 1;
+        return dest;
+    };
+
+    /**
+     * Transposes a mat4 (flips the values over the diagonal)
+     *
+     * @param {mat4} mat mat4 to transpose
+     * @param {mat4} [dest] mat4 receiving transposed values. If not specified result is written to mat
+     *
+     * @param {mat4} dest is specified, mat otherwise
+     */
+    mat4.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 a01 = mat[1], a02 = mat[2], a03 = mat[3],
+                a12 = mat[6], a13 = mat[7],
+                a23 = mat[11];
+
+            mat[1] = mat[4];
+            mat[2] = mat[8];
+            mat[3] = mat[12];
+            mat[4] = a01;
+            mat[6] = mat[9];
+            mat[7] = mat[13];
+            mat[8] = a02;
+            mat[9] = a12;
+            mat[11] = mat[14];
+            mat[12] = a03;
+            mat[13] = a13;
+            mat[14] = a23;
+            return mat;
+        }
+
+        dest[0] = mat[0];
+        dest[1] = mat[4];
+        dest[2] = mat[8];
+        dest[3] = mat[12];
+        dest[4] = mat[1];
+        dest[5] = mat[5];
+        dest[6] = mat[9];
+        dest[7] = mat[13];
+        dest[8] = mat[2];
+        dest[9] = mat[6];
+        dest[10] = mat[10];
+        dest[11] = mat[14];
+        dest[12] = mat[3];
+        dest[13] = mat[7];
+        dest[14] = mat[11];
+        dest[15] = mat[15];
+        return dest;
+    };
+
+    /**
+     * Calculates the determinant of a mat4
+     *
+     * @param {mat4} mat mat4 to calculate determinant of
+     *
+     * @returns {number} determinant of mat
+     */
+    mat4.determinant = function (mat) {
+        // Cache the matrix values (makes for huge speed increases!)
+        var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3],
+            a10 = mat[4], a11 = mat[5], a12 = mat[6], a13 = mat[7],
+            a20 = mat[8], a21 = mat[9], a22 = mat[10], a23 = mat[11],
+            a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15];
+
+        return (a30 * a21 * a12 * a03 - a20 * a31 * a12 * a03 - a30 * a11 * a22 * a03 + a10 * a31 * a22 * a03 +
+                a20 * a11 * a32 * a03 - a10 * a21 * a32 * a03 - a30 * a21 * a02 * a13 + a20 * a31 * a02 * a13 +
+                a30 * a01 * a22 * a13 - a00 * a31 * a22 * a13 - a20 * a01 * a32 * a13 + a00 * a21 * a32 * a13 +
+                a30 * a11 * a02 * a23 - a10 * a31 * a02 * a23 - a30 * a01 * a12 * a23 + a00 * a31 * a12 * a23 +
+                a10 * a01 * a32 * a23 - a00 * a11 * a32 * a23 - a20 * a11 * a02 * a33 + a10 * a21 * a02 * a33 +
+                a20 * a01 * a12 * a33 - a00 * a21 * a12 * a33 - a10 * a01 * a22 * a33 + a00 * a11 * a22 * a33);
+    };
+
+    /**
+     * Calculates the inverse matrix of a mat4
+     *
+     * @param {mat4} mat mat4 to calculate inverse of
+     * @param {mat4} [dest] mat4 receiving inverse matrix. If not specified result is written to mat
+     *
+     * @param {mat4} dest is specified, mat otherwise, null if matrix cannot be inverted
+     */
+    mat4.inverse = function (mat, dest) {
+        if (!dest) { dest = mat; }
+
+        // Cache the matrix values (makes for huge speed increases!)
+        var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3],
+            a10 = mat[4], a11 = mat[5], a12 = mat[6], a13 = mat[7],
+            a20 = mat[8], a21 = mat[9], a22 = mat[10], a23 = mat[11],
+            a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15],
+
+            b00 = a00 * a11 - a01 * a10,
+            b01 = a00 * a12 - a02 * a10,
+            b02 = a00 * a13 - a03 * a10,
+            b03 = a01 * a12 - a02 * a11,
+            b04 = a01 * a13 - a03 * a11,
+            b05 = a02 * a13 - a03 * a12,
+            b06 = a20 * a31 - a21 * a30,
+            b07 = a20 * a32 - a22 * a30,
+            b08 = a20 * a33 - a23 * a30,
+            b09 = a21 * a32 - a22 * a31,
+            b10 = a21 * a33 - a23 * a31,
+            b11 = a22 * a33 - a23 * a32,
+
+            d = (b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06),
+            invDet;
+
+            // Calculate the determinant
+            if (!d) { return null; }
+            invDet = 1 / d;
+
+        dest[0] = (a11 * b11 - a12 * b10 + a13 * b09) * invDet;
+        dest[1] = (-a01 * b11 + a02 * b10 - a03 * b09) * invDet;
+        dest[2] = (a31 * b05 - a32 * b04 + a33 * b03) * invDet;
+        dest[3] = (-a21 * b05 + a22 * b04 - a23 * b03) * invDet;
+        dest[4] = (-a10 * b11 + a12 * b08 - a13 * b07) * invDet;
+        dest[5] = (a00 * b11 - a02 * b08 + a03 * b07) * invDet;
+        dest[6] = (-a30 * b05 + a32 * b02 - a33 * b01) * invDet;
+        dest[7] = (a20 * b05 - a22 * b02 + a23 * b01) * invDet;
+        dest[8] = (a10 * b10 - a11 * b08 + a13 * b06) * invDet;
+        dest[9] = (-a00 * b10 + a01 * b08 - a03 * b06) * invDet;
+        dest[10] = (a30 * b04 - a31 * b02 + a33 * b00) * invDet;
+        dest[11] = (-a20 * b04 + a21 * b02 - a23 * b00) * invDet;
+        dest[12] = (-a10 * b09 + a11 * b07 - a12 * b06) * invDet;
+        dest[13] = (a00 * b09 - a01 * b07 + a02 * b06) * invDet;
+        dest[14] = (-a30 * b03 + a31 * b01 - a32 * b00) * invDet;
+        dest[15] = (a20 * b03 - a21 * b01 + a22 * b00) * invDet;
+
+        return dest;
+    };
+
+    /**
+     * Copies the upper 3x3 elements of a mat4 into another mat4
+     *
+     * @param {mat4} mat mat4 containing values to copy
+     * @param {mat4} [dest] mat4 receiving copied values
+     *
+     * @returns {mat4} dest is specified, a new mat4 otherwise
+     */
+    mat4.toRotationMat = function (mat, dest) {
+        if (!dest) { dest = mat4.create(); }
+
+        dest[0] = mat[0];
+        dest[1] = mat[1];
+        dest[2] = mat[2];
+        dest[3] = mat[3];
+        dest[4] = mat[4];
+        dest[5] = mat[5];
+        dest[6] = mat[6];
+        dest[7] = mat[7];
+        dest[8] = mat[8];
+        dest[9] = mat[9];
+        dest[10] = mat[10];
+        dest[11] = mat[11];
+        dest[12] = 0;
+        dest[13] = 0;
+        dest[14] = 0;
+        dest[15] = 1;
+
+        return dest;
+    };
+
+    /**
+     * Copies the upper 3x3 elements of a mat4 into a mat3
+     *
+     * @param {mat4} mat mat4 containing values to copy
+     * @param {mat3} [dest] mat3 receiving copied values
+     *
+     * @returns {mat3} dest is specified, a new mat3 otherwise
+     */
+    mat4.toMat3 = function (mat, dest) {
+        if (!dest) { dest = mat3.create(); }
+
+        dest[0] = mat[0];
+        dest[1] = mat[1];
+        dest[2] = mat[2];
+        dest[3] = mat[4];
+        dest[4] = mat[5];
+        dest[5] = mat[6];
+        dest[6] = mat[8];
+        dest[7] = mat[9];
+        dest[8] = mat[10];
+
+        return dest;
+    };
+
+    /**
+     * Calculates the inverse of the upper 3x3 elements of a mat4 and copies the result into a mat3
+     * The resulting matrix is useful for calculating transformed normals
+     *
+     * Params:
+     * @param {mat4} mat mat4 containing values to invert and copy
+     * @param {mat3} [dest] mat3 receiving values
+     *
+     * @returns {mat3} dest is specified, a new mat3 otherwise, null if the matrix cannot be inverted
+     */
+    mat4.toInverseMat3 = function (mat, dest) {
+        // Cache the matrix values (makes for huge speed increases!)
+        var a00 = mat[0], a01 = mat[1], a02 = mat[2],
+            a10 = mat[4], a11 = mat[5], a12 = mat[6],
+            a20 = mat[8], a21 = mat[9], a22 = mat[10],
+
+            b01 = a22 * a11 - a12 * a21,
+            b11 = -a22 * a10 + a12 * a20,
+            b21 = a21 * a10 - a11 * a20,
+
+            d = a00 * b01 + a01 * b11 + a02 * b21,
+            id;
+
+        if (!d) { return null; }
+        id = 1 / d;
+
+        if (!dest) { dest = mat3.create(); }
+
+        dest[0] = b01 * id;
+        dest[1] = (-a22 * a01 + a02 * a21) * id;
+        dest[2] = (a12 * a01 - a02 * a11) * id;
+        dest[3] = b11 * id;
+        dest[4] = (a22 * a00 - a02 * a20) * id;
+        dest[5] = (-a12 * a00 + a02 * a10) * id;
+        dest[6] = b21 * id;
+        dest[7] = (-a21 * a00 + a01 * a20) * id;
+        dest[8] = (a11 * a00 - a01 * a10) * id;
+
+        return dest;
+    };
+
+    /**
+     * Performs a matrix multiplication
+     *
+     * @param {mat4} mat First operand
+     * @param {mat4} mat2 Second operand
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat
+     *
+     * @returns {mat4} dest if specified, mat otherwise
+     */
+    mat4.multiply = function (mat, mat2, dest) {
+        if (!dest) { dest = mat; }
+
+        // Cache the matrix values (makes for huge speed increases!)
+        var a00 = mat[ 0], a01 = mat[ 1], a02 = mat[ 2], a03 = mat[3];
+        var a10 = mat[ 4], a11 = mat[ 5], a12 = mat[ 6], a13 = mat[7];
+        var a20 = mat[ 8], a21 = mat[ 9], a22 = mat[10], a23 = mat[11];
+        var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15];
+
+        // Cache only the current line of the second matrix
+        var b0  = mat2[0], b1 = mat2[1], b2 = mat2[2], b3 = mat2[3];  
+        dest[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+        dest[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+        dest[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+        dest[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+        b0 = mat2[4];
+        b1 = mat2[5];
+        b2 = mat2[6];
+        b3 = mat2[7];
+        dest[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+        dest[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+        dest[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+        dest[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+        b0 = mat2[8];
+        b1 = mat2[9];
+        b2 = mat2[10];
+        b3 = mat2[11];
+        dest[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+        dest[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+        dest[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+        dest[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+        b0 = mat2[12];
+        b1 = mat2[13];
+        b2 = mat2[14];
+        b3 = mat2[15];
+        dest[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+        dest[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+        dest[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+        dest[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+        return dest;
+    };
+
+    /**
+     * Transforms a vec3 with the given matrix
+     * 4th vector component is implicitly '1'
+     *
+     * @param {mat4} mat mat4 to transform the vector with
+     * @param {vec3} vec vec3 to transform
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec3} dest if specified, vec otherwise
+     */
+    mat4.multiplyVec3 = function (mat, vec, dest) {
+        if (!dest) { dest = vec; }
+
+        var x = vec[0], y = vec[1], z = vec[2];
+
+        dest[0] = mat[0] * x + mat[4] * y + mat[8] * z + mat[12];
+        dest[1] = mat[1] * x + mat[5] * y + mat[9] * z + mat[13];
+        dest[2] = mat[2] * x + mat[6] * y + mat[10] * z + mat[14];
+
+        return dest;
+    };
+
+    /**
+     * Transforms a vec4 with the given matrix
+     *
+     * @param {mat4} mat mat4 to transform the vector with
+     * @param {vec4} vec vec4 to transform
+     * @param {vec4} [dest] vec4 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec4} dest if specified, vec otherwise
+     */
+    mat4.multiplyVec4 = function (mat, vec, dest) {
+        if (!dest) { dest = vec; }
+
+        var x = vec[0], y = vec[1], z = vec[2], w = vec[3];
+
+        dest[0] = mat[0] * x + mat[4] * y + mat[8] * z + mat[12] * w;
+        dest[1] = mat[1] * x + mat[5] * y + mat[9] * z + mat[13] * w;
+        dest[2] = mat[2] * x + mat[6] * y + mat[10] * z + mat[14] * w;
+        dest[3] = mat[3] * x + mat[7] * y + mat[11] * z + mat[15] * w;
+
+        return dest;
+    };
+
+    /**
+     * Translates a matrix by the given vector
+     *
+     * @param {mat4} mat mat4 to translate
+     * @param {vec3} vec vec3 specifying the translation
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat
+     *
+     * @returns {mat4} dest if specified, mat otherwise
+     */
+    mat4.translate = function (mat, vec, dest) {
+        var x = vec[0], y = vec[1], z = vec[2],
+            a00, a01, a02, a03,
+            a10, a11, a12, a13,
+            a20, a21, a22, a23;
+
+        if (!dest || mat === dest) {
+            mat[12] = mat[0] * x + mat[4] * y + mat[8] * z + mat[12];
+            mat[13] = mat[1] * x + mat[5] * y + mat[9] * z + mat[13];
+            mat[14] = mat[2] * x + mat[6] * y + mat[10] * z + mat[14];
+            mat[15] = mat[3] * x + mat[7] * y + mat[11] * z + mat[15];
+            return mat;
+        }
+
+        a00 = mat[0]; a01 = mat[1]; a02 = mat[2]; a03 = mat[3];
+        a10 = mat[4]; a11 = mat[5]; a12 = mat[6]; a13 = mat[7];
+        a20 = mat[8]; a21 = mat[9]; a22 = mat[10]; a23 = mat[11];
+
+        dest[0] = a00; dest[1] = a01; dest[2] = a02; dest[3] = a03;
+        dest[4] = a10; dest[5] = a11; dest[6] = a12; dest[7] = a13;
+        dest[8] = a20; dest[9] = a21; dest[10] = a22; dest[11] = a23;
+
+        dest[12] = a00 * x + a10 * y + a20 * z + mat[12];
+        dest[13] = a01 * x + a11 * y + a21 * z + mat[13];
+        dest[14] = a02 * x + a12 * y + a22 * z + mat[14];
+        dest[15] = a03 * x + a13 * y + a23 * z + mat[15];
+        return dest;
+    };
+
+    /**
+     * Scales a matrix by the given vector
+     *
+     * @param {mat4} mat mat4 to scale
+     * @param {vec3} vec vec3 specifying the scale for each axis
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat
+     *
+     * @param {mat4} dest if specified, mat otherwise
+     */
+    mat4.scale = function (mat, vec, dest) {
+        var x = vec[0], y = vec[1], z = vec[2];
+
+        if (!dest || mat === dest) {
+            mat[0] *= x;
+            mat[1] *= x;
+            mat[2] *= x;
+            mat[3] *= x;
+            mat[4] *= y;
+            mat[5] *= y;
+            mat[6] *= y;
+            mat[7] *= y;
+            mat[8] *= z;
+            mat[9] *= z;
+            mat[10] *= z;
+            mat[11] *= z;
+            return mat;
+        }
+
+        dest[0] = mat[0] * x;
+        dest[1] = mat[1] * x;
+        dest[2] = mat[2] * x;
+        dest[3] = mat[3] * x;
+        dest[4] = mat[4] * y;
+        dest[5] = mat[5] * y;
+        dest[6] = mat[6] * y;
+        dest[7] = mat[7] * y;
+        dest[8] = mat[8] * z;
+        dest[9] = mat[9] * z;
+        dest[10] = mat[10] * z;
+        dest[11] = mat[11] * z;
+        dest[12] = mat[12];
+        dest[13] = mat[13];
+        dest[14] = mat[14];
+        dest[15] = mat[15];
+        return dest;
+    };
+
+    /**
+     * Rotates a matrix by the given angle around the specified axis
+     * If rotating around a primary axis (X,Y,Z) one of the specialized rotation functions should be used instead for performance
+     *
+     * @param {mat4} mat mat4 to rotate
+     * @param {number} angle Angle (in radians) to rotate
+     * @param {vec3} axis vec3 representing the axis to rotate around
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat
+     *
+     * @returns {mat4} dest if specified, mat otherwise
+     */
+    mat4.rotate = function (mat, angle, axis, dest) {
+        var x = axis[0], y = axis[1], z = axis[2],
+            len = Math.sqrt(x * x + y * y + z * z),
+            s, c, t,
+            a00, a01, a02, a03,
+            a10, a11, a12, a13,
+            a20, a21, a22, a23,
+            b00, b01, b02,
+            b10, b11, b12,
+            b20, b21, b22;
+
+        if (!len) { return null; }
+        if (len !== 1) {
+            len = 1 / len;
+            x *= len;
+            y *= len;
+            z *= len;
+        }
+
+        s = Math.sin(angle);
+        c = Math.cos(angle);
+        t = 1 - c;
+
+        a00 = mat[0]; a01 = mat[1]; a02 = mat[2]; a03 = mat[3];
+        a10 = mat[4]; a11 = mat[5]; a12 = mat[6]; a13 = mat[7];
+        a20 = mat[8]; a21 = mat[9]; a22 = mat[10]; a23 = mat[11];
+
+        // Construct the elements of the rotation matrix
+        b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s;
+        b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s;
+        b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c;
+
+        if (!dest) {
+            dest = mat;
+        } else if (mat !== dest) { // If the source and destination differ, copy the unchanged last row
+            dest[12] = mat[12];
+            dest[13] = mat[13];
+            dest[14] = mat[14];
+            dest[15] = mat[15];
+        }
+
+        // Perform rotation-specific matrix multiplication
+        dest[0] = a00 * b00 + a10 * b01 + a20 * b02;
+        dest[1] = a01 * b00 + a11 * b01 + a21 * b02;
+        dest[2] = a02 * b00 + a12 * b01 + a22 * b02;
+        dest[3] = a03 * b00 + a13 * b01 + a23 * b02;
+
+        dest[4] = a00 * b10 + a10 * b11 + a20 * b12;
+        dest[5] = a01 * b10 + a11 * b11 + a21 * b12;
+        dest[6] = a02 * b10 + a12 * b11 + a22 * b12;
+        dest[7] = a03 * b10 + a13 * b11 + a23 * b12;
+
+        dest[8] = a00 * b20 + a10 * b21 + a20 * b22;
+        dest[9] = a01 * b20 + a11 * b21 + a21 * b22;
+        dest[10] = a02 * b20 + a12 * b21 + a22 * b22;
+        dest[11] = a03 * b20 + a13 * b21 + a23 * b22;
+        return dest;
+    };
+
+    /**
+     * Rotates a matrix by the given angle around the X axis
+     *
+     * @param {mat4} mat mat4 to rotate
+     * @param {number} angle Angle (in radians) to rotate
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat
+     *
+     * @returns {mat4} dest if specified, mat otherwise
+     */
+    mat4.rotateX = function (mat, angle, dest) {
+        var s = Math.sin(angle),
+            c = Math.cos(angle),
+            a10 = mat[4],
+            a11 = mat[5],
+            a12 = mat[6],
+            a13 = mat[7],
+            a20 = mat[8],
+            a21 = mat[9],
+            a22 = mat[10],
+            a23 = mat[11];
+
+        if (!dest) {
+            dest = mat;
+        } else if (mat !== dest) { // If the source and destination differ, copy the unchanged rows
+            dest[0] = mat[0];
+            dest[1] = mat[1];
+            dest[2] = mat[2];
+            dest[3] = mat[3];
+
+            dest[12] = mat[12];
+            dest[13] = mat[13];
+            dest[14] = mat[14];
+            dest[15] = mat[15];
+        }
+
+        // Perform axis-specific matrix multiplication
+        dest[4] = a10 * c + a20 * s;
+        dest[5] = a11 * c + a21 * s;
+        dest[6] = a12 * c + a22 * s;
+        dest[7] = a13 * c + a23 * s;
+
+        dest[8] = a10 * -s + a20 * c;
+        dest[9] = a11 * -s + a21 * c;
+        dest[10] = a12 * -s + a22 * c;
+        dest[11] = a13 * -s + a23 * c;
+        return dest;
+    };
+
+    /**
+     * Rotates a matrix by the given angle around the Y axis
+     *
+     * @param {mat4} mat mat4 to rotate
+     * @param {number} angle Angle (in radians) to rotate
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat
+     *
+     * @returns {mat4} dest if specified, mat otherwise
+     */
+    mat4.rotateY = function (mat, angle, dest) {
+        var s = Math.sin(angle),
+            c = Math.cos(angle),
+            a00 = mat[0],
+            a01 = mat[1],
+            a02 = mat[2],
+            a03 = mat[3],
+            a20 = mat[8],
+            a21 = mat[9],
+            a22 = mat[10],
+            a23 = mat[11];
+
+        if (!dest) {
+            dest = mat;
+        } else if (mat !== dest) { // If the source and destination differ, copy the unchanged rows
+            dest[4] = mat[4];
+            dest[5] = mat[5];
+            dest[6] = mat[6];
+            dest[7] = mat[7];
+
+            dest[12] = mat[12];
+            dest[13] = mat[13];
+            dest[14] = mat[14];
+            dest[15] = mat[15];
+        }
+
+        // Perform axis-specific matrix multiplication
+        dest[0] = a00 * c + a20 * -s;
+        dest[1] = a01 * c + a21 * -s;
+        dest[2] = a02 * c + a22 * -s;
+        dest[3] = a03 * c + a23 * -s;
+
+        dest[8] = a00 * s + a20 * c;
+        dest[9] = a01 * s + a21 * c;
+        dest[10] = a02 * s + a22 * c;
+        dest[11] = a03 * s + a23 * c;
+        return dest;
+    };
+
+    /**
+     * Rotates a matrix by the given angle around the Z axis
+     *
+     * @param {mat4} mat mat4 to rotate
+     * @param {number} angle Angle (in radians) to rotate
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat
+     *
+     * @returns {mat4} dest if specified, mat otherwise
+     */
+    mat4.rotateZ = function (mat, angle, dest) {
+        var s = Math.sin(angle),
+            c = Math.cos(angle),
+            a00 = mat[0],
+            a01 = mat[1],
+            a02 = mat[2],
+            a03 = mat[3],
+            a10 = mat[4],
+            a11 = mat[5],
+            a12 = mat[6],
+            a13 = mat[7];
+
+        if (!dest) {
+            dest = mat;
+        } else if (mat !== dest) { // If the source and destination differ, copy the unchanged last row
+            dest[8] = mat[8];
+            dest[9] = mat[9];
+            dest[10] = mat[10];
+            dest[11] = mat[11];
+
+            dest[12] = mat[12];
+            dest[13] = mat[13];
+            dest[14] = mat[14];
+            dest[15] = mat[15];
+        }
+
+        // Perform axis-specific matrix multiplication
+        dest[0] = a00 * c + a10 * s;
+        dest[1] = a01 * c + a11 * s;
+        dest[2] = a02 * c + a12 * s;
+        dest[3] = a03 * c + a13 * s;
+
+        dest[4] = a00 * -s + a10 * c;
+        dest[5] = a01 * -s + a11 * c;
+        dest[6] = a02 * -s + a12 * c;
+        dest[7] = a03 * -s + a13 * c;
+
+        return dest;
+    };
+
+    /**
+     * Generates a frustum matrix with the given bounds
+     *
+     * @param {number} left Left bound of the frustum
+     * @param {number} right Right bound of the frustum
+     * @param {number} bottom Bottom bound of the frustum
+     * @param {number} top Top bound of the frustum
+     * @param {number} near Near bound of the frustum
+     * @param {number} far Far bound of the frustum
+     * @param {mat4} [dest] mat4 frustum matrix will be written into
+     *
+     * @returns {mat4} dest if specified, a new mat4 otherwise
+     */
+    mat4.frustum = function (left, right, bottom, top, near, far, dest) {
+        if (!dest) { dest = mat4.create(); }
+        var rl = (right - left),
+            tb = (top - bottom),
+            fn = (far - near);
+        dest[0] = (near * 2) / rl;
+        dest[1] = 0;
+        dest[2] = 0;
+        dest[3] = 0;
+        dest[4] = 0;
+        dest[5] = (near * 2) / tb;
+        dest[6] = 0;
+        dest[7] = 0;
+        dest[8] = (right + left) / rl;
+        dest[9] = (top + bottom) / tb;
+        dest[10] = -(far + near) / fn;
+        dest[11] = -1;
+        dest[12] = 0;
+        dest[13] = 0;
+        dest[14] = -(far * near * 2) / fn;
+        dest[15] = 0;
+        return dest;
+    };
+
+    /**
+     * Generates a perspective projection matrix with the given bounds
+     *
+     * @param {number} fovy Vertical field of view
+     * @param {number} aspect Aspect ratio. typically viewport width/height
+     * @param {number} near Near bound of the frustum
+     * @param {number} far Far bound of the frustum
+     * @param {mat4} [dest] mat4 frustum matrix will be written into
+     *
+     * @returns {mat4} dest if specified, a new mat4 otherwise
+     */
+    mat4.perspective = function (fovy, aspect, near, far, dest) {
+        var top = near * Math.tan(fovy * Math.PI / 360.0),
+            right = top * aspect;
+        return mat4.frustum(-right, right, -top, top, near, far, dest);
+    };
+
+    /**
+     * Generates a orthogonal projection matrix with the given bounds
+     *
+     * @param {number} left Left bound of the frustum
+     * @param {number} right Right bound of the frustum
+     * @param {number} bottom Bottom bound of the frustum
+     * @param {number} top Top bound of the frustum
+     * @param {number} near Near bound of the frustum
+     * @param {number} far Far bound of the frustum
+     * @param {mat4} [dest] mat4 frustum matrix will be written into
+     *
+     * @returns {mat4} dest if specified, a new mat4 otherwise
+     */
+    mat4.ortho = function (left, right, bottom, top, near, far, dest) {
+        if (!dest) { dest = mat4.create(); }
+        var rl = (right - left),
+            tb = (top - bottom),
+            fn = (far - near);
+        dest[0] = 2 / rl;
+        dest[1] = 0;
+        dest[2] = 0;
+        dest[3] = 0;
+        dest[4] = 0;
+        dest[5] = 2 / tb;
+        dest[6] = 0;
+        dest[7] = 0;
+        dest[8] = 0;
+        dest[9] = 0;
+        dest[10] = -2 / fn;
+        dest[11] = 0;
+        dest[12] = -(left + right) / rl;
+        dest[13] = -(top + bottom) / tb;
+        dest[14] = -(far + near) / fn;
+        dest[15] = 1;
+        return dest;
+    };
+
+    /**
+     * Generates a look-at matrix with the given eye position, focal point, and up axis
+     *
+     * @param {vec3} eye Position of the viewer
+     * @param {vec3} center Point the viewer is looking at
+     * @param {vec3} up vec3 pointing "up"
+     * @param {mat4} [dest] mat4 frustum matrix will be written into
+     *
+     * @returns {mat4} dest if specified, a new mat4 otherwise
+     */
+    mat4.lookAt = function (eye, center, up, dest) {
+        if (!dest) { dest = mat4.create(); }
+
+        var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
+            eyex = eye[0],
+            eyey = eye[1],
+            eyez = eye[2],
+            upx = up[0],
+            upy = up[1],
+            upz = up[2],
+            centerx = center[0],
+            centery = center[1],
+            centerz = center[2];
+
+        if (eyex === centerx && eyey === centery && eyez === centerz) {
+            return mat4.identity(dest);
+        }
+
+        //vec3.direction(eye, center, z);
+        z0 = eyex - centerx;
+        z1 = eyey - centery;
+        z2 = eyez - centerz;
+
+        // normalize (no check needed for 0 because of early return)
+        len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
+        z0 *= len;
+        z1 *= len;
+        z2 *= len;
+
+        //vec3.normalize(vec3.cross(up, z, x));
+        x0 = upy * z2 - upz * z1;
+        x1 = upz * z0 - upx * z2;
+        x2 = upx * z1 - upy * z0;
+        len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
+        if (!len) {
+            x0 = 0;
+            x1 = 0;
+            x2 = 0;
+        } else {
+            len = 1 / len;
+            x0 *= len;
+            x1 *= len;
+            x2 *= len;
+        }
+
+        //vec3.normalize(vec3.cross(z, x, y));
+        y0 = z1 * x2 - z2 * x1;
+        y1 = z2 * x0 - z0 * x2;
+        y2 = z0 * x1 - z1 * x0;
+
+        len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
+        if (!len) {
+            y0 = 0;
+            y1 = 0;
+            y2 = 0;
+        } else {
+            len = 1 / len;
+            y0 *= len;
+            y1 *= len;
+            y2 *= len;
+        }
+
+        dest[0] = x0;
+        dest[1] = y0;
+        dest[2] = z0;
+        dest[3] = 0;
+        dest[4] = x1;
+        dest[5] = y1;
+        dest[6] = z1;
+        dest[7] = 0;
+        dest[8] = x2;
+        dest[9] = y2;
+        dest[10] = z2;
+        dest[11] = 0;
+        dest[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
+        dest[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
+        dest[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
+        dest[15] = 1;
+
+        return dest;
+    };
+
+    /**
+     * Creates a matrix from a quaternion rotation and vector translation
+     * This is equivalent to (but much faster than):
+     *
+     *     mat4.identity(dest);
+     *     mat4.translate(dest, vec);
+     *     var quatMat = mat4.create();
+     *     quat4.toMat4(quat, quatMat);
+     *     mat4.multiply(dest, quatMat);
+     *
+     * @param {quat4} quat Rotation quaternion
+     * @param {vec3} vec Translation vector
+     * @param {mat4} [dest] mat4 receiving operation result. If not specified result is written to a new mat4
+     *
+     * @returns {mat4} dest if specified, a new mat4 otherwise
+     */
+    mat4.fromRotationTranslation = function (quat, vec, dest) {
+        if (!dest) { dest = mat4.create(); }
+
+        // Quaternion math
+        var x = quat[0], y = quat[1], z = quat[2], w = quat[3],
+            x2 = x + x,
+            y2 = y + y,
+            z2 = z + z,
+
+            xx = x * x2,
+            xy = x * y2,
+            xz = x * z2,
+            yy = y * y2,
+            yz = y * z2,
+            zz = z * z2,
+            wx = w * x2,
+            wy = w * y2,
+            wz = w * z2;
+
+        dest[0] = 1 - (yy + zz);
+        dest[1] = xy + wz;
+        dest[2] = xz - wy;
+        dest[3] = 0;
+        dest[4] = xy - wz;
+        dest[5] = 1 - (xx + zz);
+        dest[6] = yz + wx;
+        dest[7] = 0;
+        dest[8] = xz + wy;
+        dest[9] = yz - wx;
+        dest[10] = 1 - (xx + yy);
+        dest[11] = 0;
+        dest[12] = vec[0];
+        dest[13] = vec[1];
+        dest[14] = vec[2];
+        dest[15] = 1;
+        
+        return dest;
+    };
+
+    /**
+     * Returns a string representation of a mat4
+     *
+     * @param {mat4} mat mat4 to represent as a string
+     *
+     * @returns {string} String representation of mat
+     */
+    mat4.str = function (mat) {
+        return '[' + mat[0] + ', ' + mat[1] + ', ' + mat[2] + ', ' + mat[3] +
+            ', ' + mat[4] + ', ' + mat[5] + ', ' + mat[6] + ', ' + mat[7] +
+            ', ' + mat[8] + ', ' + mat[9] + ', ' + mat[10] + ', ' + mat[11] +
+            ', ' + mat[12] + ', ' + mat[13] + ', ' + mat[14] + ', ' + mat[15] + ']';
+    };
+
+    /**
+     * @class Quaternion
+     * @name quat4
+     */
+    var quat4 = {};
+
+    /**
+     * Creates a new instance of a quat4 using the default array type
+     * Any javascript array containing at least 4 numeric elements can serve as a quat4
+     *
+     * @param {quat4} [quat] quat4 containing values to initialize with
+     *
+     * @returns {quat4} New quat4
+     */
+    quat4.create = function (quat) {
+        var dest = new MatrixArray(4);
+
+        if (quat) {
+            dest[0] = quat[0];
+            dest[1] = quat[1];
+            dest[2] = quat[2];
+            dest[3] = quat[3];
+        } else {
+            dest[0] = dest[1] = dest[2] = dest[3] = 0;
+        }
+
+        return dest;
+    };
+
+    /**
+     * Creates a new instance of a quat4, initializing it with the given arguments
+     *
+     * @param {number} x X value
+     * @param {number} y Y value
+     * @param {number} z Z value
+     * @param {number} w W value
+
+     * @returns {quat4} New quat4
+     */
+    quat4.createFrom = function (x, y, z, w) {
+        var dest = new MatrixArray(4);
+
+        dest[0] = x;
+        dest[1] = y;
+        dest[2] = z;
+        dest[3] = w;
+
+        return dest;
+    };
+
+    /**
+     * Copies the values of one quat4 to another
+     *
+     * @param {quat4} quat quat4 containing values to copy
+     * @param {quat4} dest quat4 receiving copied values
+     *
+     * @returns {quat4} dest
+     */
+    quat4.set = function (quat, dest) {
+        dest[0] = quat[0];
+        dest[1] = quat[1];
+        dest[2] = quat[2];
+        dest[3] = quat[3];
+
+        return dest;
+    };
+
+    /**
+     * Compares two quaternions for equality within a certain margin of error
+     *
+     * @param {quat4} a First vector
+     * @param {quat4} b Second vector
+     *
+     * @returns {Boolean} True if a is equivalent to b
+     */
+    quat4.equal = function (a, b) {
+        return a === b || (
+            Math.abs(a[0] - b[0]) < FLOAT_EPSILON &&
+            Math.abs(a[1] - b[1]) < FLOAT_EPSILON &&
+            Math.abs(a[2] - b[2]) < FLOAT_EPSILON &&
+            Math.abs(a[3] - b[3]) < FLOAT_EPSILON
+        );
+    };
+
+    /**
+     * Creates a new identity Quat4
+     *
+     * @param {quat4} [dest] quat4 receiving copied values
+     *
+     * @returns {quat4} dest is specified, new quat4 otherwise
+     */
+    quat4.identity = function (dest) {
+        if (!dest) { dest = quat4.create(); }
+        dest[0] = 0;
+        dest[1] = 0;
+        dest[2] = 0;
+        dest[3] = 1;
+        return dest;
+    };
+
+    var identityQuat4 = quat4.identity();
+
+    /**
+     * Calculates the W component of a quat4 from the X, Y, and Z components.
+     * Assumes that quaternion is 1 unit in length.
+     * Any existing W component will be ignored.
+     *
+     * @param {quat4} quat quat4 to calculate W component of
+     * @param {quat4} [dest] quat4 receiving calculated values. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.calculateW = function (quat, dest) {
+        var x = quat[0], y = quat[1], z = quat[2];
+
+        if (!dest || quat === dest) {
+            quat[3] = -Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
+            return quat;
+        }
+        dest[0] = x;
+        dest[1] = y;
+        dest[2] = z;
+        dest[3] = -Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
+        return dest;
+    };
+
+    /**
+     * Calculates the dot product of two quaternions
+     *
+     * @param {quat4} quat First operand
+     * @param {quat4} quat2 Second operand
+     *
+     * @return {number} Dot product of quat and quat2
+     */
+    quat4.dot = function(quat, quat2){
+        return quat[0]*quat2[0] + quat[1]*quat2[1] + quat[2]*quat2[2] + quat[3]*quat2[3];
+    };
+
+    /**
+     * Calculates the inverse of a quat4
+     *
+     * @param {quat4} quat quat4 to calculate inverse of
+     * @param {quat4} [dest] quat4 receiving inverse values. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.inverse = function(quat, dest) {
+        var q0 = quat[0], q1 = quat[1], q2 = quat[2], q3 = quat[3],
+            dot = q0*q0 + q1*q1 + q2*q2 + q3*q3,
+            invDot = dot ? 1.0/dot : 0;
+        
+        // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
+        
+        if(!dest || quat === dest) {
+            quat[0] *= -invDot;
+            quat[1] *= -invDot;
+            quat[2] *= -invDot;
+            quat[3] *= invDot;
+            return quat;
+        }
+        dest[0] = -quat[0]*invDot;
+        dest[1] = -quat[1]*invDot;
+        dest[2] = -quat[2]*invDot;
+        dest[3] = quat[3]*invDot;
+        return dest;
+    };
+
+
+    /**
+     * Calculates the conjugate of a quat4
+     * If the quaternion is normalized, this function is faster than quat4.inverse and produces the same result.
+     *
+     * @param {quat4} quat quat4 to calculate conjugate of
+     * @param {quat4} [dest] quat4 receiving conjugate values. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.conjugate = function (quat, dest) {
+        if (!dest || quat === dest) {
+            quat[0] *= -1;
+            quat[1] *= -1;
+            quat[2] *= -1;
+            return quat;
+        }
+        dest[0] = -quat[0];
+        dest[1] = -quat[1];
+        dest[2] = -quat[2];
+        dest[3] = quat[3];
+        return dest;
+    };
+
+    /**
+     * Calculates the length of a quat4
+     *
+     * Params:
+     * @param {quat4} quat quat4 to calculate length of
+     *
+     * @returns Length of quat
+     */
+    quat4.length = function (quat) {
+        var x = quat[0], y = quat[1], z = quat[2], w = quat[3];
+        return Math.sqrt(x * x + y * y + z * z + w * w);
+    };
+
+    /**
+     * Generates a unit quaternion of the same direction as the provided quat4
+     * If quaternion length is 0, returns [0, 0, 0, 0]
+     *
+     * @param {quat4} quat quat4 to normalize
+     * @param {quat4} [dest] quat4 receiving operation result. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.normalize = function (quat, dest) {
+        if (!dest) { dest = quat; }
+
+        var x = quat[0], y = quat[1], z = quat[2], w = quat[3],
+            len = Math.sqrt(x * x + y * y + z * z + w * w);
+        if (len === 0) {
+            dest[0] = 0;
+            dest[1] = 0;
+            dest[2] = 0;
+            dest[3] = 0;
+            return dest;
+        }
+        len = 1 / len;
+        dest[0] = x * len;
+        dest[1] = y * len;
+        dest[2] = z * len;
+        dest[3] = w * len;
+
+        return dest;
+    };
+
+    /**
+     * Performs quaternion addition
+     *
+     * @param {quat4} quat First operand
+     * @param {quat4} quat2 Second operand
+     * @param {quat4} [dest] quat4 receiving operation result. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.add = function (quat, quat2, dest) {
+        if(!dest || quat === dest) {
+            quat[0] += quat2[0];
+            quat[1] += quat2[1];
+            quat[2] += quat2[2];
+            quat[3] += quat2[3];
+            return quat;
+        }
+        dest[0] = quat[0]+quat2[0];
+        dest[1] = quat[1]+quat2[1];
+        dest[2] = quat[2]+quat2[2];
+        dest[3] = quat[3]+quat2[3];
+        return dest;
+    };
+
+    /**
+     * Performs a quaternion multiplication
+     *
+     * @param {quat4} quat First operand
+     * @param {quat4} quat2 Second operand
+     * @param {quat4} [dest] quat4 receiving operation result. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.multiply = function (quat, quat2, dest) {
+        if (!dest) { dest = quat; }
+
+        var qax = quat[0], qay = quat[1], qaz = quat[2], qaw = quat[3],
+            qbx = quat2[0], qby = quat2[1], qbz = quat2[2], qbw = quat2[3];
+
+        dest[0] = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
+        dest[1] = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
+        dest[2] = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
+        dest[3] = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
+
+        return dest;
+    };
+
+    /**
+     * Transforms a vec3 with the given quaternion
+     *
+     * @param {quat4} quat quat4 to transform the vector with
+     * @param {vec3} vec vec3 to transform
+     * @param {vec3} [dest] vec3 receiving operation result. If not specified result is written to vec
+     *
+     * @returns dest if specified, vec otherwise
+     */
+    quat4.multiplyVec3 = function (quat, vec, dest) {
+        if (!dest) { dest = vec; }
+
+        var x = vec[0], y = vec[1], z = vec[2],
+            qx = quat[0], qy = quat[1], qz = quat[2], qw = quat[3],
+
+            // calculate quat * vec
+            ix = qw * x + qy * z - qz * y,
+            iy = qw * y + qz * x - qx * z,
+            iz = qw * z + qx * y - qy * x,
+            iw = -qx * x - qy * y - qz * z;
+
+        // calculate result * inverse quat
+        dest[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
+        dest[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
+        dest[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
+
+        return dest;
+    };
+
+    /**
+     * Multiplies the components of a quaternion by a scalar value
+     *
+     * @param {quat4} quat to scale
+     * @param {number} val Value to scale by
+     * @param {quat4} [dest] quat4 receiving operation result. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.scale = function (quat, val, dest) {
+        if(!dest || quat === dest) {
+            quat[0] *= val;
+            quat[1] *= val;
+            quat[2] *= val;
+            quat[3] *= val;
+            return quat;
+        }
+        dest[0] = quat[0]*val;
+        dest[1] = quat[1]*val;
+        dest[2] = quat[2]*val;
+        dest[3] = quat[3]*val;
+        return dest;
+    };
+
+    /**
+     * Calculates a 3x3 matrix from the given quat4
+     *
+     * @param {quat4} quat quat4 to create matrix from
+     * @param {mat3} [dest] mat3 receiving operation result
+     *
+     * @returns {mat3} dest if specified, a new mat3 otherwise
+     */
+    quat4.toMat3 = function (quat, dest) {
+        if (!dest) { dest = mat3.create(); }
+
+        var x = quat[0], y = quat[1], z = quat[2], w = quat[3],
+            x2 = x + x,
+            y2 = y + y,
+            z2 = z + z,
+
+            xx = x * x2,
+            xy = x * y2,
+            xz = x * z2,
+            yy = y * y2,
+            yz = y * z2,
+            zz = z * z2,
+            wx = w * x2,
+            wy = w * y2,
+            wz = w * z2;
+
+        dest[0] = 1 - (yy + zz);
+        dest[1] = xy + wz;
+        dest[2] = xz - wy;
+
+        dest[3] = xy - wz;
+        dest[4] = 1 - (xx + zz);
+        dest[5] = yz + wx;
+
+        dest[6] = xz + wy;
+        dest[7] = yz - wx;
+        dest[8] = 1 - (xx + yy);
+
+        return dest;
+    };
+
+    /**
+     * Calculates a 4x4 matrix from the given quat4
+     *
+     * @param {quat4} quat quat4 to create matrix from
+     * @param {mat4} [dest] mat4 receiving operation result
+     *
+     * @returns {mat4} dest if specified, a new mat4 otherwise
+     */
+    quat4.toMat4 = function (quat, dest) {
+        if (!dest) { dest = mat4.create(); }
+
+        var x = quat[0], y = quat[1], z = quat[2], w = quat[3],
+            x2 = x + x,
+            y2 = y + y,
+            z2 = z + z,
+
+            xx = x * x2,
+            xy = x * y2,
+            xz = x * z2,
+            yy = y * y2,
+            yz = y * z2,
+            zz = z * z2,
+            wx = w * x2,
+            wy = w * y2,
+            wz = w * z2;
+
+        dest[0] = 1 - (yy + zz);
+        dest[1] = xy + wz;
+        dest[2] = xz - wy;
+        dest[3] = 0;
+
+        dest[4] = xy - wz;
+        dest[5] = 1 - (xx + zz);
+        dest[6] = yz + wx;
+        dest[7] = 0;
+
+        dest[8] = xz + wy;
+        dest[9] = yz - wx;
+        dest[10] = 1 - (xx + yy);
+        dest[11] = 0;
+
+        dest[12] = 0;
+        dest[13] = 0;
+        dest[14] = 0;
+        dest[15] = 1;
+
+        return dest;
+    };
+
+    /**
+     * Performs a spherical linear interpolation between two quat4
+     *
+     * @param {quat4} quat First quaternion
+     * @param {quat4} quat2 Second quaternion
+     * @param {number} slerp Interpolation amount between the two inputs
+     * @param {quat4} [dest] quat4 receiving operation result. If not specified result is written to quat
+     *
+     * @returns {quat4} dest if specified, quat otherwise
+     */
+    quat4.slerp = function (quat, quat2, slerp, dest) {
+        if (!dest) { dest = quat; }
+
+        var cosHalfTheta = quat[0] * quat2[0] + quat[1] * quat2[1] + quat[2] * quat2[2] + quat[3] * quat2[3],
+            halfTheta,
+            sinHalfTheta,
+            ratioA,
+            ratioB;
+
+        if (Math.abs(cosHalfTheta) >= 1.0) {
+            if (dest !== quat) {
+                dest[0] = quat[0];
+                dest[1] = quat[1];
+                dest[2] = quat[2];
+                dest[3] = quat[3];
+            }
+            return dest;
+        }
+
+        halfTheta = Math.acos(cosHalfTheta);
+        sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
+
+        if (Math.abs(sinHalfTheta) < 0.001) {
+            dest[0] = (quat[0] * 0.5 + quat2[0] * 0.5);
+            dest[1] = (quat[1] * 0.5 + quat2[1] * 0.5);
+            dest[2] = (quat[2] * 0.5 + quat2[2] * 0.5);
+            dest[3] = (quat[3] * 0.5 + quat2[3] * 0.5);
+            return dest;
+        }
+
+        ratioA = Math.sin((1 - slerp) * halfTheta) / sinHalfTheta;
+        ratioB = Math.sin(slerp * halfTheta) / sinHalfTheta;
+
+        dest[0] = (quat[0] * ratioA + quat2[0] * ratioB);
+        dest[1] = (quat[1] * ratioA + quat2[1] * ratioB);
+        dest[2] = (quat[2] * ratioA + quat2[2] * ratioB);
+        dest[3] = (quat[3] * ratioA + quat2[3] * ratioB);
+
+        return dest;
+    };
+
+    /**
+     * Creates a quaternion from the given 3x3 rotation matrix.
+     * If dest is omitted, a new quaternion will be created.
+     *
+     * @param {mat3}  mat    the rotation matrix
+     * @param {quat4} [dest] an optional receiving quaternion
+     *
+     * @returns {quat4} the quaternion constructed from the rotation matrix
+     *
+     */
+    quat4.fromRotationMatrix = function(mat, dest) {
+        if (!dest) dest = quat4.create();
+        
+        // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
+        // article "Quaternion Calculus and Fast Animation".
+
+        var fTrace = mat[0] + mat[4] + mat[8];
+        var fRoot;
+
+        if ( fTrace > 0.0 ) {
+            // |w| > 1/2, may as well choose w > 1/2
+            fRoot = Math.sqrt(fTrace + 1.0);  // 2w
+            dest[3] = 0.5 * fRoot;
+            fRoot = 0.5/fRoot;  // 1/(4w)
+            dest[0] = (mat[7]-mat[5])*fRoot;
+            dest[1] = (mat[2]-mat[6])*fRoot;
+            dest[2] = (mat[3]-mat[1])*fRoot;
+        } else {
+            // |w| <= 1/2
+            var s_iNext = quat4.fromRotationMatrix.s_iNext = quat4.fromRotationMatrix.s_iNext || [1,2,0];
+            var i = 0;
+            if ( mat[4] > mat[0] )
+              i = 1;
+            if ( mat[8] > mat[i*3+i] )
+              i = 2;
+            var j = s_iNext[i];
+            var k = s_iNext[j];
+            
+            fRoot = Math.sqrt(mat[i*3+i]-mat[j*3+j]-mat[k*3+k] + 1.0);
+            dest[i] = 0.5 * fRoot;
+            fRoot = 0.5 / fRoot;
+            dest[3] = (mat[k*3+j] - mat[j*3+k]) * fRoot;
+            dest[j] = (mat[j*3+i] + mat[i*3+j]) * fRoot;
+            dest[k] = (mat[k*3+i] + mat[i*3+k]) * fRoot;
+        }
+        
+        return dest;
+    };
+
+    /**
+     * Alias. See the description for quat4.fromRotationMatrix().
+     */
+    mat3.toQuat4 = quat4.fromRotationMatrix;
+
+    (function() {
+        var mat = mat3.create();
+        
+        /**
+         * Creates a quaternion from the 3 given vectors. They must be perpendicular
+         * to one another and represent the X, Y and Z axes.
+         *
+         * If dest is omitted, a new quat4 will be created.
+         *
+         * Example: The default OpenGL orientation has a view vector [0, 0, -1],
+         * right vector [1, 0, 0], and up vector [0, 1, 0]. A quaternion representing
+         * this orientation could be constructed with:
+         *
+         *   quat = quat4.fromAxes([0, 0, -1], [1, 0, 0], [0, 1, 0], quat4.create());
+         *
+         * @param {vec3}  view   the view vector, or direction the object is pointing in
+         * @param {vec3}  right  the right vector, or direction to the "right" of the object
+         * @param {vec3}  up     the up vector, or direction towards the object's "up"
+         * @param {quat4} [dest] an optional receiving quat4
+         *
+         * @returns {quat4} dest
+         **/
+        quat4.fromAxes = function(view, right, up, dest) {
+            mat[0] = right[0];
+            mat[3] = right[1];
+            mat[6] = right[2];
+
+            mat[1] = up[0];
+            mat[4] = up[1];
+            mat[7] = up[2];
+
+            mat[2] = view[0];
+            mat[5] = view[1];
+            mat[8] = view[2];
+
+            return quat4.fromRotationMatrix(mat, dest);
+        };
+    })();
+
+    /**
+     * Sets a quat4 to the Identity and returns it.
+     *
+     * @param {quat4} [dest] quat4 to set. If omitted, a
+     * new quat4 will be created.
+     *
+     * @returns {quat4} dest
+     */
+    quat4.identity = function(dest) {
+        if (!dest) dest = quat4.create();
+        dest[0] = 0;
+        dest[1] = 0;
+        dest[2] = 0;
+        dest[3] = 1;
+        return dest;
+    };
+
+    /**
+     * Sets a quat4 from the given angle and rotation axis,
+     * then returns it. If dest is not given, a new quat4 is created.
+     *
+     * @param {Number} angle  the angle in radians
+     * @param {vec3}   axis   the axis around which to rotate
+     * @param {quat4}  [dest] the optional quat4 to store the result
+     *
+     * @returns {quat4} dest
+     **/
+    quat4.fromAngleAxis = function(angle, axis, dest) {
+        // The quaternion representing the rotation is
+        //   q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
+        if (!dest) dest = quat4.create();
+        
+        var half = angle * 0.5;
+        var s = Math.sin(half);
+        dest[3] = Math.cos(half);
+        dest[0] = s * axis[0];
+        dest[1] = s * axis[1];
+        dest[2] = s * axis[2];
+        
+        return dest;
+    };
+
+    /**
+     * Stores the angle and axis in a vec4, where the XYZ components represent
+     * the axis and the W (4th) component is the angle in radians.
+     *
+     * If dest is not given, src will be modified in place and returned, after
+     * which it should not be considered not a quaternion (just an axis and angle).
+     *
+     * @param {quat4} quat   the quaternion whose angle and axis to store
+     * @param {vec4}  [dest] the optional vec4 to receive the data
+     *
+     * @returns {vec4} dest
+     */
+    quat4.toAngleAxis = function(src, dest) {
+        if (!dest) dest = src;
+        // The quaternion representing the rotation is
+        //   q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
+
+        var sqrlen = src[0]*src[0]+src[1]*src[1]+src[2]*src[2];
+        if (sqrlen > 0)
+        {
+            dest[3] = 2 * Math.acos(src[3]);
+            var invlen = glMath.invsqrt(sqrlen);
+            dest[0] = src[0]*invlen;
+            dest[1] = src[1]*invlen;
+            dest[2] = src[2]*invlen;
+        } else {
+            // angle is 0 (mod 2*pi), so any axis will do
+            dest[3] = 0;
+            dest[0] = 1;
+            dest[1] = 0;
+            dest[2] = 0;
+        }
+        
+        return dest;
+    };
+
+    /**
+     * Returns a string representation of a quaternion
+     *
+     * @param {quat4} quat quat4 to represent as a string
+     *
+     * @returns {string} String representation of quat
+     */
+    quat4.str = function (quat) {
+        return '[' + quat[0] + ', ' + quat[1] + ', ' + quat[2] + ', ' + quat[3] + ']';
+    };
+    
+    /**
+     * @class 2 Dimensional Vector
+     * @name vec2
+     */
+    var vec2 = {};
+     
+    /**
+     * Creates a new vec2, initializing it from vec if vec
+     * is given.
+     *
+     * @param {vec2} [vec] the vector's initial contents
+     * @returns {vec2} a new 2D vector
+     */
+    vec2.create = function(vec) {
+        var dest = new MatrixArray(2);
+
+        if (vec) {
+            dest[0] = vec[0];
+            dest[1] = vec[1];
+        } else {
+            dest[0] = 0;
+            dest[1] = 0;
+        }
+        return dest;
+    };
+
+    /**
+     * Creates a new instance of a vec2, initializing it with the given arguments
+     *
+     * @param {number} x X value
+     * @param {number} y Y value
+
+     * @returns {vec2} New vec2
+     */
+    vec2.createFrom = function (x, y) {
+        var dest = new MatrixArray(2);
+
+        dest[0] = x;
+        dest[1] = y;
+
+        return dest;
+    };
+    
+    /**
+     * Adds the vec2's together. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec2} vecA the first operand
+     * @param {vec2} vecB the second operand
+     * @param {vec2} [dest] the optional receiving vector
+     * @returns {vec2} dest
+     */
+    vec2.add = function(vecA, vecB, dest) {
+        if (!dest) dest = vecB;
+        dest[0] = vecA[0] + vecB[0];
+        dest[1] = vecA[1] + vecB[1];
+        return dest;
+    };
+    
+    /**
+     * Subtracts vecB from vecA. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec2} vecA the first operand
+     * @param {vec2} vecB the second operand
+     * @param {vec2} [dest] the optional receiving vector
+     * @returns {vec2} dest
+     */
+    vec2.subtract = function(vecA, vecB, dest) {
+        if (!dest) dest = vecB;
+        dest[0] = vecA[0] - vecB[0];
+        dest[1] = vecA[1] - vecB[1];
+        return dest;
+    };
+    
+    /**
+     * Multiplies vecA with vecB. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec2} vecA the first operand
+     * @param {vec2} vecB the second operand
+     * @param {vec2} [dest] the optional receiving vector
+     * @returns {vec2} dest
+     */
+    vec2.multiply = function(vecA, vecB, dest) {
+        if (!dest) dest = vecB;
+        dest[0] = vecA[0] * vecB[0];
+        dest[1] = vecA[1] * vecB[1];
+        return dest;
+    };
+    
+    /**
+     * Divides vecA by vecB. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec2} vecA the first operand
+     * @param {vec2} vecB the second operand
+     * @param {vec2} [dest] the optional receiving vector
+     * @returns {vec2} dest
+     */
+    vec2.divide = function(vecA, vecB, dest) {
+        if (!dest) dest = vecB;
+        dest[0] = vecA[0] / vecB[0];
+        dest[1] = vecA[1] / vecB[1];
+        return dest;
+    };
+    
+    /**
+     * Scales vecA by some scalar number. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecA.
+     *
+     * This is the same as multiplying each component of vecA
+     * by the given scalar.
+     *
+     * @param {vec2}   vecA the vector to be scaled
+     * @param {Number} scalar the amount to scale the vector by
+     * @param {vec2}   [dest] the optional receiving vector
+     * @returns {vec2} dest
+     */
+    vec2.scale = function(vecA, scalar, dest) {
+        if (!dest) dest = vecA;
+        dest[0] = vecA[0] * scalar;
+        dest[1] = vecA[1] * scalar;
+        return dest;
+    };
+
+    /**
+     * Calculates the euclidian distance between two vec2
+     *
+     * Params:
+     * @param {vec2} vecA First vector
+     * @param {vec2} vecB Second vector
+     *
+     * @returns {number} Distance between vecA and vecB
+     */
+    vec2.dist = function (vecA, vecB) {
+        var x = vecB[0] - vecA[0],
+            y = vecB[1] - vecA[1];
+        return Math.sqrt(x*x + y*y);
+    };
+
+    /**
+     * Copies the values of one vec2 to another
+     *
+     * @param {vec2} vec vec2 containing values to copy
+     * @param {vec2} dest vec2 receiving copied values
+     *
+     * @returns {vec2} dest
+     */
+    vec2.set = function (vec, dest) {
+        dest[0] = vec[0];
+        dest[1] = vec[1];
+        return dest;
+    };
+
+    /**
+     * Compares two vectors for equality within a certain margin of error
+     *
+     * @param {vec2} a First vector
+     * @param {vec2} b Second vector
+     *
+     * @returns {Boolean} True if a is equivalent to b
+     */
+    vec2.equal = function (a, b) {
+        return a === b || (
+            Math.abs(a[0] - b[0]) < FLOAT_EPSILON &&
+            Math.abs(a[1] - b[1]) < FLOAT_EPSILON
+        );
+    };
+
+    /**
+     * Negates the components of a vec2
+     *
+     * @param {vec2} vec vec2 to negate
+     * @param {vec2} [dest] vec2 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec2} dest if specified, vec otherwise
+     */
+    vec2.negate = function (vec, dest) {
+        if (!dest) { dest = vec; }
+        dest[0] = -vec[0];
+        dest[1] = -vec[1];
+        return dest;
+    };
+
+    /**
+     * Normlize a vec2
+     *
+     * @param {vec2} vec vec2 to normalize
+     * @param {vec2} [dest] vec2 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec2} dest if specified, vec otherwise
+     */
+    vec2.normalize = function (vec, dest) {
+        if (!dest) { dest = vec; }
+        var mag = vec[0] * vec[0] + vec[1] * vec[1];
+        if (mag > 0) {
+            mag = Math.sqrt(mag);
+            dest[0] = vec[0] / mag;
+            dest[1] = vec[1] / mag;
+        } else {
+            dest[0] = dest[1] = 0;
+        }
+        return dest;
+    };
+
+    /**
+     * Computes the cross product of two vec2's. Note that the cross product must by definition
+     * produce a 3D vector. If a dest vector is given, it will contain the resultant 3D vector.
+     * Otherwise, a scalar number will be returned, representing the vector's Z coordinate, since
+     * its X and Y must always equal 0.
+     *
+     * Examples:
+     *    var crossResult = vec3.create();
+     *    vec2.cross([1, 2], [3, 4], crossResult);
+     *    //=> [0, 0, -2]
+     *
+     *    vec2.cross([1, 2], [3, 4]);
+     *    //=> -2
+     *
+     * See http://stackoverflow.com/questions/243945/calculating-a-2d-vectors-cross-product
+     * for some interesting facts.
+     *
+     * @param {vec2} vecA left operand
+     * @param {vec2} vecB right operand
+     * @param {vec2} [dest] optional vec2 receiving result. If not specified a scalar is returned
+     *
+     */
+    vec2.cross = function (vecA, vecB, dest) {
+        var z = vecA[0] * vecB[1] - vecA[1] * vecB[0];
+        if (!dest) return z;
+        dest[0] = dest[1] = 0;
+        dest[2] = z;
+        return dest;
+    };
+    
+    /**
+     * Caclulates the length of a vec2
+     *
+     * @param {vec2} vec vec2 to calculate length of
+     *
+     * @returns {Number} Length of vec
+     */
+    vec2.length = function (vec) {
+      var x = vec[0], y = vec[1];
+      return Math.sqrt(x * x + y * y);
+    };
+
+    /**
+     * Caclulates the squared length of a vec2
+     *
+     * @param {vec2} vec vec2 to calculate squared length of
+     *
+     * @returns {Number} Squared Length of vec
+     */
+    vec2.squaredLength = function (vec) {
+      var x = vec[0], y = vec[1];
+      return x * x + y * y;
+    };
+
+    /**
+     * Caclulates the dot product of two vec2s
+     *
+     * @param {vec2} vecA First operand
+     * @param {vec2} vecB Second operand
+     *
+     * @returns {Number} Dot product of vecA and vecB
+     */
+    vec2.dot = function (vecA, vecB) {
+        return vecA[0] * vecB[0] + vecA[1] * vecB[1];
+    };
+    
+    /**
+     * Generates a 2D unit vector pointing from one vector to another
+     *
+     * @param {vec2} vecA Origin vec2
+     * @param {vec2} vecB vec2 to point to
+     * @param {vec2} [dest] vec2 receiving operation result. If not specified result is written to vecA
+     *
+     * @returns {vec2} dest if specified, vecA otherwise
+     */
+    vec2.direction = function (vecA, vecB, dest) {
+        if (!dest) { dest = vecA; }
+
+        var x = vecA[0] - vecB[0],
+            y = vecA[1] - vecB[1],
+            len = x * x + y * y;
+
+        if (!len) {
+            dest[0] = 0;
+            dest[1] = 0;
+            dest[2] = 0;
+            return dest;
+        }
+
+        len = 1 / Math.sqrt(len);
+        dest[0] = x * len;
+        dest[1] = y * len;
+        return dest;
+    };
+
+    /**
+     * Performs a linear interpolation between two vec2
+     *
+     * @param {vec2} vecA First vector
+     * @param {vec2} vecB Second vector
+     * @param {Number} lerp Interpolation amount between the two inputs
+     * @param {vec2} [dest] vec2 receiving operation result. If not specified result is written to vecA
+     *
+     * @returns {vec2} dest if specified, vecA otherwise
+     */
+    vec2.lerp = function (vecA, vecB, lerp, dest) {
+        if (!dest) { dest = vecA; }
+        dest[0] = vecA[0] + lerp * (vecB[0] - vecA[0]);
+        dest[1] = vecA[1] + lerp * (vecB[1] - vecA[1]);
+        return dest;
+    };
+
+    /**
+     * Returns a string representation of a vector
+     *
+     * @param {vec2} vec Vector to represent as a string
+     *
+     * @returns {String} String representation of vec
+     */
+    vec2.str = function (vec) {
+        return '[' + vec[0] + ', ' + vec[1] + ']';
+    };
+    
+    /**
+     * @class 2x2 Matrix
+     * @name mat2
+     */
+    var mat2 = {};
+    
+    /**
+     * Creates a new 2x2 matrix. If src is given, the new matrix
+     * is initialized to those values.
+     *
+     * @param {mat2} [src] the seed values for the new matrix, if any
+     * @returns {mat2} a new matrix
+     */
+    mat2.create = function(src) {
+        var dest = new MatrixArray(4);
+        
+        if (src) {
+            dest[0] = src[0];
+            dest[1] = src[1];
+            dest[2] = src[2];
+            dest[3] = src[3];
+        } else {
+            dest[0] = dest[1] = dest[2] = dest[3] = 0;
+        }
+        return dest;
+    };
+
+    /**
+     * Creates a new instance of a mat2, initializing it with the given arguments
+     *
+     * @param {number} m00
+     * @param {number} m01
+     * @param {number} m10
+     * @param {number} m11
+
+     * @returns {mat2} New mat2
+     */
+    mat2.createFrom = function (m00, m01, m10, m11) {
+        var dest = new MatrixArray(4);
+
+        dest[0] = m00;
+        dest[1] = m01;
+        dest[2] = m10;
+        dest[3] = m11;
+
+        return dest;
+    };
+    
+    /**
+     * Copies the values of one mat2 to another
+     *
+     * @param {mat2} mat mat2 containing values to copy
+     * @param {mat2} dest mat2 receiving copied values
+     *
+     * @returns {mat2} dest
+     */
+    mat2.set = function (mat, dest) {
+        dest[0] = mat[0];
+        dest[1] = mat[1];
+        dest[2] = mat[2];
+        dest[3] = mat[3];
+        return dest;
+    };
+
+    /**
+     * Compares two matrices for equality within a certain margin of error
+     *
+     * @param {mat2} a First matrix
+     * @param {mat2} b Second matrix
+     *
+     * @returns {Boolean} True if a is equivalent to b
+     */
+    mat2.equal = function (a, b) {
+        return a === b || (
+            Math.abs(a[0] - b[0]) < FLOAT_EPSILON &&
+            Math.abs(a[1] - b[1]) < FLOAT_EPSILON &&
+            Math.abs(a[2] - b[2]) < FLOAT_EPSILON &&
+            Math.abs(a[3] - b[3]) < FLOAT_EPSILON
+        );
+    };
+
+    /**
+     * Sets a mat2 to an identity matrix
+     *
+     * @param {mat2} [dest] mat2 to set. If omitted a new one will be created.
+     *
+     * @returns {mat2} dest
+     */
+    mat2.identity = function (dest) {
+        if (!dest) { dest = mat2.create(); }
+        dest[0] = 1;
+        dest[1] = 0;
+        dest[2] = 0;
+        dest[3] = 1;
+        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;
+    };
+
+    /**
+     * 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;
+    };
+    
+    /**
+     * Performs a matrix multiplication
+     *
+     * @param {mat2} matA First operand
+     * @param {mat2} matB Second operand
+     * @param {mat2} [dest] mat2 receiving operation result. If not specified result is written to matA
+     *
+     * @returns {mat2} dest if specified, matA otherwise
+     */
+    mat2.multiply = function (matA, matB, dest) {
+        if (!dest) { dest = matA; }
+        var a11 = matA[0],
+            a12 = matA[1],
+            a21 = matA[2],
+            a22 = matA[3];
+        dest[0] = a11 * matB[0] + a12 * matB[2];
+        dest[1] = a11 * matB[1] + a12 * matB[3];
+        dest[2] = a21 * matB[0] + a22 * matB[2];
+        dest[3] = a21 * matB[1] + a22 * matB[3];
+        return dest;
+    };
+
+    /**
+     * Rotates a 2x2 matrix by an angle
+     *
+     * @param {mat2}   mat   The matrix to rotate
+     * @param {Number} angle The angle in radians
+     * @param {mat2} [dest]  Optional mat2 receiving the result. If omitted mat will be used.
+     *
+     * @returns {mat2} dest if specified, mat otherwise
+     */
+    mat2.rotate = function (mat, angle, dest) {
+        if (!dest) { dest = mat; }
+        var a11 = mat[0],
+            a12 = mat[1],
+            a21 = mat[2],
+            a22 = mat[3],
+            s = Math.sin(angle),
+            c = Math.cos(angle);
+        dest[0] = a11 *  c + a12 * s;
+        dest[1] = a11 * -s + a12 * c;
+        dest[2] = a21 *  c + a22 * s;
+        dest[3] = a21 * -s + a22 * c;
+        return dest;
+    };
+
+    /**
+     * Multiplies the vec2 by the given 2x2 matrix
+     *
+     * @param {mat2} matrix the 2x2 matrix to multiply against
+     * @param {vec2} vec    the vector to multiply
+     * @param {vec2} [dest] an optional receiving vector. If not given, vec is used.
+     *
+     * @returns {vec2} The multiplication result
+     **/
+    mat2.multiplyVec2 = function(matrix, vec, dest) {
+      if (!dest) dest = vec;
+      var x = vec[0], y = vec[1];
+      dest[0] = x * matrix[0] + y * matrix[1];
+      dest[1] = x * matrix[2] + y * matrix[3];
+      return dest;
+    };
+    
+    /**
+     * Scales the mat2 by the dimensions in the given vec2
+     *
+     * @param {mat2} matrix the 2x2 matrix to scale
+     * @param {vec2} vec    the vector containing the dimensions to scale by
+     * @param {vec2} [dest] an optional receiving mat2. If not given, matrix is used.
+     *
+     * @returns {mat2} dest if specified, matrix otherwise
+     **/
+    mat2.scale = function(matrix, vec, dest) {
+      if (!dest) { dest = matrix; }
+      var a11 = matrix[0],
+          a12 = matrix[1],
+          a21 = matrix[2],
+          a22 = matrix[3],
+          b11 = vec[0],
+          b22 = vec[1];
+      dest[0] = a11 * b11;
+      dest[1] = a12 * b22;
+      dest[2] = a21 * b11;
+      dest[3] = a22 * b22;
+      return dest;
+    };
+
+    /**
+     * Returns a string representation of a mat2
+     *
+     * @param {mat2} mat mat2 to represent as a string
+     *
+     * @param {String} String representation of mat
+     */
+    mat2.str = function (mat) {
+        return '[' + mat[0] + ', ' + mat[1] + ', ' + mat[2] + ', ' + mat[3] + ']';
+    };
+    
+    /**
+     * @class 4 Dimensional Vector
+     * @name vec4
+     */
+    var vec4 = {};
+     
+    /**
+     * Creates a new vec4, initializing it from vec if vec
+     * is given.
+     *
+     * @param {vec4} [vec] the vector's initial contents
+     * @returns {vec4} a new 2D vector
+     */
+    vec4.create = function(vec) {
+        var dest = new MatrixArray(4);
+        
+        if (vec) {
+            dest[0] = vec[0];
+            dest[1] = vec[1];
+            dest[2] = vec[2];
+            dest[3] = vec[3];
+        } else {
+            dest[0] = 0;
+            dest[1] = 0;
+            dest[2] = 0;
+            dest[3] = 0;
+        }
+        return dest;
+    };
+
+    /**
+     * Creates a new instance of a vec4, initializing it with the given arguments
+     *
+     * @param {number} x X value
+     * @param {number} y Y value
+     * @param {number} z Z value
+     * @param {number} w W value
+
+     * @returns {vec4} New vec4
+     */
+    vec4.createFrom = function (x, y, z, w) {
+        var dest = new MatrixArray(4);
+
+        dest[0] = x;
+        dest[1] = y;
+        dest[2] = z;
+        dest[3] = w;
+
+        return dest;
+    };
+    
+    /**
+     * Adds the vec4's together. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec4} vecA the first operand
+     * @param {vec4} vecB the second operand
+     * @param {vec4} [dest] the optional receiving vector
+     * @returns {vec4} dest
+     */
+    vec4.add = function(vecA, vecB, dest) {
+      if (!dest) dest = vecB;
+      dest[0] = vecA[0] + vecB[0];
+      dest[1] = vecA[1] + vecB[1];
+      dest[2] = vecA[2] + vecB[2];
+      dest[3] = vecA[3] + vecB[3];
+      return dest;
+    };
+    
+    /**
+     * Subtracts vecB from vecA. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec4} vecA the first operand
+     * @param {vec4} vecB the second operand
+     * @param {vec4} [dest] the optional receiving vector
+     * @returns {vec4} dest
+     */
+    vec4.subtract = function(vecA, vecB, dest) {
+      if (!dest) dest = vecB;
+      dest[0] = vecA[0] - vecB[0];
+      dest[1] = vecA[1] - vecB[1];
+      dest[2] = vecA[2] - vecB[2];
+      dest[3] = vecA[3] - vecB[3];
+      return dest;
+    };
+    
+    /**
+     * Multiplies vecA with vecB. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec4} vecA the first operand
+     * @param {vec4} vecB the second operand
+     * @param {vec4} [dest] the optional receiving vector
+     * @returns {vec4} dest
+     */
+    vec4.multiply = function(vecA, vecB, dest) {
+      if (!dest) dest = vecB;
+      dest[0] = vecA[0] * vecB[0];
+      dest[1] = vecA[1] * vecB[1];
+      dest[2] = vecA[2] * vecB[2];
+      dest[3] = vecA[3] * vecB[3];
+      return dest;
+    };
+    
+    /**
+     * Divides vecA by vecB. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecB.
+     *
+     * @param {vec4} vecA the first operand
+     * @param {vec4} vecB the second operand
+     * @param {vec4} [dest] the optional receiving vector
+     * @returns {vec4} dest
+     */
+    vec4.divide = function(vecA, vecB, dest) {
+      if (!dest) dest = vecB;
+      dest[0] = vecA[0] / vecB[0];
+      dest[1] = vecA[1] / vecB[1];
+      dest[2] = vecA[2] / vecB[2];
+      dest[3] = vecA[3] / vecB[3];
+      return dest;
+    };
+    
+    /**
+     * Scales vecA by some scalar number. If dest is given, the result
+     * is stored there. Otherwise, the result is stored in vecA.
+     *
+     * This is the same as multiplying each component of vecA
+     * by the given scalar.
+     *
+     * @param {vec4}   vecA the vector to be scaled
+     * @param {Number} scalar the amount to scale the vector by
+     * @param {vec4}   [dest] the optional receiving vector
+     * @returns {vec4} dest
+     */
+    vec4.scale = function(vecA, scalar, dest) {
+      if (!dest) dest = vecA;
+      dest[0] = vecA[0] * scalar;
+      dest[1] = vecA[1] * scalar;
+      dest[2] = vecA[2] * scalar;
+      dest[3] = vecA[3] * scalar;
+      return dest;
+    };
+
+    /**
+     * Copies the values of one vec4 to another
+     *
+     * @param {vec4} vec vec4 containing values to copy
+     * @param {vec4} dest vec4 receiving copied values
+     *
+     * @returns {vec4} dest
+     */
+    vec4.set = function (vec, dest) {
+        dest[0] = vec[0];
+        dest[1] = vec[1];
+        dest[2] = vec[2];
+        dest[3] = vec[3];
+        return dest;
+    };
+
+    /**
+     * Compares two vectors for equality within a certain margin of error
+     *
+     * @param {vec4} a First vector
+     * @param {vec4} b Second vector
+     *
+     * @returns {Boolean} True if a is equivalent to b
+     */
+    vec4.equal = function (a, b) {
+        return a === b || (
+            Math.abs(a[0] - b[0]) < FLOAT_EPSILON &&
+            Math.abs(a[1] - b[1]) < FLOAT_EPSILON &&
+            Math.abs(a[2] - b[2]) < FLOAT_EPSILON &&
+            Math.abs(a[3] - b[3]) < FLOAT_EPSILON
+        );
+    };
+
+    /**
+     * Negates the components of a vec4
+     *
+     * @param {vec4} vec vec4 to negate
+     * @param {vec4} [dest] vec4 receiving operation result. If not specified result is written to vec
+     *
+     * @returns {vec4} dest if specified, vec otherwise
+     */
+    vec4.negate = function (vec, dest) {
+        if (!dest) { dest = vec; }
+        dest[0] = -vec[0];
+        dest[1] = -vec[1];
+        dest[2] = -vec[2];
+        dest[3] = -vec[3];
+        return dest;
+    };
+
+    /**
+     * Caclulates the length of a vec2
+     *
+     * @param {vec2} vec vec2 to calculate length of
+     *
+     * @returns {Number} Length of vec
+     */
+    vec4.length = function (vec) {
+      var x = vec[0], y = vec[1], z = vec[2], w = vec[3];
+      return Math.sqrt(x * x + y * y + z * z + w * w);
+    };
+
+    /**
+     * Caclulates the squared length of a vec4
+     *
+     * @param {vec4} vec vec4 to calculate squared length of
+     *
+     * @returns {Number} Squared Length of vec
+     */
+    vec4.squaredLength = function (vec) {
+      var x = vec[0], y = vec[1], z = vec[2], w = vec[3];
+      return x * x + y * y + z * z + w * w;
+    };
+
+    /**
+     * Performs a linear interpolation between two vec4
+     *
+     * @param {vec4} vecA First vector
+     * @param {vec4} vecB Second vector
+     * @param {Number} lerp Interpolation amount between the two inputs
+     * @param {vec4} [dest] vec4 receiving operation result. If not specified result is written to vecA
+     *
+     * @returns {vec4} dest if specified, vecA otherwise
+     */
+    vec4.lerp = function (vecA, vecB, lerp, dest) {
+        if (!dest) { dest = vecA; }
+        dest[0] = vecA[0] + lerp * (vecB[0] - vecA[0]);
+        dest[1] = vecA[1] + lerp * (vecB[1] - vecA[1]);
+        dest[2] = vecA[2] + lerp * (vecB[2] - vecA[2]);
+        dest[3] = vecA[3] + lerp * (vecB[3] - vecA[3]);
+        return dest;
+    };
+
+    /**
+     * Returns a string representation of a vector
+     *
+     * @param {vec4} vec Vector to represent as a string
+     *
+     * @returns {String} String representation of vec
+     */
+    vec4.str = function (vec) {
+        return '[' + vec[0] + ', ' + vec[1] + ', ' + vec[2] + ', ' + vec[3] + ']';
+    };
+
+    /*
+     * Exports
+     */
+
+    if(root) {
+        root.glMatrixArrayType = MatrixArray;
+        root.MatrixArray = MatrixArray;
+        root.setMatrixArrayType = setMatrixArrayType;
+        root.determineMatrixArrayType = determineMatrixArrayType;
+        root.glMath = glMath;
+        root.vec2 = vec2;
+        root.vec3 = vec3;
+        root.vec4 = vec4;
+        root.mat2 = mat2;
+        root.mat3 = mat3;
+        root.mat4 = mat4;
+        root.quat4 = quat4;
+    }
+
+    return {
+        glMatrixArrayType: MatrixArray,
+        MatrixArray: MatrixArray,
+        setMatrixArrayType: setMatrixArrayType,
+        determineMatrixArrayType: determineMatrixArrayType,
+        glMath: glMath,
+        vec2: vec2,
+        vec3: vec3,
+        vec4: vec4,
+        mat2: mat2,
+        mat3: mat3,
+        mat4: mat4,
+        quat4: quat4
+    };
+}));
diff --git a/src/js/widgets/components/imageloader.js b/src/js/widgets/components/imageloader.js
new file mode 100644 (file)
index 0000000..44f0514
--- /dev/null
@@ -0,0 +1,179 @@
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+//>>description: Tizen image loader component for gallery3d\r
+//>>label: Image loader\r
+//>>group: Tizen:Widgets:Components\r
+\r
+define( [ ], function ( ) {\r
+//>>excludeEnd("jqmBuildExclude");\r
+\r
+/* ***************************************************************************\r
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd.\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person obtaining a\r
+ * copy of this software and associated documentation files (the "Software"),\r
+ * to deal in the Software without restriction, including without limitation\r
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,\r
+ * and/or sell copies of the Software, and to permit persons to whom the\r
+ * Software is furnished to do so, subject to the following conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be included in\r
+ * all copies or substantial portions of the Software.\r
+ *\r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r
+ * DEALINGS IN THE SOFTWARE.\r
+ * ***************************************************************************\r
+ *\r
+ * Authors: Hyunsook Park <hyunsook.park@samsung.com>\r
+ *                     Wonseop Kim <wonseop.kim@samsung.com>\r
+*/\r
+\r
+( function ( $, window, document, undefined ) {\r
+       var _canvas = document.createElement( 'canvas' ),\r
+               _context = _canvas.getContext( '2d' );\r
+\r
+       function fileSystemErrorMessage( e ) {\r
+               var FileError = window.FileError,\r
+                       msg = '';\r
+               switch ( e.code ) {\r
+               case FileError.QUOTA_EXCEEDED_ERR:\r
+                       msg = 'QUOTA_EXCEEDED_ERR';\r
+                       break;\r
+               case FileError.NOT_FOUND_ERR:\r
+                       msg = 'NOT_FOUND_ERR';\r
+                       break;\r
+               case FileError.SECURITY_ERR:\r
+                       msg = 'SECURITY_ERR';\r
+                       break;\r
+               case FileError.INVALID_MODIFICATION_ERR:\r
+                       msg = 'INVALID_MODIFICATION_ERR';\r
+                       break;\r
+               case FileError.INVALID_STATE_ERR:\r
+                       msg = 'INVALID_STATE_ERR';\r
+                       break;\r
+               default:\r
+                       msg = 'Unknown Error';\r
+                       break;\r
+               }\r
+               return msg;\r
+       }\r
+\r
+       function getInternalURLFromURL( url ) {\r
+               var internalURL = url.replace( /\//gi, "_" );\r
+               return internalURL;\r
+       }\r
+\r
+       function resize( imagewidth, imageheight, thumbwidth, thumbheight, fit ) {\r
+               var w = 0, h = 0, x = 0, y = 0,\r
+                       widthratio = imagewidth / thumbwidth,\r
+                       heightratio = imageheight / thumbheight,\r
+                       maxratio = Math.max( widthratio, heightratio );\r
+\r
+               if ( fit ) {\r
+                       w = thumbwidth;\r
+                       h = thumbheight;\r
+               } else {\r
+                       if ( maxratio > 1 ) {\r
+                               w = imagewidth / maxratio;\r
+                               h = imageheight / maxratio;\r
+                       } else {\r
+                               w = imagewidth;\r
+                               h = imageheight;\r
+                       }\r
+                       x = ( thumbwidth - w ) / 2;\r
+                       y = ( thumbheight - h ) / 2;\r
+               }\r
+\r
+               return { w: w, h: h, x: x, y: y };\r
+       }\r
+\r
+       function getThumbnail( img, thumbwidth, thumbheight, fit ) {\r
+               var dimensions, url;\r
+               _canvas.width = thumbwidth;\r
+               _canvas.height = thumbheight;\r
+               dimensions = resize( img.width, img.height, thumbwidth, thumbheight, fit );\r
+               _context.fillStyle = "#000000";\r
+               _context.fillRect ( 0, 0, thumbwidth, thumbheight );\r
+               _context.drawImage( img, dimensions.x, dimensions.y, dimensions.w, dimensions.h );\r
+               url = _canvas.toDataURL();\r
+               return url;\r
+       }\r
+\r
+       $.imageloader = {\r
+               _grantedBytes: 1024 * 1024,\r
+               getThumbnail: function ( url, _callback ) {\r
+                       var internalURL, canvasDataURI;\r
+                       function errorHandler( e ) {\r
+                               var msg = fileSystemErrorMessage( e );\r
+                               if ( _callback ) {\r
+                                       _callback( ( msg === "NOT_FOUND_ERR" ) ? msg : null );\r
+                               }\r
+                       }\r
+\r
+                       internalURL = getInternalURLFromURL( url );\r
+                       try {\r
+                               canvasDataURI = localStorage.getItem( internalURL );\r
+                               if ( _callback ) {\r
+                                       _callback( ( canvasDataURI === null ) ? "NOT_FOUND_ERR" : canvasDataURI );\r
+                               }\r
+                       } catch ( e ) {\r
+                               if ( _callback ) {\r
+                                       _callback( ( e.type === "non_object_property_load" ) ? "NOT_FOUND_ERR" : null );\r
+                               }\r
+                       }\r
+               },\r
+\r
+               setThumbnail: function ( url, _callback, thumbWidth, thumbHeight, fit ) {\r
+                       var image, internalURL, canvasDataURI;\r
+                       function errorHandler( e ) {\r
+                               var msg = fileSystemErrorMessage( e );\r
+                               if ( _callback ) {\r
+                                       _callback( ( msg === "NOT_FOUND_ERR" ) ? msg : null );\r
+                               }\r
+                       }\r
+\r
+                       thumbWidth = thumbWidth || 128;\r
+                       thumbHeight = thumbHeight || 128;\r
+                       fit = fit || true;\r
+                       image = new Image();\r
+                       image.onload = function () {\r
+                               internalURL = getInternalURLFromURL( url );\r
+                               canvasDataURI = getThumbnail( this, thumbWidth, thumbHeight, fit );\r
+                               try {\r
+                                       localStorage.setItem( internalURL, canvasDataURI );\r
+                                       if ( _callback ) {\r
+                                               _callback( canvasDataURI );\r
+                                       }\r
+                               } catch ( e ) {\r
+                                       if ( _callback ) {\r
+                                               _callback( ( e.type === "non_object_property_load" ) ? "NOT_FOUND_ERR" : null );\r
+                                       }\r
+                               }\r
+                       };\r
+                       image.src = url;\r
+               },\r
+\r
+               removeThumbnail: function ( url ) {\r
+                       var internalURL;\r
+                       function errorHandler( e ) {\r
+                               fileSystemErrorMessage( e );\r
+                       }\r
+\r
+                       internalURL = getInternalURLFromURL( url );\r
+                       try {\r
+                               localStorage.removeItem( internalURL );\r
+                       } catch ( e ) {\r
+                               throw e;\r
+                       }\r
+               }\r
+       };\r
+\r
+} ( jQuery, window, document ) );\r
+\r
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+} );\r
+//>>excludeEnd("jqmBuildExclude");\r
diff --git a/src/js/widgets/components/motionpath.js b/src/js/widgets/components/motionpath.js
new file mode 100644 (file)
index 0000000..89799a4
--- /dev/null
@@ -0,0 +1,294 @@
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+//>>description: Tizen motion path component for gallery3d\r
+//>>label: Motion path\r
+//>>group: Tizen:Widgets:Components\r
+\r
+define( [ ], function ( ) {\r
+//>>excludeEnd("jqmBuildExclude");\r
+\r
+/* ***************************************************************************\r
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd.\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person obtaining a\r
+ * copy of this software and associated documentation files (the "Software"),\r
+ * to deal in the Software without restriction, including without limitation\r
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,\r
+ * and/or sell copies of the Software, and to permit persons to whom the\r
+ * Software is furnished to do so, subject to the following conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be included in\r
+ * all copies or substantial portions of the Software.\r
+ *\r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r
+ * DEALINGS IN THE SOFTWARE.\r
+ * ***************************************************************************\r
+ *\r
+ * Authors: Hyunsook Park <hyunsook.park@samsung.com>\r
+ *                     Wonseop Kim <wonseop.kim@samsung.com>\r
+*/\r
+\r
+( function ( $, window, undefined ) {\r
+       var HALF_PI = Math.PI / 2,\r
+               DEFAULT_STEP = 0.001,\r
+               MotionPath = {},\r
+               vec3 = window.vec3,\r
+               arcLength2d = function ( p0, p1 ) {\r
+                       var d = [ p1[0] - p0[0], p1[1] - p0[1] ],\r
+                               value = Math.sqrt( d[0] * d[0] + d[1] * d[1] );\r
+                       return value;\r
+               },\r
+               arcLength3d = function ( p0, p1 ) {\r
+                       var d = [ p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2] ],\r
+                               value = Math.sqrt( d[0] * d[0] + d[1] * d[1] + d[2] * d[2] );\r
+                       return value;\r
+               };\r
+\r
+       MotionPath.base = function () {};\r
+       MotionPath.base.prototype = {\r
+               points: [],\r
+               step: DEFAULT_STEP,\r
+               length: 0,\r
+               levels: [],\r
+               init: function ( data ) {},\r
+               calculateLevel: function ( maxLevel ) {},\r
+               calculateTotalLength: function () {},\r
+               getPosition: function ( percent ) {},\r
+               getPercent: function ( start, interval ) {},\r
+               getAngle: function ( percent ) {}\r
+       };\r
+\r
+       MotionPath.bezier2d = function () {};\r
+       MotionPath.bezier2d.prototype = $.extend( true, {}, MotionPath.base.prototype, {\r
+               init: function ( data ) {\r
+                       this.points = data.points;\r
+                       this.step = data.step || DEFAULT_STEP;\r
+                       this.length = this.calculateTotalLength();\r
+                       this.levels = this.calculateLevel( data.maxLevel ) || [];\r
+               },\r
+\r
+               calculateLevel: function ( maxLevel ) {\r
+                       var totalLength = this.length,\r
+                               interval = totalLength / maxLevel,\r
+                               levels = [],\r
+                               i;\r
+\r
+                       if ( !maxLevel ) {\r
+                               return null;\r
+                       }\r
+\r
+                       for ( i = 0; i < maxLevel; i += 1 ) {\r
+                               levels[maxLevel - i] = this.getPercent( 0, interval * i );\r
+                       }\r
+\r
+                       return levels;\r
+               },\r
+\r
+               calculateTotalLength: function () {\r
+                       var step = this.step,\r
+                               current = this.getPosition( 0 ),\r
+                               last = current,\r
+                               length = 0,\r
+                               percent;\r
+                       for ( percent = step; percent <= 1; percent += step ) {\r
+                               current = this.getPosition( percent );\r
+                               length += arcLength2d( last, current );\r
+                               last = current;\r
+                       }\r
+                       return length;\r
+               },\r
+\r
+               getPosition: function ( percent ) {\r
+                       var points = this.points,\r
+                               getValue = function ( p1, c1, c2, p2, t ) {\r
+                                       return Math.pow(1 - t, 3) * p1 +\r
+                                               3 * t * Math.pow( 1 - t, 2 ) * c1 +\r
+                                               3 * Math.pow( t, 2 ) * ( 1 - t ) * c2 +\r
+                                               Math.pow( t, 3 ) * p2;\r
+                               },\r
+                               result = [\r
+                                       getValue( points[0][0], points[1][0], points[2][0], points[3][0], percent ),\r
+                                       getValue( points[0][1], points[1][1], points[2][1], points[3][1], percent )\r
+                               ];\r
+                       return result;\r
+               },\r
+\r
+               getPercent: function ( start, interval ) {\r
+                       var step = this.step,\r
+                               current = this.getPosition( start = start || 0 ),\r
+                               last = current,\r
+                               targetLength = start + interval,\r
+                               length = 0,\r
+                               percent;\r
+\r
+                       for ( percent = start + step; percent <= 1; percent += step ) {\r
+                               current = this.getPosition( percent );\r
+                               length += arcLength2d( last, current );\r
+                               if ( length >= targetLength ) {\r
+                                       return percent;\r
+                               }\r
+                               last = current;\r
+                       }\r
+                       return 1;\r
+               },\r
+\r
+               getAngle: function ( percent ) {\r
+                       var points = this.points,\r
+                               getTangent = function ( p1, c1, c2, p2, t ) {\r
+                                       return 3 * t * t * ( -p1 + 3 * c1 - 3 * c2 + p2 ) + 6 * t * ( p1 - 2 * c1 + c2 ) + 3 * ( -p1 + c1 );\r
+                               },\r
+                               tx = getTangent( points[0][0], points[1][0], points[2][0], points[3][0], percent ),\r
+                               ty = getTangent( points[0][1], points[1][1], points[2][1], points[3][1], percent );\r
+                       return Math.atan2( tx, ty ) - HALF_PI;\r
+               }\r
+\r
+       } );\r
+\r
+       // clamped cubic B-spline curve\r
+       // http://web.mit.edu/hyperbook/Patrikalakis-Maekawa-Cho/node17.html\r
+       // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-curve-coef.html\r
+       MotionPath.bspline = function () {};\r
+       MotionPath.bspline.prototype = $.extend( true, {}, MotionPath.base.prototype, {\r
+               _degree: 3,\r
+               _numberOfControls : 0,\r
+               _knotVectors: [],\r
+               _numberOfKnots: 0,\r
+\r
+               init: function ( data ) {\r
+                       this.points = data.points;\r
+                       this.step = data.step || DEFAULT_STEP;\r
+                       this._numberOfPoints = this.points.length - 1;\r
+                       this._numberOfKnots = this._numberOfPoints + this._degree + 1;\r
+\r
+                       var deltaKnot = 1 / ( this._numberOfKnots - ( 2 * this._degree ) ),\r
+                               v = deltaKnot,\r
+                               i = 0;\r
+\r
+                       while ( i <= this._numberOfKnots ) {\r
+                               if ( i <= this._degree ) {\r
+                                       this._knotVectors.push( 0 );\r
+                               } else if ( i < this._numberOfKnots - this._degree + 1 ) {\r
+                                       this._knotVectors.push( v );\r
+                                       v += deltaKnot;\r
+                               } else {\r
+                                       this._knotVectors.push( 1 );\r
+                               }\r
+                               i += 1;\r
+                       }\r
+\r
+                       this.length = this.calculateTotalLength();\r
+                       this.levels = this.calculateLevel( data.maxLevel ) || [];\r
+               },\r
+\r
+               _Np: function ( percent, i, degree ) {\r
+                       var knots = this._knotVectors,\r
+                               A = 0,\r
+                               B = 0,\r
+                               denominator = 0,\r
+                               N0 = function ( percent, i ) {\r
+                                       return ( ( knots[i] <= percent && percent < knots[i + 1] ) ? 1 : 0 );\r
+                               };\r
+\r
+                       if ( degree === 1 ) {\r
+                               A = N0( percent, i );\r
+                               B = N0( percent, i + 1 );\r
+                       } else {\r
+                               A = this._Np( percent, i, degree - 1 );\r
+                               B = this._Np( percent, i + 1, degree - 1 );\r
+                       }\r
+\r
+                       denominator = knots[i + degree] - knots[i];\r
+                       A *= ( denominator !== 0 ) ? ( ( percent - knots[i] ) / denominator ) : 0;\r
+                       denominator = knots[i + degree + 1] - knots[i + 1];\r
+                       B *= ( denominator !== 0 ) ? ( ( knots[i + degree + 1] - percent ) / denominator ) : 0;\r
+\r
+                       return A + B;\r
+               },\r
+\r
+               calculateLevel: function ( maxLevel ) {\r
+                       var totalLength = this.length,\r
+                               interval = totalLength / maxLevel,\r
+                               levels = [],\r
+                               i;\r
+\r
+                       if ( !maxLevel ) {\r
+                               return null;\r
+                       }\r
+\r
+                       for ( i = 0; i < maxLevel; i += 1 ) {\r
+                               levels[maxLevel - i] = this.getPercent( 0, interval * i );\r
+                       }\r
+                       return levels;\r
+               },\r
+\r
+               calculateTotalLength: function () {\r
+                       var step = this.step,\r
+                               current = this.getPosition( 0 ),\r
+                               last = current,\r
+                               length = 0,\r
+                               percent;\r
+                       for ( percent = step; percent <= 1; percent += step ) {\r
+                               current = this.getPosition( percent );\r
+                               length += arcLength3d( last, current );\r
+                               last = current;\r
+                       }\r
+                       return length;\r
+               },\r
+\r
+               getPosition: function ( percent ) {\r
+                       var result = [], i, j, sum;\r
+                       percent = percent.toFixed( 4 );\r
+                       for ( j = 0; j < 3; j += 1 ) {\r
+                               sum = 0;\r
+                               for ( i = 0; i <= this._numberOfPoints; i += 1 ) {\r
+                                       sum += this.points[i][j] * this._Np( percent, i, this._degree );\r
+                               }\r
+                               result[j] = sum;\r
+                       }\r
+\r
+                       return result;\r
+               },\r
+\r
+               getPercent: function ( start, interval ) {\r
+                       var step = this.step,\r
+                               current = this.getPosition( start = start || 0 ),\r
+                               last = current,\r
+                               targetLength = start + interval,\r
+                               length = 0,\r
+                               percent;\r
+\r
+                       for ( percent = start + step; percent <= 1; percent += step ) {\r
+                               current = this.getPosition( percent );\r
+                               length += arcLength3d( last, current );\r
+                               if ( length >= targetLength ) {\r
+                                       return percent;\r
+                               }\r
+                               last = current;\r
+                       }\r
+                       return 1;\r
+               },\r
+\r
+               getAngle: function ( percent ) {\r
+                       var prev = this.getPosition( percent ),\r
+                               next = this.getPosition( percent + 0.001 ),\r
+                               dir = vec3.normalize( vec3.direction( prev, next ) ),\r
+                               cosValue = vec3.dot( dir, [1, 0, 0] );\r
+\r
+                       return Math.acos( cosValue ) + Math.PI;\r
+               }\r
+       } );\r
+\r
+       $.motionpath = function ( type, data ) {\r
+               var object = new MotionPath[type]();\r
+               object.init( data );\r
+               return object;\r
+       };\r
+} ( jQuery, window ) );\r
+\r
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+} );\r
+//>>excludeEnd("jqmBuildExclude");\r
diff --git a/src/js/widgets/components/webgl.js b/src/js/widgets/components/webgl.js
new file mode 100644 (file)
index 0000000..bc96421
--- /dev/null
@@ -0,0 +1,125 @@
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+//>>description: Tizen WebGL component for gallery3d\r
+//>>label: WebGL\r
+//>>group: Tizen:Widgets:Lib\r
+\r
+define( [ ], function ( ) {\r
+//>>excludeEnd("jqmBuildExclude");\r
+\r
+/* ***************************************************************************\r
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd.\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person obtaining a\r
+ * copy of this software and associated documentation files (the "Software"),\r
+ * to deal in the Software without restriction, including without limitation\r
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,\r
+ * and/or sell copies of the Software, and to permit persons to whom the\r
+ * Software is furnished to do so, subject to the following conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be included in\r
+ * all copies or substantial portions of the Software.\r
+ *\r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r
+ * DEALINGS IN THE SOFTWARE.\r
+ * ***************************************************************************\r
+ *\r
+ * Authors: Hyunsook Park <hyunsook.park@samsung.com>\r
+ *                     Wonseop Kim <wonseop.kim@samsung.com>\r
+*/\r
+\r
+( function ( $, undefined ) {\r
+       $.webgl = {};\r
+\r
+       $.webgl.shader = {\r
+               _vertexShader: null,\r
+               _fragmentShader: null,\r
+\r
+               deleteShaders: function ( gl ) {\r
+                       gl.deleteShader( this._vertexShader );\r
+                       gl.deleteShader( this._fragmentShader );\r
+               },\r
+\r
+               addShaderProgram : function ( gl, vs, fs, isFile ) {\r
+                       var shaderProgram,\r
+                               vertexShaderSource = {},\r
+                               fragmentShaderSource = {};\r
+\r
+                       if ( isFile ) {\r
+                               vertexShaderSource = this.loadShaderFile( vs );\r
+                               fragmentShaderSource = this.loadShaderFile( fs );\r
+                       } else {\r
+                               vertexShaderSource.source = vs;\r
+                               fragmentShaderSource.source = fs;\r
+                       }\r
+\r
+                       this._vertexShader = this.getShader( gl, gl.VERTEX_SHADER, vertexShaderSource );\r
+                       this._fragmentShader = this.getShader( gl, gl.FRAGMENT_SHADER, fragmentShaderSource );\r
+\r
+                       shaderProgram = gl.createProgram();\r
+                       gl.attachShader( shaderProgram, this._vertexShader);\r
+                       gl.attachShader( shaderProgram, this._fragmentShader);\r
+                       gl.linkProgram( shaderProgram );\r
+\r
+                       if ( !gl.getProgramParameter( shaderProgram, gl.LINK_STATUS ) ) {\r
+                               window.alert( "Could not initialize Shaders!" );\r
+                       }\r
+                       return shaderProgram;\r
+               },\r
+\r
+               loadShaderFile : function ( path ) {\r
+                       var cache = null;\r
+                       $.ajax({\r
+                               async : false,\r
+                               url : path,\r
+                               success : function ( result ) {\r
+                                       cache = {\r
+                                               source: result\r
+                                       };\r
+                               }\r
+                       });\r
+                       return cache;\r
+               },\r
+\r
+               getShader: function ( gl, type, script ) {\r
+                       var shader;\r
+\r
+                       if ( !gl || !type || !script ) {\r
+                               return null;\r
+                       }\r
+\r
+                       shader = gl.createShader( type );\r
+\r
+                       gl.shaderSource( shader, script.source );\r
+                       gl.compileShader( shader );\r
+\r
+                       if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) ) {\r
+                               window.alert( gl.getShaderInfoLog( shader ) );\r
+                               gl.deleteShader( shader );\r
+                               return null;\r
+                       }\r
+                       return shader;\r
+               }\r
+       };\r
+\r
+       $.webgl.buffer = {\r
+               attribBufferData: function ( gl, attribArray ) {\r
+                       var attribBuffer = gl.createBuffer();\r
+\r
+                       gl.bindBuffer( gl.ARRAY_BUFFER, attribBuffer );\r
+                       gl.bufferData( gl.ARRAY_BUFFER, attribArray, gl.STATIC_DRAW );\r
+                       gl.bindBuffer( gl.ARRAY_BUFFER, null );\r
+\r
+                       return attribBuffer;\r
+               }\r
+       };\r
+\r
+} ( jQuery ) );\r
+\r
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+} );\r
+//>>excludeEnd("jqmBuildExclude");\r
diff --git a/src/js/widgets/jquery.mobile.tizen.gallery3d.js b/src/js/widgets/jquery.mobile.tizen.gallery3d.js
new file mode 100644 (file)
index 0000000..6d66ac2
--- /dev/null
@@ -0,0 +1,1292 @@
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+//>>description: 3D photo gallery widget.\r
+//>>label: Gallery3d\r
+//>>group: Tizen:Widgets\r
+\r
+define( [ "components/imageloader", "components/motionpath", "components/webgl" ], function ( ) {\r
+//>>excludeEnd("jqmBuildExclude");\r
+\r
+\r
+/* ***************************************************************************\r
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd.\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person obtaining a\r
+ * copy of this software and associated documentation files (the "Software"),\r
+ * to deal in the Software without restriction, including without limitation\r
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,\r
+ * and/or sell copies of the Software, and to permit persons to whom the\r
+ * Software is furnished to do so, subject to the following conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be included in\r
+ * all copies or substantial portions of the Software.\r
+ *\r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r
+ * DEALINGS IN THE SOFTWARE.\r
+ * ***************************************************************************\r
+ *\r
+ * Authors: Hyunsook Park <hyunsook.park@samsung.com>\r
+ *                     Wonseop Kim <wonseop.kim@samsung.com>\r
+ */\r
+\r
+/**\r
+ *     'Gallery3D' is a 3D photo gallery widget.\r
+ *     Images are arranged with a S-shaped curve on a 3-dimensional coordinate system.\r
+ *     A user can rotate images by swiping the widget area.\r
+ *     To improve performance, the size of image(s) displayed on the screen should be a square(under\r
+ *     128X128 pixel) as possible. But if a user can't resize the images, this widget supports an image\r
+ *     resizing feature and he/she can use it with "data-thumbnail-cache" option. ("data-thumbnail-cache"\r
+ *     option resizes the gallery images under 128x128 pixels and stores the images on a local storage.\r
+ *     So when a gallery3D widget is re-launched, the widget reuse the storage and a user can improve\r
+ *     launching time. A browser or web runtime engine should support "Web Storage" feature to use that\r
+ *     option.)\r
+ *\r
+ *     HTML Attributes:\r
+ *\r
+ *             data-thumbnail-cache : Determines whether to cache and resize images.\r
+ *\r
+ *     APIs:\r
+ *\r
+ *             next ( void )\r
+ *                     : This method moves each image forward one by one.\r
+ *             prev ( void )\r
+ *                     : This method moves each image backward one by one.\r
+ *             select ( [number] )\r
+ *                     : When the "select" method is called with an argument, the method selects the image of given index.\r
+ *                     If the method is called with no argument, it will return the Javascript object having "src"\r
+ *                     attribute having the selected image’s URL.\r
+ *             add ( object or string [, number] )\r
+ *                     This method adds an image to Gallery3D widget.\r
+ *                     If the second argument isn't inputted, the image is added at the 0th position.\r
+ *             remove ( [number] )\r
+ *                     : This method deletes an image from Gallery3d widget.\r
+ *                     The argument defines the index of the image to be deleted.\r
+ *                     If an argument isn't inputted, it removes current image.\r
+ *             clearThumbnailCache ( void )\r
+ *                     : This method clears the cache data of all images when thumbnailCache option is set as 'true'.\r
+ *             refresh ( void )\r
+ *                     : This method updates and redraws current widget.\r
+ *             empty ( void )\r
+ *                     : This method removes all of images from Gallery3D widget.\r
+ *             length ( void )\r
+ *                     : This method gets the number of images.\r
+ *\r
+ *     Events:\r
+ *\r
+ *             select : Triggered when an image is selected.\r
+ *\r
+ *     Examples:\r
+ *\r
+ *             <script>\r
+ *                     $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+ *                             $( "#gallery3d" ).gallery3d( "add", "01.jpg" );\r
+ *                     });\r
+ *             </script>\r
+ *             <div id="gallery3d" data-role="gallery3d"></div>\r
+ */\r
+\r
+/**\r
+       @class Gallery3D\r
+       The gallery3d widget is a 3D photo gallery widget.\r
+       Images are arranged with a S-shaped curve on a 3-dimensional coordinate system.\r
+       A user can rotate images by swiping the widget area.\r
+       <br/><br/>To add an gallery3d widget to the application, use the following code:\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", "01.jpg" );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @property {Boolean} data-thumbnail-cache\r
+       Determines whether to cache and resize images.\r
+       To improve performance, the size of image(s) displayed on the screen should be a square (under 128X128 pixels).\r
+       "data-thumbnail-cache" option resizes the gallery images under 128x128 pixels and stores the images on a local storage.\r
+       So when a gallery3D widget is re-launched, the widget reuses the storage and the launching time can be improved.\r
+       A browser or web runtime engine must support "Web Storage" feature to use this option.\r
+*/\r
+/**\r
+       @event select\r
+       Triggered when an image is selected.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } );\r
+                       }).on( "select", function ( event, data, index ) {\r
+                               // Handle the select event\r
+                               var urlOfImage = data.src, indexOfImage = index;\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method next\r
+       This method moves each image forward one by one.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } )\r
+                                       .gallery3d( "next" );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method prev\r
+       This method moves each image backward one by one.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } )\r
+                                       .gallery3d( "prev" );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method select\r
+       When the "select" method is called with an argument, the method selects the image of given index.\r
+       If the method is called with no argument, it will return the Javascript object having "src" attribute having the selected image’s URL.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } );\r
+                               var selectedImage = $("#gallery3d"). gallery3d( "select" );\r
+                               // selectedImage = { src: "3.jpg" };\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method add\r
+       This method adds an image to Gallery3D widget.\r
+       The first argument is a Javascript object having a "src" attribute or a string of image's path.\r
+       The second argument is an index of images.\r
+       If second argument isn't inputted, the image is added at the 0th position.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", "2.jpg", 1 );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method remove\r
+       This method deletes an image from Gallery3d widget.\r
+       The argument defines the index of the image to be deleted.\r
+       If an argument isn't inputted, it removes current image.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } );\r
+\r
+                               $( "#gallery3d" ).gallery3d( "remove" );\r
+                               $( "#gallery3d" ).gallery3d( "remove", 1 );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method clearThumbnailCache\r
+       This method clears the cache data of all images when thumbnailCache option is set as 'true'\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } );\r
+\r
+                               $( "#gallery3d" ).gallery3d( "clearThumbnailCache" );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d" data-thumbnail-cache="true"></div>\r
+*/\r
+/**\r
+       @method refresh\r
+       This method updates and redraws current widget.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } );\r
+\r
+                               $( "#gallery3d" ).gallery3d( "refresh" );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method empty\r
+       This method removes all of images from Gallery3D widget.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } );\r
+\r
+                               $( "#gallery3d" ).gallery3d( "empty" );\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+/**\r
+       @method length\r
+       This method gets the number of images.\r
+\r
+               <script>\r
+                       $( "#gallery3d" ).on( "gallery3dcreate", function () {\r
+                               $( "#gallery3d" ).gallery3d( "add", { src: "1.jpg" } )\r
+                                       .gallery3d( "add", { src: "2.jpg" } )\r
+                                       .gallery3d( "add", { src: "3.jpg" } );\r
+\r
+                               var imagesLength = $( "#gallery3d" ).gallery3d( "length" );\r
+                               // imagesLength = 3;\r
+                       });\r
+               </script>\r
+               <div id="gallery3d" data-role="gallery3d"></div>\r
+*/\r
+\r
+( function ( $, document, window, undefined ) {\r
+       window.requestAnimationFrame = ( function () {\r
+               return function ( callback ) {\r
+                       var id = window.setTimeout( callback, 1000 / 60 );\r
+                       return id;\r
+               };\r
+       } () );\r
+\r
+       window.cancelAnimationFrame = ( function () {\r
+               return function ( id ) {\r
+                       window.clearTimeout( id );\r
+               };\r
+       } () );\r
+\r
+       var vec3 = window.vec3,\r
+               mat3 = window.mat3,\r
+               mat4 = window.mat4,\r
+               GlArray32 = ( typeof window.Float32Array !== "undefined" ? window.Float32Array : ( typeof window.WebGLFloatArray !== "undefined" ? window.WebGLFloatArray : Array ) ),\r
+               GlArray16 = ( typeof window.Uint16Array !== "undefined" ? window.Uint16Array : Array ),\r
+               getContext3D = function ( canvas ) {\r
+                       var gl, i,\r
+                               contextNames = [ "experimental-webgl", "webkit-3d", "webgl", "moz-webgl" ];\r
+\r
+                       for ( i = 0; i < contextNames.length; i += 1 ) {\r
+                               try {\r
+                                       gl = canvas.getContext( contextNames[i] );\r
+                                       if ( gl ) {\r
+                                               break;\r
+                                       }\r
+                               } catch ( e ) {\r
+                                       window.alert( "Unfortunately, there's a WebGL compatibility problem. </br> You may want to check your system settings." );\r
+                                       return;\r
+                               }\r
+                       }\r
+                       return gl;\r
+               },\r
+               VERTEX_SHADER = [\r
+                       "attribute vec3 aVertexPosition;",\r
+                       "attribute vec2 aTextureCoord;",\r
+                       "attribute vec3 aVertexNormal;",\r
+                       "uniform mat4 uMoveMatrix;",\r
+                       "uniform mat4 uPerspectiveMatrix;",\r
+                       "uniform mat3 nNormalMatrix;",\r
+                       "uniform vec3 uAmbientColor;",\r
+                       "uniform vec3 uLightDirection;",\r
+                       "uniform vec3 uDirectionColor;",\r
+                       "uniform vec3 uLightDirection_first;",\r
+                       "uniform vec3 uLightDirection_second;",\r
+                       "varying vec2 vTextureCoord;",\r
+                       "varying vec3 vLightWeight;",\r
+                       "varying vec4 vFogWeight;",\r
+\r
+                       "void main(void) {",\r
+                       "       vec4 v_Position = uMoveMatrix * vec4(aVertexPosition, 1.0);",\r
+                       "       gl_Position = uPerspectiveMatrix * v_Position;",\r
+                       "       vTextureCoord = aTextureCoord;",\r
+                       "       float fog = 1.0 - ((gl_Position.z + 1.5) / 60.0);",\r
+                       "       vFogWeight = clamp( vec4( fog, fog, fog, 1.0), 0.0, 1.0);",\r
+                       "       vec3 transNormalVector = nNormalMatrix * aVertexNormal;",\r
+\r
+                       "       float vLightWeightFirst = 0.0;",\r
+                       "       float vLightWeightSecond = max( dot(transNormalVector, uLightDirection_second), 0.0 );",\r
+\r
+                       "       vLightWeight = uAmbientColor + uDirectionColor * vLightWeightSecond;",\r
+                       "}"\r
+               ].join( "\n" ),\r
+               FRAGMENT_SHADER = [\r
+                       "precision mediump float;",\r
+                       "varying vec2 vTextureCoord;",\r
+                       "varying vec3 vLightWeight;",\r
+                       "uniform sampler2D uSampler;",\r
+                       "varying vec4 vFogWeight;",\r
+\r
+                       "void main(void) {",\r
+                       "       vec4 TextureColor = (texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t))) * vFogWeight;",\r
+                       "       gl_FragColor = vec4(TextureColor.rgb * vLightWeight, TextureColor.a);",\r
+                       "}"\r
+               ].join( "\n" );\r
+\r
+       function Node() {\r
+               this.vertices = [\r
+                       -1.0, -1.0, 0.0,\r
+                       1.0, -1.0, 0.0,\r
+                       1.0,  1.0, 0.0,\r
+                       -1.0,  1.0, 0.0\r
+               ];\r
+               this.textureCoords = [\r
+                       1.0, 0.0,\r
+                       0.0, 0.0,\r
+                       0.0, 1.0,\r
+                       1.0, 1.0\r
+               ];\r
+               this.normalVectors = [\r
+                       0.0, 0.0, 1.0,\r
+                       0.0, 0.0, 1.0,\r
+                       0.0, 0.0, 1.0,\r
+                       0.0, 0.0, 1.0\r
+               ];\r
+               this.texture = null;\r
+               this.textureBuffer = null;\r
+               this.textureBufferItemSize = 0;\r
+               this.mashOrder = [];\r
+               this.mvMatrix = null;\r
+               this.level = -1;\r
+               this.targetLevel = 0;\r
+               this.drawable = false;\r
+               this.image = null;\r
+               this.imageID = 0;\r
+       }\r
+\r
+       $.widget( "tizen.gallery3d", $.mobile.widget, {\r
+               options: {\r
+                       thumbnailCache: false\r
+               },\r
+\r
+               _MAX_ITEM_COUNT: 28,\r
+               _ANIMATION_END: 999,\r
+               _DURATION_DEFAULT: 300,\r
+               _DURATION_FIRST: 1600,\r
+               _VIEWPORT_WIDTH: 1024,\r
+               _VIEWPORT_HEIGHT: 456,\r
+               _DIRECTION_LEFT: -1,\r
+               _DIRECTION_RIGHT: +1,\r
+\r
+               _gl: null,\r
+               _shaderProgram : null,\r
+               _positionBuffer : null,\r
+               _textureCoordBuffer : null,\r
+               _normalVectorBuffer : null,\r
+               _nodes: null,\r
+               _pMatrix : null,\r
+               _animationID: 0,\r
+               _dragInterval : 0,\r
+               _startTime : 0,\r
+               _sumTime : 0,\r
+               _lightsPositionStack : [\r
+                       [0.0, 0.0, -1.0],       // back\r
+                       [-0.2, 0.0, 0.7]        // front\r
+               ],\r
+               _path: null,\r
+               _swipeThresholdOfBasetimeGap: ( $.support.touch ? 30 : 70 ),\r
+               _swipeThresholdOfSensitivity: ( $.support.touch ? 2.0 : 10.0 ),\r
+               _canvas: null,\r
+               _imageList: [],\r
+               _maxDrawLength: 0,\r
+               _firstImageNumber: 0,\r
+               _lastImageNumber: 0,\r
+\r
+               _create: function () {\r
+                       var self = this,\r
+                               view = self.element,\r
+                               option = self.options;\r
+\r
+                       self._canvas = $( "<canvas class='ui-gallery3d-canvas'></canvas>" );\r
+\r
+                       view.addClass( "ui-gallery3d" ).append( self._canvas );\r
+                       self._addBehavier();\r
+\r
+                       self._dragInterval = 1000 / 30; // 30fps\r
+\r
+                       $.each( self.options, function ( key, value ) {\r
+                               self.options[ key ] = undefined;\r
+                               self._setOption( key, value );\r
+                       });\r
+\r
+               },\r
+\r
+               _setOption: function ( key, value ) {\r
+                       switch ( key ) {\r
+                       case "thumbnailCache" :\r
+                               if ( typeof value === "string" ) {\r
+                                       value = ( value === "true" ) ? true : false;\r
+                               } else {\r
+                                       value = !!value;\r
+                               }\r
+                               this._reset();\r
+                               break;\r
+                       }\r
+\r
+                       $.mobile.widget.prototype._setOption.call( this, key, value );\r
+               },\r
+\r
+               _init: function ( canvas ) {\r
+                       var self = this,\r
+                               pathPoints = [\r
+                                       [40, 0, -48],\r
+                                       [-12, 0, -40],  // contorl Point of Point1\r
+                                       [24, 0, -9],            // contorl Point of Point2\r
+                                       [-5, 0, -5]\r
+                               ],\r
+                               i;\r
+\r
+                       canvas = canvas || self._canvas;\r
+\r
+                       if ( !canvas ) {\r
+                               return;\r
+                       }\r
+\r
+                       self._gl = self._gl || self._initGL( canvas[0] );\r
+                       if ( !self._gl ) {\r
+                               return;\r
+                       }\r
+\r
+                       if ( !self._imageList ) {\r
+                               return;\r
+                       }\r
+\r
+                       self._shaderProgram = self._shaderProgram || self._initShader( self._gl );\r
+                       if ( !self._shaderProgram ) {\r
+                               return;\r
+                       }\r
+\r
+                       if ( self._imageList.length > self._MAX_ITEM_COUNT ) {\r
+                               self._firstImageNumber = self._imageList.length - 1;\r
+                               self._lastImageNumber = self._MAX_ITEM_COUNT - 1;\r
+                       }\r
+\r
+                       self._nodes = self._initBuffers( self._gl, self._shaderProgram );\r
+                       self._initTextures( self._gl, self._nodes );\r
+                       self._path = $.motionpath( "bspline", {\r
+                               points: pathPoints,\r
+                               maxLevel: self._MAX_ITEM_COUNT\r
+                       } );\r
+                       for ( i = 0; i < self._nodes.length; i += 1 ) {\r
+                               self._path.levels[i] = self._path.levels[i + 1] || 0;\r
+                               self._nodes[i].level = i;\r
+                       }\r
+               },\r
+\r
+               _final: function ( canvas ) {\r
+                       var self = this,\r
+                               gl = self._gl;\r
+\r
+                       if ( !gl ) {\r
+                               return;\r
+                       }\r
+\r
+                       canvas = canvas || self._canvas;\r
+\r
+                       $( self._nodes ).each( function ( i ) {\r
+                               var node = self._nodes[i];\r
+                               gl.deleteTexture( node.texture );\r
+                               node.texture = null;\r
+                       });\r
+                       self._nodes = null;\r
+\r
+                       gl.deleteBuffer( self._positionBuffer );\r
+                       self._positionBuffer = null;\r
+                       gl.deleteBuffer( self._textureCoordBuffer );\r
+                       self._textureCoordBuffer = null;\r
+                       gl.deleteBuffer( self._normalVectorBuffer );\r
+                       self._normalVectorBuffer = null;\r
+\r
+                       $.webgl.shader.deleteShaders( gl );\r
+                       gl.deleteProgram( self._shaderProgram );\r
+                       self._shaderProgram = null;\r
+\r
+                       self._gl = gl = null;\r
+               },\r
+\r
+               _addBehavier : function () {\r
+                       var self = this,\r
+                               view = self.element,\r
+                               canvas = self._canvas,\r
+                               touchStartEvt = ( $.support.touch ? "touchstart" : "mousedown" ),\r
+                               touchMoveEvt = ( $.support.touch ? "touchmove" : "mousemove" ) + ".gallery3d",\r
+                               touchEndEvt = ( $.support.touch ? "touchend" : "mouseup" ) + ".gallery3d",\r
+                               touchLeaveEvt = ( $.support.touch ? "touchleave" : "mouseout" ) + ".gallery3d";\r
+\r
+                       $( document ).unbind( ".gallery3d" ).bind( "pagechange.gallery3d", function ( e ) {\r
+                               $( e.target ).find( ".ui-gallery3d" ).gallery3d( "refresh" );\r
+                       }).bind( "pageremove.gallery3d", function ( e ) {\r
+                               $( e.target ).find( ".ui-gallery3d" ).trigger( "_destory" );\r
+                       });\r
+\r
+                       $( window ).unbind( ".gallery3d" ).bind( "resize.gallery3d orientationchange.gallery3d", function ( e ) {\r
+                               $( ".ui-page-active" ).find( ".ui-gallery3d" ).gallery3d( "refresh" );\r
+                       }).bind( "unload.gallery3d", function ( e ) {\r
+                               $( e.target ).find( ".ui-gallery3d" ).trigger( "_destory" );\r
+                       });\r
+\r
+                       view.bind( "_destory", function ( e ) {\r
+                               self._final();\r
+                       });\r
+\r
+                       canvas.bind( "webglcontextlost", function ( e ) {\r
+                               e.preventDefault();\r
+                       }).bind( "webglcontextrestored", function ( e ) {\r
+                               self._init();\r
+                       }).bind( touchStartEvt, function ( e ) {\r
+                               var i = 0,\r
+                                       startX = 0,\r
+                                       deltaMaxSteps = 20,\r
+                                       deltas = [ deltaMaxSteps ],\r
+                                       deltaTimes = [ deltaMaxSteps ],\r
+                                       deltaIndex = 0,\r
+                                       dragValue = 0,\r
+                                       dragDirection = false,\r
+                                       prevTime = 0;\r
+\r
+                               e.preventDefault();\r
+                               e.stopPropagation();\r
+\r
+                               if ( self._imageList.length <= 1 ) {\r
+                                       return;\r
+                               }\r
+\r
+                               self._stop();\r
+\r
+                               startX =  $.support.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX;\r
+                               prevTime = $.now();\r
+\r
+                               for ( i = 0; i < deltaMaxSteps; i += 1 ) {\r
+                                       deltas[i] = startX;\r
+                                       deltaTimes[i] = $.now();\r
+                               }\r
+\r
+                               deltaIndex += 1;\r
+\r
+                               view.bind( touchMoveEvt, function ( e ) {\r
+                                       var x, dx, interval;\r
+\r
+                                       e.preventDefault();\r
+                                       e.stopPropagation();\r
+\r
+                                       x =  $.support.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX;\r
+                                       dx = startX - x;\r
+\r
+                                       deltas[deltaIndex] = x;\r
+                                       deltaTimes[deltaIndex] = $.now();\r
+                                       interval = deltaTimes[deltaIndex] - prevTime;\r
+\r
+                                       deltaIndex = ( deltaIndex + 1 ) % deltaMaxSteps;\r
+\r
+                                       // Validation of drag\r
+                                       if ( Math.abs( dx ) >= 10 && interval >= self._dragInterval ) {\r
+                                               if ( dragDirection !== ( ( dx < 0 ) ? self._DIRECTION_RIGHT : self._DIRECTION_LEFT ) ) {\r
+                                                       dragValue = 0;\r
+                                                       dragDirection = ( dx < 0 ) ? self._DIRECTION_RIGHT : self._DIRECTION_LEFT;\r
+                                               }\r
+\r
+                                               dragValue += Math.abs( dx ) / 100;\r
+                                               if ( dragValue >= 1 ) {\r
+                                                       self._setPosition( self._ANIMATION_END, dragDirection );\r
+                                                       dragValue = 0;\r
+                                               } else {\r
+                                                       self._setPosition( dragValue, dragDirection );\r
+                                               }\r
+                                               self._drawScene();\r
+                                               startX = x;\r
+                                               prevTime = $.now();\r
+                                       }\r
+                               }).bind( touchEndEvt, function ( e ) {\r
+                                       var baseTime = 0,\r
+                                               recent = -1,\r
+                                               index = 0,\r
+                                               previous = 0,\r
+                                               baseTimeRatio = 0,\r
+                                               fx = 0,\r
+                                               lastX = 0,\r
+                                               velocityX = 0,\r
+                                               dx = 0,\r
+                                               isSwipe = true,\r
+                                               direction;\r
+\r
+                                       e.preventDefault();\r
+                                       e.stopPropagation();\r
+\r
+                                       // Validation of swipe\r
+                                       baseTime = $.now() - self._swipeThresholdOfBasetimeGap;\r
+                                       lastX = $.support.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX;\r
+                                       dx = startX - lastX;\r
+                                       startX = 0;\r
+                                       for ( i = 0; i < deltaMaxSteps; i += 1 ) {\r
+                                               index = ( deltaIndex + i ) % deltaMaxSteps;\r
+                                               if ( deltaTimes[index] > baseTime ) {\r
+                                                       recent = index;\r
+                                                       break;\r
+                                               }\r
+                                       }\r
+                                       if ( recent < 0 ) {\r
+                                               isSwipe = false;\r
+                                       }\r
+\r
+                                       if ( isSwipe ) {\r
+                                               previous = recent;\r
+                                               for ( i = 0; i < deltaMaxSteps; i += 1 ) {\r
+                                                       previous = ( previous - 1 + deltaMaxSteps ) % deltaMaxSteps;\r
+                                                       if ( deltaTimes[previous] < deltaTimes[recent] ) {\r
+                                                               break;\r
+                                                       }\r
+                                               }\r
+                                               // too slow or too fast\r
+                                               if ( i === deltaMaxSteps || baseTime < deltaTimes[previous] ) {\r
+                                                       isSwipe = false;\r
+                                               }\r
+                                       }\r
+\r
+                                       if ( isSwipe ) {\r
+                                               baseTimeRatio = ( baseTime - deltaTimes[previous] ) / ( deltaTimes[recent] - deltaTimes[previous] );\r
+                                               fx = ( 1.0 - baseTimeRatio ) * deltas[previous] + baseTimeRatio * deltas[recent];\r
+                                               if ( Math.abs( fx - lastX ) < self._swipeThresholdOfSensitivity ) {\r
+                                                       fx = lastX;\r
+                                               }\r
+                                               velocityX = parseInt( ( lastX - fx ) / ( $.now() - baseTime ), 10 );\r
+                                       }\r
+\r
+                                       if ( isSwipe && velocityX ) {\r
+                                               direction = ( velocityX < 0 ) ? self._DIRECTION_LEFT : self._DIRECTION_RIGHT;\r
+                                               self._run( direction, Math.abs( velocityX ), dragValue );\r
+                                       } else if ( dragDirection !== 0 && dragValue ) {\r
+                                               self._animate( null, self._DURATION_DEFAULT * ( 1 - dragValue ), dragDirection, 0, dragValue );\r
+                                       }\r
+\r
+                                       view.unbind( ".gallery3d" );\r
+                               }).bind( touchLeaveEvt, function ( e ) {\r
+                                       view.trigger( touchEndEvt );\r
+                               });\r
+                       });\r
+               },\r
+\r
+               // ----------------------------------------------------------\r
+               // Data parsing\r
+               // ----------------------------------------------------------\r
+               _loadData: function ( jsonUrl, key ) {\r
+                       var self = this;\r
+\r
+                       $.ajax({\r
+                               async : false,\r
+                               url : jsonUrl,\r
+                               dataType: "json",\r
+                               success : function ( data ) {\r
+                                       self._imageList = $.extend( [], data[ key ] );\r
+                               }\r
+                       });\r
+               },\r
+\r
+               // ----------------------------------------------------------\r
+               // WebGL\r
+               // ----------------------------------------------------------\r
+               _initGL: function ( canvas ) {\r
+                       var self = this,\r
+                               gl;\r
+\r
+                       gl = getContext3D( canvas );\r
+                       if ( !gl ) {\r
+                               window.alert( "There's no WebGL context available!!!" );\r
+                               return null;\r
+                       }\r
+\r
+                       gl.enable( gl.BLEND );\r
+                       gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );\r
+\r
+                       gl.enable( gl.DEPTH_TEST );\r
+                       gl.depthFunc( gl.LEQUAL );\r
+\r
+                       canvas.width = self._VIEWPORT_WIDTH;\r
+                       canvas.height = self._VIEWPORT_HEIGHT;\r
+                       gl.viewportWidth = canvas.width;\r
+                       gl.viewportHeight = canvas.height;\r
+                       gl.viewport( 0, 0, gl.viewportWidth, gl.viewportHeight );\r
+                       self._pMatrix = mat4.create();\r
+                       mat4.perspective( 40, gl.viewportWidth / gl.viewportHeight, 0.1, 10000.0, self._pMatrix );\r
+\r
+                       gl.clearColor( 0.0, 0.0, 0.0, 1.0 );\r
+                       gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );\r
+\r
+                       return gl;\r
+               },\r
+\r
+               _initShader : function ( gl ) {\r
+                       var self = this,\r
+                               shaderProgram;\r
+\r
+                       shaderProgram = $.webgl.shader.addShaderProgram( self._gl, VERTEX_SHADER, FRAGMENT_SHADER );\r
+                       gl.useProgram( shaderProgram );\r
+\r
+                       shaderProgram.vertexPositionAttr = gl.getAttribLocation( shaderProgram, "aVertexPosition" );\r
+                       gl.enableVertexAttribArray( shaderProgram.vertexPositionAttr );\r
+\r
+                       shaderProgram.textureCoordAttr = gl.getAttribLocation( shaderProgram, "aTextureCoord" );\r
+                       gl.enableVertexAttribArray( shaderProgram.textureCoordAttr );\r
+\r
+                       // Set light normal vectors for lighting~\r
+                       shaderProgram.vertexNormalAttr = gl.getAttribLocation( shaderProgram, "aVertexNormal" );\r
+                       gl.enableVertexAttribArray( shaderProgram.vertexNormalAttr );\r
+\r
+                       shaderProgram.perspectiveMU = gl.getUniformLocation( shaderProgram, "uPerspectiveMatrix");\r
+                       shaderProgram.transformMU = gl.getUniformLocation( shaderProgram, "uMoveMatrix");\r
+                       shaderProgram.sampleUniform = gl.getUniformLocation( shaderProgram, "uSampler");\r
+\r
+                       // Set light variables~\r
+                       shaderProgram.normalMU = gl.getUniformLocation( shaderProgram, "nNormalMatrix");\r
+                       shaderProgram.ambientColorU = gl.getUniformLocation( shaderProgram, "uAmbientColor");\r
+                       shaderProgram.lightDirU_first = gl.getUniformLocation( shaderProgram, "uLightDirection_first");\r
+                       shaderProgram.lightDirU_second = gl.getUniformLocation( shaderProgram, "uLightDirection_second");\r
+                       shaderProgram.directionColorU = gl.getUniformLocation( shaderProgram, "uDirectionColor");\r
+\r
+                       return shaderProgram;\r
+               },\r
+\r
+               _initBuffers: function ( gl, shaderProgram ) {\r
+                       var self = this,\r
+                               i = 0,\r
+                               mashBase = 0,\r
+                               vertices = [],\r
+                               textureCoords = [],\r
+                               normalVectors = [],\r
+                               nodes = [],\r
+                               maxDrawLength = self._MAX_ITEM_COUNT;\r
+\r
+                       for ( i = 0; i < self._imageList.length + 1; i += 1 ) {\r
+                               nodes[i] = new Node();\r
+                               $.merge( vertices, nodes[i].vertices );\r
+                               $.merge( textureCoords, nodes[i].textureCoords );\r
+                               $.merge( normalVectors, nodes[i].normalVectors );\r
+\r
+                               nodes[i].textureBuffer = gl.createBuffer();\r
+                               gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, nodes[i].textureBuffer );\r
+                               mashBase = i * 4;\r
+                               nodes[i].meshOrder = [\r
+                                       mashBase, mashBase + 1, mashBase + 2,\r
+                                       mashBase + 2, mashBase + 3, mashBase\r
+                               ];\r
+                               gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new GlArray16( nodes[i].meshOrder ), gl.STATIC_DRAW );\r
+                               gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null ); // release buffer memory\r
+                               nodes[i].textureBufferItemSize = 6;\r
+                       }\r
+\r
+                       self._positionBuffer = $.webgl.buffer.attribBufferData( gl, new GlArray32( vertices ) );\r
+                       self._positionBuffer.itemSize = 3;\r
+\r
+                       self._textureCoordBuffer = $.webgl.buffer.attribBufferData( gl, new GlArray32( textureCoords ) );\r
+                       self._textureCoordBuffer.itemSize = 2;\r
+\r
+                       self._normalVectorBuffer = $.webgl.buffer.attribBufferData( gl, new GlArray32( normalVectors ) ); // Vertex's normal vector for Direction light\r
+                       self._normalVectorBuffer.itemSize = 3;\r
+\r
+                       // Ambient light\r
+                       gl.uniform3f( shaderProgram.ambientColorU, 0.1, 0.1, 0.1 );\r
+                       // Direcntion light\r
+                       gl.uniform3f( shaderProgram.directionColorU, 1.0, 1.0, 1.0 );\r
+\r
+                       return nodes;\r
+               },\r
+\r
+               // ----------------------------------------------------------\r
+               // Texture\r
+               // ----------------------------------------------------------\r
+               _initTextures: function ( gl, nodes ) {\r
+                       var self = this;\r
+\r
+                       $( nodes ).each( function ( i ) {\r
+                               var node = nodes[i],\r
+                                       url;\r
+\r
+                               if ( !self._imageList[i] ) {\r
+                                       return false;\r
+                               }\r
+\r
+                               url = self._imageList[i].src;\r
+                               node.texture = gl.createTexture();\r
+                               self._loadImage( url, i, i, gl, nodes );\r
+                       });\r
+               },\r
+\r
+               _loadImage: function ( url, i, imageID, gl, nodes ) {\r
+                       var self = this,\r
+                               isMipmap = false,\r
+                               image,\r
+                               node;\r
+\r
+                       gl = gl || self._gl;\r
+                       nodes = nodes || self._nodes;\r
+                       isMipmap = isMipmap || false;\r
+                       node = nodes[i];\r
+                       node.image = node.image || new Image();\r
+\r
+                       $( node.image ).one( "load", function ( e ) {\r
+                               self._bindTexture( gl, node, this, isMipmap );\r
+                               node.imageID = imageID;\r
+\r
+                               if ( !self._animationID ) {\r
+                                       self._setPosition( 0, 0 );\r
+                               }\r
+                       });\r
+\r
+                       if ( self.options.thumbnailCache ) {\r
+                               $.imageloader.getThumbnail( url, function ( result ) {\r
+                                       if ( result === "NOT_FOUND_ERR" ) {\r
+                                               $.imageloader.setThumbnail( url, function ( result ) {\r
+                                                       if ( result && result.length > 30 ) {\r
+                                                               node.image.src = result;\r
+                                                               isMipmap = true;\r
+                                                       } else {\r
+                                                               node.image.src = url;\r
+                                                       }\r
+                                               });\r
+                                       } else if ( result && result.length > 30 ) {\r
+                                               node.image.src = result;\r
+                                               isMipmap = true;\r
+                                       } else {\r
+                                               node.image.src = url;\r
+                                       }\r
+                               });\r
+                       } else {\r
+                               node.image.src = url;\r
+                       }\r
+               },\r
+\r
+               _bindTexture: function ( gl, node, image, isMipmap ) {\r
+                       if ( !node || !node.texture ) {\r
+                               return;\r
+                       }\r
+\r
+                       gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, true );\r
+\r
+                       gl.bindTexture( gl.TEXTURE_2D, node.texture );\r
+                       gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image );\r
+\r
+                       if ( isMipmap ) {\r
+                               gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );\r
+                               gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST );\r
+                               gl.generateMipmap( gl.TEXTURE_2D );\r
+                       } else {\r
+                               gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );\r
+                               gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR );\r
+                       }\r
+\r
+                       gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );\r
+                       gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );\r
+\r
+                       node.texture.loaded = true;\r
+\r
+                       // release texture memory\r
+                       gl.bindTexture( gl.TEXTURE_2D, null );\r
+               },\r
+\r
+               // ----------------------------------------------------------\r
+               // rendering\r
+               // ----------------------------------------------------------\r
+               _setPosition: function ( progress, direction ) {\r
+                       var self = this,\r
+                               nodes = self._nodes,\r
+                               imageList = self._imageList,\r
+                               imageListLength = imageList.length,\r
+                               itemCount = self._MAX_ITEM_COUNT,\r
+                               displayLength = ( imageListLength > itemCount ) ? itemCount : imageListLength,\r
+                               nextLevelLenth = 0,\r
+                               i = 0,\r
+                               t = 0,\r
+                               position = 0,\r
+                               angle = 0,\r
+                               current = 0,\r
+                               next = 0,\r
+                               nextLevel = 0,\r
+                               path = self._path,\r
+                               nextImageID = 0;\r
+\r
+                       nextLevelLenth = ( direction >= 0 ) ? displayLength + 1 : displayLength;\r
+\r
+                       if ( !nodes[i].level ) {\r
+                               nodes[i].level = displayLength;\r
+                       }\r
+\r
+                       for ( i = 0; i < displayLength; i += 1 ) {\r
+                               if ( !nodes[i].mvMatrix ) {\r
+                                       nodes[i].mvMatrix = mat4.create();\r
+                               }\r
+\r
+                               if ( direction > 0 && nodes[i].level >= displayLength ) {\r
+                                       nodes[i].level = 0;\r
+                               }\r
+\r
+                               current = path.levels[nodes[i].level];\r
+                               nextLevel = ( nodes[i].level + nextLevelLenth + direction ) % nextLevelLenth;\r
+                               next = path.levels[nextLevel];\r
+\r
+                               if ( imageListLength > itemCount ) {\r
+                                       if ( direction > 0 && nextLevel === 1\r
+                                                       && self._firstImageNumber !== nodes[i].imageID ) {\r
+                                               self._loadImage( imageList[self._firstImageNumber].src, i, self._firstImageNumber );\r
+                                       } else if ( direction < 0 && nextLevel === nextLevelLenth - 1\r
+                                                       && self._lastImageNumber !== nodes[i].imageID ) {\r
+                                               self._loadImage( imageList[self._lastImageNumber].src, i, self._lastImageNumber );\r
+                                       }\r
+                               }\r
+\r
+                               mat4.identity( nodes[i].mvMatrix );\r
+                               mat4.translate( nodes[i].mvMatrix, [-2.0, -2.0, 1.0] );\r
+                               mat4.rotate( nodes[i].mvMatrix, self._degreeToRadian( 19 ), [1, 0, 0] );\r
+\r
+                               t = ( current + ( next - current ) * ( ( progress > 1 ) ? 1 : progress ) );\r
+\r
+                               if ( progress >= self._ANIMATION_END ) {\r
+                                       nodes[i].level = nextLevel || displayLength;\r
+                                       t = path.levels[nodes[i].level];\r
+                               }\r
+\r
+                               if ( ( progress < self._ANIMATION_END )\r
+                                               && ( direction <= 0 && nodes[i].level < 1 ) ) {\r
+                                       nodes[i].drawable = false;\r
+                               } else {\r
+                                       nodes[i].drawable = true;\r
+                               }\r
+\r
+                               if ( progress === self._ANIMATION_END && nodes[i].level === 1 ) {\r
+                                       self.element.trigger( "select", imageList[ nodes[i].imageID ], nodes[i].imageID );\r
+                               }\r
+\r
+                               position = path.getPosition( t );\r
+                               angle = path.getAngle( t );\r
+\r
+                               mat4.translate( nodes[i].mvMatrix, position );\r
+                               mat4.rotate( nodes[i].mvMatrix, angle, [0, 1, 0] );\r
+                       }\r
+\r
+                       if ( imageListLength > itemCount && progress >= self._ANIMATION_END ) {\r
+                               self._firstImageNumber = ( self._firstImageNumber - direction ) % imageListLength;\r
+                               if ( self._firstImageNumber < 0 ) {\r
+                                       self._firstImageNumber = imageListLength - 1;\r
+                               }\r
+\r
+                               self._lastImageNumber = ( self._lastImageNumber - direction ) % imageListLength;\r
+                               if ( self._lastImageNumber < 0 ) {\r
+                                       self._lastImageNumber = imageListLength - 1;\r
+                               }\r
+                       }\r
+                       self._drawScene();\r
+               },\r
+\r
+               _drawScene: function () {\r
+                       if ( !this._gl || !this._shaderProgram ) {\r
+                               return;\r
+                       }\r
+\r
+                       var self = this,\r
+                               gl = self._gl,\r
+                               shaderProgram = self._shaderProgram,\r
+                               nodes = self._nodes,\r
+                               nodesLength = nodes.length,\r
+                               i;\r
+\r
+                       gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );\r
+\r
+                       gl.bindBuffer( gl.ARRAY_BUFFER, self._positionBuffer );\r
+                       gl.vertexAttribPointer( shaderProgram.vertexPositionAttr, self._positionBuffer.itemSize, gl.FLOAT, false, 0, 0 );\r
+\r
+                       gl.bindBuffer( gl.ARRAY_BUFFER, self._textureCoordBuffer );\r
+                       gl.vertexAttribPointer( shaderProgram.textureCoordAttr, self._textureCoordBuffer.itemSize, gl.FLOAT, false, 0, 0 );\r
+\r
+                       gl.bindBuffer( gl.ARRAY_BUFFER, self._normalVectorBuffer );\r
+                       gl.vertexAttribPointer( shaderProgram.vertexNormalAttr, self._normalVectorBuffer.itemSize, gl.FLOAT, false, 0, 0 );\r
+\r
+                       for ( i = 0; i < nodesLength; i += 1 ) {\r
+                               if ( nodes[i].drawable ) {\r
+                                       self._drawElement( self._pMatrix, nodes[i] );\r
+                               }\r
+                       }\r
+               },\r
+\r
+               _drawElement: function ( perspectiveMatrix, targetNode ) {\r
+                       var self = this,\r
+                               gl = self._gl,\r
+                               shaderProgram = self._shaderProgram,\r
+                               moveMatrix = targetNode.mvMatrix,\r
+                               texture = targetNode.texture,\r
+                               meshIndexBuffer = targetNode.textureBuffer,\r
+                               meshIndexBufferItemSize = targetNode.textureBufferItemSize,\r
+                               lightPositions = self._lightsPositionStack,\r
+                               LightDir,\r
+                               normalMatrix;\r
+\r
+                       if ( !moveMatrix ) {\r
+                               return;\r
+                       }\r
+\r
+                       gl.activeTexture( gl.TEXTURE0 );\r
+                       if ( texture && texture.loaded ) {\r
+                               gl.bindTexture( gl.TEXTURE_2D, texture );\r
+                       }\r
+                       gl.uniform1i( shaderProgram.sampleUniform, 0 );\r
+\r
+                       LightDir = vec3.create();\r
+                       vec3.normalize( lightPositions[0], LightDir );\r
+                       vec3.scale( LightDir, -8 );\r
+                       gl.uniform3fv( shaderProgram.lightDirU_first, LightDir );\r
+\r
+                       vec3.normalize( lightPositions[1], LightDir );\r
+                       vec3.scale( LightDir, -1 );\r
+                       gl.uniform3fv( shaderProgram.lightDirU_second, LightDir );\r
+                       gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, meshIndexBuffer );\r
+\r
+                       gl.uniformMatrix4fv( shaderProgram.perspectiveMU, false, perspectiveMatrix );\r
+                       gl.uniformMatrix4fv( shaderProgram.transformMU, false, moveMatrix );\r
+\r
+                       normalMatrix = mat3.create();\r
+                       mat4.toInverseMat3( moveMatrix, normalMatrix );\r
+                       mat3.transpose( normalMatrix );\r
+                       gl.uniformMatrix3fv( shaderProgram.normalMU, false, normalMatrix );\r
+\r
+                       gl.drawElements( gl.TRIANGLES, meshIndexBufferItemSize, gl.UNSIGNED_SHORT, 0 );\r
+\r
+                       // release buffer memory\r
+                       gl.bindBuffer( gl.ARRAY_BUFFER, null );\r
+                       gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );\r
+\r
+                       // release texture memory\r
+                       gl.bindTexture( gl.TEXTURE_2D, null );\r
+               },\r
+\r
+               // ----------------------------------------------------------\r
+               // Animation\r
+               // ----------------------------------------------------------\r
+               _animate: function ( easingType, duration, direction, repeatCount, startValue, _removeCount ) {\r
+                       var self = this,\r
+                               timeNow = $.now(),\r
+                               progress,\r
+                               removeCount = 0;\r
+\r
+                       easingType = easingType || "linear";\r
+                       startValue = startValue || 0;\r
+                       _removeCount = _removeCount || 0;\r
+\r
+                       if ( self._sumTime >= duration ) {\r
+                               self._setPosition( self._ANIMATION_END, direction );\r
+                               self._stop();\r
+                               return;\r
+                       }\r
+\r
+                       if ( self._startTime === 0 ) {\r
+                               self._startTime = timeNow;\r
+                       } else {\r
+                               self._sumTime = timeNow - self._startTime;\r
+                               progress = $.easing[ easingType ]( self._sumTime / duration, self._sumTime, startValue, repeatCount + 1, duration );\r
+                               removeCount = parseInt( Math.abs( progress ), 10 );\r
+\r
+                               if ( _removeCount !== removeCount ) {\r
+                                       self._setPosition( self._ANIMATION_END, direction );\r
+                                       _removeCount = removeCount;\r
+\r
+                                       if ( ( repeatCount - _removeCount ) >= 0 ) {\r
+                                               self._animate( easingType, duration, direction, repeatCount, startValue, _removeCount );\r
+                                       } else {\r
+                                               self._stop();\r
+                                       }\r
+                                       return;\r
+                               }\r
+\r
+                               self._setPosition( progress - _removeCount, direction );\r
+                       }\r
+\r
+                       self._animationID = window.requestAnimationFrame( function () {\r
+                               self._animate( easingType, duration, direction, repeatCount, startValue, _removeCount );\r
+                       });\r
+               },\r
+\r
+               _run: function ( direction, repeatCount, startValue ) {\r
+                       var self = this,\r
+                               repeat = repeatCount || 0,\r
+                               duration = self._DURATION_DEFAULT * ( repeat + 1 );\r
+\r
+                       if ( self._imageList.length <= 1 ) {\r
+                               return;\r
+                       }\r
+\r
+                       startValue = startValue || 0;\r
+                       duration = ( duration >= 0 ) ? duration : 0;\r
+\r
+                       if ( self._animationID ) {\r
+                               self._setPosition( self._ANIMATION_END, direction );\r
+                               self._stop();\r
+                       }\r
+\r
+                       self._animate( "easeOutExpo", duration, direction, repeat, startValue );\r
+               },\r
+\r
+               _reset: function () {\r
+                       if ( !this._canvas || !this._gl ) {\r
+                               return;\r
+                       }\r
+\r
+                       this._final();\r
+                       this._init();\r
+                       this.refresh();\r
+               },\r
+\r
+               _stop: function () {\r
+                       if ( this._animationID ) {\r
+                               window.cancelAnimationFrame( this._animationID );\r
+                       }\r
+                       this._animationID = 0;\r
+\r
+                       this._startTime = 0;\r
+                       this._sumTime = 0;\r
+               },\r
+\r
+               _degreeToRadian: function ( degree ) {\r
+                       return degree * Math.PI / 180;\r
+               },\r
+\r
+               next: function () {\r
+                       this._run( this._DIRECTION_LEFT , 0 );\r
+               },\r
+\r
+               prev: function () {\r
+                       this._run( this._DIRECTION_RIGHT, 0 );\r
+               },\r
+\r
+               refresh: function () {\r
+                       var view = this.element,\r
+                               canvas = view.find( "canvas.ui-gallery3d-canvas" );\r
+\r
+                       if ( canvas.width() !== view.width() ) {\r
+                               canvas.width( view.width() );\r
+                       }\r
+\r
+                       if ( !this._animationID ) {\r
+                               this._setPosition( 0, 0 );\r
+                       }\r
+               },\r
+\r
+               select: function ( index ) {\r
+                       var nodes = this._nodes,\r
+                               repeat,\r
+                               i,\r
+                               imageID,\r
+                               object = null,\r
+                               target = 0,\r
+                               direction = 0;\r
+\r
+                       if ( index && this._animationID ) {\r
+                               this._stop();\r
+                       }\r
+\r
+                       for ( i in nodes ) {\r
+                               if ( nodes[i].level === 1 ) {\r
+                                       object = this._imageList[ nodes[i].imageID ];\r
+                                       imageID = nodes[i].imageID;\r
+                                       break;\r
+                               }\r
+                       }\r
+\r
+                       if ( !index ) {\r
+                               return object;\r
+                       }\r
+\r
+                       if ( index < 0 && index >= this._imageList.length ) {\r
+                               return;\r
+                       }\r
+\r
+                       target = index - imageID;\r
+                       direction = ( target > 0 ) ? this._DIRECTION_LEFT\r
+                               : ( ( target < 0 ) ? this._DIRECTION_RIGHT : 0 );\r
+                       if ( direction ) {\r
+                               this._run( direction, Math.abs( target ) - 1  );\r
+                       }\r
+               },\r
+\r
+               add: function ( item, index ) {\r
+                       if ( !item ) {\r
+                               return;\r
+                       }\r
+\r
+                       if ( typeof item === "string" ) {\r
+                               item = { "src" : item };\r
+                       }\r
+\r
+                       index = index || 0;\r
+                       if ( typeof index !== "number" && index < 0\r
+                                       && index >= this._imageList.length ) {\r
+                               return;\r
+                       }\r
+\r
+                       this._imageList.splice( index, 0, item );\r
+                       if ( this._gl ) {\r
+                               this._reset();\r
+                       }\r
+               },\r
+\r
+               remove: function ( index ) {\r
+                       index = index || 0;\r
+                       if ( typeof index !== "number" && index < 0\r
+                                       && index >= this._imageList.length ) {\r
+                               return;\r
+                       }\r
+\r
+                       this._imageList.splice( index, 1 );\r
+                       if ( this._gl ) {\r
+                               this._reset();\r
+                       }\r
+               },\r
+\r
+               clearThumbnailCache: function () {\r
+                       if ( !this._nodes || ( this._nodes.length <= 0 ) ) {\r
+                               return;\r
+                       }\r
+\r
+                       var i, url;\r
+                       for ( i = 0; i < this._imageList.length; i += 1 ) {\r
+                               url = this._imageList[i].src;\r
+                               $.imageloader.removeThumbnail( url );\r
+                       }\r
+               },\r
+\r
+               empty: function () {\r
+                       this._imageList = [];\r
+                       this._reset();\r
+               },\r
+\r
+               length: function () {\r
+                       return this._imageList.length;\r
+               }\r
+       });\r
+\r
+       $( document ).bind( "pagecreate create", function ( e ) {\r
+               $( ":jqmData(role='gallery3d')" ).gallery3d();\r
+       });\r
+\r
+} ( jQuery, document, window ) );\r
+\r
+//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);\r
+} );\r
+//>>excludeEnd("jqmBuildExclude");
\ No newline at end of file
diff --git a/tests/unit-tests/gallery3d/gallery3d-tests.js b/tests/unit-tests/gallery3d/gallery3d-tests.js
new file mode 100644 (file)
index 0000000..cd16f78
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Unit Test: Gallery3d
+ *
+ * Wonseop Kim <wonseop.kim@samsung.com>
+ */
+
+( function ( $ ) {
+       $.mobile.defaultTransition = "none";
+
+       module( "Galley3d" );
+
+       asyncTest( "galley3d", function () {
+               var widget = $( "#galley3dTest" ),
+                       imageList = [
+                               { src: "../../../demos/tizen-winsets/widgets/test/01.jpg" },
+                               { src: "../../../demos/tizen-winsets/widgets/test/02.jpg" }
+                       ],
+                       elem = "ui-gallery3d",
+                       currentItem,
+                       image = { "src" : "../../../demos/tizen-winsets/widgets/test/05.jpg" };
+
+               /* Create */
+               widget.gallery3d();
+               ok( widget.hasClass( elem ), "Create" );
+
+               /* API */
+               widget.gallery3d( "add", image );
+               currentItem = widget.gallery3d( "select" );
+               equal( currentItem.src, image.src, "API : add (by object)" );
+
+               widget.gallery3d( "add", "../../../demos/tizen-winsets/widgets/test/04.jpg" );
+               currentItem = widget.gallery3d( "select" );
+               equal( currentItem.src, "../../../demos/tizen-winsets/widgets/test/04.jpg", "API : add (by image's path')" );
+
+               equal( widget.gallery3d( "length" ), 2, "API : length" );
+
+               widget.gallery3d( "remove" );
+               notEqual( widget.gallery3d( "select" ), currentItem, "API : remove" );
+
+               widget.gallery3d( "empty" );
+               equal( widget.gallery3d( "length" ), 0, "API : empty" );
+
+               widget.gallery3d( "add", imageList[1] )
+                       .gallery3d( "add", imageList[0] );
+
+               widget.gallery3d( "select", 1 );
+               setTimeout( function () {
+                       equal( widget.gallery3d( "select" ), imageList[0], "API : select" );
+
+                       widget.gallery3d( "next" );
+                       setTimeout( function () {
+                               equal( widget.gallery3d( "select" ), imageList[1], "API : next" );
+
+                               widget.gallery3d( "prev" );
+                               setTimeout( function () {
+                                       equal( widget.gallery3d( "select" ), imageList[0], "API : prev" );
+                                       start();
+
+                               }, 340 );
+                       }, 340 );
+               }, 340 );
+       });
+}( jQuery ));
diff --git a/tests/unit-tests/gallery3d/index.html b/tests/unit-tests/gallery3d/index.html
new file mode 100644 (file)
index 0000000..c45fc92
--- /dev/null
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<html>
+<head>
+       <script src="../../../build/tizen-web-ui-fw/latest/js/jquery.js"></script>
+       <script src="../../../build/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.min.js"></script>
+       <script src="../../../build/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js"
+               data-framework-theme="tizen-white"
+               data-framework-viewport-scale="false">
+       </script>
+
+       <link rel="stylesheet" href="../../../libs/js/jquery-mobile-1.2.0/external/qunit.css" />
+
+       <script src="../../../libs/js/jquery-mobile-1.2.0/external/qunit.js"></script>
+       <script src="gallery3d-tests.js"></script>
+       <title>Galley3d</title>
+</head>
+
+<body>
+
+<h1 id="qunit-header">Galley3d</h1>
+<h2 id="qunit-banner"></h2>
+<div id="qunit-testrunner-toolbar"></div>
+<h2 id="qunit-userAgent"></h2>
+<ol id="qunit-tests"></ol>
+
+<div id="qunit-fixture">
+
+       <div data-role="page">
+               <div data-role="header" data-position="fixed">
+                       <h1>Galley3d</h1>
+               </div>
+               <div data-role="content">
+                       <div id="galley3dTest" data-role="galley3d" style="width: 100%;"></div>
+               </div>
+       </div>
+</div>
+
+</body>
+</html>
index 7963c9b..dd4fe33 100755 (executable)
@@ -8,6 +8,7 @@ var TESTS = {
                "extendablelist",
                "handler",
                "gallery",
+               "gallery3d",
                "multimediaview",
                "navigationbar",
                "notification",