diff options
-rw-r--r-- | src/gl-matrix.js | 1952 | ||||
-rw-r--r-- | src/intertyper.js | 2 | ||||
-rw-r--r-- | src/jsifier.js | 6 | ||||
-rw-r--r-- | src/library.js | 12 | ||||
-rw-r--r-- | src/library_gl.js | 19 | ||||
-rw-r--r-- | src/parseTools.js | 17 | ||||
-rw-r--r-- | src/preamble.js | 2 | ||||
-rw-r--r-- | src/utility.js | 18 | ||||
-rw-r--r-- | tests/browser_harness.html | 6 | ||||
-rw-r--r-- | tests/htmltest.png | bin | 0 -> 743 bytes | |||
-rwxr-xr-x | tests/runner.py | 105 | ||||
-rw-r--r-- | tools/autodebugger.py | 18 | ||||
-rw-r--r-- | tools/shared.py | 39 |
13 files changed, 2105 insertions, 91 deletions
diff --git a/src/gl-matrix.js b/src/gl-matrix.js new file mode 100644 index 00000000..a21cd431 --- /dev/null +++ b/src/gl-matrix.js @@ -0,0 +1,1952 @@ +(function() { + +/** + * @fileoverview gl-matrix - High performance matrix and vector operations for WebGL + * @author Brandon Jones + * @version 1.2.4 + */ + +// Modifed for emscripten: Global scoping etc. + +/* + * Copyright (c) 2011 Brandon Jones + * + * 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. + */ + + +/** + * @class 3 Dimensional Vector + * @name vec3 + */ +var vec3 = {}; + +/** + * @class 3x3 Matrix + * @name mat3 + */ +var mat3 = {}; + +/** + * @class 4x4 Matrix + * @name mat4 + */ +var mat4 = {}; + +/** + * @class Quaternion + * @name quat4 + */ +var quat4 = {}; + +var MatrixArray = Float32Array; + +/* + * 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; +}; + +/** + * 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; +}; + +/** + * 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 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); +}; + +/** + * 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; } + + var m = mat4.create(); + var v = new MatrixArray(4); + + 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; +}; + +/** + * 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] + ']'; +}; + +/* + * 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]; + } + + 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; +}; + +/** + * 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] + ']'; +}; + +/* + * 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; +}; + +/** + * 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; +}; + +/** + * 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], + 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 = mat2[0], b01 = mat2[1], b02 = mat2[2], b03 = mat2[3], + b10 = mat2[4], b11 = mat2[5], b12 = mat2[6], b13 = mat2[7], + b20 = mat2[8], b21 = mat2[9], b22 = mat2[10], b23 = mat2[11], + b30 = mat2[12], b31 = mat2[13], b32 = mat2[14], b33 = mat2[15]; + + dest[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30; + dest[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31; + dest[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32; + dest[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33; + dest[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30; + dest[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31; + dest[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32; + dest[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33; + dest[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30; + dest[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31; + dest[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32; + dest[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33; + dest[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30; + dest[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31; + dest[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32; + dest[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * 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] + ']'; +}; + +/* + * 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]; + } + + 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; +}; + +/** + * 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; +}; + +/** + * 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] + ']'; +}; + + +return { + vec3: vec3, + mat3: mat3, + mat4: mat4, + quat4: quat4 +}; + +})(); + diff --git a/src/intertyper.js b/src/intertyper.js index 26f55392..0f9ce659 100644 --- a/src/intertyper.js +++ b/src/intertyper.js @@ -118,7 +118,7 @@ function intertyper(data, sidePass, baseLineNums) { var func = funcHeader.processItem(tokenizer.processItem({ lineText: currFunctionLines[0], lineNum: currFunctionLineNum }, true))[0]; if (SKIP_STACK_IN_SMALL && /emscripten_autodebug/.exec(func.ident)) { - warn('Disabling SKIP_STACK_IN_SMALL because we are apparently processing autodebugger data'); + warnOnce('Disabling SKIP_STACK_IN_SMALL because we are apparently processing autodebugger data'); SKIP_STACK_IN_SMALL = 0; } diff --git a/src/jsifier.js b/src/jsifier.js index 8e688d8d..904517e1 100644 --- a/src/jsifier.js +++ b/src/jsifier.js @@ -375,11 +375,15 @@ function JSify(data, functionsOnly, givenFunctions) { processItem: function(item) { function addFromLibrary(ident) { if (ident in addedLibraryItems) return ''; + addedLibraryItems[ident] = true; + + // dependencies can be JS functions, which we just run + if (typeof ident == 'function') return ident(); + // Don't replace implemented functions with library ones (which can happen when we add dependencies). // Note: We don't return the dependencies here. Be careful not to end up where this matters if (('_' + ident) in Functions.implementedFunctions) return ''; - addedLibraryItems[ident] = true; var snippet = LibraryManager.library[ident]; var redirectedIdent = null; var deps = LibraryManager.library[ident + '__deps'] || []; diff --git a/src/library.js b/src/library.js index 19b8e90f..b468f3f1 100644 --- a/src/library.js +++ b/src/library.js @@ -4258,19 +4258,13 @@ LibraryManager.library = { isdigit: function(chr) { return chr >= '0'.charCodeAt(0) && chr <= '9'.charCodeAt(0); }, - isdigit_l__deps: ['isdigit'], - isdigit_l: function(chr, loc) { - return _isdigit(chr); - }, + isdigit_l: 'isdigit', // no locale support yet isxdigit: function(chr) { return (chr >= '0'.charCodeAt(0) && chr <= '9'.charCodeAt(0)) || (chr >= 'a'.charCodeAt(0) && chr <= 'f'.charCodeAt(0)) || (chr >= 'A'.charCodeAt(0) && chr <= 'F'.charCodeAt(0)); }, - isxdigit_l__deps: ['isxdigit'], - isxdigit_l: function(chr, loc) { - return _isxdigit(chr); - }, + isxdigit_l: 'isxdigit', // no locale support yet isalnum: function(chr) { return (chr >= '0'.charCodeAt(0) && chr <= '9'.charCodeAt(0)) || (chr >= 'a'.charCodeAt(0) && chr <= 'z'.charCodeAt(0)) || @@ -5345,6 +5339,7 @@ LibraryManager.library = { // TODO: Implement. return 0; }, + strftime_l: 'strftime', // no locale support yet strptime: function(buf, format, tm) { // char *strptime(const char *restrict buf, const char *restrict format, struct tm *restrict tm); @@ -5352,6 +5347,7 @@ LibraryManager.library = { // TODO: Implement. return 0; }, + strptime_l: 'strptime', // no locale support yet getdate: function(string) { // struct tm *getdate(const char *string); diff --git a/src/library_gl.js b/src/library_gl.js index c462927d..e77669d6 100644 --- a/src/library_gl.js +++ b/src/library_gl.js @@ -9,7 +9,7 @@ var LibraryGL = { buffers: {}, programs: {}, framebuffers: {}, - renderbuffer: {}, + renderbuffers: {}, textures: {}, uniforms: {}, shaders: {}, @@ -1014,12 +1014,17 @@ var LibraryGL = { } return Runtime.addFunction(func); } + }, + + glBegin__deps: ['$GL', function() { return 'GL.matrix.lib = ' + read('gl-matrix.js') }], + glBegin: function() { + Module.print('TODO'); } }; -// Simple pass-through functions +// Simple pass-through functions. Starred ones have return values. [[0, 'shadeModel fogi fogfv getError finish flush'], - [1, 'clearDepth depthFunc enable disable frontFace cullFace clear enableVertexAttribArray disableVertexAttribArray lineWidth clearStencil depthMask stencilMask stencilMaskSeparate checkFramebufferStatus generateMipmap activeTexture blendEquation'], + [1, 'clearDepth depthFunc enable disable frontFace cullFace clear enableVertexAttribArray disableVertexAttribArray lineWidth clearStencil depthMask stencilMask stencilMaskSeparate checkFramebufferStatus* generateMipmap activeTexture blendEquation'], [2, 'pixelStorei blendFunc blendEquationSeparate'], [3, 'texParameteri texParameterf drawArrays vertexAttrib2f'], [4, 'viewport clearColor scissor vertexAttrib3f colorMask drawElements renderbufferStorage blendFuncSeparate'], @@ -1029,8 +1034,14 @@ var LibraryGL = { var num = data[0]; var names = data[1]; var args = range(num).map(function(i) { return 'x' + i }).join(', '); - var stub = '(function(' + args + ') { ' + (num > 0 ? 'Module.ctx.NAME(' + args + ')' : '') + ' })'; + var plainStub = '(function(' + args + ') { ' + (num > 0 ? 'Module.ctx.NAME(' + args + ')' : '') + ' })'; + var returnStub = '(function(' + args + ') { ' + (num > 0 ? 'return Module.ctx.NAME(' + args + ')' : '') + ' })'; names.split(' ').forEach(function(name_) { + var stub = plainStub; + if (name_[name_.length-1] == '*') { + name_ = name_.substr(0, name_.length-1); + stub = returnStub; + } var cName = 'gl' + name_[0].toUpperCase() + name_.substr(1); assert(!(cName in LibraryGL), "Cannot reimplement the existing function " + cName); LibraryGL[cName] = eval(stub.replace('NAME', name_)); diff --git a/src/parseTools.js b/src/parseTools.js index 8c655904..8ccf1f9f 100644 --- a/src/parseTools.js +++ b/src/parseTools.js @@ -499,7 +499,7 @@ function IEEEUnHex(stringy) { while (stringy.length < 16) stringy = '0' + stringy; if (FAKE_X86_FP80 && stringy.length > 16) { stringy = stringy.substr(stringy.length-16, 16); - warnOnce('.ll contains floating-point values with more than 64 bits. Faking values for them. If they are used, this will almost certainly fail!'); + warnOnce('.ll contains floating-point values with more than 64 bits. Faking values for them. If they are used, this will almost certainly break horribly!'); } assert(stringy.length === 16, 'Can only unhex 16-digit double numbers, nothing platform-specific'); // |long double| can cause x86_fp80 which causes this var top = eval('0x' + stringy[0]); @@ -1293,17 +1293,11 @@ function makeGetSlabs(ptr, type, allowMultiple, unsigned) { } } else { // USE_TYPED_ARRAYS == 2) if (isPointerType(type)) type = 'i32'; // Hardcoded 32-bit - var warn64 = function() { - warnOnce('.ll contains i64 or double values. These 64-bit values are dangerous in USE_TYPED_ARRAYS == 2. ' + - 'We store i64 as i32, and double as float. This can cause serious problems!'); - }; switch(type) { case 'i1': case 'i8': return [unsigned ? 'HEAPU8' : 'HEAP8']; break; case 'i16': return [unsigned ? 'HEAPU16' : 'HEAP16']; break; - case 'i64': warn64(); - case 'i32': return [unsigned ? 'HEAPU32' : 'HEAP32']; break; - case 'float': return ['HEAPF32']; break; - case 'double': warn64(); return ['HEAPF32']; break; + case 'i32': case 'i64': return [unsigned ? 'HEAPU32' : 'HEAP32']; break; + case 'float': case 'double': return ['HEAPF32']; break; default: { throw 'what, exactly, can we do for unknown types in TA2?! ' + new Error().stack; } @@ -1322,8 +1316,7 @@ function finalizeLLVMFunctionCall(item, noIndexizeFunctions) { var newType = item.type; if (isPossiblyFunctionType(oldType) && isPossiblyFunctionType(newType) && countNormalArgs(oldType) != countNormalArgs(newType)) { - warn('Casting a function pointer type to another with a different number of arguments. See more info in the source (grep for this text). ' + - oldType + ' ==> ' + newType); + warnOnce('Casting a function pointer type to another with a different number of arguments. See more info in the source'); // This may be dangerous as clang generates different code for C and C++ calling conventions. The only problem // case appears to be passing a structure by value, C will have (field1, field2) as function args, and the // function will internally create a structure with that data, while C++ will have (struct* byVal) and it @@ -1417,7 +1410,7 @@ function handleOverflow(text, bits) { // TODO: handle overflows of i64s if (!bits) return text; var correct = correctOverflows(); - warn(!correct || bits <= 32, 'Cannot correct overflows of this many bits: ' + bits + ' at line ' + Framework.currItem.lineNum); + warnOnce(!correct || bits <= 32, 'Cannot correct overflows of this many bits: ' + bits); if (CHECK_OVERFLOWS) return 'CHECK_OVERFLOW(' + text + ', ' + bits + ', ' + Math.floor(correctSpecificOverflow() && !PGO) + ( PGO ? ', "' + Debugging.getIdentifier() + '"' : '' ) + ')'; diff --git a/src/preamble.js b/src/preamble.js index 968571a0..7c2b1a50 100644 --- a/src/preamble.js +++ b/src/preamble.js @@ -104,7 +104,7 @@ function SAFE_HEAP_STORE(dest, value, type, ignore) { } function SAFE_HEAP_LOAD(dest, type, unsigned, ignore) { - SAFE_HEAP_ACCESS(dest, type, ignore); + SAFE_HEAP_ACCESS(dest, type, false, ignore); #if SAFE_HEAP_LOG Module.print('SAFE_HEAP load: ' + [dest, type, getValue(dest, type, 1), ignore]); diff --git a/src/utility.js b/src/utility.js index 31eff100..7d5e0970 100644 --- a/src/utility.js +++ b/src/utility.js @@ -62,15 +62,21 @@ function warn(a, msg) { a = false; } if (!a) { - dprint('Warning: ' + msg); + printErr('Warning: ' + msg); } } -function warnOnce(msg) { - if (!warnOnce.msgs) warnOnce.msgs = {}; - if (msg in warnOnce.msgs) return; - warnOnce.msgs[msg] = true; - dprint('Warning: ' + msg); +function warnOnce(a, msg) { + if (!msg) { + msg = a; + a = false; + } + if (!a) { + if (!warnOnce.msgs) warnOnce.msgs = {}; + if (msg in warnOnce.msgs) return; + warnOnce.msgs[msg] = true; + printErr('Warning: ' + msg); + } } function dedup(items, ident) { diff --git a/tests/browser_harness.html b/tests/browser_harness.html index 3fbe8646..86f3749f 100644 --- a/tests/browser_harness.html +++ b/tests/browser_harness.html @@ -1,5 +1,9 @@ <html> +<head> + <title>Emscripten Browser Test Harness</title> +</head> <body> +<h2><b>Running tests...</b></h2> <div id="output"></div> <script> var counter = 0; @@ -9,8 +13,8 @@ try { request.send(null); if (request.responseText != 'False') { - document.getElementById('output').innerHTML += 'opening test window ' + (counter++) + '..<br>'; window.open(request.responseText); + document.getElementById('output').innerHTML += 'opened test window ' + (counter++) + '..<br>'; } setTimeout(check, 333); } catch(e) { diff --git a/tests/htmltest.png b/tests/htmltest.png Binary files differnew file mode 100644 index 00000000..980245ee --- /dev/null +++ b/tests/htmltest.png diff --git a/tests/runner.py b/tests/runner.py index c50a259d..6db096d9 100755 --- a/tests/runner.py +++ b/tests/runner.py @@ -79,7 +79,7 @@ class RunnerCore(unittest.TestCase): if not self.save_dir: dirname = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=TEMP_DIR) else: - dirname = EMSCRIPTEN_TEMP_DIR + dirname = CANONICAL_TEMP_DIR if not os.path.exists(dirname): os.makedirs(dirname) self.working_dir = dirname @@ -2639,6 +2639,8 @@ def process(filename): # part 2: make sure we warn about mixing c and c++ calling conventions here + if not (self.emcc_args is None or self.emcc_args == []): return # Optimized code is missing the warning comments + header = r''' struct point { @@ -2691,17 +2693,11 @@ def process(filename): all_name = os.path.join(self.get_dir(), 'all.bc') Building.link([supp_name + '.o', main_name + '.o'], all_name) - try: - # This will fail! See explanation near the warning we check for, in the compiler source code - self.do_ll_run(all_name, 'pre: 54,2\ndump: 55,3\ndump: 55,3\npost: 54,2') - except Exception, e: - # Check for warning in the generated code - generated = open(os.path.join(self.get_dir(), 'src.cpp.o.js')).read() - if self.emcc_args is None or self.emcc_args == []: # Optimized code is missing the warning comments - assert 'Casting a function pointer type to another with a different number of arguments.' in generated, 'Missing expected warning' - assert 'void (i32, i32)* ==> void (%struct.point.0*)*' in generated, 'Missing expected warning details' - return - raise Exception('We should not have gotten to here!') + # This will fail! See explanation near the warning we check for, in the compiler source code + output = Popen(['python', EMCC, all_name], stderr=PIPE).communicate() + # Check for warning in the generated code + generated = open(os.path.join(self.get_dir(), 'src.cpp.o.js')).read() + assert 'Casting a function pointer type to another with a different number of arguments.' in output[1], 'Missing expected warning' def test_stdlibs(self): if Settings.USE_TYPED_ARRAYS == 2: @@ -6670,11 +6666,17 @@ elif 'browser' in str(sys.argv): if 'report_' in s.path: q.put(s.path) else: - s.send_response(200) - s.send_header("Content-type", "text/html") - s.end_headers() - s.wfile.write(open(s.path[1:]).read()) - s.wfile.close() + filename = s.path[1:] + if os.path.exists(filename): + s.send_response(200) + s.send_header("Content-type", "text/html") + s.end_headers() + s.wfile.write(open(filename).read()) + s.wfile.close() + else: + s.send_response(500) + s.send_header("Content-type", "text/html") + s.end_headers() os.chdir(self.get_dir()) httpd = BaseHTTPServer.HTTPServer(('localhost', 8888), TestServerHandler) httpd.serve_forever() # test runner will kill us @@ -6700,13 +6702,6 @@ elif 'browser' in str(sys.argv): time.sleep(5) print '(moving on..)' - def test_html(self): - # test HTML generation. - output = Popen(['python', EMCC, path_from_root('tests', 'hello_world_sdl.cpp'), '-o', 'something.html'], stdout=PIPE, stderr=PIPE).communicate() - assert len(output[0]) == 0, output[0] - assert os.path.exists('something.html'), output - self.run_browser('something.html', 'You should see "hello, world!" and a colored cube.') - def with_report_result(self, code): return code.replace('REPORT_RESULT();', ''' char output[1000]; @@ -6772,6 +6767,12 @@ elif 'browser' in str(sys.argv): }; ''' % basename) + def test_html(self): + # test HTML generation. + self.reftest(path_from_root('tests', 'htmltest.png')) + output = Popen(['python', EMCC, path_from_root('tests', 'hello_world_sdl.cpp'), '-o', 'something.html', '--pre-js', 'reftest.js']).communicate() + self.run_browser('something.html', 'You should see "hello, world!" and a colored cube.', '/report_result?0') + def test_compression(self): open(os.path.join(self.get_dir(), 'main.cpp'), 'w').write(self.with_report_result(r''' #include <stdio.h> @@ -7006,55 +7007,49 @@ elif 'browser' in str(sys.argv): html_file.write(''' <html> <body> + Worker Test <script> var worker = new Worker('worker.js'); worker.onmessage = function(event) { - document.write("<hr>Called back by the worker: " + event.data + "<br><hr>"); + var xhr = new XMLHttpRequest(); + xhr.open('GET', 'http://localhost:8888/report_result?' + event.data); + xhr.send(); + setTimeout(function() { window.close() }, 1000); }; </script> </body> </html> ''') html_file.close() - self.run_browser('main.html', 'You should see that the worker was called, and said "hello from worker!"') + self.run_browser('main.html', 'You should see that the worker was called, and said "hello from worker!"', '/report_result?hello%20from%20worker!') def test_glgears(self): self.reftest(path_from_root('tests', 'gears.png')) - output = Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles.c'), '-o', 'something.html', - '-DHAVE_BUILTIN_SINCOS', '--pre-js', 'reftest.js'], - stdout=PIPE, stderr=PIPE).communicate() - assert len(output[0]) == 0, output[0] - assert os.path.exists('something.html'), output + Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles.c'), '-o', 'something.html', + '-DHAVE_BUILTIN_SINCOS', '--pre-js', 'reftest.js']).communicate() self.run_browser('something.html', 'You should see animating gears.', '/report_result?0') def test_glgears_animation(self): - output = Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles.c'), '-o', 'something.html', + Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles.c'), '-o', 'something.html', '-DHAVE_BUILTIN_SINCOS', - '--shell-file', path_from_root('tests', 'hello_world_gles_shell.html')], - stdout=PIPE, stderr=PIPE).communicate() - assert len(output[0]) == 0, output[0] - assert os.path.exists('something.html'), output + '--shell-file', path_from_root('tests', 'hello_world_gles_shell.html')]).communicate() self.run_browser('something.html', 'You should see animating gears.', '/report_gl_result?true') def test_glgears_bad(self): # Make sure that OpenGL ES is not available if typed arrays are not used - output = Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles.c'), '-o', 'something.html', + Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles.c'), '-o', 'something.html', '-DHAVE_BUILTIN_SINCOS', '-s', 'USE_TYPED_ARRAYS=0', - '--shell-file', path_from_root('tests', 'hello_world_gles_shell.html')], - stdout=PIPE, stderr=PIPE).communicate() - assert len(output[0]) == 0, output[0] - assert os.path.exists('something.html'), output + '--shell-file', path_from_root('tests', 'hello_world_gles_shell.html')]).communicate() self.run_browser('something.html', 'You should not see animating gears.', '/report_gl_result?false') def test_glgears_deriv(self): self.reftest(path_from_root('tests', 'gears.png')) - output = Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles_deriv.c'), '-o', 'something.html', - '-DHAVE_BUILTIN_SINCOS', '--pre-js', 'reftest.js'], - stdout=PIPE, stderr=PIPE).communicate() - assert len(output[0]) == 0, output[0] - assert os.path.exists('something.html'), output + Popen(['python', EMCC, path_from_root('tests', 'hello_world_gles_deriv.c'), '-o', 'something.html', + '-DHAVE_BUILTIN_SINCOS', '--pre-js', 'reftest.js']).communicate() self.run_browser('something.html', 'You should see animating gears.', '/report_result?0') + src = open('something.html').read() + assert 'gl-matrix' not in src, 'Should not include glMatrix when not needed' def test_glbook(self): programs = self.get_library('glbook', [ @@ -7547,6 +7542,24 @@ elif 'sanity' in str(sys.argv): assert mtime(SANITY_FILE) >= mtime(CONFIG_FILE) self.assertNotContained(SANITY_FAIL_MESSAGE, output) + # emcc should be configurable directly from EM_CONFIG without any config file + restore() + config = open(CONFIG_FILE, 'r').read() + os.environ['EM_CONFIG'] = config + wipe() + dirname = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=TEMP_DIR) + open(os.path.join(dirname, 'main.cpp'), 'w').write(''' + #include <stdio.h> + int main() { + printf("hello from emcc with no config file\\n"); + return 0; + } + ''') + Popen(['python', EMCC, os.path.join(dirname, 'main.cpp'), '-o', os.path.join(dirname, 'a.out.js')]).communicate() + self.assertContained('hello from emcc with no config file', run_js(os.path.join(dirname, 'a.out.js'))) + del os.environ['EM_CONFIG'] + shutil.rmtree(dirname) + def test_emcc_caching(self): INCLUDING_MESSAGE = 'emcc: including X' BUILDING_MESSAGE = 'emcc: building X for cache' diff --git a/tools/autodebugger.py b/tools/autodebugger.py index 51661ec7..943ff043 100644 --- a/tools/autodebugger.py +++ b/tools/autodebugger.py @@ -11,6 +11,7 @@ Warning: You probably want to compile with SKIP_STACK_IN_SMALL=0! Otherwise import os, sys, re ALLOW_POINTERS = False +ALLOW_MISC = True MEMCPY = False POSTAMBLE = ''' @@ -242,6 +243,23 @@ for i in range(len(lines)): index = i+1+lines_added lines[i] += '\n call void @emscripten_autodebug_%s(i32 %d, %s %%%s)' % (m.group('type'), index, m.group('type'), m.group('var')) lines_added += 1 + continue + if ALLOW_MISC: + m = re.match(' %(?P<var>[\w_.]+) = (call|mul|add) (nsw )?(?P<type>i64|i32|i16|i8|float|double+) .*', lines[i]) + if m: + index = i+1+lines_added + lines[i] += '\n call void @emscripten_autodebug_%s(i32 %d, %s %%%s)' % (m.group('type'), index, m.group('type'), m.group('var')) + lines_added += 1 + continue + m = re.match(' call void @llvm\.memcpy\.p0i8\.p0i8\.i32\(i8\* %(?P<dst>[\w_.]+), i8\* %(?P<src>[\w_.]+), i32 8, i32 (?P<align>\d+),.*', lines[i]) + if m: + index = i+1+lines_added + lines[i] += '\n %%adpretemp%d = bitcast i8* %%%s to i64*' % (index, m.group('src')) + \ + '\n %%adtemp%d = load i64* %%adpretemp%d, align %s' % (index, index, m.group('align')) + \ + '\n call void @emscripten_autodebug_%s(i32 %d, %s %%adtemp%d)' % ('i64', index, 'i64', index) + lines_added += 3 + continue + finally: if len(pre) > 0: lines[i] = pre + '\n' + lines[i] diff --git a/tools/shared.py b/tools/shared.py index 532f561f..58ca4ca5 100644 --- a/tools/shared.py +++ b/tools/shared.py @@ -6,15 +6,22 @@ __rootpath__ = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) def path_from_root(*pathelems): return os.path.join(__rootpath__, *pathelems) -# Config file +# Emscripten configuration is done through the EM_CONFIG environment variable. +# If the string value contained in this environment variable contains newline +# separated definitions, then these definitions will be used to configure +# Emscripten. Otherwise, the string is understood to be a path to a settings +# file that contains the required definitions. EM_CONFIG = os.environ.get('EM_CONFIG') if not EM_CONFIG: EM_CONFIG = '~/.emscripten' -CONFIG_FILE = os.path.expanduser(EM_CONFIG) -if not os.path.exists(CONFIG_FILE): - shutil.copy(path_from_root('settings.py'), CONFIG_FILE) - print >> sys.stderr, ''' +if '\n' in EM_CONFIG: + CONFIG_FILE = None +else: + CONFIG_FILE = os.path.expanduser(EM_CONFIG) + if not os.path.exists(CONFIG_FILE): + shutil.copy(path_from_root('settings.py'), CONFIG_FILE) + print >> sys.stderr, ''' ============================================================================== Welcome to Emscripten! @@ -28,9 +35,9 @@ make sure LLVM_ROOT and NODE_JS are correct. This command will now exit. When you are done editing those paths, re-run it. ============================================================================== ''' % (EM_CONFIG, CONFIG_FILE) - sys.exit(0) + sys.exit(0) try: - exec(open(CONFIG_FILE, 'r').read()) + exec(open(CONFIG_FILE, 'r').read() if CONFIG_FILE else EM_CONFIG) except Exception, e: print >> sys.stderr, 'Error in evaluating %s (at %s): %s' % (EM_CONFIG, CONFIG_FILE, str(e)) sys.exit(1) @@ -43,6 +50,8 @@ except Exception, e: def check_sanity(force=False): try: if not force: + if not CONFIG_FILE: + return # config stored directly in EM_CONFIG => skip sanity checks settings_mtime = os.stat(CONFIG_FILE).st_mtime sanity_file = CONFIG_FILE + '_sanity' try: @@ -117,11 +126,12 @@ JS_OPTIMIZER = path_from_root('tools', 'js-optimizer.js') # Temp dir. Create a random one, unless EMCC_DEBUG is set, in which case use TEMP_DIR/emscripten_temp +CANONICAL_TEMP_DIR = os.path.join(TEMP_DIR, 'emscripten_temp') EMSCRIPTEN_TEMP_DIR = None if os.environ.get('EMCC_DEBUG'): try: - EMSCRIPTEN_TEMP_DIR = os.path.join(TEMP_DIR, 'emscripten_temp') + EMSCRIPTEN_TEMP_DIR = CANONICAL_TEMP_DIR if not os.path.exists(EMSCRIPTEN_TEMP_DIR): os.makedirs(EMSCRIPTEN_TEMP_DIR) except: @@ -183,8 +193,11 @@ else: #if 'strict' not in str(SPIDERMONKEY_ENGINE): # XXX temporarily disable strict mode until we sort out some stuff # SPIDERMONKEY_ENGINE += ['-e', "options('strict')"] # Strict mode in SpiderMonkey. With V8 we check that fallback to non-strict works too -if 'gcparam' not in str(SPIDERMONKEY_ENGINE): - SPIDERMONKEY_ENGINE += ['-e', "gcparam('maxBytes', 1024*1024*1024);"] # Our very large files need lots of gc heap +try: + if 'gcparam' not in str(SPIDERMONKEY_ENGINE): + SPIDERMONKEY_ENGINE += ['-e', "gcparam('maxBytes', 1024*1024*1024);"] # Our very large files need lots of gc heap +except NameError: + pass WINDOWS = sys.platform.startswith ('win') @@ -228,6 +241,8 @@ class TempFiles: def check_engine(engine): # TODO: we call this several times, perhaps cache the results? try: + if not CONFIG_FILE: + return True # config stored directly in EM_CONFIG => skip engine check return 'hello, world!' in run_js(path_from_root('tests', 'hello_world.js'), engine) except Exception, e: print 'Checking JS engine %s failed. Check %s. Details: %s' % (str(engine), EM_CONFIG, str(e)) @@ -810,7 +825,9 @@ set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)''' % { 'winfix': '' if not WINDOWS e # Permanent cache for dlmalloc and stdlibc++ class Cache: - dirname = os.path.expanduser(os.path.join('~', '.emscripten_cache')) + dirname = os.environ.get('EM_CACHE') + if not dirname: + dirname = os.path.expanduser(os.path.join('~', '.emscripten_cache')) @staticmethod def erase(): |