An introduction to GLSL shaders and graphics programming that runs in your\nbrowser. shader-school is a NodeSchool workshop\noriginally created for NodeConf 2014. Everything is\npowered by browserify, glslify and modules from the stackgl ecosystem under\nthe hood.
'];
+
+map.text =
+map.circle =
+map.ellipse =
+map.line =
+map.path =
+map.polygon =
+map.polyline =
+map.rect = [1, ''];
+
+/**
+ * Parse `html` and return a DOM Node instance, which could be a TextNode,
+ * HTML DOM Node of some kind (
for example), or a DocumentFragment
+ * instance, depending on the contents of the `html` string.
+ *
+ * @param {String} html - HTML string to "domify"
+ * @param {Document} doc - The `document` instance to create the Node for
+ * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance
+ * @api private
+ */
+
+function parse(html, doc) {
+ if ('string' != typeof html) throw new TypeError('String expected');
+
+ // default to the global `document` object
+ if (!doc) doc = document;
+
+ // tag name
+ var m = /<([\w:]+)/.exec(html);
+ if (!m) return doc.createTextNode(html);
+
+ html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
+
+ var tag = m[1];
+
+ // body support
+ if (tag == 'body') {
+ var el = doc.createElement('html');
+ el.innerHTML = html;
+ return el.removeChild(el.lastChild);
+ }
+
+ // wrap map
+ var wrap = map[tag] || map._default;
+ var depth = wrap[0];
+ var prefix = wrap[1];
+ var suffix = wrap[2];
+ var el = doc.createElement('div');
+ el.innerHTML = prefix + html + suffix;
+ while (depth--) el = el.lastChild;
+
+ // one element
+ if (el.firstChild == el.lastChild) {
+ return el.removeChild(el.firstChild);
+ }
+
+ // several elements
+ var fragment = doc.createDocumentFragment();
+ while (el.firstChild) {
+ fragment.appendChild(el.removeChild(el.firstChild));
+ }
+
+ return fragment;
+}
+
+},{}],7:[function(require,module,exports){
+module.exports = findup
+
+function findup(child, check) {
+ if (typeof check === 'string') check = byName(check)
+ if (typeof check !== 'function') check = byExact(check)
+
+ while (
+ child &&
+ !check(child)
+ ) child = child.parentNode
+
+
+ return child || null
+}
+
+function byName(name) {
+ name = String(name).toUpperCase()
+
+ return function(element) {
+ return name === element.nodeName
+ }
+}
+
+function byExact(el) {
+ return function(element) {
+ return el === element
+ }
+}
+
+},{}],8:[function(require,module,exports){
+(function (process){
+var slice = require('sliced')
+
+if (process.browser) {
+ var raf = require('raf-component')
+} else {
+ var raf = typeof setImmediate !== 'undefined'
+ ? setImmediate
+ : process.nextTick
+}
+
+module.exports = debounce
+
+function debounce(fn, now) {
+ var args = null
+ var ctx = null
+
+ return debounced
+
+ function debounced() {
+ if (args !== null) return
+ args = slice(arguments)
+ ctx = this
+ if (now) fn.apply(ctx, args)
+ raf(next)
+ }
+
+ function next() {
+ if (!now) fn.apply(ctx, args)
+ args = null
+ ctx = null
+ }
+}
+
+}).call(this,require("lppjwH"))
+},{"lppjwH":109,"raf-component":9,"sliced":11}],9:[function(require,module,exports){
+/**
+ * Expose `requestAnimationFrame()`.
+ */
+
+exports = module.exports = window.requestAnimationFrame
+ || window.webkitRequestAnimationFrame
+ || window.mozRequestAnimationFrame
+ || window.oRequestAnimationFrame
+ || window.msRequestAnimationFrame
+ || fallback;
+
+/**
+ * Fallback implementation.
+ */
+
+var prev = new Date().getTime();
+function fallback(fn) {
+ var curr = new Date().getTime();
+ var ms = Math.max(0, 16 - (curr - prev));
+ var req = setTimeout(fn, ms);
+ prev = curr;
+ return req;
+}
+
+/**
+ * Cancel.
+ */
+
+var cancel = window.cancelAnimationFrame
+ || window.webkitCancelAnimationFrame
+ || window.mozCancelAnimationFrame
+ || window.oCancelAnimationFrame
+ || window.msCancelAnimationFrame
+ || window.clearTimeout;
+
+exports.cancel = function(id){
+ cancel.call(window, id);
+};
+
+},{}],10:[function(require,module,exports){
+
+/**
+ * Expose `render()`.`
+ */
+
+exports = module.exports = render;
+
+/**
+ * Expose `compile()`.
+ */
+
+exports.compile = compile;
+
+/**
+ * Render the given mustache `str` with `obj`.
+ *
+ * @param {String} str
+ * @param {Object} obj
+ * @return {String}
+ * @api public
+ */
+
+function render(str, obj) {
+ obj = obj || {};
+ var fn = compile(str);
+ return fn(obj);
+}
+
+/**
+ * Compile the given `str` to a `Function`.
+ *
+ * @param {String} str
+ * @return {Function}
+ * @api public
+ */
+
+function compile(str) {
+ var js = [];
+ var toks = parse(str);
+ var tok;
+
+ for (var i = 0; i < toks.length; ++i) {
+ tok = toks[i];
+ if (i % 2 == 0) {
+ js.push('"' + tok.replace(/"/g, '\\"') + '"');
+ } else {
+ switch (tok[0]) {
+ case '/':
+ tok = tok.slice(1);
+ js.push(' }) + ');
+ break;
+ case '^':
+ tok = tok.slice(1);
+ assertProperty(tok);
+ js.push(' + section(obj, "' + tok + '", true, function(obj){ return ');
+ break;
+ case '#':
+ tok = tok.slice(1);
+ assertProperty(tok);
+ js.push(' + section(obj, "' + tok + '", false, function(obj){ return ');
+ break;
+ case '!':
+ tok = tok.slice(1);
+ assertProperty(tok);
+ js.push(' + obj.' + tok + ' + ');
+ break;
+ default:
+ assertProperty(tok);
+ js.push(' + escape(obj.' + tok + ') + ');
+ }
+ }
+ }
+
+ js = '\n'
+ + indent(escape.toString()) + ';\n\n'
+ + indent(section.toString()) + ';\n\n'
+ + ' return ' + js.join('').replace(/\n/g, '\\n');
+
+ return new Function('obj', js);
+}
+
+/**
+ * Assert that `prop` is a valid property.
+ *
+ * @param {String} prop
+ * @api private
+ */
+
+function assertProperty(prop) {
+ if (!prop.match(/^[\w.]+$/)) throw new Error('invalid property "' + prop + '"');
+}
+
+/**
+ * Parse `str`.
+ *
+ * @param {String} str
+ * @return {Array}
+ * @api private
+ */
+
+function parse(str) {
+ return str.split(/\{\{|\}\}/);
+}
+
+/**
+ * Indent `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+function indent(str) {
+ return str.replace(/^/gm, ' ');
+}
+
+/**
+ * Section handler.
+ *
+ * @param {Object} context obj
+ * @param {String} prop
+ * @param {Function} thunk
+ * @param {Boolean} negate
+ * @api private
+ */
+
+function section(obj, prop, negate, thunk) {
+ var val = obj[prop];
+ if (Array.isArray(val)) return val.map(thunk).join('');
+ if ('function' == typeof val) return val.call(obj, thunk(obj));
+ if (negate) val = !val;
+ if (val) return thunk(obj);
+ return '';
+}
+
+/**
+ * Escape the given `html`.
+ *
+ * @param {String} html
+ * @return {String}
+ * @api private
+ */
+
+function escape(html) {
+ return String(html)
+ .replace(/&/g, '&')
+ .replace(/"/g, '"')
+ .replace(//g, '>');
+}
+
+},{}],11:[function(require,module,exports){
+module.exports = exports = require('./lib/sliced');
+
+},{"./lib/sliced":12}],12:[function(require,module,exports){
+
+/**
+ * An Array.prototype.slice.call(arguments) alternative
+ *
+ * @param {Object} args something with a length
+ * @param {Number} slice
+ * @param {Number} sliceEnd
+ * @api public
+ */
+
+module.exports = function (args, slice, sliceEnd) {
+ var ret = [];
+ var len = args.length;
+
+ if (0 === len) return ret;
+
+ var start = slice < 0
+ ? Math.max(0, slice + len)
+ : slice || 0;
+
+ if (sliceEnd !== undefined) {
+ len = sliceEnd < 0
+ ? sliceEnd + len
+ : sliceEnd
+ }
+
+ while (len-- > start) {
+ ret[len - start] = args[len];
+ }
+
+ return ret;
+}
+
+
+},{}],13:[function(require,module,exports){
+module.exports=require('ndpack-image')(1,256,4,"iVBORw0KGgoAAAANSUhEUgAAAQAAAAABCAYAAAAxWXB3AAAAAklEQVR4AewaftIAAADsSURBVCXBgXEEIQADsZW5/lv+DERS/dBDF3roQlkXeoj1EOshVnSxItZjoSzWQyzWb2JFF6e2WBGrLVbEaosV2YpYka0sZCti/SZWZMpClIQQ2oROQhRC6BBCUwiNRmhEobM1oqTRmdCIGp1JGlGzvokaoW9Cq9C3Yk1R3xY1QseaQqMzjajR6BCaGp0JjaizRY3QmUaq0ZnQCI02nUSh0aYRoqSzRSGEDiGKYlGsqU0IoRHLtC2EkImFItTEykIRshWhiPUjFKEs1ISyUIQi1kMoMqHoQhGKLlYkPYSiC0UXii70KPRPF3ro+gNf1gb72t6EvgAAAABJRU5ErkJggg==")
+
+},{"ndpack-image":101}],14:[function(require,module,exports){
+var createCamera = require("orbit-camera");
+var createTex2d = require("gl-texture2d");
+var createGeom = require("gl-geometry");
+var createFBO = require("gl-fbo");
+var createShader = require("glslify");
+
+var clear = require("gl-clear")({
+ color: [1, 1, 1, 1]
+});
+
+var mat4 = require("gl-matrix").mat4;
+var quat = require("gl-matrix").quat;
+var triangle = require("a-big-triangle");
+var debounce = require("frame-debounce");
+var unindex = require("unindex-mesh");
+var normals = require("face-normals");
+var combine = require("mesh-combine");
+var fit = require("canvas-fit");
+var qbqb = require("cube-cube");
+var getTime = require("right-now");
+var clone = require("clone");
+var TIMESCALE = 0.5;
+var SIZE = 16;
+var RES = [1 / SIZE, 1 / SIZE];
+
+module.exports = function(canvas) {
+ var gl = require("gl-context")(canvas, render);
+
+ var heightmap = createFBO(gl, [SIZE, SIZE], {
+ float: true
+ });
+
+ var gradient = createTex2d(gl, require("./gradient-map"));
+ var voxels = createMesh();
+ var projection = mat4.create();
+ var viewrot = mat4.create();
+ var view = mat4.create();
+ var model = mat4.create();
+ var camera = createCamera([0, 10, 30], [0, 0, 0], [0, 1, 0]);
+ var shader = require("glslify/adapter.js")("\n#define GLSLIFY 1\n\nprecision mediump float;\nattribute vec3 aPosition;\nattribute vec3 aCentroid;\nattribute vec3 aNormal;\nattribute vec3 aEdge;\nvarying vec4 vNeighbours;\nvarying vec3 vNormal;\nvarying vec2 vEdge;\nuniform sampler2D tHeightmap;\nuniform vec2 uResolution;\nuniform mat4 uProjection;\nuniform mat4 uModel;\nuniform mat4 uView;\nconst float threshold = 1.0 / 0.01;\nvoid main() {\n vec3 position = aPosition;\n vec2 coord = aCentroid.xz;\n float height = texture2D(tHeightmap, aCentroid.xz).r;\n float nht = texture2D(tHeightmap, coord + uResolution * vec2(+0.0, -1.0)).r;\n float nhb = texture2D(tHeightmap, coord + uResolution * vec2(+0.0, +1.0)).r;\n float nhl = texture2D(tHeightmap, coord + uResolution * vec2(-1.0, +0.0)).r;\n float nhr = texture2D(tHeightmap, coord + uResolution * vec2(+1.0, +0.0)).r;\n position.y = mix(position.y, height, position.y);\n gl_Position = (uProjection * uView * uModel * vec4(position, 1.0)) + vec4(0.35, -0.2, 0.0, 0.0);\n vNormal = aNormal;\n vEdge = aEdge.xz;\n vNeighbours = vec4(clamp((nht - height) * threshold, -1.0, 1.0), clamp((nhb - height) * threshold, -1.0, 1.0), clamp((nhl - height) * threshold, -1.0, 1.0), clamp((nhr - height) * threshold, -1.0, 1.0));\n}", "\n#define GLSLIFY 1\n\nprecision mediump float;\nuniform sampler2D tGradient;\nuniform mat4 uViewRotation;\nvarying vec4 vNeighbours;\nvarying vec3 vNormal;\nvarying vec2 vEdge;\n#define EDGE_SHARPNESS 1.8\n\n#define EDGE_SHADOW 0.2\n\n#define BLOCK_COLOR 1.1\n\nvoid main() {\n vec4 lightDirection = vec4(normalize(vec3(-0.2, 1.2, 0.8)), 1.0);\n lightDirection = uViewRotation * lightDirection;\n float nhr = max(0.0, vNeighbours.x);\n float nhl = max(0.0, vNeighbours.y);\n float nhb = max(0.0, vNeighbours.z);\n float nht = max(0.0, vNeighbours.w);\n float top = abs(vNormal.y);\n vec2 de = vec2(max(0.0, nht * vEdge.x) - min(0.0, nhb * vEdge.x), max(0.0, nhl * vEdge.y) - min(0.0, nhr * vEdge.y));\n float d1 = smoothstep(0.0, 1.0, abs(de.x));\n float d2 = smoothstep(0.0, 1.0, abs(de.y));\n float d = (pow(d1, EDGE_SHARPNESS) + pow(d2, EDGE_SHARPNESS));\n vec3 diffuse = vec3(1.0 - min(d, 1.0) * top * EDGE_SHADOW) * BLOCK_COLOR;\n vec3 ambient = vec3(0.1);\n float lambert = max(0.0, dot(vNormal, normalize(lightDirection.xyz)));\n vec3 color = diffuse * lambert + ambient;\n gl_FragColor.rgb = texture2D(tGradient, vec2(0.0, color.r)).rgb;\n gl_FragColor.a = 1.0;\n}", [{"name":"tHeightmap","type":"sampler2D"},{"name":"uResolution","type":"vec2"},{"name":"uProjection","type":"mat4"},{"name":"uModel","type":"mat4"},{"name":"uView","type":"mat4"},{"name":"tGradient","type":"sampler2D"},{"name":"uViewRotation","type":"mat4"}], [{"name":"aPosition","type":"vec3"},{"name":"aCentroid","type":"vec3"},{"name":"aNormal","type":"vec3"},{"name":"aEdge","type":"vec3"}])(gl);
+ var heightShader = require("glslify/adapter.js")("\n#define GLSLIFY 1\n\nprecision mediump float;\nattribute vec2 position;\nvoid main() {\n gl_Position = vec4(position.xy, 1.0, 1.0);\n}", "\n#define GLSLIFY 1\n\nprecision mediump float;\nuniform vec2 uResolution;\nuniform float uTime;\nvoid main() {\n vec2 coord = (gl_FragCoord.xy * uResolution - 0.5) * 2.0;\n float height = 0.0;\n height += sin(uTime * 0.00062 + coord.y * 2.5) * 0.4;\n height += cos(uTime * 0.00048 + coord.x * 1.8) * 0.6;\n height += sin(uTime * 0.0048 + coord.x * 7.9) * 0.2;\n height += cos(uTime * 0.0038 + coord.y * 6.8) * 0.1;\n height += sin(uTime * 0.0028 + coord.y * 2.8 + 0.5) * 0.3;\n height -= clamp(1.0 - uTime * 0.0005, 0.0, 1.0) * 2.0;\n height = max(0.0, height * 0.2);\n height *= max(0.0, 0.85 - max(0.0, coord.x * coord.x + coord.y * coord.y));\n gl_FragColor.r = height;\n gl_FragColor.gba = vec3(1.0);\n}", [{"name":"uResolution","type":"vec2"},{"name":"uTime","type":"float"}], [{"name":"position","type":"vec2"}])(gl);
+ var geom = createGeom(gl).attr("aPosition", voxels.positions).attr("aCentroid", voxels.centroids).attr("aNormal", voxels.normals).attr("aEdge", voxels.edges);
+ camera.distance = 1.5;
+ heightmap.color[0].wrap = gl.CLAMP_TO_EDGE;
+ heightmap.color[0].minFilter = gl.NEAREST;
+ heightmap.color[0].maxFilter = gl.NEAREST;
+ mat4.translate(model, model, [-0.5, 0, -0.5]);
+ window.addEventListener("resize", debounce(fit(canvas)), false);
+
+ function render() {
+ var width = canvas.width;
+ var height = canvas.height;
+ var now = getTime() * TIMESCALE;
+ heightmap.bind();
+ gl.viewport(0, 0, SIZE, SIZE);
+ gl.disable(gl.DEPTH_TEST);
+ gl.disable(gl.CULL_FACE);
+ heightShader.bind();
+ heightShader.uniforms.uTime = now;
+ heightShader.uniforms.uResolution = RES;
+ triangle(gl);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, width, height);
+ gl.enable(gl.DEPTH_TEST);
+ gl.enable(gl.CULL_FACE);
+ clear(gl);
+ mat4.perspective(projection, Math.PI / 4, width / height, 0.001, 100);
+ quat.identity(camera.rotation);
+ quat.rotateY(camera.rotation, camera.rotation, now * 0.0002);
+ quat.rotateX(camera.rotation, camera.rotation, -0.5);
+ camera.view(view);
+ quat.identity(camera.rotation);
+ quat.rotateY(camera.rotation, camera.rotation, now * 0.0002);
+ geom.bind(shader);
+ shader.uniforms.uResolution = RES;
+ shader.uniforms.uViewRotation = mat4.fromQuat(viewrot, camera.rotation);
+ shader.uniforms.uProjection = projection;
+ shader.uniforms.uModel = model;
+ shader.uniforms.uView = view;
+ shader.uniforms.tHeightmap = heightmap.color[0].bind(0);
+ shader.uniforms.tGradient = gradient.bind(1);
+ geom.draw();
+ geom.unbind();
+ }
+};
+
+function createMesh() {
+ var voxels = qbqb(SIZE, 1, SIZE);
+ var positions = unindex(combine(voxels));
+ var edges = unindex(combine(getEdges(voxels)));
+ var centroids = unindex(combine(getCentroids(voxels)));
+
+ return {
+ positions: positions,
+ centroids: centroids,
+ normals: normals(positions),
+ edges: edges
+ };
+}
+
+function getCentroids(meshes) {
+ return meshes.map(function(mesh) {
+ mesh = clone(mesh);
+
+ for (var i = 0; i < mesh.positions.length; i++) {
+ mesh.positions[i] = mesh.centroid;
+ }
+
+ return mesh;
+ });
+}
+
+function getEdges(meshes) {
+ return meshes.map(function(mesh) {
+ mesh = clone(mesh);
+ var idx = mesh.index;
+
+ for (var i = 0; i < mesh.positions.length; i++) {
+ var pos = mesh.positions[i];
+ mesh.positions[i] = mesh.positions[i].slice();
+ mesh.positions[i][0] = (pos[0] * SIZE - idx[0] - 0.5) * 2;
+ mesh.positions[i][2] = (pos[2] * SIZE - idx[2] - 0.5) * 2;
+ mesh.positions[i][1] = (pos[1] - idx[1] - 0.5) * 2;
+ }
+
+ return mesh;
+ });
+}
+},{"./gradient-map":13,"a-big-triangle":31,"canvas-fit":32,"clone":34,"cube-cube":35,"face-normals":38,"frame-debounce":39,"gl-clear":44,"gl-context":45,"gl-fbo":47,"gl-geometry":50,"gl-matrix":75,"gl-texture2d":88,"glslify":90,"glslify/adapter.js":89,"mesh-combine":96,"orbit-camera":103,"right-now":104,"unindex-mesh":105}],15:[function(require,module,exports){
+"use strict"
+
+var pool = require("typedarray-pool")
+var ops = require("ndarray-ops")
+var ndarray = require("ndarray")
+
+function GLBuffer(gl, type, handle, length, usage) {
+ this.gl = gl
+ this.type = type
+ this.handle = handle
+ this.length = length
+ this.usage = usage
+}
+
+GLBuffer.prototype.bind = function() {
+ this.gl.bindBuffer(this.type, this.handle)
+}
+
+GLBuffer.prototype.dispose = function() {
+ this.gl.deleteBuffer(this.handle)
+}
+
+function updateTypeArray(gl, type, len, usage, data, offset) {
+ if(offset <= 0 && data.length > len) {
+ gl.bufferData(type, data, usage)
+ return data.length
+ }
+ if(data.length + offset > len) {
+ throw new Error("gl-buffer: If resizing buffer, offset must be 0")
+ }
+ gl.bufferSubData(type, offset, data)
+ return len
+}
+
+function makeScratchTypeArray(array, dtype) {
+ var res = pool.malloc(array.length, dtype)
+ var n = array.length
+ for(var i=0; i 0) {
+ throw new Error("gl-buffer: Cannot specify offset when resizing buffer")
+ }
+ this.gl.bufferData(this.type, array, this.usage)
+ this.length = array
+ } else if(array.shape) {
+ var dtype = array.dtype
+ if(dtype === "float64" || dtype === "array" || dtype === "generic") {
+ dtype = "float32"
+ }
+ if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
+ dtype = "uint16"
+ }
+ if(array.shape.length !== 1) {
+ throw new Error("gl-buffer: Array length must be 1")
+ }
+ if(dtype === array.dtype && array.stride[0] === 1) {
+ if(array.offset === 0 && array.data.length === array.shape[0]) {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset)
+ } else {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset)
+ }
+ } else {
+ var tmp = pool.malloc(array.shape[0], dtype)
+ var ndt = ndarray(tmp)
+ ops.assign(ndt, array)
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset)
+ pool.free(tmp)
+ }
+ } else if(Array.isArray(array)) {
+ if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
+ var t = makeScratchTypeArray(array, "uint16")
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
+ pool.freeUint16(t)
+ } else {
+ var t = makeScratchTypeArray(array, "float32")
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
+ pool.freeFloat32(t)
+ }
+ } else {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset)
+ }
+}
+
+GLBuffer.prototype.draw = function(mode, count, offset) {
+ offset = offset || 0
+ var gl = this.gl
+ if(this.type === gl.ARRAY_BUFFER) {
+ gl.drawArrays(mode, offset, count)
+ } else if(this.type === gl.ELEMENT_ARRAY_BUFFER) {
+ this.bind()
+ gl.drawElements(mode, count, gl.UNSIGNED_SHORT, offset)
+ } else {
+ throw new Error("Invalid type for WebGL buffer")
+ }
+}
+
+function createBuffer(gl, type, data, usage) {
+ if(data === undefined) {
+ data = type
+ type = gl.ARRAY_BUFFER
+ }
+ if(!usage) {
+ usage = gl.DYNAMIC_DRAW
+ }
+ var len = 0
+ var handle = gl.createBuffer()
+ gl.bindBuffer(type, handle)
+ if(typeof data === "number") {
+ gl.bufferData(type, data, usage)
+ len = data
+ } else if(data instanceof Array) {
+ if(type === gl.ELEMENT_ARRAY_BUFFER) {
+ gl.bufferData(type, new Uint16Array(data), usage)
+ } else {
+ gl.bufferData(type, new Float32Array(data), usage)
+ }
+ len = data.length
+ } else if(data.length) {
+ gl.bufferData(type, data, usage)
+ len = data.length
+ } else if(data.shape) {
+ var dtype = data.dtype
+ if(dtype === "float64" || dtype === "array" || dtype === "generic") {
+ dtype = "float32"
+ }
+ if(type === gl.ELEMENT_ARRAY_BUFFER) {
+ dtype = "uint16"
+ }
+ if(data.shape.length !== 1) {
+ throw new Error("gl-buffer: Array shape must be 1D")
+ }
+ var len = data.shape[0]
+ if(dtype === data.type && data.stride[0] === 1) {
+ gl.bufferData(type, data.data.subarray(data.offset, data.offset+len), usage)
+ } else {
+ var tmp = pool.malloc(data.shape[0], dtype)
+ var ndt = ndarray(tmp)
+ ops.assign(ndt, data)
+ gl.bufferData(type, tmp, usage)
+ pool.free(tmp)
+ }
+ } else {
+ throw new Error("gl-buffer: Invalid format for buffer data")
+ }
+ if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) {
+ throw new Error("gl-buffer: Invalid type for webgl buffer")
+ }
+ if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) {
+ throw new Error("gl-buffer: Invalid usage for buffer")
+ }
+ return new GLBuffer(gl, type, handle, len, usage)
+}
+
+module.exports = createBuffer
+},{"ndarray":21,"ndarray-ops":16,"typedarray-pool":25}],16:[function(require,module,exports){
+"use strict"
+
+var compile = require("cwise-compiler")
+
+var EmptyProc = {
+ body: "",
+ args: [],
+ thisVars: [],
+ localVars: []
+}
+
+function fixup(x) {
+ if(!x) {
+ return EmptyProc
+ }
+ for(var i=0; i>",
+ rrshift: ">>>"
+}
+;(function(){
+ for(var id in assign_ops) {
+ var op = assign_ops[id]
+ exports[id] = makeOp({
+ args: ["array","array","array"],
+ body: {args:["a","b","c"],
+ body: "a=b"+op+"c"},
+ funcName: id
+ })
+ exports[id+"eq"] = makeOp({
+ args: ["array","array"],
+ body: {args:["a","b"],
+ body:"a"+op+"=b"},
+ rvalue: true,
+ funcName: id+"eq"
+ })
+ exports[id+"s"] = makeOp({
+ args: ["array", "array", "scalar"],
+ body: {args:["a","b","s"],
+ body:"a=b"+op+"s"},
+ funcName: id+"s"
+ })
+ exports[id+"seq"] = makeOp({
+ args: ["array","scalar"],
+ body: {args:["a","s"],
+ body:"a"+op+"=s"},
+ rvalue: true,
+ funcName: id+"seq"
+ })
+ }
+})();
+
+var unary_ops = {
+ not: "!",
+ bnot: "~",
+ neg: "-",
+ recip: "1.0/"
+}
+;(function(){
+ for(var id in unary_ops) {
+ var op = unary_ops[id]
+ exports[id] = makeOp({
+ args: ["array", "array"],
+ body: {args:["a","b"],
+ body:"a="+op+"b"},
+ funcName: id
+ })
+ exports[id+"eq"] = makeOp({
+ args: ["array"],
+ body: {args:["a"],
+ body:"a="+op+"a"},
+ rvalue: true,
+ count: 2,
+ funcName: id+"eq"
+ })
+ }
+})();
+
+var binary_ops = {
+ and: "&&",
+ or: "||",
+ eq: "===",
+ neq: "!==",
+ lt: "<",
+ gt: ">",
+ leq: "<=",
+ geq: ">="
+}
+;(function() {
+ for(var id in binary_ops) {
+ var op = binary_ops[id]
+ exports[id] = makeOp({
+ args: ["array","array","array"],
+ body: {args:["a", "b", "c"],
+ body:"a=b"+op+"c"},
+ funcName: id
+ })
+ exports[id+"s"] = makeOp({
+ args: ["array","array","scalar"],
+ body: {args:["a", "b", "s"],
+ body:"a=b"+op+"s"},
+ funcName: id+"s"
+ })
+ exports[id+"eq"] = makeOp({
+ args: ["array", "array"],
+ body: {args:["a", "b"],
+ body:"a=a"+op+"b"},
+ rvalue:true,
+ count:2,
+ funcName: id+"eq"
+ })
+ exports[id+"seq"] = makeOp({
+ args: ["array", "scalar"],
+ body: {args:["a","s"],
+ body:"a=a"+op+"s"},
+ rvalue:true,
+ count:2,
+ funcName: id+"seq"
+ })
+ }
+})();
+
+var math_unary = [
+ "abs",
+ "acos",
+ "asin",
+ "atan",
+ "ceil",
+ "cos",
+ "exp",
+ "floor",
+ "log",
+ "round",
+ "sin",
+ "sqrt",
+ "tan"
+]
+;(function() {
+ for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]},
+ post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
+ funcName: "norminf"
+})
+
+exports.norm1 = compile({
+ args:["array"],
+ pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
+ body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]},
+ post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
+ funcName: "norm1"
+})
+
+exports.sup = compile({
+ args: [ "array" ],
+ pre:
+ { body: "this_h=-Infinity",
+ args: [],
+ thisVars: [ "this_h" ],
+ localVars: [] },
+ body:
+ { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",
+ args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
+ thisVars: [ "this_h" ],
+ localVars: [] },
+ post:
+ { body: "return this_h",
+ args: [],
+ thisVars: [ "this_h" ],
+ localVars: [] }
+ })
+
+exports.inf = compile({
+ args: [ "array" ],
+ pre:
+ { body: "this_h=Infinity",
+ args: [],
+ thisVars: [ "this_h" ],
+ localVars: [] },
+ body:
+ { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
+ args:[
+ {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
+ {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
+ thisVars:["this_i","this_v"],
+ localVars:["_inline_1_k"]},
+ post:{
+ body:"{return this_i}",
+ args:[],
+ thisVars:["this_i"],
+ localVars:[]}
+})
+
+exports.random = makeOp({
+ args: ["array"],
+ pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]},
+ body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]},
+ funcName: "random"
+})
+
+exports.assign = makeOp({
+ args:["array", "array"],
+ body: {args:["a", "b"], body:"a=b"},
+ funcName: "assign" })
+
+exports.assigns = makeOp({
+ args:["array", "scalar"],
+ body: {args:["a", "b"], body:"a=b"},
+ funcName: "assigns" })
+
+
+exports.equals = compile({
+ args:["array", "array"],
+ pre: EmptyProc,
+ body: {args:[{name:"x", lvalue:false, rvalue:true, count:1},
+ {name:"y", lvalue:false, rvalue:true, count:1}],
+ body: "if(x!==y){return false}",
+ localVars: [],
+ thisVars: []},
+ post: {args:[], localVars:[], thisVars:[], body:"return true"},
+ funcName: "equals"
+})
+
+
+
+},{"cwise-compiler":17}],17:[function(require,module,exports){
+"use strict"
+
+var createThunk = require("./lib/thunk.js")
+
+function Procedure() {
+ this.argTypes = []
+ this.shimArgs = []
+ this.arrayArgs = []
+ this.scalarArgs = []
+ this.offsetArgs = []
+ this.offsetArgIndex = []
+ this.indexArgs = []
+ this.shapeArgs = []
+ this.funcName = ""
+ this.pre = null
+ this.body = null
+ this.post = null
+ this.debug = false
+}
+
+function compileCwise(user_args) {
+ //Create procedure
+ var proc = new Procedure()
+
+ //Parse blocks
+ proc.pre = user_args.pre
+ proc.body = user_args.body
+ proc.post = user_args.post
+
+ //Parse arguments
+ var proc_args = user_args.args.slice(0)
+ proc.argTypes = proc_args
+ for(var i=0; i0) {
+ throw new Error("cwise: pre() block may not reference array args")
+ }
+ if(i < proc.post.args.length && proc.post.args[i].count>0) {
+ throw new Error("cwise: post() block may not reference array args")
+ }
+ } else if(arg_type === "scalar") {
+ proc.scalarArgs.push(i)
+ proc.shimArgs.push("scalar" + i)
+ } else if(arg_type === "index") {
+ proc.indexArgs.push(i)
+ if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {
+ throw new Error("cwise: pre() block may not reference array index")
+ }
+ if(i < proc.body.args.length && proc.body.args[i].lvalue) {
+ throw new Error("cwise: body() block may not write to array index")
+ }
+ if(i < proc.post.args.length && proc.post.args[i].count > 0) {
+ throw new Error("cwise: post() block may not reference array index")
+ }
+ } else if(arg_type === "shape") {
+ proc.shapeArgs.push(i)
+ if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {
+ throw new Error("cwise: pre() block may not write to array shape")
+ }
+ if(i < proc.body.args.length && proc.body.args[i].lvalue) {
+ throw new Error("cwise: body() block may not write to array shape")
+ }
+ if(i < proc.post.args.length && proc.post.args[i].lvalue) {
+ throw new Error("cwise: post() block may not write to array shape")
+ }
+ } else if(typeof arg_type === "object" && arg_type.offset) {
+ proc.argTypes[i] = "offset"
+ proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })
+ proc.offsetArgIndex.push(i)
+ } else {
+ throw new Error("cwise: Unknown argument type " + proc_args[i])
+ }
+ }
+
+ //Make sure at least one array argument was specified
+ if(proc.arrayArgs.length <= 0) {
+ throw new Error("cwise: No array arguments specified")
+ }
+
+ //Make sure arguments are correct
+ if(proc.pre.args.length > proc_args.length) {
+ throw new Error("cwise: Too many arguments in pre() block")
+ }
+ if(proc.body.args.length > proc_args.length) {
+ throw new Error("cwise: Too many arguments in body() block")
+ }
+ if(proc.post.args.length > proc_args.length) {
+ throw new Error("cwise: Too many arguments in post() block")
+ }
+
+ //Check debug flag
+ proc.debug = !!user_args.printCode || !!user_args.debug
+
+ //Retrieve name
+ proc.funcName = user_args.funcName || "cwise"
+
+ //Read in block size
+ proc.blockSize = user_args.blockSize || 64
+
+ return createThunk(proc)
+}
+
+module.exports = compileCwise
+
+},{"./lib/thunk.js":19}],18:[function(require,module,exports){
+"use strict"
+
+var uniq = require("uniq")
+
+function innerFill(order, proc, body) {
+ var dimension = order.length
+ , nargs = proc.arrayArgs.length
+ , has_index = proc.indexArgs.length>0
+ , code = []
+ , vars = []
+ , idx=0, pidx=0, i, j
+ for(i=0; i=0; --i) {
+ idx = order[i]
+ code.push(["for(i",i,"=0;i",i," 0) {
+ code.push(["index[",pidx,"]-=s",pidx].join(""))
+ }
+ code.push(["++index[",idx,"]"].join(""))
+ }
+ code.push("}")
+ }
+ return code.join("\n")
+}
+
+function outerFill(matched, order, proc, body) {
+ var dimension = order.length
+ , nargs = proc.arrayArgs.length
+ , blockSize = proc.blockSize
+ , has_index = proc.indexArgs.length > 0
+ , code = []
+ for(var i=0; i0;){"].join(""))
+ code.push(["if(j",i,"<",blockSize,"){"].join(""))
+ code.push(["s",order[i],"=j",i].join(""))
+ code.push(["j",i,"=0"].join(""))
+ code.push(["}else{s",order[i],"=",blockSize].join(""))
+ code.push(["j",i,"-=",blockSize,"}"].join(""))
+ if(has_index) {
+ code.push(["index[",order[i],"]=j",i].join(""))
+ }
+ }
+ for(var i=0; i 0) {
+ allEqual = allEqual && summary[i] === summary[i-1]
+ }
+ }
+ if(allEqual) {
+ return summary[0]
+ }
+ return summary.join("")
+}
+
+//Generates a cwise operator
+function generateCWiseOp(proc, typesig) {
+
+ //Compute dimension
+ var dimension = typesig[1].length|0
+ var orders = new Array(proc.arrayArgs.length)
+ var dtypes = new Array(proc.arrayArgs.length)
+
+ //First create arguments for procedure
+ var arglist = ["SS"]
+ var code = ["'use strict'"]
+ var vars = []
+
+ for(var j=0; j 0) {
+ vars.push("shape=SS.slice(0)")
+ }
+ if(proc.indexArgs.length > 0) {
+ var zeros = new Array(dimension)
+ for(var i=0; i 3) {
+ code.push(processBlock(proc.pre, proc, dtypes))
+ }
+
+ //Process body
+ var body = processBlock(proc.body, proc, dtypes)
+ var matched = countMatches(orders)
+ if(matched < dimension) {
+ code.push(outerFill(matched, orders[0], proc, body))
+ } else {
+ code.push(innerFill(orders[0], proc, body))
+ }
+
+ //Inline epilog
+ if(proc.post.body.length > 3) {
+ code.push(processBlock(proc.post, proc, dtypes))
+ }
+
+ if(proc.debug) {
+ console.log("Generated cwise routine for ", typesig, ":\n\n", code.join("\n"))
+ }
+
+ var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("")
+ var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join(""))
+ return f()
+}
+module.exports = generateCWiseOp
+},{"uniq":20}],19:[function(require,module,exports){
+"use strict"
+
+var compile = require("./compile.js")
+
+function createThunk(proc) {
+ var code = ["'use strict'", "var CACHED={}"]
+ var vars = []
+ var thunkName = proc.funcName + "_cwise_thunk"
+
+ //Build thunk
+ code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join(""))
+ var typesig = []
+ var string_typesig = []
+ var proc_args = [["array",proc.arrayArgs[0],".shape"].join("")]
+ for(var i=0; iMath.abs(this._stride1))?[1,0]:[0,1]}})")
+ } else if(dimension === 3) {
+ code.push(
+"var s0=Math.abs(this._stride0),s1=Math.abs(this._stride1),s2=Math.abs(this._stride2);\
+if(s0>s1){\
+if(s1>s2){\
+return [2,1,0];\
+}else if(s0>s2){\
+return [1,2,0];\
+}else{\
+return [1,0,2];\
+}\
+}else if(s0>s2){\
+return [2,0,1];\
+}else if(s2>s1){\
+return [0,1,2];\
+}else{\
+return [0,2,1];\
+}}})")
+ }
+ } else {
+ code.push("ORDER})")
+ }
+ }
+
+ //view.set(i0, ..., v):
+ code.push(
+"proto.set=function "+className+"_set("+args.join(",")+",v){")
+ if(useGetters) {
+ code.push("return this.data.set("+index_str+",v)}")
+ } else {
+ code.push("return this.data["+index_str+"]=v}")
+ }
+
+ //view.get(i0, ...):
+ code.push("proto.get=function "+className+"_get("+args.join(",")+"){")
+ if(useGetters) {
+ code.push("return this.data.get("+index_str+")}")
+ } else {
+ code.push("return this.data["+index_str+"]}")
+ }
+
+ //view.index:
+ code.push(
+ "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}")
+
+ //view.hi():
+ code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
+ indices.map(function(i) {
+ return ["(typeof i",i,"!=='number'||i",i,"<0)?this._shape", i, ":i", i,"|0"].join("")
+ }).join(",")+","+
+ indices.map(function(i) {
+ return "this._stride"+i
+ }).join(",")+",this.offset)}")
+
+ //view.lo():
+ var a_vars = indices.map(function(i) { return "a"+i+"=this._shape"+i })
+ var c_vars = indices.map(function(i) { return "c"+i+"=this._stride"+i })
+ code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","))
+ for(var i=0; i=0){\
+d=i"+i+"|0;\
+b+=c"+i+"*d;\
+a"+i+"-=d}")
+ }
+ code.push("return new "+className+"(this.data,"+
+ indices.map(function(i) {
+ return "a"+i
+ }).join(",")+","+
+ indices.map(function(i) {
+ return "c"+i
+ }).join(",")+",b)}")
+
+ //view.step():
+ code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
+ indices.map(function(i) {
+ return "a"+i+"=this._shape"+i
+ }).join(",")+","+
+ indices.map(function(i) {
+ return "b"+i+"=this._stride"+i
+ }).join(",")+",c=this.offset,d=0,ceil=Math.ceil")
+ for(var i=0; i=0){c=(c+this._stride"+i+"*i"+i+")|0}else{a.push(this._shape"+i+");b.push(this._stride"+i+")}")
+ }
+ code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}")
+
+ //Add return statement
+ code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
+ indices.map(function(i) {
+ return "shape["+i+"]"
+ }).join(",")+","+
+ indices.map(function(i) {
+ return "stride["+i+"]"
+ }).join(",")+",offset)}")
+
+ //Compile procedure
+ var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"))
+ return procedure(CACHED_CONSTRUCTORS[dtype], order)
+}
+
+function arrayDType(data) {
+ if(hasBuffer) {
+ if(Buffer.isBuffer(data)) {
+ return "buffer"
+ }
+ }
+ if(hasTypedArrays) {
+ switch(Object.prototype.toString.call(data)) {
+ case "[object Float64Array]":
+ return "float64"
+ case "[object Float32Array]":
+ return "float32"
+ case "[object Int8Array]":
+ return "int8"
+ case "[object Int16Array]":
+ return "int16"
+ case "[object Int32Array]":
+ return "int32"
+ case "[object Uint8Array]":
+ return "uint8"
+ case "[object Uint16Array]":
+ return "uint16"
+ case "[object Uint32Array]":
+ return "uint32"
+ case "[object Uint8ClampedArray]":
+ return "uint8_clamped"
+ }
+ }
+ if(Array.isArray(data)) {
+ return "array"
+ }
+ return "generic"
+}
+
+var CACHED_CONSTRUCTORS = {
+ "float32":[],
+ "float64":[],
+ "int8":[],
+ "int16":[],
+ "int32":[],
+ "uint8":[],
+ "uint16":[],
+ "uint32":[],
+ "array":[],
+ "uint8_clamped":[],
+ "buffer":[],
+ "generic":[]
+}
+
+;(function() {
+ for(var id in CACHED_CONSTRUCTORS) {
+ CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))
+ }
+});
+
+function wrappedNDArrayCtor(data, shape, stride, offset) {
+ if(data === undefined) {
+ var ctor = CACHED_CONSTRUCTORS.array[0]
+ return ctor([])
+ } else if(typeof data === "number") {
+ data = [data]
+ }
+ if(shape === undefined) {
+ shape = [ data.length ]
+ }
+ var d = shape.length
+ if(stride === undefined) {
+ stride = new Array(d)
+ for(var i=d-1, sz=1; i>=0; --i) {
+ stride[i] = sz
+ sz *= shape[i]
+ }
+ }
+ if(offset === undefined) {
+ offset = 0
+ for(var i=0; i 0) - (v < 0);
+}
+
+//Computes absolute value of integer
+exports.abs = function(v) {
+ var mask = v >> (INT_BITS-1);
+ return (v ^ mask) - mask;
+}
+
+//Computes minimum of integers x and y
+exports.min = function(x, y) {
+ return y ^ ((x ^ y) & -(x < y));
+}
+
+//Computes maximum of integers x and y
+exports.max = function(x, y) {
+ return x ^ ((x ^ y) & -(x < y));
+}
+
+//Checks if a number is a power of two
+exports.isPow2 = function(v) {
+ return !(v & (v-1)) && (!!v);
+}
+
+//Computes log base 2 of v
+exports.log2 = function(v) {
+ var r, shift;
+ r = (v > 0xFFFF) << 4; v >>>= r;
+ shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift;
+ shift = (v > 0xF ) << 2; v >>>= shift; r |= shift;
+ shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift;
+ return r | (v >> 1);
+}
+
+//Computes log base 10 of v
+exports.log10 = function(v) {
+ return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
+ (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
+ (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
+}
+
+//Counts number of bits
+exports.popCount = function(v) {
+ v = v - ((v >>> 1) & 0x55555555);
+ v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
+ return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;
+}
+
+//Counts number of trailing zeros
+function countTrailingZeros(v) {
+ var c = 32;
+ v &= -v;
+ if (v) c--;
+ if (v & 0x0000FFFF) c -= 16;
+ if (v & 0x00FF00FF) c -= 8;
+ if (v & 0x0F0F0F0F) c -= 4;
+ if (v & 0x33333333) c -= 2;
+ if (v & 0x55555555) c -= 1;
+ return c;
+}
+exports.countTrailingZeros = countTrailingZeros;
+
+//Rounds to next power of 2
+exports.nextPow2 = function(v) {
+ v += v === 0;
+ --v;
+ v |= v >>> 1;
+ v |= v >>> 2;
+ v |= v >>> 4;
+ v |= v >>> 8;
+ v |= v >>> 16;
+ return v + 1;
+}
+
+//Rounds down to previous power of 2
+exports.prevPow2 = function(v) {
+ v |= v >>> 1;
+ v |= v >>> 2;
+ v |= v >>> 4;
+ v |= v >>> 8;
+ v |= v >>> 16;
+ return v - (v>>>1);
+}
+
+//Computes parity of word
+exports.parity = function(v) {
+ v ^= v >>> 16;
+ v ^= v >>> 8;
+ v ^= v >>> 4;
+ v &= 0xf;
+ return (0x6996 >>> v) & 1;
+}
+
+var REVERSE_TABLE = new Array(256);
+
+(function(tab) {
+ for(var i=0; i<256; ++i) {
+ var v = i, r = i, s = 7;
+ for (v >>>= 1; v; v >>>= 1) {
+ r <<= 1;
+ r |= v & 1;
+ --s;
+ }
+ tab[i] = (r << s) & 0xff;
+ }
+})(REVERSE_TABLE);
+
+//Reverse bits in a 32 bit word
+exports.reverse = function(v) {
+ return (REVERSE_TABLE[ v & 0xff] << 24) |
+ (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) |
+ (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) |
+ REVERSE_TABLE[(v >>> 24) & 0xff];
+}
+
+//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes
+exports.interleave2 = function(x, y) {
+ x &= 0xFFFF;
+ x = (x | (x << 8)) & 0x00FF00FF;
+ x = (x | (x << 4)) & 0x0F0F0F0F;
+ x = (x | (x << 2)) & 0x33333333;
+ x = (x | (x << 1)) & 0x55555555;
+
+ y &= 0xFFFF;
+ y = (y | (y << 8)) & 0x00FF00FF;
+ y = (y | (y << 4)) & 0x0F0F0F0F;
+ y = (y | (y << 2)) & 0x33333333;
+ y = (y | (y << 1)) & 0x55555555;
+
+ return x | (y << 1);
+}
+
+//Extracts the nth interleaved component
+exports.deinterleave2 = function(v, n) {
+ v = (v >>> n) & 0x55555555;
+ v = (v | (v >>> 1)) & 0x33333333;
+ v = (v | (v >>> 2)) & 0x0F0F0F0F;
+ v = (v | (v >>> 4)) & 0x00FF00FF;
+ v = (v | (v >>> 16)) & 0x000FFFF;
+ return (v << 16) >> 16;
+}
+
+
+//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes
+exports.interleave3 = function(x, y, z) {
+ x &= 0x3FF;
+ x = (x | (x<<16)) & 4278190335;
+ x = (x | (x<<8)) & 251719695;
+ x = (x | (x<<4)) & 3272356035;
+ x = (x | (x<<2)) & 1227133513;
+
+ y &= 0x3FF;
+ y = (y | (y<<16)) & 4278190335;
+ y = (y | (y<<8)) & 251719695;
+ y = (y | (y<<4)) & 3272356035;
+ y = (y | (y<<2)) & 1227133513;
+ x |= (y << 1);
+
+ z &= 0x3FF;
+ z = (z | (z<<16)) & 4278190335;
+ z = (z | (z<<8)) & 251719695;
+ z = (z | (z<<4)) & 3272356035;
+ z = (z | (z<<2)) & 1227133513;
+
+ return x | (z << 2);
+}
+
+//Extracts nth interleaved component of a 3-tuple
+exports.deinterleave3 = function(v, n) {
+ v = (v >>> n) & 1227133513;
+ v = (v | (v>>>2)) & 3272356035;
+ v = (v | (v>>>4)) & 251719695;
+ v = (v | (v>>>8)) & 4278190335;
+ v = (v | (v>>>16)) & 0x3FF;
+ return (v<<22)>>22;
+}
+
+//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
+exports.nextCombination = function(v) {
+ var t = v | (v - 1);
+ return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1));
+}
+
+
+},{}],24:[function(require,module,exports){
+"use strict"
+
+function dupe_array(count, value, i) {
+ var c = count[i]|0
+ if(c <= 0) {
+ return []
+ }
+ var result = new Array(c), j
+ if(i === count.length-1) {
+ for(j=0; j 0) {
+ return dupe_number(count|0, value)
+ }
+ break
+ case "object":
+ if(typeof (count.length) === "number") {
+ return dupe_array(count, value, 0)
+ }
+ break
+ }
+ return []
+}
+
+module.exports = dupe
+},{}],25:[function(require,module,exports){
+(function (global){
+"use strict"
+
+var bits = require("bit-twiddle")
+var dup = require("dup")
+if(!global.__TYPEDARRAY_POOL) {
+ global.__TYPEDARRAY_POOL = {
+ UINT8 : dup([32, 0])
+ , UINT16 : dup([32, 0])
+ , UINT32 : dup([32, 0])
+ , INT8 : dup([32, 0])
+ , INT16 : dup([32, 0])
+ , INT32 : dup([32, 0])
+ , FLOAT : dup([32, 0])
+ , DOUBLE : dup([32, 0])
+ , DATA : dup([32, 0])
+ }
+}
+var POOL = global.__TYPEDARRAY_POOL
+var UINT8 = POOL.UINT8
+ , UINT16 = POOL.UINT16
+ , UINT32 = POOL.UINT32
+ , INT8 = POOL.INT8
+ , INT16 = POOL.INT16
+ , INT32 = POOL.INT32
+ , FLOAT = POOL.FLOAT
+ , DOUBLE = POOL.DOUBLE
+ , DATA = POOL.DATA
+
+exports.free = function free(array) {
+ if(array instanceof ArrayBuffer) {
+ var n = array.byteLength|0
+ , log_n = bits.log2(n)
+ DATA[log_n].push(array)
+ } else {
+ var n = array.length|0
+ , log_n = bits.log2(n)
+ if(array instanceof Uint8Array) {
+ UINT8[log_n].push(array)
+ } else if(array instanceof Uint16Array) {
+ UINT16[log_n].push(array)
+ } else if(array instanceof Uint32Array) {
+ UINT32[log_n].push(array)
+ } else if(array instanceof Int8Array) {
+ INT8[log_n].push(array)
+ } else if(array instanceof Int16Array) {
+ INT16[log_n].push(array)
+ } else if(array instanceof Int32Array) {
+ INT32[log_n].push(array)
+ } else if(array instanceof Float32Array) {
+ FLOAT[log_n].push(array)
+ } else if(array instanceof Float64Array) {
+ DOUBLE[log_n].push(array)
+ }
+ }
+}
+
+exports.freeUint8 = function freeUint8(array) {
+ UINT8[bits.log2(array.length)].push(array)
+}
+
+exports.freeUint16 = function freeUint16(array) {
+ UINT16[bits.log2(array.length)].push(array)
+}
+
+exports.freeUint32 = function freeUint32(array) {
+ UINT32[bits.log2(array.length)].push(array)
+}
+
+exports.freeInt8 = function freeInt8(array) {
+ INT8[bits.log2(array.length)].push(array)
+}
+
+exports.freeInt16 = function freeInt16(array) {
+ INT16[bits.log2(array.length)].push(array)
+}
+
+exports.freeInt32 = function freeInt32(array) {
+ INT32[bits.log2(array.length)].push(array)
+}
+
+exports.freeFloat32 = exports.freeFloat = function freeFloat(array) {
+ FLOAT[bits.log2(array.length)].push(array)
+}
+
+exports.freeFloat64 = exports.freeDouble = function freeDouble(array) {
+ DOUBLE[bits.log2(array.length)].push(array)
+}
+
+exports.freeArrayBuffer = function freeArrayBuffer(array) {
+ DATA[bits.log2(array.length)].push(array)
+}
+
+exports.malloc = function malloc(n, dtype) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ if(dtype === undefined) {
+ var d = DATA[log_n]
+ if(d.length > 0) {
+ var r = d[d.length-1]
+ d.pop()
+ return r
+ }
+ return new ArrayBuffer(n)
+ } else {
+ switch(dtype) {
+ case "uint8":
+ var u8 = UINT8[log_n]
+ if(u8.length > 0) {
+ return u8.pop()
+ }
+ return new Uint8Array(n)
+ break
+
+ case "uint16":
+ var u16 = UINT16[log_n]
+ if(u16.length > 0) {
+ return u16.pop()
+ }
+ return new Uint16Array(n)
+ break
+
+ case "uint32":
+ var u32 = UINT32[log_n]
+ if(u32.length > 0) {
+ return u32.pop()
+ }
+ return new Uint32Array(n)
+ break
+
+ case "int8":
+ var i8 = INT8[log_n]
+ if(i8.length > 0) {
+ return i8.pop()
+ }
+ return new Int8Array(n)
+ break
+
+ case "int16":
+ var i16 = INT16[log_n]
+ if(i16.length > 0) {
+ return i16.pop()
+ }
+ return new Int16Array(n)
+ break
+
+ case "int32":
+ var i32 = INT32[log_n]
+ if(i32.length > 0) {
+ return i32.pop()
+ }
+ return new Int32Array(n)
+ break
+
+ case "float":
+ case "float32":
+ var f = FLOAT[log_n]
+ if(f.length > 0) {
+ return f.pop()
+ }
+ return new Float32Array(n)
+ break
+
+ case "double":
+ case "float64":
+ var dd = DOUBLE[log_n]
+ if(dd.length > 0) {
+ return dd.pop()
+ }
+ return new Float64Array(n)
+ break
+
+ default:
+ return null
+ }
+ }
+ return null
+}
+
+exports.mallocUint8 = function mallocUint8(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = UINT8[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Uint8Array(n)
+}
+
+exports.mallocUint16 = function mallocUint16(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = UINT16[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Uint16Array(n)
+}
+
+exports.mallocUint32 = function mallocUint32(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = UINT32[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Uint32Array(n)
+}
+
+exports.mallocInt8 = function mallocInt8(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = INT8[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Int8Array(n)
+}
+
+exports.mallocInt16 = function mallocInt16(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = INT16[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Int16Array(n)
+}
+
+exports.mallocInt32 = function mallocInt32(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = INT32[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Int32Array(n)
+}
+
+exports.mallocFloat32 = exports.mallocFloat = function mallocFloat(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = FLOAT[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Float32Array(n)
+}
+
+exports.mallocFloat64 = exports.mallocDouble = function mallocDouble(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = DOUBLE[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Float64Array(n)
+}
+
+exports.mallocArrayBuffer = function mallocArrayBuffer(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = DATA[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new ArrayBuffer(n)
+}
+
+exports.clearCache = function clearCache() {
+ for(var i=0; i<32; ++i) {
+ UINT8[i].length = 0
+ UINT16[i].length = 0
+ UINT32[i].length = 0
+ INT8[i].length = 0
+ INT16[i].length = 0
+ INT32[i].length = 0
+ FLOAT[i].length = 0
+ DOUBLE[i].length = 0
+ DATA[i].length = 0
+ }
+}
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"bit-twiddle":23,"dup":24}],26:[function(require,module,exports){
+"use strict"
+
+function doBind(gl, elements, attributes) {
+ if(elements) {
+ elements.bind()
+ } else {
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
+ }
+ var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0
+ if(attributes) {
+ if(attributes.length > nattribs) {
+ throw new Error("Too many vertex attributes")
+ }
+ for(var i=0; i 1) {
+ ext.drawBuffersWEBGL(colorAttachmentArrays[numColor])
+ }
+
+ //Allocate depth/stencil buffers
+ if(extensions.WEBGL_depth_texture) {
+ if(useStencil) {
+ fbo.depth = initTexture(gl, width, height,
+ extensions.WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL,
+ gl.DEPTH_STENCIL,
+ gl.DEPTH_STENCIL_ATTACHMENT)
+ } else if(useDepth) {
+ fbo.depth = initTexture(gl, width, height,
+ gl.UNSIGNED_SHORT,
+ gl.DEPTH_COMPONENT,
+ gl.DEPTH_ATTACHMENT)
+ }
+ } else {
+ if(useDepth && useStencil) {
+ fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT)
+ } else if(useDepth) {
+ fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT)
+ } else if(useStencil) {
+ fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT)
+ }
+ }
+
+ //Check frame buffer state
+ var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)
+ if(status !== gl.FRAMEBUFFER_COMPLETE) {
+
+ //Release all partially allocated resources
+ fbo._destroyed = true
+
+ //Release all resources
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+ gl.deleteFramebuffer(fbo.handle)
+ fbo.handle = null
+ if(fbo.depth) {
+ fbo.depth.dispose()
+ fbo.depth = null
+ }
+ if(fbo._depth_rb) {
+ gl.deleteRenderbuffer(fbo._depth_rb)
+ fbo._depth_rb = null
+ }
+ for(var i=0; i maxFBOSize ||
+ x[1] < 0 || x[1] > maxFBOSize) {
+ throw new Error("gl-fbo: Can't resize FBO, invalid dimensions")
+ }
+
+ //Update shape
+ this._shape[0] = x[0]|0
+ this._shape[1] = x[1]|0
+
+ //Resize framebuffer attachments
+ for(var i=0; i maxFBOSize || height < 0 || height > maxFBOSize) {
+ throw new Error("gl-fbo: Parameters are too large for FBO")
+ }
+
+ //Handle each option type
+ options = options || {}
+
+ //Figure out number of color buffers to use
+ var numColors = 1
+ if("color" in options) {
+ numColors = Math.max(options.color|0, 0)
+ if(numColors < 0) {
+ throw new Error("gl-fbo: Must specify a nonnegative number of colors")
+ }
+ if(numColors > 1) {
+ //Check if multiple render targets supported
+ var mrtext = extensions.WEBGL_draw_buffers
+ if(!mrtext) {
+ throw new Error("gl-fbo: Multiple draw buffer extension not supported")
+ } else if(numColors > gl.getParameter(mrtext.MAX_COLOR_ATTACHMENTS_WEBGL)) {
+ throw new Error("gl-fbo: Context does not support " + numColors + " draw buffers")
+ }
+ }
+ }
+
+ //Determine whether to use floating point textures
+ var colorType = gl.UNSIGNED_BYTE
+ if(options.float && numColors > 0) {
+ if(!extensions.OES_texture_float) {
+ throw new Error("gl-fbo: Context does not support floating point textures")
+ }
+ colorType = gl.FLOAT
+ } else if(options.preferFloat && numColors > 0) {
+ if(extensions.OES_texture_float) {
+ colorType = gl.FLOAT
+ }
+ }
+
+ //Check if we should use depth buffer
+ var useDepth = true
+ if("depth" in options) {
+ useDepth = !!options.depth
+ }
+
+ //Check if we should use a stencil buffer
+ var useStencil = false
+ if("stencil" in options) {
+ useStencil = !!options.stencil
+ }
+
+ return new Framebuffer(
+ gl,
+ width,
+ height,
+ colorType,
+ numColors,
+ useDepth,
+ useStencil,
+ extensions.WEBGL_draw_buffers)
+}
+},{"gl-texture2d":88,"webglew":49}],48:[function(require,module,exports){
+/* (The MIT License)
+ *
+ * Copyright (c) 2012 Brandon Benvie
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+ * associated documentation files (the 'Software'), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included with all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+// Original WeakMap implementation by Gozala @ https://gist.github.com/1269991
+// Updated and bugfixed by Raynos @ https://gist.github.com/1638059
+// Expanded by Benvie @ https://github.com/Benvie/harmony-collections
+
+void function(global, undefined_, undefined){
+ var getProps = Object.getOwnPropertyNames,
+ defProp = Object.defineProperty,
+ toSource = Function.prototype.toString,
+ create = Object.create,
+ hasOwn = Object.prototype.hasOwnProperty,
+ funcName = /^\n?function\s?(\w*)?_?\(/;
+
+
+ function define(object, key, value){
+ if (typeof key === 'function') {
+ value = key;
+ key = nameOf(value).replace(/_$/, '');
+ }
+ return defProp(object, key, { configurable: true, writable: true, value: value });
+ }
+
+ function nameOf(func){
+ return typeof func !== 'function'
+ ? '' : 'name' in func
+ ? func.name : toSource.call(func).match(funcName)[1];
+ }
+
+ // ############
+ // ### Data ###
+ // ############
+
+ var Data = (function(){
+ var dataDesc = { value: { writable: true, value: undefined } },
+ datalock = 'return function(k){if(k===s)return l}',
+ uids = create(null),
+
+ createUID = function(){
+ var key = Math.random().toString(36).slice(2);
+ return key in uids ? createUID() : uids[key] = key;
+ },
+
+ globalID = createUID(),
+
+ storage = function(obj){
+ if (hasOwn.call(obj, globalID))
+ return obj[globalID];
+
+ if (!Object.isExtensible(obj))
+ throw new TypeError("Object must be extensible");
+
+ var store = create(null);
+ defProp(obj, globalID, { value: store });
+ return store;
+ };
+
+ // common per-object storage area made visible by patching getOwnPropertyNames'
+ define(Object, function getOwnPropertyNames(obj){
+ var props = getProps(obj);
+ if (hasOwn.call(obj, globalID))
+ props.splice(props.indexOf(globalID), 1);
+ return props;
+ });
+
+ function Data(){
+ var puid = createUID(),
+ secret = {};
+
+ this.unlock = function(obj){
+ var store = storage(obj);
+ if (hasOwn.call(store, puid))
+ return store[puid](secret);
+
+ var data = create(null, dataDesc);
+ defProp(store, puid, {
+ value: new Function('s', 'l', datalock)(secret, data)
+ });
+ return data;
+ }
+ }
+
+ define(Data.prototype, function get(o){ return this.unlock(o).value });
+ define(Data.prototype, function set(o, v){ this.unlock(o).value = v });
+
+ return Data;
+ }());
+
+
+ var WM = (function(data){
+ var validate = function(key){
+ if (key == null || typeof key !== 'object' && typeof key !== 'function')
+ throw new TypeError("Invalid WeakMap key");
+ }
+
+ var wrap = function(collection, value){
+ var store = data.unlock(collection);
+ if (store.value)
+ throw new TypeError("Object is already a WeakMap");
+ store.value = value;
+ }
+
+ var unwrap = function(collection){
+ var storage = data.unlock(collection).value;
+ if (!storage)
+ throw new TypeError("WeakMap is not generic");
+ return storage;
+ }
+
+ var initialize = function(weakmap, iterable){
+ if (iterable !== null && typeof iterable === 'object' && typeof iterable.forEach === 'function') {
+ iterable.forEach(function(item, i){
+ if (item instanceof Array && item.length === 2)
+ set.call(weakmap, iterable[i][0], iterable[i][1]);
+ });
+ }
+ }
+
+
+ function WeakMap(iterable){
+ if (this === global || this == null || this === WeakMap.prototype)
+ return new WeakMap(iterable);
+
+ wrap(this, new Data);
+ initialize(this, iterable);
+ }
+
+ function get(key){
+ validate(key);
+ var value = unwrap(this).get(key);
+ return value === undefined_ ? undefined : value;
+ }
+
+ function set(key, value){
+ validate(key);
+ // store a token for explicit undefined so that "has" works correctly
+ unwrap(this).set(key, value === undefined ? undefined_ : value);
+ }
+
+ function has(key){
+ validate(key);
+ return unwrap(this).get(key) !== undefined;
+ }
+
+ function delete_(key){
+ validate(key);
+ var data = unwrap(this),
+ had = data.get(key) !== undefined;
+ data.set(key, undefined);
+ return had;
+ }
+
+ function toString(){
+ unwrap(this);
+ return '[object WeakMap]';
+ }
+
+ try {
+ var src = ('return '+delete_).replace('e_', '\\u0065'),
+ del = new Function('unwrap', 'validate', src)(unwrap, validate);
+ } catch (e) {
+ var del = delete_;
+ }
+
+ var src = (''+Object).split('Object');
+ var stringifier = function toString(){
+ return src[0] + nameOf(this) + src[1];
+ };
+
+ define(stringifier, stringifier);
+
+ var prep = { __proto__: [] } instanceof Array
+ ? function(f){ f.__proto__ = stringifier }
+ : function(f){ define(f, stringifier) };
+
+ prep(WeakMap);
+
+ [toString, get, set, has, del].forEach(function(method){
+ define(WeakMap.prototype, method);
+ prep(method);
+ });
+
+ return WeakMap;
+ }(new Data));
+
+ var defaultCreator = Object.create
+ ? function(){ return Object.create(null) }
+ : function(){ return {} };
+
+ function createStorage(creator){
+ var weakmap = new WM;
+ creator || (creator = defaultCreator);
+
+ function storage(object, value){
+ if (value || arguments.length === 2) {
+ weakmap.set(object, value);
+ } else {
+ value = weakmap.get(object);
+ if (value === undefined) {
+ value = creator(object);
+ weakmap.set(object, value);
+ }
+ }
+ return value;
+ }
+
+ return storage;
+ }
+
+
+ if (typeof module !== 'undefined') {
+ module.exports = WM;
+ } else if (typeof exports !== 'undefined') {
+ exports.WeakMap = WM;
+ } else if (!('WeakMap' in global)) {
+ global.WeakMap = WM;
+ }
+
+ WM.createStorage = createStorage;
+ if (global.WeakMap)
+ global.WeakMap.createStorage = createStorage;
+}((0, eval)('this'));
+
+},{}],49:[function(require,module,exports){
+"use strict";
+
+var weakMap = typeof WeakMap === "undefined" ? require("weakmap") : WeakMap
+
+var WebGLEWStruct = new weakMap()
+
+function baseName(ext_name) {
+ return ext_name.replace(/^[A-Z]+_/, "")
+}
+
+function initWebGLEW(gl) {
+ var struct = WebGLEWStruct.get(gl)
+ if(struct) {
+ return struct
+ }
+ var extensions = {}
+ var supported = gl.getSupportedExtensions()
+ for(var i=0; i len) {
+ throw new Error("gl-buffer: If resizing buffer, must not specify offset")
+ }
+ gl.bufferSubData(type, offset, data)
+ return len
+}
+
+function makeScratchTypeArray(array, dtype) {
+ var res = pool.malloc(array.length, dtype)
+ var n = array.length
+ for(var i=0; i=0; --i) {
+ if(stride[i] !== n) {
+ return false
+ }
+ n *= shape[i]
+ }
+ return true
+}
+
+proto.update = function(array, offset) {
+ if(typeof offset !== "number") {
+ offset = -1
+ }
+ this.bind()
+ if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray
+ var dtype = array.dtype
+ if(SUPPORTED_TYPES.indexOf(dtype) < 0) {
+ dtype = "float32"
+ }
+ if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
+ var wgl = webglew(gl)
+ var ext = wgl.OES_element_index_uint
+ if(ext && dtype !== "uint16") {
+ dtype = "uint32"
+ } else {
+ dtype = "uint16"
+ }
+ }
+ if(dtype === array.dtype && isPacked(array.shape, array.stride)) {
+ if(array.offset === 0 && array.data.length === array.shape[0]) {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset)
+ } else {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset)
+ }
+ } else {
+ var tmp = pool.malloc(array.size, dtype)
+ var ndt = ndarray(tmp, array.shape)
+ ops.assign(ndt, array)
+ if(offset < 0) {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset)
+ } else {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset)
+ }
+ pool.free(tmp)
+ }
+ } else if(Array.isArray(array)) { //Vanilla array
+ var t
+ if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
+ t = makeScratchTypeArray(array, "uint16")
+ } else {
+ t = makeScratchTypeArray(array, "float32")
+ }
+ if(offset < 0) {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset)
+ } else {
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
+ }
+ pool.free(t)
+ } else if(typeof array === "object" && typeof array.length === "number") { //Typed array
+ this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset)
+ } else if(typeof array === "number" || array === undefined) { //Number/default
+ if(offset >= 0) {
+ throw new Error("gl-buffer: Cannot specify offset when resizing buffer")
+ }
+ array = array | 0
+ if(array <= 0) {
+ array = 1
+ }
+ this.gl.bufferData(this.type, array|0, this.usage)
+ this.length = array
+ } else { //Error, case should not happen
+ throw new Error("gl-buffer: Invalid data type")
+ }
+}
+
+function createBuffer(gl, data, type, usage) {
+ webglew(gl)
+ type = type || gl.ARRAY_BUFFER
+ usage = usage || gl.DYNAMIC_DRAW
+ if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) {
+ throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER")
+ }
+ if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) {
+ throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW")
+ }
+ var handle = gl.createBuffer()
+ var result = new GLBuffer(gl, type, handle, 0, usage)
+ result.update(data)
+ return result
+}
+
+module.exports = createBuffer
+},{"ndarray":59,"ndarray-ops":54,"typedarray-pool":63,"webglew":65}],54:[function(require,module,exports){
+module.exports=require(16)
+},{"cwise-compiler":55}],55:[function(require,module,exports){
+module.exports=require(17)
+},{"./lib/thunk.js":57}],56:[function(require,module,exports){
+module.exports=require(18)
+},{"uniq":58}],57:[function(require,module,exports){
+module.exports=require(19)
+},{"./compile.js":56}],58:[function(require,module,exports){
+module.exports=require(20)
+},{}],59:[function(require,module,exports){
+module.exports=require(21)
+},{"buffer":106,"iota-array":60}],60:[function(require,module,exports){
+module.exports=require(22)
+},{}],61:[function(require,module,exports){
+module.exports=require(23)
+},{}],62:[function(require,module,exports){
+module.exports=require(24)
+},{}],63:[function(require,module,exports){
+(function (global,Buffer){
+var bits = require("bit-twiddle")
+var dup = require("dup")
+if(!global.__TYPEDARRAY_POOL) {
+ global.__TYPEDARRAY_POOL = {
+ UINT8 : dup([32, 0])
+ , UINT16 : dup([32, 0])
+ , UINT32 : dup([32, 0])
+ , INT8 : dup([32, 0])
+ , INT16 : dup([32, 0])
+ , INT32 : dup([32, 0])
+ , FLOAT : dup([32, 0])
+ , DOUBLE : dup([32, 0])
+ , DATA : dup([32, 0])
+ , UINT8C : dup([32, 0])
+ , BUFFER : dup([32, 0])
+ }
+}
+var hasUint8C = (typeof Uint8ClampedArray) !== "undefined"
+var POOL = global.__TYPEDARRAY_POOL
+if(!POOL.UINT8C) {
+ POOL.UINT8C = dup([32, 0])
+}
+if(!POOL.BUFFER) {
+ POOL.BUFFER = dup([32, 0])
+}
+var UINT8 = POOL.UINT8
+ , UINT16 = POOL.UINT16
+ , UINT32 = POOL.UINT32
+ , INT8 = POOL.INT8
+ , INT16 = POOL.INT16
+ , INT32 = POOL.INT32
+ , FLOAT = POOL.FLOAT
+ , DOUBLE = POOL.DOUBLE
+ , DATA = POOL.DATA
+ , UINT8C = POOL.UINT8C
+ , BUFFER = POOL.BUFFER
+
+exports.free = function free(array) {
+ var n = array.length|0
+ , log_n = bits.log2(n)
+ if(Buffer.isBuffer(array)) {
+ BUFFER[log_n].push(array)
+ } else {
+ switch(Object.prototype.toString.call(array)) {
+ case "[object Uint8Array]":
+ UINT8[log_n].push(array)
+ break
+ case "[object Uint16Array]":
+ UINT16[log_n].push(array)
+ break
+ case "[object Uint32Array]":
+ UINT32[log_n].push(array)
+ break
+ case "[object Int8Array]":
+ INT8[log_n].push(array)
+ break
+ case "[object Int16Array]":
+ INT16[log_n].push(array)
+ break
+ case "[object Int32Array]":
+ INT32[log_n].push(array)
+ break
+ case "[object Uint8ClampedArray]":
+ UINT8C[log_n].push(array)
+ break
+ case "[object Float32Array]":
+ FLOAT[log_n].push(array)
+ break
+ case "[object Float64Array]":
+ DOUBLE[log_n].push(array)
+ break
+ case "[object ArrayBuffer]":
+ DATA[log_n].push(array)
+ break
+ default:
+ throw new Error("typedarray-pool: Unspecified array type")
+ }
+ }
+}
+
+exports.freeUint8 = function freeUint8(array) {
+ UINT8[bits.log2(array.length)].push(array)
+}
+
+exports.freeUint16 = function freeUint16(array) {
+ UINT16[bits.log2(array.length)].push(array)
+}
+
+exports.freeUint32 = function freeUint32(array) {
+ UINT32[bits.log2(array.length)].push(array)
+}
+
+exports.freeInt8 = function freeInt8(array) {
+ INT8[bits.log2(array.length)].push(array)
+}
+
+exports.freeInt16 = function freeInt16(array) {
+ INT16[bits.log2(array.length)].push(array)
+}
+
+exports.freeInt32 = function freeInt32(array) {
+ INT32[bits.log2(array.length)].push(array)
+}
+
+exports.freeFloat32 = exports.freeFloat = function freeFloat(array) {
+ FLOAT[bits.log2(array.length)].push(array)
+}
+
+exports.freeFloat64 = exports.freeDouble = function freeDouble(array) {
+ DOUBLE[bits.log2(array.length)].push(array)
+}
+
+exports.freeArrayBuffer = function freeArrayBuffer(array) {
+ DATA[bits.log2(array.length)].push(array)
+}
+
+if(hasUint8C) {
+ exports.freeUint8Clamped = function freeUint8Clamped(array) {
+ UINT8C[bits.log2(array.length)].push(array)
+ }
+} else {
+ exports.freeUint8Clamped = exports.freeUint8
+}
+
+exports.freeBuffer = function freeBuffer(array) {
+ BUFFER[bits.log2(array.length)].push(array)
+}
+
+exports.malloc = function malloc(n, dtype) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ if(dtype === undefined || dtype === "arraybuffer") {
+ var d = DATA[log_n]
+ if(d.length > 0) {
+ var r = d[d.length-1]
+ d.pop()
+ return r
+ }
+ return new ArrayBuffer(n)
+ } else {
+ switch(dtype) {
+ case "uint8":
+ var u8 = UINT8[log_n]
+ if(u8.length > 0) {
+ return u8.pop()
+ }
+ return new Uint8Array(n)
+ break
+
+ case "uint16":
+ var u16 = UINT16[log_n]
+ if(u16.length > 0) {
+ return u16.pop()
+ }
+ return new Uint16Array(n)
+ break
+
+ case "uint32":
+ var u32 = UINT32[log_n]
+ if(u32.length > 0) {
+ return u32.pop()
+ }
+ return new Uint32Array(n)
+ break
+
+ case "int8":
+ var i8 = INT8[log_n]
+ if(i8.length > 0) {
+ return i8.pop()
+ }
+ return new Int8Array(n)
+ break
+
+ case "int16":
+ var i16 = INT16[log_n]
+ if(i16.length > 0) {
+ return i16.pop()
+ }
+ return new Int16Array(n)
+ break
+
+ case "int32":
+ var i32 = INT32[log_n]
+ if(i32.length > 0) {
+ return i32.pop()
+ }
+ return new Int32Array(n)
+ break
+
+ case "float":
+ case "float32":
+ var f = FLOAT[log_n]
+ if(f.length > 0) {
+ return f.pop()
+ }
+ return new Float32Array(n)
+ break
+
+ case "double":
+ case "float64":
+ var dd = DOUBLE[log_n]
+ if(dd.length > 0) {
+ return dd.pop()
+ }
+ return new Float64Array(n)
+ break
+
+ case "uint8_clamped":
+ if(hasUint8C) {
+ var u8c = UINT8C[log_n]
+ if(u8c.length > 0) {
+ return u8c.pop()
+ }
+ return new Uint8ClampedArray(n)
+ } else {
+ var u8 = UINT8[log_n]
+ if(u8.length > 0) {
+ return u8.pop()
+ }
+ return new Uint8Array(n)
+ }
+ break
+
+ case "buffer":
+ var buf = BUFFER[log_n]
+ if(buf.length > 0) {
+ return buf.pop()
+ }
+ return new Buffer(n)
+ break
+
+ default:
+ return null
+ }
+ }
+ return null
+}
+
+exports.mallocUint8 = function mallocUint8(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = UINT8[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Uint8Array(n)
+}
+
+exports.mallocUint16 = function mallocUint16(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = UINT16[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Uint16Array(n)
+}
+
+exports.mallocUint32 = function mallocUint32(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = UINT32[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Uint32Array(n)
+}
+
+exports.mallocInt8 = function mallocInt8(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = INT8[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Int8Array(n)
+}
+
+exports.mallocInt16 = function mallocInt16(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = INT16[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Int16Array(n)
+}
+
+exports.mallocInt32 = function mallocInt32(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = INT32[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Int32Array(n)
+}
+
+exports.mallocFloat32 = exports.mallocFloat = function mallocFloat(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = FLOAT[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Float32Array(n)
+}
+
+exports.mallocFloat64 = exports.mallocDouble = function mallocDouble(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = DOUBLE[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Float64Array(n)
+}
+
+exports.mallocArrayBuffer = function mallocArrayBuffer(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = DATA[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new ArrayBuffer(n)
+}
+
+if(hasUint8C) {
+ exports.mallocUint8Clamped = function mallocUint8Clamped(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = UINT8C[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Uint8ClampedArray(n)
+ }
+} else {
+ exports.mallocUint8Clamped = exports.mallocUint8
+}
+
+exports.mallocBuffer = function mallocBuffer(n) {
+ n = bits.nextPow2(n)
+ var log_n = bits.log2(n)
+ var cache = BUFFER[log_n]
+ if(cache.length > 0) {
+ return cache.pop()
+ }
+ return new Buffer(n)
+}
+
+exports.clearCache = function clearCache() {
+ for(var i=0; i<32; ++i) {
+ UINT8[i].length = 0
+ UINT16[i].length = 0
+ UINT32[i].length = 0
+ INT8[i].length = 0
+ INT16[i].length = 0
+ INT32[i].length = 0
+ FLOAT[i].length = 0
+ DOUBLE[i].length = 0
+ DATA[i].length = 0
+ UINT8C[i].length = 0
+ BUFFER[i].length = 0
+ }
+}
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
+},{"bit-twiddle":61,"buffer":106,"dup":62}],64:[function(require,module,exports){
+module.exports=require(48)
+},{}],65:[function(require,module,exports){
+module.exports=require(49)
+},{"weakmap":64}],66:[function(require,module,exports){
+"use strict"
+
+function doBind(gl, elements, attributes) {
+ if(elements) {
+ elements.bind()
+ } else {
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
+ }
+ var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0
+ if(attributes) {
+ if(attributes.length > nattribs) {
+ throw new Error("gl-vao: Too many vertex attributes")
+ }
+ for(var i=0; i 0) {
+ //TODO: evaluate use of glm_invsqrt here?
+ len = 1 / Math.sqrt(len);
+ out[0] = a[0] * len;
+ out[1] = a[1] * len;
+ }
+ return out;
+};
+
+/**
+ * Calculates the dot product of two vec2's
+ *
+ * @param {vec2} a the first operand
+ * @param {vec2} b the second operand
+ * @returns {Number} dot product of a and b
+ */
+vec2.dot = function (a, b) {
+ return a[0] * b[0] + a[1] * b[1];
+};
+
+/**
+ * Computes the cross product of two vec2's
+ * Note that the cross product must by definition produce a 3D vector
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec2} a the first operand
+ * @param {vec2} b the second operand
+ * @returns {vec3} out
+ */
+vec2.cross = function(out, a, b) {
+ var z = a[0] * b[1] - a[1] * b[0];
+ out[0] = out[1] = 0;
+ out[2] = z;
+ return out;
+};
+
+/**
+ * Performs a linear interpolation between two vec2's
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the first operand
+ * @param {vec2} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {vec2} out
+ */
+vec2.lerp = function (out, a, b, t) {
+ var ax = a[0],
+ ay = a[1];
+ out[0] = ax + t * (b[0] - ax);
+ out[1] = ay + t * (b[1] - ay);
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat2
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat2} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat2 = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[2] * y;
+ out[1] = m[1] * x + m[3] * y;
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat2d
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat2d} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat2d = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[2] * y + m[4];
+ out[1] = m[1] * x + m[3] * y + m[5];
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat3
+ * 3rd vector component is implicitly '1'
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat3} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat3 = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[3] * y + m[6];
+ out[1] = m[1] * x + m[4] * y + m[7];
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat4
+ * 3rd vector component is implicitly '0'
+ * 4th vector component is implicitly '1'
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat4} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat4 = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[4] * y + m[12];
+ out[1] = m[1] * x + m[5] * y + m[13];
+ return out;
+};
+
+/**
+ * Perform some operation over an array of vec2s.
+ *
+ * @param {Array} a the array of vectors to iterate over
+ * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
+ * @param {Number} offset Number of elements to skip at the beginning of the array
+ * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
+ * @param {Function} fn Function to call for each vector in the array
+ * @param {Object} [arg] additional argument to pass to fn
+ * @returns {Array} a
+ * @function
+ */
+vec2.forEach = (function() {
+ var vec = vec2.create();
+
+ return function(a, stride, offset, count, fn, arg) {
+ var i, l;
+ if(!stride) {
+ stride = 2;
+ }
+
+ if(!offset) {
+ offset = 0;
+ }
+
+ if(count) {
+ l = Math.min((count * stride) + offset, a.length);
+ } else {
+ l = a.length;
+ }
+
+ for(i = offset; i < l; i += stride) {
+ vec[0] = a[i]; vec[1] = a[i+1];
+ fn(vec, vec, arg);
+ a[i] = vec[0]; a[i+1] = vec[1];
+ }
+
+ return a;
+ };
+})();
+
+/**
+ * Returns a string representation of a vector
+ *
+ * @param {vec2} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+vec2.str = function (a) {
+ return 'vec2(' + a[0] + ', ' + a[1] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.vec2 = vec2;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 3 Dimensional Vector
+ * @name vec3
+ */
+
+var vec3 = {};
+
+/**
+ * Creates a new, empty vec3
+ *
+ * @returns {vec3} a new 3D vector
+ */
+vec3.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(3);
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ return out;
+};
+
+/**
+ * Creates a new vec3 initialized with values from an existing vector
+ *
+ * @param {vec3} a vector to clone
+ * @returns {vec3} a new 3D vector
+ */
+vec3.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(3);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ return out;
+};
+
+/**
+ * Creates a new vec3 initialized with the given values
+ *
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @returns {vec3} a new 3D vector
+ */
+vec3.fromValues = function(x, y, z) {
+ var out = new GLMAT_ARRAY_TYPE(3);
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ return out;
+};
+
+/**
+ * Copy the values from one vec3 to another
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the source vector
+ * @returns {vec3} out
+ */
+vec3.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ return out;
+};
+
+/**
+ * Set the components of a vec3 to the given values
+ *
+ * @param {vec3} out the receiving vector
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @returns {vec3} out
+ */
+vec3.set = function(out, x, y, z) {
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ return out;
+};
+
+/**
+ * Adds two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.add = function(out, a, b) {
+ out[0] = a[0] + b[0];
+ out[1] = a[1] + b[1];
+ out[2] = a[2] + b[2];
+ return out;
+};
+
+/**
+ * Subtracts two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.subtract = function(out, a, b) {
+ out[0] = a[0] - b[0];
+ out[1] = a[1] - b[1];
+ out[2] = a[2] - b[2];
+ return out;
+};
+
+/**
+ * Alias for {@link vec3.subtract}
+ * @function
+ */
+vec3.sub = vec3.subtract;
+
+/**
+ * Multiplies two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.multiply = function(out, a, b) {
+ out[0] = a[0] * b[0];
+ out[1] = a[1] * b[1];
+ out[2] = a[2] * b[2];
+ return out;
+};
+
+/**
+ * Alias for {@link vec3.multiply}
+ * @function
+ */
+vec3.mul = vec3.multiply;
+
+/**
+ * Divides two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.divide = function(out, a, b) {
+ out[0] = a[0] / b[0];
+ out[1] = a[1] / b[1];
+ out[2] = a[2] / b[2];
+ return out;
+};
+
+/**
+ * Alias for {@link vec3.divide}
+ * @function
+ */
+vec3.div = vec3.divide;
+
+/**
+ * Returns the minimum of two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.min = function(out, a, b) {
+ out[0] = Math.min(a[0], b[0]);
+ out[1] = Math.min(a[1], b[1]);
+ out[2] = Math.min(a[2], b[2]);
+ return out;
+};
+
+/**
+ * Returns the maximum of two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.max = function(out, a, b) {
+ out[0] = Math.max(a[0], b[0]);
+ out[1] = Math.max(a[1], b[1]);
+ out[2] = Math.max(a[2], b[2]);
+ return out;
+};
+
+/**
+ * Scales a vec3 by a scalar number
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the vector to scale
+ * @param {Number} b amount to scale the vector by
+ * @returns {vec3} out
+ */
+vec3.scale = function(out, a, b) {
+ out[0] = a[0] * b;
+ out[1] = a[1] * b;
+ out[2] = a[2] * b;
+ return out;
+};
+
+/**
+ * Calculates the euclidian distance between two vec3's
+ *
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {Number} distance between a and b
+ */
+vec3.distance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2];
+ return Math.sqrt(x*x + y*y + z*z);
+};
+
+/**
+ * Alias for {@link vec3.distance}
+ * @function
+ */
+vec3.dist = vec3.distance;
+
+/**
+ * Calculates the squared euclidian distance between two vec3's
+ *
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {Number} squared distance between a and b
+ */
+vec3.squaredDistance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2];
+ return x*x + y*y + z*z;
+};
+
+/**
+ * Alias for {@link vec3.squaredDistance}
+ * @function
+ */
+vec3.sqrDist = vec3.squaredDistance;
+
+/**
+ * Calculates the length of a vec3
+ *
+ * @param {vec3} a vector to calculate length of
+ * @returns {Number} length of a
+ */
+vec3.length = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2];
+ return Math.sqrt(x*x + y*y + z*z);
+};
+
+/**
+ * Alias for {@link vec3.length}
+ * @function
+ */
+vec3.len = vec3.length;
+
+/**
+ * Calculates the squared length of a vec3
+ *
+ * @param {vec3} a vector to calculate squared length of
+ * @returns {Number} squared length of a
+ */
+vec3.squaredLength = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2];
+ return x*x + y*y + z*z;
+};
+
+/**
+ * Alias for {@link vec3.squaredLength}
+ * @function
+ */
+vec3.sqrLen = vec3.squaredLength;
+
+/**
+ * Negates the components of a vec3
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a vector to negate
+ * @returns {vec3} out
+ */
+vec3.negate = function(out, a) {
+ out[0] = -a[0];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ return out;
+};
+
+/**
+ * Normalize a vec3
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a vector to normalize
+ * @returns {vec3} out
+ */
+vec3.normalize = function(out, a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2];
+ var len = x*x + y*y + z*z;
+ if (len > 0) {
+ //TODO: evaluate use of glm_invsqrt here?
+ len = 1 / Math.sqrt(len);
+ out[0] = a[0] * len;
+ out[1] = a[1] * len;
+ out[2] = a[2] * len;
+ }
+ return out;
+};
+
+/**
+ * Calculates the dot product of two vec3's
+ *
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {Number} dot product of a and b
+ */
+vec3.dot = function (a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+};
+
+/**
+ * Computes the cross product of two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.cross = function(out, a, b) {
+ var ax = a[0], ay = a[1], az = a[2],
+ bx = b[0], by = b[1], bz = b[2];
+
+ out[0] = ay * bz - az * by;
+ out[1] = az * bx - ax * bz;
+ out[2] = ax * by - ay * bx;
+ return out;
+};
+
+/**
+ * Performs a linear interpolation between two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {vec3} out
+ */
+vec3.lerp = function (out, a, b, t) {
+ var ax = a[0],
+ ay = a[1],
+ az = a[2];
+ out[0] = ax + t * (b[0] - ax);
+ out[1] = ay + t * (b[1] - ay);
+ out[2] = az + t * (b[2] - az);
+ return out;
+};
+
+/**
+ * Transforms the vec3 with a mat4.
+ * 4th vector component is implicitly '1'
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the vector to transform
+ * @param {mat4} m matrix to transform with
+ * @returns {vec3} out
+ */
+vec3.transformMat4 = function(out, a, m) {
+ var x = a[0], y = a[1], z = a[2];
+ out[0] = m[0] * x + m[4] * y + m[8] * z + m[12];
+ out[1] = m[1] * x + m[5] * y + m[9] * z + m[13];
+ out[2] = m[2] * x + m[6] * y + m[10] * z + m[14];
+ return out;
+};
+
+/**
+ * Transforms the vec3 with a quat
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the vector to transform
+ * @param {quat} q quaternion to transform with
+ * @returns {vec3} out
+ */
+vec3.transformQuat = function(out, a, q) {
+ var x = a[0], y = a[1], z = a[2],
+ qx = q[0], qy = q[1], qz = q[2], qw = q[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
+ out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
+ out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
+ out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
+ return out;
+};
+
+/**
+ * Perform some operation over an array of vec3s.
+ *
+ * @param {Array} a the array of vectors to iterate over
+ * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
+ * @param {Number} offset Number of elements to skip at the beginning of the array
+ * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
+ * @param {Function} fn Function to call for each vector in the array
+ * @param {Object} [arg] additional argument to pass to fn
+ * @returns {Array} a
+ * @function
+ */
+vec3.forEach = (function() {
+ var vec = vec3.create();
+
+ return function(a, stride, offset, count, fn, arg) {
+ var i, l;
+ if(!stride) {
+ stride = 3;
+ }
+
+ if(!offset) {
+ offset = 0;
+ }
+
+ if(count) {
+ l = Math.min((count * stride) + offset, a.length);
+ } else {
+ l = a.length;
+ }
+
+ for(i = offset; i < l; i += stride) {
+ vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2];
+ fn(vec, vec, arg);
+ a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2];
+ }
+
+ return a;
+ };
+})();
+
+/**
+ * Returns a string representation of a vector
+ *
+ * @param {vec3} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+vec3.str = function (a) {
+ return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.vec3 = vec3;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 4 Dimensional Vector
+ * @name vec4
+ */
+
+var vec4 = {};
+
+/**
+ * Creates a new, empty vec4
+ *
+ * @returns {vec4} a new 4D vector
+ */
+vec4.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ return out;
+};
+
+/**
+ * Creates a new vec4 initialized with values from an existing vector
+ *
+ * @param {vec4} a vector to clone
+ * @returns {vec4} a new 4D vector
+ */
+vec4.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Creates a new vec4 initialized with the given values
+ *
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {vec4} a new 4D vector
+ */
+vec4.fromValues = function(x, y, z, w) {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ out[3] = w;
+ return out;
+};
+
+/**
+ * Copy the values from one vec4 to another
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the source vector
+ * @returns {vec4} out
+ */
+vec4.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Set the components of a vec4 to the given values
+ *
+ * @param {vec4} out the receiving vector
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {vec4} out
+ */
+vec4.set = function(out, x, y, z, w) {
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ out[3] = w;
+ return out;
+};
+
+/**
+ * Adds two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.add = function(out, a, b) {
+ out[0] = a[0] + b[0];
+ out[1] = a[1] + b[1];
+ out[2] = a[2] + b[2];
+ out[3] = a[3] + b[3];
+ return out;
+};
+
+/**
+ * Subtracts two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.subtract = function(out, a, b) {
+ out[0] = a[0] - b[0];
+ out[1] = a[1] - b[1];
+ out[2] = a[2] - b[2];
+ out[3] = a[3] - b[3];
+ return out;
+};
+
+/**
+ * Alias for {@link vec4.subtract}
+ * @function
+ */
+vec4.sub = vec4.subtract;
+
+/**
+ * Multiplies two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.multiply = function(out, a, b) {
+ out[0] = a[0] * b[0];
+ out[1] = a[1] * b[1];
+ out[2] = a[2] * b[2];
+ out[3] = a[3] * b[3];
+ return out;
+};
+
+/**
+ * Alias for {@link vec4.multiply}
+ * @function
+ */
+vec4.mul = vec4.multiply;
+
+/**
+ * Divides two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.divide = function(out, a, b) {
+ out[0] = a[0] / b[0];
+ out[1] = a[1] / b[1];
+ out[2] = a[2] / b[2];
+ out[3] = a[3] / b[3];
+ return out;
+};
+
+/**
+ * Alias for {@link vec4.divide}
+ * @function
+ */
+vec4.div = vec4.divide;
+
+/**
+ * Returns the minimum of two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.min = function(out, a, b) {
+ out[0] = Math.min(a[0], b[0]);
+ out[1] = Math.min(a[1], b[1]);
+ out[2] = Math.min(a[2], b[2]);
+ out[3] = Math.min(a[3], b[3]);
+ return out;
+};
+
+/**
+ * Returns the maximum of two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.max = function(out, a, b) {
+ out[0] = Math.max(a[0], b[0]);
+ out[1] = Math.max(a[1], b[1]);
+ out[2] = Math.max(a[2], b[2]);
+ out[3] = Math.max(a[3], b[3]);
+ return out;
+};
+
+/**
+ * Scales a vec4 by a scalar number
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the vector to scale
+ * @param {Number} b amount to scale the vector by
+ * @returns {vec4} out
+ */
+vec4.scale = function(out, a, b) {
+ out[0] = a[0] * b;
+ out[1] = a[1] * b;
+ out[2] = a[2] * b;
+ out[3] = a[3] * b;
+ return out;
+};
+
+/**
+ * Calculates the euclidian distance between two vec4's
+ *
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {Number} distance between a and b
+ */
+vec4.distance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2],
+ w = b[3] - a[3];
+ return Math.sqrt(x*x + y*y + z*z + w*w);
+};
+
+/**
+ * Alias for {@link vec4.distance}
+ * @function
+ */
+vec4.dist = vec4.distance;
+
+/**
+ * Calculates the squared euclidian distance between two vec4's
+ *
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {Number} squared distance between a and b
+ */
+vec4.squaredDistance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2],
+ w = b[3] - a[3];
+ return x*x + y*y + z*z + w*w;
+};
+
+/**
+ * Alias for {@link vec4.squaredDistance}
+ * @function
+ */
+vec4.sqrDist = vec4.squaredDistance;
+
+/**
+ * Calculates the length of a vec4
+ *
+ * @param {vec4} a vector to calculate length of
+ * @returns {Number} length of a
+ */
+vec4.length = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2],
+ w = a[3];
+ return Math.sqrt(x*x + y*y + z*z + w*w);
+};
+
+/**
+ * Alias for {@link vec4.length}
+ * @function
+ */
+vec4.len = vec4.length;
+
+/**
+ * Calculates the squared length of a vec4
+ *
+ * @param {vec4} a vector to calculate squared length of
+ * @returns {Number} squared length of a
+ */
+vec4.squaredLength = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2],
+ w = a[3];
+ return x*x + y*y + z*z + w*w;
+};
+
+/**
+ * Alias for {@link vec4.squaredLength}
+ * @function
+ */
+vec4.sqrLen = vec4.squaredLength;
+
+/**
+ * Negates the components of a vec4
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a vector to negate
+ * @returns {vec4} out
+ */
+vec4.negate = function(out, a) {
+ out[0] = -a[0];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ out[3] = -a[3];
+ return out;
+};
+
+/**
+ * Normalize a vec4
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a vector to normalize
+ * @returns {vec4} out
+ */
+vec4.normalize = function(out, a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2],
+ w = a[3];
+ var len = x*x + y*y + z*z + w*w;
+ if (len > 0) {
+ len = 1 / Math.sqrt(len);
+ out[0] = a[0] * len;
+ out[1] = a[1] * len;
+ out[2] = a[2] * len;
+ out[3] = a[3] * len;
+ }
+ return out;
+};
+
+/**
+ * Calculates the dot product of two vec4's
+ *
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {Number} dot product of a and b
+ */
+vec4.dot = function (a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
+};
+
+/**
+ * Performs a linear interpolation between two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {vec4} out
+ */
+vec4.lerp = function (out, a, b, t) {
+ var ax = a[0],
+ ay = a[1],
+ az = a[2],
+ aw = a[3];
+ out[0] = ax + t * (b[0] - ax);
+ out[1] = ay + t * (b[1] - ay);
+ out[2] = az + t * (b[2] - az);
+ out[3] = aw + t * (b[3] - aw);
+ return out;
+};
+
+/**
+ * Transforms the vec4 with a mat4.
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the vector to transform
+ * @param {mat4} m matrix to transform with
+ * @returns {vec4} out
+ */
+vec4.transformMat4 = function(out, a, m) {
+ var x = a[0], y = a[1], z = a[2], w = a[3];
+ out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
+ out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
+ out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
+ out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
+ return out;
+};
+
+/**
+ * Transforms the vec4 with a quat
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the vector to transform
+ * @param {quat} q quaternion to transform with
+ * @returns {vec4} out
+ */
+vec4.transformQuat = function(out, a, q) {
+ var x = a[0], y = a[1], z = a[2],
+ qx = q[0], qy = q[1], qz = q[2], qw = q[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
+ out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
+ out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
+ out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
+ return out;
+};
+
+/**
+ * Perform some operation over an array of vec4s.
+ *
+ * @param {Array} a the array of vectors to iterate over
+ * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
+ * @param {Number} offset Number of elements to skip at the beginning of the array
+ * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
+ * @param {Function} fn Function to call for each vector in the array
+ * @param {Object} [arg] additional argument to pass to fn
+ * @returns {Array} a
+ * @function
+ */
+vec4.forEach = (function() {
+ var vec = vec4.create();
+
+ return function(a, stride, offset, count, fn, arg) {
+ var i, l;
+ if(!stride) {
+ stride = 4;
+ }
+
+ if(!offset) {
+ offset = 0;
+ }
+
+ if(count) {
+ l = Math.min((count * stride) + offset, a.length);
+ } else {
+ l = a.length;
+ }
+
+ for(i = offset; i < l; i += stride) {
+ vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; vec[3] = a[i+3];
+ fn(vec, vec, arg);
+ a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; a[i+3] = vec[3];
+ }
+
+ return a;
+ };
+})();
+
+/**
+ * Returns a string representation of a vector
+ *
+ * @param {vec4} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+vec4.str = function (a) {
+ return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.vec4 = vec4;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 2x2 Matrix
+ * @name mat2
+ */
+
+var mat2 = {};
+
+var mat2Identity = new Float32Array([
+ 1, 0,
+ 0, 1
+]);
+
+/**
+ * Creates a new identity mat2
+ *
+ * @returns {mat2} a new 2x2 matrix
+ */
+mat2.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Creates a new mat2 initialized with values from an existing matrix
+ *
+ * @param {mat2} a matrix to clone
+ * @returns {mat2} a new 2x2 matrix
+ */
+mat2.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Copy the values from one mat2 to another
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Set a mat2 to the identity matrix
+ *
+ * @param {mat2} out the receiving matrix
+ * @returns {mat2} out
+ */
+mat2.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Transpose the values of a mat2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.transpose = function(out, a) {
+ // If we are transposing ourselves we can skip a few steps but have to cache some values
+ if (out === a) {
+ var a1 = a[1];
+ out[1] = a[2];
+ out[2] = a1;
+ } else {
+ out[0] = a[0];
+ out[1] = a[2];
+ out[2] = a[1];
+ out[3] = a[3];
+ }
+
+ return out;
+};
+
+/**
+ * Inverts a mat2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.invert = function(out, a) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+
+ // Calculate the determinant
+ det = a0 * a3 - a2 * a1;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = a3 * det;
+ out[1] = -a1 * det;
+ out[2] = -a2 * det;
+ out[3] = a0 * det;
+
+ return out;
+};
+
+/**
+ * Calculates the adjugate of a mat2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.adjoint = function(out, a) {
+ // Caching this value is nessecary if out == a
+ var a0 = a[0];
+ out[0] = a[3];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ out[3] = a0;
+
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat2
+ *
+ * @param {mat2} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat2.determinant = function (a) {
+ return a[0] * a[3] - a[2] * a[1];
+};
+
+/**
+ * Multiplies two mat2's
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the first operand
+ * @param {mat2} b the second operand
+ * @returns {mat2} out
+ */
+mat2.multiply = function (out, a, b) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
+ var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
+ out[0] = a0 * b0 + a1 * b2;
+ out[1] = a0 * b1 + a1 * b3;
+ out[2] = a2 * b0 + a3 * b2;
+ out[3] = a2 * b1 + a3 * b3;
+ return out;
+};
+
+/**
+ * Alias for {@link mat2.multiply}
+ * @function
+ */
+mat2.mul = mat2.multiply;
+
+/**
+ * Rotates a mat2 by the given angle
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat2} out
+ */
+mat2.rotate = function (out, a, rad) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+ s = Math.sin(rad),
+ c = Math.cos(rad);
+ out[0] = a0 * c + a1 * s;
+ out[1] = a0 * -s + a1 * c;
+ out[2] = a2 * c + a3 * s;
+ out[3] = a2 * -s + a3 * c;
+ return out;
+};
+
+/**
+ * Scales the mat2 by the dimensions in the given vec2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the matrix to rotate
+ * @param {vec2} v the vec2 to scale the matrix by
+ * @returns {mat2} out
+ **/
+mat2.scale = function(out, a, v) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+ v0 = v[0], v1 = v[1];
+ out[0] = a0 * v0;
+ out[1] = a1 * v1;
+ out[2] = a2 * v0;
+ out[3] = a3 * v1;
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat2
+ *
+ * @param {mat2} mat matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat2.str = function (a) {
+ return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat2 = mat2;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 2x3 Matrix
+ * @name mat2d
+ *
+ * @description
+ * A mat2d contains six elements defined as:
+ *
+ * [a, b,
+ * c, d,
+ * tx,ty]
+ *
+ * This is a short form for the 3x3 matrix:
+ *
+ * [a, b, 0
+ * c, d, 0
+ * tx,ty,1]
+ *
+ * The last column is ignored so the array is shorter and operations are faster.
+ */
+
+var mat2d = {};
+
+var mat2dIdentity = new Float32Array([
+ 1, 0,
+ 0, 1,
+ 0, 0
+]);
+
+/**
+ * Creates a new identity mat2d
+ *
+ * @returns {mat2d} a new 2x3 matrix
+ */
+mat2d.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(6);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ out[4] = 0;
+ out[5] = 0;
+ return out;
+};
+
+/**
+ * Creates a new mat2d initialized with values from an existing matrix
+ *
+ * @param {mat2d} a matrix to clone
+ * @returns {mat2d} a new 2x3 matrix
+ */
+mat2d.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(6);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ return out;
+};
+
+/**
+ * Copy the values from one mat2d to another
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the source matrix
+ * @returns {mat2d} out
+ */
+mat2d.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ return out;
+};
+
+/**
+ * Set a mat2d to the identity matrix
+ *
+ * @param {mat2d} out the receiving matrix
+ * @returns {mat2d} out
+ */
+mat2d.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ out[4] = 0;
+ out[5] = 0;
+ return out;
+};
+
+/**
+ * Inverts a mat2d
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the source matrix
+ * @returns {mat2d} out
+ */
+mat2d.invert = function(out, a) {
+ var aa = a[0], ab = a[1], ac = a[2], ad = a[3],
+ atx = a[4], aty = a[5];
+
+ var det = aa * ad - ab * ac;
+ if(!det){
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = ad * det;
+ out[1] = -ab * det;
+ out[2] = -ac * det;
+ out[3] = aa * det;
+ out[4] = (ac * aty - ad * atx) * det;
+ out[5] = (ab * atx - aa * aty) * det;
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat2d
+ *
+ * @param {mat2d} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat2d.determinant = function (a) {
+ return a[0] * a[3] - a[1] * a[2];
+};
+
+/**
+ * Multiplies two mat2d's
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the first operand
+ * @param {mat2d} b the second operand
+ * @returns {mat2d} out
+ */
+mat2d.multiply = function (out, a, b) {
+ var aa = a[0], ab = a[1], ac = a[2], ad = a[3],
+ atx = a[4], aty = a[5],
+ ba = b[0], bb = b[1], bc = b[2], bd = b[3],
+ btx = b[4], bty = b[5];
+
+ out[0] = aa*ba + ab*bc;
+ out[1] = aa*bb + ab*bd;
+ out[2] = ac*ba + ad*bc;
+ out[3] = ac*bb + ad*bd;
+ out[4] = ba*atx + bc*aty + btx;
+ out[5] = bb*atx + bd*aty + bty;
+ return out;
+};
+
+/**
+ * Alias for {@link mat2d.multiply}
+ * @function
+ */
+mat2d.mul = mat2d.multiply;
+
+
+/**
+ * Rotates a mat2d by the given angle
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat2d} out
+ */
+mat2d.rotate = function (out, a, rad) {
+ var aa = a[0],
+ ab = a[1],
+ ac = a[2],
+ ad = a[3],
+ atx = a[4],
+ aty = a[5],
+ st = Math.sin(rad),
+ ct = Math.cos(rad);
+
+ out[0] = aa*ct + ab*st;
+ out[1] = -aa*st + ab*ct;
+ out[2] = ac*ct + ad*st;
+ out[3] = -ac*st + ct*ad;
+ out[4] = ct*atx + st*aty;
+ out[5] = ct*aty - st*atx;
+ return out;
+};
+
+/**
+ * Scales the mat2d by the dimensions in the given vec2
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the matrix to translate
+ * @param {mat2d} v the vec2 to scale the matrix by
+ * @returns {mat2d} out
+ **/
+mat2d.scale = function(out, a, v) {
+ var vx = v[0], vy = v[1];
+ out[0] = a[0] * vx;
+ out[1] = a[1] * vy;
+ out[2] = a[2] * vx;
+ out[3] = a[3] * vy;
+ out[4] = a[4] * vx;
+ out[5] = a[5] * vy;
+ return out;
+};
+
+/**
+ * Translates the mat2d by the dimensions in the given vec2
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the matrix to translate
+ * @param {mat2d} v the vec2 to translate the matrix by
+ * @returns {mat2d} out
+ **/
+mat2d.translate = function(out, a, v) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4] + v[0];
+ out[5] = a[5] + v[1];
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat2d
+ *
+ * @param {mat2d} a matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat2d.str = function (a) {
+ return 'mat2d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' +
+ a[3] + ', ' + a[4] + ', ' + a[5] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat2d = mat2d;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 3x3 Matrix
+ * @name mat3
+ */
+
+var mat3 = {};
+
+var mat3Identity = new Float32Array([
+ 1, 0, 0,
+ 0, 1, 0,
+ 0, 0, 1
+]);
+
+/**
+ * Creates a new identity mat3
+ *
+ * @returns {mat3} a new 3x3 matrix
+ */
+mat3.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(9);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 1;
+ out[5] = 0;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 1;
+ return out;
+};
+
+/**
+ * Creates a new mat3 initialized with values from an existing matrix
+ *
+ * @param {mat3} a matrix to clone
+ * @returns {mat3} a new 3x3 matrix
+ */
+mat3.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(9);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ return out;
+};
+
+/**
+ * Copy the values from one mat3 to another
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ return out;
+};
+
+/**
+ * Set a mat3 to the identity matrix
+ *
+ * @param {mat3} out the receiving matrix
+ * @returns {mat3} out
+ */
+mat3.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 1;
+ out[5] = 0;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 1;
+ return out;
+};
+
+/**
+ * Transpose the values of a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.transpose = function(out, a) {
+ // If we are transposing ourselves we can skip a few steps but have to cache some values
+ if (out === a) {
+ var a01 = a[1], a02 = a[2], a12 = a[5];
+ out[1] = a[3];
+ out[2] = a[6];
+ out[3] = a01;
+ out[5] = a[7];
+ out[6] = a02;
+ out[7] = a12;
+ } else {
+ out[0] = a[0];
+ out[1] = a[3];
+ out[2] = a[6];
+ out[3] = a[1];
+ out[4] = a[4];
+ out[5] = a[7];
+ out[6] = a[2];
+ out[7] = a[5];
+ out[8] = a[8];
+ }
+
+ return out;
+};
+
+/**
+ * Inverts a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.invert = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+
+ b01 = a22 * a11 - a12 * a21,
+ b11 = -a22 * a10 + a12 * a20,
+ b21 = a21 * a10 - a11 * a20,
+
+ // Calculate the determinant
+ det = a00 * b01 + a01 * b11 + a02 * b21;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = b01 * det;
+ out[1] = (-a22 * a01 + a02 * a21) * det;
+ out[2] = (a12 * a01 - a02 * a11) * det;
+ out[3] = b11 * det;
+ out[4] = (a22 * a00 - a02 * a20) * det;
+ out[5] = (-a12 * a00 + a02 * a10) * det;
+ out[6] = b21 * det;
+ out[7] = (-a21 * a00 + a01 * a20) * det;
+ out[8] = (a11 * a00 - a01 * a10) * det;
+ return out;
+};
+
+/**
+ * Calculates the adjugate of a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.adjoint = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8];
+
+ out[0] = (a11 * a22 - a12 * a21);
+ out[1] = (a02 * a21 - a01 * a22);
+ out[2] = (a01 * a12 - a02 * a11);
+ out[3] = (a12 * a20 - a10 * a22);
+ out[4] = (a00 * a22 - a02 * a20);
+ out[5] = (a02 * a10 - a00 * a12);
+ out[6] = (a10 * a21 - a11 * a20);
+ out[7] = (a01 * a20 - a00 * a21);
+ out[8] = (a00 * a11 - a01 * a10);
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat3
+ *
+ * @param {mat3} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat3.determinant = function (a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8];
+
+ return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
+};
+
+/**
+ * Multiplies two mat3's
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the first operand
+ * @param {mat3} b the second operand
+ * @returns {mat3} out
+ */
+mat3.multiply = function (out, a, b) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+
+ b00 = b[0], b01 = b[1], b02 = b[2],
+ b10 = b[3], b11 = b[4], b12 = b[5],
+ b20 = b[6], b21 = b[7], b22 = b[8];
+
+ out[0] = b00 * a00 + b01 * a10 + b02 * a20;
+ out[1] = b00 * a01 + b01 * a11 + b02 * a21;
+ out[2] = b00 * a02 + b01 * a12 + b02 * a22;
+
+ out[3] = b10 * a00 + b11 * a10 + b12 * a20;
+ out[4] = b10 * a01 + b11 * a11 + b12 * a21;
+ out[5] = b10 * a02 + b11 * a12 + b12 * a22;
+
+ out[6] = b20 * a00 + b21 * a10 + b22 * a20;
+ out[7] = b20 * a01 + b21 * a11 + b22 * a21;
+ out[8] = b20 * a02 + b21 * a12 + b22 * a22;
+ return out;
+};
+
+/**
+ * Alias for {@link mat3.multiply}
+ * @function
+ */
+mat3.mul = mat3.multiply;
+
+/**
+ * Translate a mat3 by the given vector
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the matrix to translate
+ * @param {vec2} v vector to translate by
+ * @returns {mat3} out
+ */
+mat3.translate = function(out, a, v) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+ x = v[0], y = v[1];
+
+ out[0] = a00;
+ out[1] = a01;
+ out[2] = a02;
+
+ out[3] = a10;
+ out[4] = a11;
+ out[5] = a12;
+
+ out[6] = x * a00 + y * a10 + a20;
+ out[7] = x * a01 + y * a11 + a21;
+ out[8] = x * a02 + y * a12 + a22;
+ return out;
+};
+
+/**
+ * Rotates a mat3 by the given angle
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat3} out
+ */
+mat3.rotate = function (out, a, rad) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+
+ s = Math.sin(rad),
+ c = Math.cos(rad);
+
+ out[0] = c * a00 + s * a10;
+ out[1] = c * a01 + s * a11;
+ out[2] = c * a02 + s * a12;
+
+ out[3] = c * a10 - s * a00;
+ out[4] = c * a11 - s * a01;
+ out[5] = c * a12 - s * a02;
+
+ out[6] = a20;
+ out[7] = a21;
+ out[8] = a22;
+ return out;
+};
+
+/**
+ * Scales the mat3 by the dimensions in the given vec2
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the matrix to rotate
+ * @param {vec2} v the vec2 to scale the matrix by
+ * @returns {mat3} out
+ **/
+mat3.scale = function(out, a, v) {
+ var x = v[0], y = v[2];
+
+ out[0] = x * a[0];
+ out[1] = x * a[1];
+ out[2] = x * a[2];
+
+ out[3] = y * a[3];
+ out[4] = y * a[4];
+ out[5] = y * a[5];
+
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ return out;
+};
+
+/**
+ * Copies the values from a mat2d into a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the matrix to rotate
+ * @param {vec2} v the vec2 to scale the matrix by
+ * @returns {mat3} out
+ **/
+mat3.fromMat2d = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = 0;
+
+ out[3] = a[2];
+ out[4] = a[3];
+ out[5] = 0;
+
+ out[6] = a[4];
+ out[7] = a[5];
+ out[8] = 1;
+ return out;
+};
+
+/**
+* Calculates a 3x3 matrix from the given quaternion
+*
+* @param {mat3} out mat3 receiving operation result
+* @param {quat} q Quaternion to create matrix from
+*
+* @returns {mat3} out
+*/
+mat3.fromQuat = function (out, q) {
+ var x = q[0], y = q[1], z = q[2], w = q[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;
+
+ out[0] = 1 - (yy + zz);
+ out[1] = xy + wz;
+ out[2] = xz - wy;
+
+ out[3] = xy - wz;
+ out[4] = 1 - (xx + zz);
+ out[5] = yz + wx;
+
+ out[6] = xz + wy;
+ out[7] = yz - wx;
+ out[8] = 1 - (xx + yy);
+
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat3
+ *
+ * @param {mat3} mat matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat3.str = function (a) {
+ return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' +
+ a[3] + ', ' + a[4] + ', ' + a[5] + ', ' +
+ a[6] + ', ' + a[7] + ', ' + a[8] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat3 = mat3;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 4x4 Matrix
+ * @name mat4
+ */
+
+var mat4 = {};
+
+var mat4Identity = new Float32Array([
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1
+]);
+
+/**
+ * Creates a new identity mat4
+ *
+ * @returns {mat4} a new 4x4 matrix
+ */
+mat4.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(16);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = 1;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = 1;
+ out[11] = 0;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = 0;
+ out[15] = 1;
+ return out;
+};
+
+/**
+ * Creates a new mat4 initialized with values from an existing matrix
+ *
+ * @param {mat4} a matrix to clone
+ * @returns {mat4} a new 4x4 matrix
+ */
+mat4.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(16);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ out[9] = a[9];
+ out[10] = a[10];
+ out[11] = a[11];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ return out;
+};
+
+/**
+ * Copy the values from one mat4 to another
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ out[9] = a[9];
+ out[10] = a[10];
+ out[11] = a[11];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ return out;
+};
+
+/**
+ * Set a mat4 to the identity matrix
+ *
+ * @param {mat4} out the receiving matrix
+ * @returns {mat4} out
+ */
+mat4.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = 1;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = 1;
+ out[11] = 0;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = 0;
+ out[15] = 1;
+ return out;
+};
+
+/**
+ * Transpose the values of a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.transpose = function(out, a) {
+ // If we are transposing ourselves we can skip a few steps but have to cache some values
+ if (out === a) {
+ var a01 = a[1], a02 = a[2], a03 = a[3],
+ a12 = a[6], a13 = a[7],
+ a23 = a[11];
+
+ out[1] = a[4];
+ out[2] = a[8];
+ out[3] = a[12];
+ out[4] = a01;
+ out[6] = a[9];
+ out[7] = a[13];
+ out[8] = a02;
+ out[9] = a12;
+ out[11] = a[14];
+ out[12] = a03;
+ out[13] = a13;
+ out[14] = a23;
+ } else {
+ out[0] = a[0];
+ out[1] = a[4];
+ out[2] = a[8];
+ out[3] = a[12];
+ out[4] = a[1];
+ out[5] = a[5];
+ out[6] = a[9];
+ out[7] = a[13];
+ out[8] = a[2];
+ out[9] = a[6];
+ out[10] = a[10];
+ out[11] = a[14];
+ out[12] = a[3];
+ out[13] = a[7];
+ out[14] = a[11];
+ out[15] = a[15];
+ }
+
+ return out;
+};
+
+/**
+ * Inverts a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.invert = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[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,
+
+ // Calculate the determinant
+ det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
+ out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
+ out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
+ out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
+ out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
+ out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
+ out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
+ out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
+ out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
+ out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
+ out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
+ out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
+ out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
+ out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
+ out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
+ out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
+
+ return out;
+};
+
+/**
+ * Calculates the adjugate of a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.adjoint = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
+
+ out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22));
+ out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
+ out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12));
+ out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
+ out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
+ out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22));
+ out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
+ out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12));
+ out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21));
+ out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
+ out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11));
+ out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
+ out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
+ out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21));
+ out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
+ out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11));
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat4
+ *
+ * @param {mat4} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat4.determinant = function (a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[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;
+
+ // Calculate the determinant
+ return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+};
+
+/**
+ * Multiplies two mat4's
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the first operand
+ * @param {mat4} b the second operand
+ * @returns {mat4} out
+ */
+mat4.multiply = function (out, a, b) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
+
+ // Cache only the current line of the second matrix
+ var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
+ out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+ b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
+ out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+ b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
+ out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+ b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
+ out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+ return out;
+};
+
+/**
+ * Alias for {@link mat4.multiply}
+ * @function
+ */
+mat4.mul = mat4.multiply;
+
+/**
+ * Translate a mat4 by the given vector
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to translate
+ * @param {vec3} v vector to translate by
+ * @returns {mat4} out
+ */
+mat4.translate = function (out, a, v) {
+ var x = v[0], y = v[1], z = v[2],
+ a00, a01, a02, a03,
+ a10, a11, a12, a13,
+ a20, a21, a22, a23;
+
+ if (a === out) {
+ out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
+ out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
+ out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
+ out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
+ } else {
+ a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
+ a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
+ a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
+
+ out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
+ out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
+ out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
+
+ out[12] = a00 * x + a10 * y + a20 * z + a[12];
+ out[13] = a01 * x + a11 * y + a21 * z + a[13];
+ out[14] = a02 * x + a12 * y + a22 * z + a[14];
+ out[15] = a03 * x + a13 * y + a23 * z + a[15];
+ }
+
+ return out;
+};
+
+/**
+ * Scales the mat4 by the dimensions in the given vec3
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to scale
+ * @param {vec3} v the vec3 to scale the matrix by
+ * @returns {mat4} out
+ **/
+mat4.scale = function(out, a, v) {
+ var x = v[0], y = v[1], z = v[2];
+
+ out[0] = a[0] * x;
+ out[1] = a[1] * x;
+ out[2] = a[2] * x;
+ out[3] = a[3] * x;
+ out[4] = a[4] * y;
+ out[5] = a[5] * y;
+ out[6] = a[6] * y;
+ out[7] = a[7] * y;
+ out[8] = a[8] * z;
+ out[9] = a[9] * z;
+ out[10] = a[10] * z;
+ out[11] = a[11] * z;
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ return out;
+};
+
+/**
+ * Rotates a mat4 by the given angle
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @param {vec3} axis the axis to rotate around
+ * @returns {mat4} out
+ */
+mat4.rotate = function (out, a, rad, axis) {
+ 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 (Math.abs(len) < GLMAT_EPSILON) { return null; }
+
+ len = 1 / len;
+ x *= len;
+ y *= len;
+ z *= len;
+
+ s = Math.sin(rad);
+ c = Math.cos(rad);
+ t = 1 - c;
+
+ a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
+ a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
+ a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[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;
+
+ // Perform rotation-specific matrix multiplication
+ out[0] = a00 * b00 + a10 * b01 + a20 * b02;
+ out[1] = a01 * b00 + a11 * b01 + a21 * b02;
+ out[2] = a02 * b00 + a12 * b01 + a22 * b02;
+ out[3] = a03 * b00 + a13 * b01 + a23 * b02;
+ out[4] = a00 * b10 + a10 * b11 + a20 * b12;
+ out[5] = a01 * b10 + a11 * b11 + a21 * b12;
+ out[6] = a02 * b10 + a12 * b11 + a22 * b12;
+ out[7] = a03 * b10 + a13 * b11 + a23 * b12;
+ out[8] = a00 * b20 + a10 * b21 + a20 * b22;
+ out[9] = a01 * b20 + a11 * b21 + a21 * b22;
+ out[10] = a02 * b20 + a12 * b21 + a22 * b22;
+ out[11] = a03 * b20 + a13 * b21 + a23 * b22;
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged last row
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+ return out;
+};
+
+/**
+ * Rotates a matrix by the given angle around the X axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+mat4.rotateX = function (out, a, rad) {
+ var s = Math.sin(rad),
+ c = Math.cos(rad),
+ a10 = a[4],
+ a11 = a[5],
+ a12 = a[6],
+ a13 = a[7],
+ a20 = a[8],
+ a21 = a[9],
+ a22 = a[10],
+ a23 = a[11];
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged rows
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+
+ // Perform axis-specific matrix multiplication
+ out[4] = a10 * c + a20 * s;
+ out[5] = a11 * c + a21 * s;
+ out[6] = a12 * c + a22 * s;
+ out[7] = a13 * c + a23 * s;
+ out[8] = a20 * c - a10 * s;
+ out[9] = a21 * c - a11 * s;
+ out[10] = a22 * c - a12 * s;
+ out[11] = a23 * c - a13 * s;
+ return out;
+};
+
+/**
+ * Rotates a matrix by the given angle around the Y axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+mat4.rotateY = function (out, a, rad) {
+ var s = Math.sin(rad),
+ c = Math.cos(rad),
+ a00 = a[0],
+ a01 = a[1],
+ a02 = a[2],
+ a03 = a[3],
+ a20 = a[8],
+ a21 = a[9],
+ a22 = a[10],
+ a23 = a[11];
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged rows
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+
+ // Perform axis-specific matrix multiplication
+ out[0] = a00 * c - a20 * s;
+ out[1] = a01 * c - a21 * s;
+ out[2] = a02 * c - a22 * s;
+ out[3] = a03 * c - a23 * s;
+ out[8] = a00 * s + a20 * c;
+ out[9] = a01 * s + a21 * c;
+ out[10] = a02 * s + a22 * c;
+ out[11] = a03 * s + a23 * c;
+ return out;
+};
+
+/**
+ * Rotates a matrix by the given angle around the Z axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+mat4.rotateZ = function (out, a, rad) {
+ var s = Math.sin(rad),
+ c = Math.cos(rad),
+ a00 = a[0],
+ a01 = a[1],
+ a02 = a[2],
+ a03 = a[3],
+ a10 = a[4],
+ a11 = a[5],
+ a12 = a[6],
+ a13 = a[7];
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged last row
+ out[8] = a[8];
+ out[9] = a[9];
+ out[10] = a[10];
+ out[11] = a[11];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+
+ // Perform axis-specific matrix multiplication
+ out[0] = a00 * c + a10 * s;
+ out[1] = a01 * c + a11 * s;
+ out[2] = a02 * c + a12 * s;
+ out[3] = a03 * c + a13 * s;
+ out[4] = a10 * c - a00 * s;
+ out[5] = a11 * c - a01 * s;
+ out[6] = a12 * c - a02 * s;
+ out[7] = a13 * c - a03 * s;
+ return out;
+};
+
+/**
+ * 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 {mat4} out mat4 receiving operation result
+ * @param {quat4} q Rotation quaternion
+ * @param {vec3} v Translation vector
+ * @returns {mat4} out
+ */
+mat4.fromRotationTranslation = function (out, q, v) {
+ // Quaternion math
+ var x = q[0], y = q[1], z = q[2], w = q[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;
+
+ out[0] = 1 - (yy + zz);
+ out[1] = xy + wz;
+ out[2] = xz - wy;
+ out[3] = 0;
+ out[4] = xy - wz;
+ out[5] = 1 - (xx + zz);
+ out[6] = yz + wx;
+ out[7] = 0;
+ out[8] = xz + wy;
+ out[9] = yz - wx;
+ out[10] = 1 - (xx + yy);
+ out[11] = 0;
+ out[12] = v[0];
+ out[13] = v[1];
+ out[14] = v[2];
+ out[15] = 1;
+
+ return out;
+};
+
+/**
+* Calculates a 4x4 matrix from the given quaternion
+*
+* @param {mat4} out mat4 receiving operation result
+* @param {quat} q Quaternion to create matrix from
+*
+* @returns {mat4} out
+*/
+mat4.fromQuat = function (out, q) {
+ var x = q[0], y = q[1], z = q[2], w = q[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;
+
+ out[0] = 1 - (yy + zz);
+ out[1] = xy + wz;
+ out[2] = xz - wy;
+ out[3] = 0;
+
+ out[4] = xy - wz;
+ out[5] = 1 - (xx + zz);
+ out[6] = yz + wx;
+ out[7] = 0;
+
+ out[8] = xz + wy;
+ out[9] = yz - wx;
+ out[10] = 1 - (xx + yy);
+ out[11] = 0;
+
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = 0;
+ out[15] = 1;
+
+ return out;
+};
+
+/**
+ * Generates a frustum matrix with the given bounds
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @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
+ * @returns {mat4} out
+ */
+mat4.frustum = function (out, left, right, bottom, top, near, far) {
+ var rl = 1 / (right - left),
+ tb = 1 / (top - bottom),
+ nf = 1 / (near - far);
+ out[0] = (near * 2) * rl;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = (near * 2) * tb;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = (right + left) * rl;
+ out[9] = (top + bottom) * tb;
+ out[10] = (far + near) * nf;
+ out[11] = -1;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = (far * near * 2) * nf;
+ out[15] = 0;
+ return out;
+};
+
+/**
+ * Generates a perspective projection matrix with the given bounds
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @param {number} fovy Vertical field of view in radians
+ * @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
+ * @returns {mat4} out
+ */
+mat4.perspective = function (out, fovy, aspect, near, far) {
+ var f = 1.0 / Math.tan(fovy / 2),
+ nf = 1 / (near - far);
+ out[0] = f / aspect;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = f;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = (far + near) * nf;
+ out[11] = -1;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = (2 * far * near) * nf;
+ out[15] = 0;
+ return out;
+};
+
+/**
+ * Generates a orthogonal projection matrix with the given bounds
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @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
+ * @returns {mat4} out
+ */
+mat4.ortho = function (out, left, right, bottom, top, near, far) {
+ var lr = 1 / (left - right),
+ bt = 1 / (bottom - top),
+ nf = 1 / (near - far);
+ out[0] = -2 * lr;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = -2 * bt;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = 2 * nf;
+ out[11] = 0;
+ out[12] = (left + right) * lr;
+ out[13] = (top + bottom) * bt;
+ out[14] = (far + near) * nf;
+ out[15] = 1;
+ return out;
+};
+
+/**
+ * Generates a look-at matrix with the given eye position, focal point, and up axis
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @param {vec3} eye Position of the viewer
+ * @param {vec3} center Point the viewer is looking at
+ * @param {vec3} up vec3 pointing up
+ * @returns {mat4} out
+ */
+mat4.lookAt = function (out, eye, center, up) {
+ 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 (Math.abs(eyex - centerx) < GLMAT_EPSILON &&
+ Math.abs(eyey - centery) < GLMAT_EPSILON &&
+ Math.abs(eyez - centerz) < GLMAT_EPSILON) {
+ return mat4.identity(out);
+ }
+
+ z0 = eyex - centerx;
+ z1 = eyey - centery;
+ z2 = eyez - centerz;
+
+ len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
+ z0 *= len;
+ z1 *= len;
+ z2 *= len;
+
+ 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;
+ }
+
+ 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;
+ }
+
+ out[0] = x0;
+ out[1] = y0;
+ out[2] = z0;
+ out[3] = 0;
+ out[4] = x1;
+ out[5] = y1;
+ out[6] = z1;
+ out[7] = 0;
+ out[8] = x2;
+ out[9] = y2;
+ out[10] = z2;
+ out[11] = 0;
+ out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
+ out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
+ out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
+ out[15] = 1;
+
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat4
+ *
+ * @param {mat4} mat matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat4.str = function (a) {
+ return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' +
+ a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' +
+ a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' +
+ a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat4 = mat4;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class Quaternion
+ * @name quat
+ */
+
+var quat = {};
+
+var quatIdentity = new Float32Array([0, 0, 0, 1]);
+
+/**
+ * Creates a new identity quat
+ *
+ * @returns {quat} a new quaternion
+ */
+quat.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Creates a new quat initialized with values from an existing quaternion
+ *
+ * @param {quat} a quaternion to clone
+ * @returns {quat} a new quaternion
+ * @function
+ */
+quat.clone = vec4.clone;
+
+/**
+ * Creates a new quat initialized with the given values
+ *
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {quat} a new quaternion
+ * @function
+ */
+quat.fromValues = vec4.fromValues;
+
+/**
+ * Copy the values from one quat to another
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the source quaternion
+ * @returns {quat} out
+ * @function
+ */
+quat.copy = vec4.copy;
+
+/**
+ * Set the components of a quat to the given values
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {quat} out
+ * @function
+ */
+quat.set = vec4.set;
+
+/**
+ * Set a quat to the identity quaternion
+ *
+ * @param {quat} out the receiving quaternion
+ * @returns {quat} out
+ */
+quat.identity = function(out) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Sets a quat from the given angle and rotation axis,
+ * then returns it.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {vec3} axis the axis around which to rotate
+ * @param {Number} rad the angle in radians
+ * @returns {quat} out
+ **/
+quat.setAxisAngle = function(out, axis, rad) {
+ rad = rad * 0.5;
+ var s = Math.sin(rad);
+ out[0] = s * axis[0];
+ out[1] = s * axis[1];
+ out[2] = s * axis[2];
+ out[3] = Math.cos(rad);
+ return out;
+};
+
+/**
+ * Adds two quat's
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @returns {quat} out
+ * @function
+ */
+quat.add = vec4.add;
+
+/**
+ * Multiplies two quat's
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @returns {quat} out
+ */
+quat.multiply = function(out, a, b) {
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bx = b[0], by = b[1], bz = b[2], bw = b[3];
+
+ out[0] = ax * bw + aw * bx + ay * bz - az * by;
+ out[1] = ay * bw + aw * by + az * bx - ax * bz;
+ out[2] = az * bw + aw * bz + ax * by - ay * bx;
+ out[3] = aw * bw - ax * bx - ay * by - az * bz;
+ return out;
+};
+
+/**
+ * Alias for {@link quat.multiply}
+ * @function
+ */
+quat.mul = quat.multiply;
+
+/**
+ * Scales a quat by a scalar number
+ *
+ * @param {quat} out the receiving vector
+ * @param {quat} a the vector to scale
+ * @param {Number} b amount to scale the vector by
+ * @returns {quat} out
+ * @function
+ */
+quat.scale = vec4.scale;
+
+/**
+ * Rotates a quaternion by the given angle around the X axis
+ *
+ * @param {quat} out quat receiving operation result
+ * @param {quat} a quat to rotate
+ * @param {number} rad angle (in radians) to rotate
+ * @returns {quat} out
+ */
+quat.rotateX = function (out, a, rad) {
+ rad *= 0.5;
+
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bx = Math.sin(rad), bw = Math.cos(rad);
+
+ out[0] = ax * bw + aw * bx;
+ out[1] = ay * bw + az * bx;
+ out[2] = az * bw - ay * bx;
+ out[3] = aw * bw - ax * bx;
+ return out;
+};
+
+/**
+ * Rotates a quaternion by the given angle around the Y axis
+ *
+ * @param {quat} out quat receiving operation result
+ * @param {quat} a quat to rotate
+ * @param {number} rad angle (in radians) to rotate
+ * @returns {quat} out
+ */
+quat.rotateY = function (out, a, rad) {
+ rad *= 0.5;
+
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ by = Math.sin(rad), bw = Math.cos(rad);
+
+ out[0] = ax * bw - az * by;
+ out[1] = ay * bw + aw * by;
+ out[2] = az * bw + ax * by;
+ out[3] = aw * bw - ay * by;
+ return out;
+};
+
+/**
+ * Rotates a quaternion by the given angle around the Z axis
+ *
+ * @param {quat} out quat receiving operation result
+ * @param {quat} a quat to rotate
+ * @param {number} rad angle (in radians) to rotate
+ * @returns {quat} out
+ */
+quat.rotateZ = function (out, a, rad) {
+ rad *= 0.5;
+
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bz = Math.sin(rad), bw = Math.cos(rad);
+
+ out[0] = ax * bw + ay * bz;
+ out[1] = ay * bw - ax * bz;
+ out[2] = az * bw + aw * bz;
+ out[3] = aw * bw - az * bz;
+ return out;
+};
+
+/**
+ * Calculates the W component of a quat from the X, Y, and Z components.
+ * Assumes that quaternion is 1 unit in length.
+ * Any existing W component will be ignored.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quat to calculate W component of
+ * @returns {quat} out
+ */
+quat.calculateW = function (out, a) {
+ var x = a[0], y = a[1], z = a[2];
+
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ out[3] = -Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
+ return out;
+};
+
+/**
+ * Calculates the dot product of two quat's
+ *
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @returns {Number} dot product of a and b
+ * @function
+ */
+quat.dot = vec4.dot;
+
+/**
+ * Performs a linear interpolation between two quat's
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {quat} out
+ * @function
+ */
+quat.lerp = vec4.lerp;
+
+/**
+ * Performs a spherical linear interpolation between two quat
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {quat} out
+ */
+quat.slerp = function (out, a, b, t) {
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bx = b[0], by = b[1], bz = b[2], bw = b[3];
+
+ var cosHalfTheta = ax * bx + ay * by + az * bz + aw * bw,
+ halfTheta,
+ sinHalfTheta,
+ ratioA,
+ ratioB;
+
+ if (Math.abs(cosHalfTheta) >= 1.0) {
+ if (out !== a) {
+ out[0] = ax;
+ out[1] = ay;
+ out[2] = az;
+ out[3] = aw;
+ }
+ return out;
+ }
+
+ halfTheta = Math.acos(cosHalfTheta);
+ sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
+
+ if (Math.abs(sinHalfTheta) < 0.001) {
+ out[0] = (ax * 0.5 + bx * 0.5);
+ out[1] = (ay * 0.5 + by * 0.5);
+ out[2] = (az * 0.5 + bz * 0.5);
+ out[3] = (aw * 0.5 + bw * 0.5);
+ return out;
+ }
+
+ ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta;
+ ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
+
+ out[0] = (ax * ratioA + bx * ratioB);
+ out[1] = (ay * ratioA + by * ratioB);
+ out[2] = (az * ratioA + bz * ratioB);
+ out[3] = (aw * ratioA + bw * ratioB);
+
+ return out;
+};
+
+/**
+ * Calculates the inverse of a quat
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quat to calculate inverse of
+ * @returns {quat} out
+ */
+quat.invert = function(out, a) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+ dot = a0*a0 + a1*a1 + a2*a2 + a3*a3,
+ invDot = dot ? 1.0/dot : 0;
+
+ // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
+
+ out[0] = -a0*invDot;
+ out[1] = -a1*invDot;
+ out[2] = -a2*invDot;
+ out[3] = a3*invDot;
+ return out;
+};
+
+/**
+ * Calculates the conjugate of a quat
+ * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quat to calculate conjugate of
+ * @returns {quat} out
+ */
+quat.conjugate = function (out, a) {
+ out[0] = -a[0];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Calculates the length of a quat
+ *
+ * @param {quat} a vector to calculate length of
+ * @returns {Number} length of a
+ * @function
+ */
+quat.length = vec4.length;
+
+/**
+ * Alias for {@link quat.length}
+ * @function
+ */
+quat.len = quat.length;
+
+/**
+ * Calculates the squared length of a quat
+ *
+ * @param {quat} a vector to calculate squared length of
+ * @returns {Number} squared length of a
+ * @function
+ */
+quat.squaredLength = vec4.squaredLength;
+
+/**
+ * Alias for {@link quat.squaredLength}
+ * @function
+ */
+quat.sqrLen = quat.squaredLength;
+
+/**
+ * Normalize a quat
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quaternion to normalize
+ * @returns {quat} out
+ * @function
+ */
+quat.normalize = vec4.normalize;
+
+/**
+ * Creates a quaternion from the given 3x3 rotation matrix.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {mat3} m rotation matrix
+ * @returns {quat} out
+ * @function
+ */
+quat.fromMat3 = (function() {
+ var s_iNext = [1,2,0];
+ return function(out, m) {
+ // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
+ // article "Quaternion Calculus and Fast Animation".
+ var fTrace = m[0] + m[4] + m[8];
+ var fRoot;
+
+ if ( fTrace > 0.0 ) {
+ // |w| > 1/2, may as well choose w > 1/2
+ fRoot = Math.sqrt(fTrace + 1.0); // 2w
+ out[3] = 0.5 * fRoot;
+ fRoot = 0.5/fRoot; // 1/(4w)
+ out[0] = (m[7]-m[5])*fRoot;
+ out[1] = (m[2]-m[6])*fRoot;
+ out[2] = (m[3]-m[1])*fRoot;
+ } else {
+ // |w| <= 1/2
+ var i = 0;
+ if ( m[4] > m[0] )
+ i = 1;
+ if ( m[8] > m[i*3+i] )
+ i = 2;
+ var j = s_iNext[i];
+ var k = s_iNext[j];
+
+ fRoot = Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k] + 1.0);
+ out[i] = 0.5 * fRoot;
+ fRoot = 0.5 / fRoot;
+ out[3] = (m[k*3+j] - m[j*3+k]) * fRoot;
+ out[j] = (m[j*3+i] + m[i*3+j]) * fRoot;
+ out[k] = (m[k*3+i] + m[i*3+k]) * fRoot;
+ }
+
+ return out;
+ };
+})();
+
+/**
+ * Returns a string representation of a quatenion
+ *
+ * @param {quat} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+quat.str = function (a) {
+ return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.quat = quat;
+}
+;
+
+
+
+
+
+
+
+
+
+
+
+
+
+ })(shim.exports);
+})();
+
+},{}],76:[function(require,module,exports){
+module.exports=require(16)
+},{"cwise-compiler":77}],77:[function(require,module,exports){
+module.exports=require(17)
+},{"./lib/thunk.js":79}],78:[function(require,module,exports){
+module.exports=require(18)
+},{"uniq":80}],79:[function(require,module,exports){
+module.exports=require(19)
+},{"./compile.js":78}],80:[function(require,module,exports){
+module.exports=require(20)
+},{}],81:[function(require,module,exports){
+module.exports=require(21)
+},{"buffer":106,"iota-array":82}],82:[function(require,module,exports){
+module.exports=require(22)
+},{}],83:[function(require,module,exports){
+module.exports=require(23)
+},{}],84:[function(require,module,exports){
+module.exports=require(24)
+},{}],85:[function(require,module,exports){
+module.exports=require(63)
+},{"bit-twiddle":83,"buffer":106,"dup":84}],86:[function(require,module,exports){
+module.exports=require(48)
+},{}],87:[function(require,module,exports){
+module.exports=require(49)
+},{"weakmap":86}],88:[function(require,module,exports){
+"use strict"
+
+var ndarray = require("ndarray")
+var ops = require("ndarray-ops")
+var pool = require("typedarray-pool")
+var webglew = require("webglew")
+
+var linearTypes = null
+var filterTypes = null
+var wrapTypes = null
+
+function lazyInitLinearTypes(gl) {
+ linearTypes = [
+ gl.LINEAR,
+ gl.NEAREST_MIPMAP_LINEAR,
+ gl.LINEAR_MIPMAP_NEAREST,
+ gl.LINEAR_MIPMAP_NEAREST
+ ]
+ filterTypes = [
+ gl.NEAREST,
+ gl.LINEAR,
+ gl.NEAREST_MIPMAP_NEAREST,
+ gl.NEAREST_MIPMAP_LINEAR,
+ gl.LINEAR_MIPMAP_NEAREST,
+ gl.LINEAR_MIPMAP_LINEAR
+ ]
+ wrapTypes = [
+ gl.REPEAT,
+ gl.CLAMP_TO_EDGE,
+ gl.MIRRORED_REPEAT
+ ]
+}
+
+var convertFloatToUint8 = function(out, inp) {
+ ops.muls(out, inp, 255.0)
+}
+
+function Texture2D(gl, handle, width, height, format, type) {
+ this.gl = gl
+ this.handle = handle
+ this.format = format
+ this.type = type
+ this._shape = [height, width]
+ this._mipLevels = [0]
+ this._magFilter = gl.NEAREST
+ this._minFilter = gl.NEAREST
+ this._wrapS = gl.CLAMP_TO_EDGE
+ this._wrapT = gl.CLAMP_TO_EDGE
+ this._anisoSamples = 1
+}
+
+Object.defineProperty(Texture2D.prototype, "minFilter", {
+ get: function() {
+ return this._minFilter
+ },
+ set: function(v) {
+ this.bind()
+ var gl = this.gl
+ if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
+ if(!webglew(gl).OES_texture_float_linear) {
+ v = gl.NEAREST
+ }
+ }
+ if(filterTypes.indexOf(v) < 0) {
+ throw new Error("gl-texture2d: Unknown filter mode " + v)
+ }
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v)
+ return this._minFilter = v
+ }
+})
+
+var proto = Texture2D.prototype
+
+Object.defineProperty(proto, "magFilter", {
+ get: function() {
+ return this._magFilter
+ },
+ set: function(v) {
+ this.bind()
+ var gl = this.gl
+ if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
+ if(!webglew(gl).OES_texture_float_linear) {
+ v = gl.NEAREST
+ }
+ }
+ if(filterTypes.indexOf(v) < 0) {
+ throw new Error("gl-texture2d: Unknown filter mode " + v)
+ }
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v)
+ return this._magFilter = v
+ }
+})
+
+Object.defineProperty(proto, "wrapS", {
+ get: function() {
+ return this._wrapS
+ },
+ set: function(v) {
+ this.bind()
+ if(wrapTypes.indexOf(v) < 0) {
+ throw new Error("gl-texture2d: Unknown wrap mode " + v)
+ }
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v)
+ return this._wrapS = v
+ }
+})
+
+Object.defineProperty(proto, "wrapT", {
+ get: function() {
+ return this._wrapT
+ },
+ set: function(v) {
+ this.bind()
+ if(wrapTypes.indexOf(v) < 0) {
+ throw new Error("gl-texture2d: Unknown wrap mode " + v)
+ }
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v)
+ return this._wrapT = v
+ }
+})
+
+
+Object.defineProperty(proto, "wrap", {
+ get: function() {
+ return [this._wrapT, this._wrapS]
+ },
+ set: function(v) {
+ if(!Array.isArray(v)) {
+ v = [v,v]
+ }
+ if(v.length !== 2) {
+ throw new Error("gl-texture2d: Must specify wrap mode for rows and columns")
+ }
+ for(var i=0; i<2; ++i) {
+ if(wrapTypes.indexOf(v[i]) < 0) {
+ throw new Error("gl-texture2d: Unknown wrap mode " + v)
+ }
+ }
+ this._wrapT = v[0]
+ this._wrapS = v[1]
+
+ var gl = this.gl
+ this.bind()
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS)
+
+ return v
+ }
+})
+
+Object.defineProperty(proto, "mipSamples", {
+ get: function() {
+ return this._anisoSamples
+ },
+ set: function(i) {
+ var psamples = this._anisoSamples
+ this._anisoSamples = Math.max(i, 1)|0
+ if(psamples !== this._anisoSamples) {
+ var ext = webglew(this.gl).EXT_texture_filter_anisotropic
+ if(ext) {
+ this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples)
+ }
+ }
+ return this._anisoSamples
+ }
+})
+
+Object.defineProperty(proto, "shape", {
+ get: function() {
+ return this._shape
+ },
+ set: function(x) {
+ if(!Array.isArray(x)) {
+ x = [x|0,x|0]
+ } else {
+ if(x.length !== 2) {
+ throw new Error("gl-texture2d: Invalid texture shape")
+ }
+ }
+ var r = x[0]|0
+ var c = x[1]|0
+ if(this.height === r && this.width === c) {
+ return x
+ }
+ var gl = this.gl
+ var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
+ if(c < 0 || c > maxSize || r < 0 || r > maxSize) {
+ throw new Error("gl-texture2d: Invalid texture size")
+ }
+ this._shape = [r, c]
+ this.bind()
+ gl.texImage2D(gl.TEXTURE_2D, 0, this.format, c, r, 0, this.format, this.type, null)
+ this._mipLevels = [0]
+ return x
+ }
+})
+
+proto.bind = function bindTexture2D(unit) {
+ var gl = this.gl
+ if(unit !== undefined) {
+ gl.activeTexture(gl.TEXTURE0 + (unit|0))
+ }
+ gl.bindTexture(gl.TEXTURE_2D, this.handle)
+ if(unit !== undefined) {
+ return unit
+ }
+ return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0
+}
+
+proto.dispose = function disposeTexture2D() {
+ this.gl.deleteTexture(this.handle)
+}
+
+proto.generateMipmap = function() {
+ this.bind()
+ this.gl.generateMipmap(this.gl.TEXTURE_2D)
+
+ //Update mip levels
+ var l = Math.min(this._shape[0], this._shape[1])
+ for(var i=0; l>0; ++i, l>>>=1) {
+ if(this._mipLevels.indexOf(i) < 0) {
+ this._mipLevels.push(i)
+ }
+ }
+}
+
+proto.setPixels = function(data, x_off, y_off, mip_level) {
+ var gl = this.gl
+ this.bind()
+ if(Array.isArray(x_off)) {
+ mip_level = y_off
+ y_off = x_off[0]|0
+ x_off = x_off[1]|0
+ } else {
+ x_off = x_off || 0
+ y_off = y_off || 0
+ }
+ mip_level = mip_level || 0
+ if(data instanceof HTMLCanvasElement ||
+ data instanceof ImageData ||
+ data instanceof HTMLImageElement ||
+ data instanceof HTMLVideoElement) {
+ var needsMip = this._mipLevels.indexOf(mip_level) < 0
+ if(needsMip) {
+ gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data)
+ this._mipLevels.push(mip_level)
+ } else {
+ gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data)
+ }
+ } else if(data.shape && data.stride && data.data) {
+ if(data.shape.length < 2 ||
+ x_off + data.shape[1] > this._shape[1]>>>mip_level ||
+ y_off + data.shape[0] > this._shape[0]>>>mip_level ||
+ x_off < 0 ||
+ y_off < 0) {
+ throw new Error("gl-texture2d: Texture dimensions are out of bounds")
+ }
+ texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data)
+ } else {
+ throw new Error("gl-texture2d: Unsupported data type")
+ }
+}
+
+function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) {
+ var dtype = array.dtype
+ var shape = array.shape
+ var packed = isPacked(array)
+ var type = 0, format = 0
+ if(dtype === "float32") {
+ type = gl.FLOAT
+ } else if(dtype === "float64") {
+ type = gl.FLOAT
+ packed = false
+ dtype = "float32"
+ } else if(dtype === "uint8") {
+ type = gl.UNSIGNED_BYTE
+ } else {
+ type = gl.UNSIGNED_BYTE
+ packed = false
+ dtype = "uint8"
+ }
+ if(shape.length === 2) {
+ format = gl.LUMINANCE
+ } else if(shape.length === 3) {
+ if(shape[2] === 1) {
+ format = gl.ALPHA
+ } else if(shape[2] === 2) {
+ format = gl.LUMINANCE_ALPHA
+ } else if(shape[2] === 3) {
+ format = gl.RGB
+ } else if(shape[2] === 4) {
+ format = gl.RGBA
+ } else {
+ throw new Error("gl-texture2d: Invalid shape for pixel coords")
+ }
+ } else {
+ throw new Error("gl-texture2d: Invalid shape for texture")
+ }
+ //For 1-channel textures allow conversion between formats
+ if((format === gl.LUMINANCE || format === gl.ALPHA) &&
+ (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) {
+ format = cformat
+ }
+ if(format !== cformat) {
+ throw new Error("gl-texture2d: Incompatible texture format for setPixels")
+ }
+ var size = array.size
+ var needsMip = mipLevels.indexOf(mip_level) < 0
+ if(needsMip) {
+ mipLevels.push(mip_level)
+ }
+ if(type === ctype && packed) {
+ //Array data types are compatible, can directly copy into texture
+ if(array.offset === 0 && array.data.length === size) {
+ if(needsMip) {
+ gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[1], shape[0], 0, cformat, ctype, array.data)
+ } else {
+ gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[1], shape[0], cformat, ctype, array.data)
+ }
+ } else {
+ if(needsMip) {
+ gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[1], shape[0], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size))
+ } else {
+ gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[1], shape[0], cformat, ctype, array.data.subarray(array.offset, array.offset+size))
+ }
+ }
+ } else {
+ //Need to do type conversion to pack data into buffer
+ var pack_buffer
+ if(ctype === gl.FLOAT) {
+ pack_buffer = pool.mallocFloat32(size)
+ } else {
+ pack_buffer = pool.mallocUint8(size)
+ }
+ var pack_view = ndarray(pack_buffer, shape)
+ if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) {
+ convertFloatToUint8(pack_view, array)
+ } else {
+ ops.assign(pack_view, array)
+ }
+ if(needsMip) {
+ gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[1], shape[0], 0, cformat, ctype, pack_buffer.subarray(0, size))
+ } else {
+ gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[1], shape[0], cformat, ctype, pack_buffer.subarray(0, size))
+ }
+ if(ctype === gl.FLOAT) {
+ pool.freeFloat32(pack_buffer)
+ } else {
+ pool.freeUint8(pack_buffer)
+ }
+ }
+}
+
+function initTexture(gl) {
+ var tex = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, tex)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+ return tex
+}
+
+function createTextureShape(gl, width, height, format, type) {
+ var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
+ if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) {
+ throw new Error("gl-texture2d: Invalid texture shape")
+ }
+ var tex = initTexture(gl)
+ gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null)
+ return new Texture2D(gl, tex, width, height, format, type)
+}
+
+function createTextureDOM(gl, element, format, type) {
+ var tex = initTexture(gl)
+ gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element)
+ return new Texture2D(gl, tex, element.width|0, element.height|0, format, type)
+}
+
+function isPacked(array) {
+ var shape = array.shape
+ var stride = array.stride
+ var s = 1
+ for(var i=shape.length-1; i>=0; --i) {
+ if(stride[i] !== s) {
+ return false
+ }
+ s *= shape[i]
+ }
+ return true
+}
+
+//Creates a texture from an ndarray
+function createTextureArray(gl, array) {
+ var dtype = array.dtype
+ var shape = array.shape.slice()
+ var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
+ if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {
+ throw new Error("gl-texture2d: Invalid texture size")
+ }
+
+ var packed = isPacked(array)
+ var type = 0
+ if(dtype === "float32") {
+ type = gl.FLOAT
+ } else if(dtype === "float64") {
+ type = gl.FLOAT
+ packed = false
+ dtype = "float32"
+ } else if(dtype === "uint8") {
+ type = gl.UNSIGNED_BYTE
+ } else {
+ type = gl.UNSIGNED_BYTE
+ packed = false
+ dtype = "uint8"
+ }
+ var format = 0
+ if(shape.length === 2) {
+ format = gl.LUMINANCE
+ } else if(shape.length === 3) {
+ if(shape[2] === 1) {
+ format = gl.ALPHA
+ } else if(shape[2] === 2) {
+ format = gl.LUMINANCE_ALPHA
+ } else if(shape[2] === 3) {
+ format = gl.RGB
+ } else if(shape[2] === 4) {
+ format = gl.RGBA
+ } else {
+ throw new Error("Invalid shape for pixel coords")
+ }
+ } else {
+ throw new Error("Invalid shape for texture")
+ }
+ if(type === gl.FLOAT && !!webglew(gl).texture_float) {
+ type = gl.UNSIGNED_BYTE
+ packed = false
+ }
+ var buffer, buf_store
+ if(!packed) {
+ var sz = 1
+ var stride = new Array(shape.length)
+ for(var i=shape.length-1; i>=0; --i) {
+ stride[i] = sz
+ sz *= shape[i]
+ }
+ buf_store = pool.malloc(sz, dtype)
+ var buf_array = ndarray(buf_store, array.shape, stride, 0)
+ if((dtype === "float32" || dtype === "float64") && type === gl.UNSIGNED_BYTE) {
+ convertFloatToUint8(buf_array, array)
+ } else {
+ ops.assign(buf_array, array)
+ }
+ buffer = buf_store.subarray(0, sz)
+ } else {
+ var array_size = array.size
+ buffer = array.data.subarray(array.offset, array.offset + array_size)
+ }
+ var tex = initTexture(gl)
+ gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[1], shape[0], 0, format, type, buffer)
+ if(!packed) {
+ pool.free(buf_store)
+ }
+ return new Texture2D(gl, tex, shape[1], shape[0], format, type)
+}
+
+function createTexture2D(gl) {
+ if(arguments.length <= 1) {
+ throw new Error("Missing arguments for texture2d constructor")
+ }
+ if(!linearTypes) {
+ lazyInitLinearTypes(gl)
+ }
+ if(typeof arguments[1] === "number") {
+ return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE)
+ }
+ if(Array.isArray(arguments[1])) {
+ return createTextureShape(gl, arguments[1][1]|0, arguments[1][0]|0, arguments[2]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE)
+ }
+ if(typeof arguments[1] === "object") {
+ var obj = arguments[1]
+ if(obj instanceof HTMLCanvasElement ||
+ obj instanceof HTMLImageElement ||
+ obj instanceof HTMLVideoElement ||
+ obj instanceof ImageData) {
+ return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE)
+ } else if(obj.shape && obj.data && obj.stride) {
+ return createTextureArray(gl, obj)
+ }
+ }
+ throw new Error("Invalid arguments for texture2d constructor")
+}
+module.exports = createTexture2D
+
+},{"ndarray":81,"ndarray-ops":76,"typedarray-pool":85,"webglew":87}],89:[function(require,module,exports){
+module.exports = programify
+
+var shader = require('gl-shader-core')
+
+function programify(vertex, fragment, uniforms, attributes) {
+ return function(gl) {
+ return shader(gl, vertex, fragment, uniforms, attributes)
+ }
+}
+
+},{"gl-shader-core":95}],90:[function(require,module,exports){
+module.exports = noop
+
+function noop() {
+ throw new Error(
+ 'You should bundle your code ' +
+ 'using `glslify` as a transform.'
+ )
+}
+
+},{}],91:[function(require,module,exports){
+"use strict"
+
+module.exports = createAttributeWrapper
+
+//Shader attribute class
+function ShaderAttribute(gl, program, location, dimension, name, constFunc, relink) {
+ this._gl = gl
+ this._program = program
+ this._location = location
+ this._dimension = dimension
+ this._name = name
+ this._constFunc = constFunc
+ this._relink = relink
+}
+
+var proto = ShaderAttribute.prototype
+
+proto.pointer = function setAttribPointer(type, normalized, stride, offset) {
+ var gl = this._gl
+ gl.vertexAttribPointer(this._location, this._dimension, type||gl.FLOAT, normalized?gl.TRUE:gl.FALSE, stride||0, offset||0)
+ this._gl.enableVertexAttribArray(this._location)
+}
+
+Object.defineProperty(proto, "location", {
+ get: function() {
+ return this._location
+ }
+ , set: function(v) {
+ if(v !== this._location) {
+ this._location = v
+ this._gl.bindAttribLocation(this._program, v, this._name)
+ this._gl.linkProgram(this._program)
+ this._relink()
+ }
+ }
+})
+
+
+//Adds a vector attribute to obj
+function addVectorAttribute(gl, program, location, dimension, obj, name, doLink) {
+ var constFuncArgs = [ "gl", "v" ]
+ var varNames = []
+ for(var i=0; i= 0) {
+ var d = type.charCodeAt(type.length-1) - 48
+ if(d < 2 || d > 4) {
+ throw new Error("Invalid data type for attribute " + name + ": " + type)
+ }
+ addVectorAttribute(gl, program, location, d, obj, name, doLink)
+ } else {
+ throw new Error("Unknown data type for attribute " + name + ": " + type)
+ }
+ break
+ }
+ }
+ return obj
+}
+
+},{}],92:[function(require,module,exports){
+"use strict"
+
+var dup = require("dup")
+var coallesceUniforms = require("./reflect.js")
+
+module.exports = createUniformWrapper
+
+//Binds a function and returns a value
+function identity(x) {
+ var c = new Function("y", "return function(){return y}")
+ return c(x)
+}
+
+//Create shims for uniforms
+function createUniformWrapper(gl, program, uniforms, locations) {
+
+ function makeGetter(index) {
+ var proc = new Function("gl", "prog", "locations",
+ "return function(){return gl.getUniform(prog,locations[" + index + "])}")
+ return proc(gl, program, locations)
+ }
+
+ function makePropSetter(path, index, type) {
+ switch(type) {
+ case "bool":
+ case "int":
+ case "sampler2D":
+ case "samplerCube":
+ return "gl.uniform1i(locations[" + index + "],obj" + path + ")"
+ case "float":
+ return "gl.uniform1f(locations[" + index + "],obj" + path + ")"
+ default:
+ var vidx = type.indexOf("vec")
+ if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
+ var d = type.charCodeAt(type.length-1) - 48
+ if(d < 2 || d > 4) {
+ throw new Error("Invalid data type")
+ }
+ switch(type.charAt(0)) {
+ case "b":
+ case "i":
+ return "gl.uniform" + d + "iv(locations[" + index + "],obj" + path + ")"
+ case "v":
+ return "gl.uniform" + d + "fv(locations[" + index + "],obj" + path + ")"
+ default:
+ throw new Error("Unrecognized data type for vector " + name + ": " + type)
+ }
+ } else if(type.indexOf("mat") === 0 && type.length === 4) {
+ var d = type.charCodeAt(type.length-1) - 48
+ if(d < 2 || d > 4) {
+ throw new Error("Invalid uniform dimension type for matrix " + name + ": " + type)
+ }
+ return "gl.uniformMatrix" + d + "fv(locations[" + index + "],false,obj" + path + ")"
+ } else {
+ throw new Error("Unknown uniform data type for " + name + ": " + type)
+ }
+ break
+ }
+ }
+
+ function enumerateIndices(prefix, type) {
+ if(typeof type !== "object") {
+ return [ [prefix, type] ]
+ }
+ var indices = []
+ for(var id in type) {
+ var prop = type[id]
+ var tprefix = prefix
+ if(parseInt(id) + "" === id) {
+ tprefix += "[" + id + "]"
+ } else {
+ tprefix += "." + id
+ }
+ if(typeof prop === "object") {
+ indices.push.apply(indices, enumerateIndices(tprefix, prop))
+ } else {
+ indices.push([tprefix, prop])
+ }
+ }
+ return indices
+ }
+
+ function makeSetter(type) {
+ var code = [ "return function updateProperty(obj){" ]
+ var indices = enumerateIndices("", type)
+ for(var i=0; i 4) {
+ throw new Error("Invalid data type")
+ }
+ if(type.charAt(0) === "b") {
+ return dup(d, false)
+ }
+ return dup(d)
+ } else if(type.indexOf("mat") === 0 && type.length === 4) {
+ var d = type.charCodeAt(type.length-1) - 48
+ if(d < 2 || d > 4) {
+ throw new Error("Invalid uniform dimension type for matrix " + name + ": " + type)
+ }
+ return dup([d,d])
+ } else {
+ throw new Error("Unknown uniform data type for " + name + ": " + type)
+ }
+ break
+ }
+ }
+
+ function storeProperty(obj, prop, type) {
+ if(typeof type === "object") {
+ var child = processObject(type)
+ Object.defineProperty(obj, prop, {
+ get: identity(child),
+ set: makeSetter(type),
+ enumerable: true,
+ configurable: false
+ })
+ } else {
+ if(locations[type]) {
+ Object.defineProperty(obj, prop, {
+ get: makeGetter(type),
+ set: makeSetter(type),
+ enumerable: true,
+ configurable: false
+ })
+ } else {
+ obj[prop] = defaultValue(uniforms[type].type)
+ }
+ }
+ }
+
+ function processObject(obj) {
+ var result
+ if(Array.isArray(obj)) {
+ result = new Array(obj.length)
+ for(var i=0; i 1) {
+ if(!(x[0] in o)) {
+ o[x[0]] = []
+ }
+ o = o[x[0]]
+ for(var k=1; k 0) {
+ //TODO: evaluate use of glm_invsqrt here?
+ len = 1 / Math.sqrt(len);
+ out[0] = a[0] * len;
+ out[1] = a[1] * len;
+ }
+ return out;
+};
+
+/**
+ * Calculates the dot product of two vec2's
+ *
+ * @param {vec2} a the first operand
+ * @param {vec2} b the second operand
+ * @returns {Number} dot product of a and b
+ */
+vec2.dot = function (a, b) {
+ return a[0] * b[0] + a[1] * b[1];
+};
+
+/**
+ * Computes the cross product of two vec2's
+ * Note that the cross product must by definition produce a 3D vector
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec2} a the first operand
+ * @param {vec2} b the second operand
+ * @returns {vec3} out
+ */
+vec2.cross = function(out, a, b) {
+ var z = a[0] * b[1] - a[1] * b[0];
+ out[0] = out[1] = 0;
+ out[2] = z;
+ return out;
+};
+
+/**
+ * Performs a linear interpolation between two vec2's
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the first operand
+ * @param {vec2} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {vec2} out
+ */
+vec2.lerp = function (out, a, b, t) {
+ var ax = a[0],
+ ay = a[1];
+ out[0] = ax + t * (b[0] - ax);
+ out[1] = ay + t * (b[1] - ay);
+ return out;
+};
+
+/**
+ * Generates a random vector with the given scale
+ *
+ * @param {vec2} out the receiving vector
+ * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
+ * @returns {vec2} out
+ */
+vec2.random = function (out, scale) {
+ scale = scale || 1.0;
+ var r = GLMAT_RANDOM() * 2.0 * Math.PI;
+ out[0] = Math.cos(r) * scale;
+ out[1] = Math.sin(r) * scale;
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat2
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat2} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat2 = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[2] * y;
+ out[1] = m[1] * x + m[3] * y;
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat2d
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat2d} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat2d = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[2] * y + m[4];
+ out[1] = m[1] * x + m[3] * y + m[5];
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat3
+ * 3rd vector component is implicitly '1'
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat3} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat3 = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[3] * y + m[6];
+ out[1] = m[1] * x + m[4] * y + m[7];
+ return out;
+};
+
+/**
+ * Transforms the vec2 with a mat4
+ * 3rd vector component is implicitly '0'
+ * 4th vector component is implicitly '1'
+ *
+ * @param {vec2} out the receiving vector
+ * @param {vec2} a the vector to transform
+ * @param {mat4} m matrix to transform with
+ * @returns {vec2} out
+ */
+vec2.transformMat4 = function(out, a, m) {
+ var x = a[0],
+ y = a[1];
+ out[0] = m[0] * x + m[4] * y + m[12];
+ out[1] = m[1] * x + m[5] * y + m[13];
+ return out;
+};
+
+/**
+ * Perform some operation over an array of vec2s.
+ *
+ * @param {Array} a the array of vectors to iterate over
+ * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
+ * @param {Number} offset Number of elements to skip at the beginning of the array
+ * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
+ * @param {Function} fn Function to call for each vector in the array
+ * @param {Object} [arg] additional argument to pass to fn
+ * @returns {Array} a
+ * @function
+ */
+vec2.forEach = (function() {
+ var vec = vec2.create();
+
+ return function(a, stride, offset, count, fn, arg) {
+ var i, l;
+ if(!stride) {
+ stride = 2;
+ }
+
+ if(!offset) {
+ offset = 0;
+ }
+
+ if(count) {
+ l = Math.min((count * stride) + offset, a.length);
+ } else {
+ l = a.length;
+ }
+
+ for(i = offset; i < l; i += stride) {
+ vec[0] = a[i]; vec[1] = a[i+1];
+ fn(vec, vec, arg);
+ a[i] = vec[0]; a[i+1] = vec[1];
+ }
+
+ return a;
+ };
+})();
+
+/**
+ * Returns a string representation of a vector
+ *
+ * @param {vec2} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+vec2.str = function (a) {
+ return 'vec2(' + a[0] + ', ' + a[1] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.vec2 = vec2;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 3 Dimensional Vector
+ * @name vec3
+ */
+
+var vec3 = {};
+
+/**
+ * Creates a new, empty vec3
+ *
+ * @returns {vec3} a new 3D vector
+ */
+vec3.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(3);
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ return out;
+};
+
+/**
+ * Creates a new vec3 initialized with values from an existing vector
+ *
+ * @param {vec3} a vector to clone
+ * @returns {vec3} a new 3D vector
+ */
+vec3.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(3);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ return out;
+};
+
+/**
+ * Creates a new vec3 initialized with the given values
+ *
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @returns {vec3} a new 3D vector
+ */
+vec3.fromValues = function(x, y, z) {
+ var out = new GLMAT_ARRAY_TYPE(3);
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ return out;
+};
+
+/**
+ * Copy the values from one vec3 to another
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the source vector
+ * @returns {vec3} out
+ */
+vec3.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ return out;
+};
+
+/**
+ * Set the components of a vec3 to the given values
+ *
+ * @param {vec3} out the receiving vector
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @returns {vec3} out
+ */
+vec3.set = function(out, x, y, z) {
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ return out;
+};
+
+/**
+ * Adds two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.add = function(out, a, b) {
+ out[0] = a[0] + b[0];
+ out[1] = a[1] + b[1];
+ out[2] = a[2] + b[2];
+ return out;
+};
+
+/**
+ * Subtracts vector b from vector a
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.subtract = function(out, a, b) {
+ out[0] = a[0] - b[0];
+ out[1] = a[1] - b[1];
+ out[2] = a[2] - b[2];
+ return out;
+};
+
+/**
+ * Alias for {@link vec3.subtract}
+ * @function
+ */
+vec3.sub = vec3.subtract;
+
+/**
+ * Multiplies two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.multiply = function(out, a, b) {
+ out[0] = a[0] * b[0];
+ out[1] = a[1] * b[1];
+ out[2] = a[2] * b[2];
+ return out;
+};
+
+/**
+ * Alias for {@link vec3.multiply}
+ * @function
+ */
+vec3.mul = vec3.multiply;
+
+/**
+ * Divides two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.divide = function(out, a, b) {
+ out[0] = a[0] / b[0];
+ out[1] = a[1] / b[1];
+ out[2] = a[2] / b[2];
+ return out;
+};
+
+/**
+ * Alias for {@link vec3.divide}
+ * @function
+ */
+vec3.div = vec3.divide;
+
+/**
+ * Returns the minimum of two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.min = function(out, a, b) {
+ out[0] = Math.min(a[0], b[0]);
+ out[1] = Math.min(a[1], b[1]);
+ out[2] = Math.min(a[2], b[2]);
+ return out;
+};
+
+/**
+ * Returns the maximum of two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.max = function(out, a, b) {
+ out[0] = Math.max(a[0], b[0]);
+ out[1] = Math.max(a[1], b[1]);
+ out[2] = Math.max(a[2], b[2]);
+ return out;
+};
+
+/**
+ * Scales a vec3 by a scalar number
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the vector to scale
+ * @param {Number} b amount to scale the vector by
+ * @returns {vec3} out
+ */
+vec3.scale = function(out, a, b) {
+ out[0] = a[0] * b;
+ out[1] = a[1] * b;
+ out[2] = a[2] * b;
+ return out;
+};
+
+/**
+ * Adds two vec3's after scaling the second operand by a scalar value
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @param {Number} scale the amount to scale b by before adding
+ * @returns {vec3} out
+ */
+vec3.scaleAndAdd = function(out, a, b, scale) {
+ out[0] = a[0] + (b[0] * scale);
+ out[1] = a[1] + (b[1] * scale);
+ out[2] = a[2] + (b[2] * scale);
+ return out;
+};
+
+/**
+ * Calculates the euclidian distance between two vec3's
+ *
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {Number} distance between a and b
+ */
+vec3.distance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2];
+ return Math.sqrt(x*x + y*y + z*z);
+};
+
+/**
+ * Alias for {@link vec3.distance}
+ * @function
+ */
+vec3.dist = vec3.distance;
+
+/**
+ * Calculates the squared euclidian distance between two vec3's
+ *
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {Number} squared distance between a and b
+ */
+vec3.squaredDistance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2];
+ return x*x + y*y + z*z;
+};
+
+/**
+ * Alias for {@link vec3.squaredDistance}
+ * @function
+ */
+vec3.sqrDist = vec3.squaredDistance;
+
+/**
+ * Calculates the length of a vec3
+ *
+ * @param {vec3} a vector to calculate length of
+ * @returns {Number} length of a
+ */
+vec3.length = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2];
+ return Math.sqrt(x*x + y*y + z*z);
+};
+
+/**
+ * Alias for {@link vec3.length}
+ * @function
+ */
+vec3.len = vec3.length;
+
+/**
+ * Calculates the squared length of a vec3
+ *
+ * @param {vec3} a vector to calculate squared length of
+ * @returns {Number} squared length of a
+ */
+vec3.squaredLength = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2];
+ return x*x + y*y + z*z;
+};
+
+/**
+ * Alias for {@link vec3.squaredLength}
+ * @function
+ */
+vec3.sqrLen = vec3.squaredLength;
+
+/**
+ * Negates the components of a vec3
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a vector to negate
+ * @returns {vec3} out
+ */
+vec3.negate = function(out, a) {
+ out[0] = -a[0];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ return out;
+};
+
+/**
+ * Normalize a vec3
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a vector to normalize
+ * @returns {vec3} out
+ */
+vec3.normalize = function(out, a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2];
+ var len = x*x + y*y + z*z;
+ if (len > 0) {
+ //TODO: evaluate use of glm_invsqrt here?
+ len = 1 / Math.sqrt(len);
+ out[0] = a[0] * len;
+ out[1] = a[1] * len;
+ out[2] = a[2] * len;
+ }
+ return out;
+};
+
+/**
+ * Calculates the dot product of two vec3's
+ *
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {Number} dot product of a and b
+ */
+vec3.dot = function (a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+};
+
+/**
+ * Computes the cross product of two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+vec3.cross = function(out, a, b) {
+ var ax = a[0], ay = a[1], az = a[2],
+ bx = b[0], by = b[1], bz = b[2];
+
+ out[0] = ay * bz - az * by;
+ out[1] = az * bx - ax * bz;
+ out[2] = ax * by - ay * bx;
+ return out;
+};
+
+/**
+ * Performs a linear interpolation between two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {vec3} out
+ */
+vec3.lerp = function (out, a, b, t) {
+ var ax = a[0],
+ ay = a[1],
+ az = a[2];
+ out[0] = ax + t * (b[0] - ax);
+ out[1] = ay + t * (b[1] - ay);
+ out[2] = az + t * (b[2] - az);
+ return out;
+};
+
+/**
+ * Generates a random vector with the given scale
+ *
+ * @param {vec3} out the receiving vector
+ * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
+ * @returns {vec3} out
+ */
+vec3.random = function (out, scale) {
+ scale = scale || 1.0;
+
+ var r = GLMAT_RANDOM() * 2.0 * Math.PI;
+ var z = (GLMAT_RANDOM() * 2.0) - 1.0;
+ var zScale = Math.sqrt(1.0-z*z) * scale;
+
+ out[0] = Math.cos(r) * zScale;
+ out[1] = Math.sin(r) * zScale;
+ out[2] = z * scale;
+ return out;
+};
+
+/**
+ * Transforms the vec3 with a mat4.
+ * 4th vector component is implicitly '1'
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the vector to transform
+ * @param {mat4} m matrix to transform with
+ * @returns {vec3} out
+ */
+vec3.transformMat4 = function(out, a, m) {
+ var x = a[0], y = a[1], z = a[2];
+ out[0] = m[0] * x + m[4] * y + m[8] * z + m[12];
+ out[1] = m[1] * x + m[5] * y + m[9] * z + m[13];
+ out[2] = m[2] * x + m[6] * y + m[10] * z + m[14];
+ return out;
+};
+
+/**
+ * Transforms the vec3 with a mat3.
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the vector to transform
+ * @param {mat4} m the 3x3 matrix to transform with
+ * @returns {vec3} out
+ */
+vec3.transformMat3 = function(out, a, m) {
+ var x = a[0], y = a[1], z = a[2];
+ out[0] = x * m[0] + y * m[3] + z * m[6];
+ out[1] = x * m[1] + y * m[4] + z * m[7];
+ out[2] = x * m[2] + y * m[5] + z * m[8];
+ return out;
+};
+
+/**
+ * Transforms the vec3 with a quat
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the vector to transform
+ * @param {quat} q quaternion to transform with
+ * @returns {vec3} out
+ */
+vec3.transformQuat = function(out, a, q) {
+ // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
+
+ var x = a[0], y = a[1], z = a[2],
+ qx = q[0], qy = q[1], qz = q[2], qw = q[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
+ out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
+ out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
+ out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
+ return out;
+};
+
+/*
+* Rotate a 3D vector around the x-axis
+* @param {vec3} out The receiving vec3
+* @param {vec3} a The vec3 point to rotate
+* @param {vec3} b The origin of the rotation
+* @param {Number} c The angle of rotation
+* @returns {vec3} out
+*/
+vec3.rotateX = function(out, a, b, c){
+ var p = [], r=[];
+ //Translate point to the origin
+ p[0] = a[0] - b[0];
+ p[1] = a[1] - b[1];
+ p[2] = a[2] - b[2];
+
+ //perform rotation
+ r[0] = p[0];
+ r[1] = p[1]*Math.cos(c) - p[2]*Math.sin(c);
+ r[2] = p[1]*Math.sin(c) + p[2]*Math.cos(c);
+
+ //translate to correct position
+ out[0] = r[0] + b[0];
+ out[1] = r[1] + b[1];
+ out[2] = r[2] + b[2];
+
+ return out;
+};
+
+/*
+* Rotate a 3D vector around the y-axis
+* @param {vec3} out The receiving vec3
+* @param {vec3} a The vec3 point to rotate
+* @param {vec3} b The origin of the rotation
+* @param {Number} c The angle of rotation
+* @returns {vec3} out
+*/
+vec3.rotateY = function(out, a, b, c){
+ var p = [], r=[];
+ //Translate point to the origin
+ p[0] = a[0] - b[0];
+ p[1] = a[1] - b[1];
+ p[2] = a[2] - b[2];
+
+ //perform rotation
+ r[0] = p[2]*Math.sin(c) + p[0]*Math.cos(c);
+ r[1] = p[1];
+ r[2] = p[2]*Math.cos(c) - p[0]*Math.sin(c);
+
+ //translate to correct position
+ out[0] = r[0] + b[0];
+ out[1] = r[1] + b[1];
+ out[2] = r[2] + b[2];
+
+ return out;
+};
+
+/*
+* Rotate a 3D vector around the z-axis
+* @param {vec3} out The receiving vec3
+* @param {vec3} a The vec3 point to rotate
+* @param {vec3} b The origin of the rotation
+* @param {Number} c The angle of rotation
+* @returns {vec3} out
+*/
+vec3.rotateZ = function(out, a, b, c){
+ var p = [], r=[];
+ //Translate point to the origin
+ p[0] = a[0] - b[0];
+ p[1] = a[1] - b[1];
+ p[2] = a[2] - b[2];
+
+ //perform rotation
+ r[0] = p[0]*Math.cos(c) - p[1]*Math.sin(c);
+ r[1] = p[0]*Math.sin(c) + p[1]*Math.cos(c);
+ r[2] = p[2];
+
+ //translate to correct position
+ out[0] = r[0] + b[0];
+ out[1] = r[1] + b[1];
+ out[2] = r[2] + b[2];
+
+ return out;
+};
+
+/**
+ * Perform some operation over an array of vec3s.
+ *
+ * @param {Array} a the array of vectors to iterate over
+ * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
+ * @param {Number} offset Number of elements to skip at the beginning of the array
+ * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
+ * @param {Function} fn Function to call for each vector in the array
+ * @param {Object} [arg] additional argument to pass to fn
+ * @returns {Array} a
+ * @function
+ */
+vec3.forEach = (function() {
+ var vec = vec3.create();
+
+ return function(a, stride, offset, count, fn, arg) {
+ var i, l;
+ if(!stride) {
+ stride = 3;
+ }
+
+ if(!offset) {
+ offset = 0;
+ }
+
+ if(count) {
+ l = Math.min((count * stride) + offset, a.length);
+ } else {
+ l = a.length;
+ }
+
+ for(i = offset; i < l; i += stride) {
+ vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2];
+ fn(vec, vec, arg);
+ a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2];
+ }
+
+ return a;
+ };
+})();
+
+/**
+ * Returns a string representation of a vector
+ *
+ * @param {vec3} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+vec3.str = function (a) {
+ return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.vec3 = vec3;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 4 Dimensional Vector
+ * @name vec4
+ */
+
+var vec4 = {};
+
+/**
+ * Creates a new, empty vec4
+ *
+ * @returns {vec4} a new 4D vector
+ */
+vec4.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ return out;
+};
+
+/**
+ * Creates a new vec4 initialized with values from an existing vector
+ *
+ * @param {vec4} a vector to clone
+ * @returns {vec4} a new 4D vector
+ */
+vec4.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Creates a new vec4 initialized with the given values
+ *
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {vec4} a new 4D vector
+ */
+vec4.fromValues = function(x, y, z, w) {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ out[3] = w;
+ return out;
+};
+
+/**
+ * Copy the values from one vec4 to another
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the source vector
+ * @returns {vec4} out
+ */
+vec4.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Set the components of a vec4 to the given values
+ *
+ * @param {vec4} out the receiving vector
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {vec4} out
+ */
+vec4.set = function(out, x, y, z, w) {
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ out[3] = w;
+ return out;
+};
+
+/**
+ * Adds two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.add = function(out, a, b) {
+ out[0] = a[0] + b[0];
+ out[1] = a[1] + b[1];
+ out[2] = a[2] + b[2];
+ out[3] = a[3] + b[3];
+ return out;
+};
+
+/**
+ * Subtracts vector b from vector a
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.subtract = function(out, a, b) {
+ out[0] = a[0] - b[0];
+ out[1] = a[1] - b[1];
+ out[2] = a[2] - b[2];
+ out[3] = a[3] - b[3];
+ return out;
+};
+
+/**
+ * Alias for {@link vec4.subtract}
+ * @function
+ */
+vec4.sub = vec4.subtract;
+
+/**
+ * Multiplies two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.multiply = function(out, a, b) {
+ out[0] = a[0] * b[0];
+ out[1] = a[1] * b[1];
+ out[2] = a[2] * b[2];
+ out[3] = a[3] * b[3];
+ return out;
+};
+
+/**
+ * Alias for {@link vec4.multiply}
+ * @function
+ */
+vec4.mul = vec4.multiply;
+
+/**
+ * Divides two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.divide = function(out, a, b) {
+ out[0] = a[0] / b[0];
+ out[1] = a[1] / b[1];
+ out[2] = a[2] / b[2];
+ out[3] = a[3] / b[3];
+ return out;
+};
+
+/**
+ * Alias for {@link vec4.divide}
+ * @function
+ */
+vec4.div = vec4.divide;
+
+/**
+ * Returns the minimum of two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.min = function(out, a, b) {
+ out[0] = Math.min(a[0], b[0]);
+ out[1] = Math.min(a[1], b[1]);
+ out[2] = Math.min(a[2], b[2]);
+ out[3] = Math.min(a[3], b[3]);
+ return out;
+};
+
+/**
+ * Returns the maximum of two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {vec4} out
+ */
+vec4.max = function(out, a, b) {
+ out[0] = Math.max(a[0], b[0]);
+ out[1] = Math.max(a[1], b[1]);
+ out[2] = Math.max(a[2], b[2]);
+ out[3] = Math.max(a[3], b[3]);
+ return out;
+};
+
+/**
+ * Scales a vec4 by a scalar number
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the vector to scale
+ * @param {Number} b amount to scale the vector by
+ * @returns {vec4} out
+ */
+vec4.scale = function(out, a, b) {
+ out[0] = a[0] * b;
+ out[1] = a[1] * b;
+ out[2] = a[2] * b;
+ out[3] = a[3] * b;
+ return out;
+};
+
+/**
+ * Adds two vec4's after scaling the second operand by a scalar value
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @param {Number} scale the amount to scale b by before adding
+ * @returns {vec4} out
+ */
+vec4.scaleAndAdd = function(out, a, b, scale) {
+ out[0] = a[0] + (b[0] * scale);
+ out[1] = a[1] + (b[1] * scale);
+ out[2] = a[2] + (b[2] * scale);
+ out[3] = a[3] + (b[3] * scale);
+ return out;
+};
+
+/**
+ * Calculates the euclidian distance between two vec4's
+ *
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {Number} distance between a and b
+ */
+vec4.distance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2],
+ w = b[3] - a[3];
+ return Math.sqrt(x*x + y*y + z*z + w*w);
+};
+
+/**
+ * Alias for {@link vec4.distance}
+ * @function
+ */
+vec4.dist = vec4.distance;
+
+/**
+ * Calculates the squared euclidian distance between two vec4's
+ *
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {Number} squared distance between a and b
+ */
+vec4.squaredDistance = function(a, b) {
+ var x = b[0] - a[0],
+ y = b[1] - a[1],
+ z = b[2] - a[2],
+ w = b[3] - a[3];
+ return x*x + y*y + z*z + w*w;
+};
+
+/**
+ * Alias for {@link vec4.squaredDistance}
+ * @function
+ */
+vec4.sqrDist = vec4.squaredDistance;
+
+/**
+ * Calculates the length of a vec4
+ *
+ * @param {vec4} a vector to calculate length of
+ * @returns {Number} length of a
+ */
+vec4.length = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2],
+ w = a[3];
+ return Math.sqrt(x*x + y*y + z*z + w*w);
+};
+
+/**
+ * Alias for {@link vec4.length}
+ * @function
+ */
+vec4.len = vec4.length;
+
+/**
+ * Calculates the squared length of a vec4
+ *
+ * @param {vec4} a vector to calculate squared length of
+ * @returns {Number} squared length of a
+ */
+vec4.squaredLength = function (a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2],
+ w = a[3];
+ return x*x + y*y + z*z + w*w;
+};
+
+/**
+ * Alias for {@link vec4.squaredLength}
+ * @function
+ */
+vec4.sqrLen = vec4.squaredLength;
+
+/**
+ * Negates the components of a vec4
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a vector to negate
+ * @returns {vec4} out
+ */
+vec4.negate = function(out, a) {
+ out[0] = -a[0];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ out[3] = -a[3];
+ return out;
+};
+
+/**
+ * Normalize a vec4
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a vector to normalize
+ * @returns {vec4} out
+ */
+vec4.normalize = function(out, a) {
+ var x = a[0],
+ y = a[1],
+ z = a[2],
+ w = a[3];
+ var len = x*x + y*y + z*z + w*w;
+ if (len > 0) {
+ len = 1 / Math.sqrt(len);
+ out[0] = a[0] * len;
+ out[1] = a[1] * len;
+ out[2] = a[2] * len;
+ out[3] = a[3] * len;
+ }
+ return out;
+};
+
+/**
+ * Calculates the dot product of two vec4's
+ *
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @returns {Number} dot product of a and b
+ */
+vec4.dot = function (a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
+};
+
+/**
+ * Performs a linear interpolation between two vec4's
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the first operand
+ * @param {vec4} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {vec4} out
+ */
+vec4.lerp = function (out, a, b, t) {
+ var ax = a[0],
+ ay = a[1],
+ az = a[2],
+ aw = a[3];
+ out[0] = ax + t * (b[0] - ax);
+ out[1] = ay + t * (b[1] - ay);
+ out[2] = az + t * (b[2] - az);
+ out[3] = aw + t * (b[3] - aw);
+ return out;
+};
+
+/**
+ * Generates a random vector with the given scale
+ *
+ * @param {vec4} out the receiving vector
+ * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
+ * @returns {vec4} out
+ */
+vec4.random = function (out, scale) {
+ scale = scale || 1.0;
+
+ //TODO: This is a pretty awful way of doing this. Find something better.
+ out[0] = GLMAT_RANDOM();
+ out[1] = GLMAT_RANDOM();
+ out[2] = GLMAT_RANDOM();
+ out[3] = GLMAT_RANDOM();
+ vec4.normalize(out, out);
+ vec4.scale(out, out, scale);
+ return out;
+};
+
+/**
+ * Transforms the vec4 with a mat4.
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the vector to transform
+ * @param {mat4} m matrix to transform with
+ * @returns {vec4} out
+ */
+vec4.transformMat4 = function(out, a, m) {
+ var x = a[0], y = a[1], z = a[2], w = a[3];
+ out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
+ out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
+ out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
+ out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
+ return out;
+};
+
+/**
+ * Transforms the vec4 with a quat
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the vector to transform
+ * @param {quat} q quaternion to transform with
+ * @returns {vec4} out
+ */
+vec4.transformQuat = function(out, a, q) {
+ var x = a[0], y = a[1], z = a[2],
+ qx = q[0], qy = q[1], qz = q[2], qw = q[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
+ out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
+ out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
+ out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
+ return out;
+};
+
+/**
+ * Perform some operation over an array of vec4s.
+ *
+ * @param {Array} a the array of vectors to iterate over
+ * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
+ * @param {Number} offset Number of elements to skip at the beginning of the array
+ * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
+ * @param {Function} fn Function to call for each vector in the array
+ * @param {Object} [arg] additional argument to pass to fn
+ * @returns {Array} a
+ * @function
+ */
+vec4.forEach = (function() {
+ var vec = vec4.create();
+
+ return function(a, stride, offset, count, fn, arg) {
+ var i, l;
+ if(!stride) {
+ stride = 4;
+ }
+
+ if(!offset) {
+ offset = 0;
+ }
+
+ if(count) {
+ l = Math.min((count * stride) + offset, a.length);
+ } else {
+ l = a.length;
+ }
+
+ for(i = offset; i < l; i += stride) {
+ vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; vec[3] = a[i+3];
+ fn(vec, vec, arg);
+ a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; a[i+3] = vec[3];
+ }
+
+ return a;
+ };
+})();
+
+/**
+ * Returns a string representation of a vector
+ *
+ * @param {vec4} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+vec4.str = function (a) {
+ return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.vec4 = vec4;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 2x2 Matrix
+ * @name mat2
+ */
+
+var mat2 = {};
+
+/**
+ * Creates a new identity mat2
+ *
+ * @returns {mat2} a new 2x2 matrix
+ */
+mat2.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Creates a new mat2 initialized with values from an existing matrix
+ *
+ * @param {mat2} a matrix to clone
+ * @returns {mat2} a new 2x2 matrix
+ */
+mat2.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Copy the values from one mat2 to another
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Set a mat2 to the identity matrix
+ *
+ * @param {mat2} out the receiving matrix
+ * @returns {mat2} out
+ */
+mat2.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Transpose the values of a mat2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.transpose = function(out, a) {
+ // If we are transposing ourselves we can skip a few steps but have to cache some values
+ if (out === a) {
+ var a1 = a[1];
+ out[1] = a[2];
+ out[2] = a1;
+ } else {
+ out[0] = a[0];
+ out[1] = a[2];
+ out[2] = a[1];
+ out[3] = a[3];
+ }
+
+ return out;
+};
+
+/**
+ * Inverts a mat2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.invert = function(out, a) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+
+ // Calculate the determinant
+ det = a0 * a3 - a2 * a1;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = a3 * det;
+ out[1] = -a1 * det;
+ out[2] = -a2 * det;
+ out[3] = a0 * det;
+
+ return out;
+};
+
+/**
+ * Calculates the adjugate of a mat2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+mat2.adjoint = function(out, a) {
+ // Caching this value is nessecary if out == a
+ var a0 = a[0];
+ out[0] = a[3];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ out[3] = a0;
+
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat2
+ *
+ * @param {mat2} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat2.determinant = function (a) {
+ return a[0] * a[3] - a[2] * a[1];
+};
+
+/**
+ * Multiplies two mat2's
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the first operand
+ * @param {mat2} b the second operand
+ * @returns {mat2} out
+ */
+mat2.multiply = function (out, a, b) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
+ var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
+ out[0] = a0 * b0 + a2 * b1;
+ out[1] = a1 * b0 + a3 * b1;
+ out[2] = a0 * b2 + a2 * b3;
+ out[3] = a1 * b2 + a3 * b3;
+ return out;
+};
+
+/**
+ * Alias for {@link mat2.multiply}
+ * @function
+ */
+mat2.mul = mat2.multiply;
+
+/**
+ * Rotates a mat2 by the given angle
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat2} out
+ */
+mat2.rotate = function (out, a, rad) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+ s = Math.sin(rad),
+ c = Math.cos(rad);
+ out[0] = a0 * c + a2 * s;
+ out[1] = a1 * c + a3 * s;
+ out[2] = a0 * -s + a2 * c;
+ out[3] = a1 * -s + a3 * c;
+ return out;
+};
+
+/**
+ * Scales the mat2 by the dimensions in the given vec2
+ *
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the matrix to rotate
+ * @param {vec2} v the vec2 to scale the matrix by
+ * @returns {mat2} out
+ **/
+mat2.scale = function(out, a, v) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+ v0 = v[0], v1 = v[1];
+ out[0] = a0 * v0;
+ out[1] = a1 * v0;
+ out[2] = a2 * v1;
+ out[3] = a3 * v1;
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat2
+ *
+ * @param {mat2} mat matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat2.str = function (a) {
+ return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
+};
+
+/**
+ * Returns Frobenius norm of a mat2
+ *
+ * @param {mat2} a the matrix to calculate Frobenius norm of
+ * @returns {Number} Frobenius norm
+ */
+mat2.frob = function (a) {
+ return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2)))
+};
+
+/**
+ * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix
+ * @param {mat2} L the lower triangular matrix
+ * @param {mat2} D the diagonal matrix
+ * @param {mat2} U the upper triangular matrix
+ * @param {mat2} a the input matrix to factorize
+ */
+
+mat2.LDU = function (L, D, U, a) {
+ L[2] = a[2]/a[0];
+ U[0] = a[0];
+ U[1] = a[1];
+ U[3] = a[3] - L[2] * U[1];
+ return [L, D, U];
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat2 = mat2;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 2x3 Matrix
+ * @name mat2d
+ *
+ * @description
+ * A mat2d contains six elements defined as:
+ *
+ * [a, c, tx,
+ * b, d, ty]
+ *
+ * This is a short form for the 3x3 matrix:
+ *
+ * [a, c, tx,
+ * b, d, ty,
+ * 0, 0, 1]
+ *
+ * The last row is ignored so the array is shorter and operations are faster.
+ */
+
+var mat2d = {};
+
+/**
+ * Creates a new identity mat2d
+ *
+ * @returns {mat2d} a new 2x3 matrix
+ */
+mat2d.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(6);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ out[4] = 0;
+ out[5] = 0;
+ return out;
+};
+
+/**
+ * Creates a new mat2d initialized with values from an existing matrix
+ *
+ * @param {mat2d} a matrix to clone
+ * @returns {mat2d} a new 2x3 matrix
+ */
+mat2d.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(6);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ return out;
+};
+
+/**
+ * Copy the values from one mat2d to another
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the source matrix
+ * @returns {mat2d} out
+ */
+mat2d.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ return out;
+};
+
+/**
+ * Set a mat2d to the identity matrix
+ *
+ * @param {mat2d} out the receiving matrix
+ * @returns {mat2d} out
+ */
+mat2d.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ out[4] = 0;
+ out[5] = 0;
+ return out;
+};
+
+/**
+ * Inverts a mat2d
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the source matrix
+ * @returns {mat2d} out
+ */
+mat2d.invert = function(out, a) {
+ var aa = a[0], ab = a[1], ac = a[2], ad = a[3],
+ atx = a[4], aty = a[5];
+
+ var det = aa * ad - ab * ac;
+ if(!det){
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = ad * det;
+ out[1] = -ab * det;
+ out[2] = -ac * det;
+ out[3] = aa * det;
+ out[4] = (ac * aty - ad * atx) * det;
+ out[5] = (ab * atx - aa * aty) * det;
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat2d
+ *
+ * @param {mat2d} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat2d.determinant = function (a) {
+ return a[0] * a[3] - a[1] * a[2];
+};
+
+/**
+ * Multiplies two mat2d's
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the first operand
+ * @param {mat2d} b the second operand
+ * @returns {mat2d} out
+ */
+mat2d.multiply = function (out, a, b) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5],
+ b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5];
+ out[0] = a0 * b0 + a2 * b1;
+ out[1] = a1 * b0 + a3 * b1;
+ out[2] = a0 * b2 + a2 * b3;
+ out[3] = a1 * b2 + a3 * b3;
+ out[4] = a0 * b4 + a2 * b5 + a4;
+ out[5] = a1 * b4 + a3 * b5 + a5;
+ return out;
+};
+
+/**
+ * Alias for {@link mat2d.multiply}
+ * @function
+ */
+mat2d.mul = mat2d.multiply;
+
+
+/**
+ * Rotates a mat2d by the given angle
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat2d} out
+ */
+mat2d.rotate = function (out, a, rad) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5],
+ s = Math.sin(rad),
+ c = Math.cos(rad);
+ out[0] = a0 * c + a2 * s;
+ out[1] = a1 * c + a3 * s;
+ out[2] = a0 * -s + a2 * c;
+ out[3] = a1 * -s + a3 * c;
+ out[4] = a4;
+ out[5] = a5;
+ return out;
+};
+
+/**
+ * Scales the mat2d by the dimensions in the given vec2
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the matrix to translate
+ * @param {vec2} v the vec2 to scale the matrix by
+ * @returns {mat2d} out
+ **/
+mat2d.scale = function(out, a, v) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5],
+ v0 = v[0], v1 = v[1];
+ out[0] = a0 * v0;
+ out[1] = a1 * v0;
+ out[2] = a2 * v1;
+ out[3] = a3 * v1;
+ out[4] = a4;
+ out[5] = a5;
+ return out;
+};
+
+/**
+ * Translates the mat2d by the dimensions in the given vec2
+ *
+ * @param {mat2d} out the receiving matrix
+ * @param {mat2d} a the matrix to translate
+ * @param {vec2} v the vec2 to translate the matrix by
+ * @returns {mat2d} out
+ **/
+mat2d.translate = function(out, a, v) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5],
+ v0 = v[0], v1 = v[1];
+ out[0] = a0;
+ out[1] = a1;
+ out[2] = a2;
+ out[3] = a3;
+ out[4] = a0 * v0 + a2 * v1 + a4;
+ out[5] = a1 * v0 + a3 * v1 + a5;
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat2d
+ *
+ * @param {mat2d} a matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat2d.str = function (a) {
+ return 'mat2d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' +
+ a[3] + ', ' + a[4] + ', ' + a[5] + ')';
+};
+
+/**
+ * Returns Frobenius norm of a mat2d
+ *
+ * @param {mat2d} a the matrix to calculate Frobenius norm of
+ * @returns {Number} Frobenius norm
+ */
+mat2d.frob = function (a) {
+ return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + 1))
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat2d = mat2d;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 3x3 Matrix
+ * @name mat3
+ */
+
+var mat3 = {};
+
+/**
+ * Creates a new identity mat3
+ *
+ * @returns {mat3} a new 3x3 matrix
+ */
+mat3.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(9);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 1;
+ out[5] = 0;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 1;
+ return out;
+};
+
+/**
+ * Copies the upper-left 3x3 values into the given mat3.
+ *
+ * @param {mat3} out the receiving 3x3 matrix
+ * @param {mat4} a the source 4x4 matrix
+ * @returns {mat3} out
+ */
+mat3.fromMat4 = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[4];
+ out[4] = a[5];
+ out[5] = a[6];
+ out[6] = a[8];
+ out[7] = a[9];
+ out[8] = a[10];
+ return out;
+};
+
+/**
+ * Creates a new mat3 initialized with values from an existing matrix
+ *
+ * @param {mat3} a matrix to clone
+ * @returns {mat3} a new 3x3 matrix
+ */
+mat3.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(9);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ return out;
+};
+
+/**
+ * Copy the values from one mat3 to another
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ return out;
+};
+
+/**
+ * Set a mat3 to the identity matrix
+ *
+ * @param {mat3} out the receiving matrix
+ * @returns {mat3} out
+ */
+mat3.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 1;
+ out[5] = 0;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 1;
+ return out;
+};
+
+/**
+ * Transpose the values of a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.transpose = function(out, a) {
+ // If we are transposing ourselves we can skip a few steps but have to cache some values
+ if (out === a) {
+ var a01 = a[1], a02 = a[2], a12 = a[5];
+ out[1] = a[3];
+ out[2] = a[6];
+ out[3] = a01;
+ out[5] = a[7];
+ out[6] = a02;
+ out[7] = a12;
+ } else {
+ out[0] = a[0];
+ out[1] = a[3];
+ out[2] = a[6];
+ out[3] = a[1];
+ out[4] = a[4];
+ out[5] = a[7];
+ out[6] = a[2];
+ out[7] = a[5];
+ out[8] = a[8];
+ }
+
+ return out;
+};
+
+/**
+ * Inverts a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.invert = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+
+ b01 = a22 * a11 - a12 * a21,
+ b11 = -a22 * a10 + a12 * a20,
+ b21 = a21 * a10 - a11 * a20,
+
+ // Calculate the determinant
+ det = a00 * b01 + a01 * b11 + a02 * b21;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = b01 * det;
+ out[1] = (-a22 * a01 + a02 * a21) * det;
+ out[2] = (a12 * a01 - a02 * a11) * det;
+ out[3] = b11 * det;
+ out[4] = (a22 * a00 - a02 * a20) * det;
+ out[5] = (-a12 * a00 + a02 * a10) * det;
+ out[6] = b21 * det;
+ out[7] = (-a21 * a00 + a01 * a20) * det;
+ out[8] = (a11 * a00 - a01 * a10) * det;
+ return out;
+};
+
+/**
+ * Calculates the adjugate of a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+mat3.adjoint = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8];
+
+ out[0] = (a11 * a22 - a12 * a21);
+ out[1] = (a02 * a21 - a01 * a22);
+ out[2] = (a01 * a12 - a02 * a11);
+ out[3] = (a12 * a20 - a10 * a22);
+ out[4] = (a00 * a22 - a02 * a20);
+ out[5] = (a02 * a10 - a00 * a12);
+ out[6] = (a10 * a21 - a11 * a20);
+ out[7] = (a01 * a20 - a00 * a21);
+ out[8] = (a00 * a11 - a01 * a10);
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat3
+ *
+ * @param {mat3} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat3.determinant = function (a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8];
+
+ return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
+};
+
+/**
+ * Multiplies two mat3's
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the first operand
+ * @param {mat3} b the second operand
+ * @returns {mat3} out
+ */
+mat3.multiply = function (out, a, b) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+
+ b00 = b[0], b01 = b[1], b02 = b[2],
+ b10 = b[3], b11 = b[4], b12 = b[5],
+ b20 = b[6], b21 = b[7], b22 = b[8];
+
+ out[0] = b00 * a00 + b01 * a10 + b02 * a20;
+ out[1] = b00 * a01 + b01 * a11 + b02 * a21;
+ out[2] = b00 * a02 + b01 * a12 + b02 * a22;
+
+ out[3] = b10 * a00 + b11 * a10 + b12 * a20;
+ out[4] = b10 * a01 + b11 * a11 + b12 * a21;
+ out[5] = b10 * a02 + b11 * a12 + b12 * a22;
+
+ out[6] = b20 * a00 + b21 * a10 + b22 * a20;
+ out[7] = b20 * a01 + b21 * a11 + b22 * a21;
+ out[8] = b20 * a02 + b21 * a12 + b22 * a22;
+ return out;
+};
+
+/**
+ * Alias for {@link mat3.multiply}
+ * @function
+ */
+mat3.mul = mat3.multiply;
+
+/**
+ * Translate a mat3 by the given vector
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the matrix to translate
+ * @param {vec2} v vector to translate by
+ * @returns {mat3} out
+ */
+mat3.translate = function(out, a, v) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+ x = v[0], y = v[1];
+
+ out[0] = a00;
+ out[1] = a01;
+ out[2] = a02;
+
+ out[3] = a10;
+ out[4] = a11;
+ out[5] = a12;
+
+ out[6] = x * a00 + y * a10 + a20;
+ out[7] = x * a01 + y * a11 + a21;
+ out[8] = x * a02 + y * a12 + a22;
+ return out;
+};
+
+/**
+ * Rotates a mat3 by the given angle
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat3} out
+ */
+mat3.rotate = function (out, a, rad) {
+ var a00 = a[0], a01 = a[1], a02 = a[2],
+ a10 = a[3], a11 = a[4], a12 = a[5],
+ a20 = a[6], a21 = a[7], a22 = a[8],
+
+ s = Math.sin(rad),
+ c = Math.cos(rad);
+
+ out[0] = c * a00 + s * a10;
+ out[1] = c * a01 + s * a11;
+ out[2] = c * a02 + s * a12;
+
+ out[3] = c * a10 - s * a00;
+ out[4] = c * a11 - s * a01;
+ out[5] = c * a12 - s * a02;
+
+ out[6] = a20;
+ out[7] = a21;
+ out[8] = a22;
+ return out;
+};
+
+/**
+ * Scales the mat3 by the dimensions in the given vec2
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the matrix to rotate
+ * @param {vec2} v the vec2 to scale the matrix by
+ * @returns {mat3} out
+ **/
+mat3.scale = function(out, a, v) {
+ var x = v[0], y = v[1];
+
+ out[0] = x * a[0];
+ out[1] = x * a[1];
+ out[2] = x * a[2];
+
+ out[3] = y * a[3];
+ out[4] = y * a[4];
+ out[5] = y * a[5];
+
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ return out;
+};
+
+/**
+ * Copies the values from a mat2d into a mat3
+ *
+ * @param {mat3} out the receiving matrix
+ * @param {mat2d} a the matrix to copy
+ * @returns {mat3} out
+ **/
+mat3.fromMat2d = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = 0;
+
+ out[3] = a[2];
+ out[4] = a[3];
+ out[5] = 0;
+
+ out[6] = a[4];
+ out[7] = a[5];
+ out[8] = 1;
+ return out;
+};
+
+/**
+* Calculates a 3x3 matrix from the given quaternion
+*
+* @param {mat3} out mat3 receiving operation result
+* @param {quat} q Quaternion to create matrix from
+*
+* @returns {mat3} out
+*/
+mat3.fromQuat = function (out, q) {
+ var x = q[0], y = q[1], z = q[2], w = q[3],
+ x2 = x + x,
+ y2 = y + y,
+ z2 = z + z,
+
+ xx = x * x2,
+ yx = y * x2,
+ yy = y * y2,
+ zx = z * x2,
+ zy = z * y2,
+ zz = z * z2,
+ wx = w * x2,
+ wy = w * y2,
+ wz = w * z2;
+
+ out[0] = 1 - yy - zz;
+ out[3] = yx - wz;
+ out[6] = zx + wy;
+
+ out[1] = yx + wz;
+ out[4] = 1 - xx - zz;
+ out[7] = zy - wx;
+
+ out[2] = zx - wy;
+ out[5] = zy + wx;
+ out[8] = 1 - xx - yy;
+
+ return out;
+};
+
+/**
+* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix
+*
+* @param {mat3} out mat3 receiving operation result
+* @param {mat4} a Mat4 to derive the normal matrix from
+*
+* @returns {mat3} out
+*/
+mat3.normalFromMat4 = function (out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[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,
+
+ // Calculate the determinant
+ det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
+ out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
+ out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
+
+ out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
+ out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
+ out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
+
+ out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
+ out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
+ out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
+
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat3
+ *
+ * @param {mat3} mat matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat3.str = function (a) {
+ return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' +
+ a[3] + ', ' + a[4] + ', ' + a[5] + ', ' +
+ a[6] + ', ' + a[7] + ', ' + a[8] + ')';
+};
+
+/**
+ * Returns Frobenius norm of a mat3
+ *
+ * @param {mat3} a the matrix to calculate Frobenius norm of
+ * @returns {Number} Frobenius norm
+ */
+mat3.frob = function (a) {
+ return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2)))
+};
+
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat3 = mat3;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class 4x4 Matrix
+ * @name mat4
+ */
+
+var mat4 = {};
+
+/**
+ * Creates a new identity mat4
+ *
+ * @returns {mat4} a new 4x4 matrix
+ */
+mat4.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(16);
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = 1;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = 1;
+ out[11] = 0;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = 0;
+ out[15] = 1;
+ return out;
+};
+
+/**
+ * Creates a new mat4 initialized with values from an existing matrix
+ *
+ * @param {mat4} a matrix to clone
+ * @returns {mat4} a new 4x4 matrix
+ */
+mat4.clone = function(a) {
+ var out = new GLMAT_ARRAY_TYPE(16);
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ out[9] = a[9];
+ out[10] = a[10];
+ out[11] = a[11];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ return out;
+};
+
+/**
+ * Copy the values from one mat4 to another
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.copy = function(out, a) {
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[8] = a[8];
+ out[9] = a[9];
+ out[10] = a[10];
+ out[11] = a[11];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ return out;
+};
+
+/**
+ * Set a mat4 to the identity matrix
+ *
+ * @param {mat4} out the receiving matrix
+ * @returns {mat4} out
+ */
+mat4.identity = function(out) {
+ out[0] = 1;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = 1;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = 1;
+ out[11] = 0;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = 0;
+ out[15] = 1;
+ return out;
+};
+
+/**
+ * Transpose the values of a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.transpose = function(out, a) {
+ // If we are transposing ourselves we can skip a few steps but have to cache some values
+ if (out === a) {
+ var a01 = a[1], a02 = a[2], a03 = a[3],
+ a12 = a[6], a13 = a[7],
+ a23 = a[11];
+
+ out[1] = a[4];
+ out[2] = a[8];
+ out[3] = a[12];
+ out[4] = a01;
+ out[6] = a[9];
+ out[7] = a[13];
+ out[8] = a02;
+ out[9] = a12;
+ out[11] = a[14];
+ out[12] = a03;
+ out[13] = a13;
+ out[14] = a23;
+ } else {
+ out[0] = a[0];
+ out[1] = a[4];
+ out[2] = a[8];
+ out[3] = a[12];
+ out[4] = a[1];
+ out[5] = a[5];
+ out[6] = a[9];
+ out[7] = a[13];
+ out[8] = a[2];
+ out[9] = a[6];
+ out[10] = a[10];
+ out[11] = a[14];
+ out[12] = a[3];
+ out[13] = a[7];
+ out[14] = a[11];
+ out[15] = a[15];
+ }
+
+ return out;
+};
+
+/**
+ * Inverts a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.invert = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[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,
+
+ // Calculate the determinant
+ det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+
+ if (!det) {
+ return null;
+ }
+ det = 1.0 / det;
+
+ out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
+ out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
+ out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
+ out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
+ out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
+ out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
+ out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
+ out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
+ out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
+ out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
+ out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
+ out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
+ out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
+ out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
+ out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
+ out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
+
+ return out;
+};
+
+/**
+ * Calculates the adjugate of a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+mat4.adjoint = function(out, a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
+
+ out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22));
+ out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
+ out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12));
+ out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
+ out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
+ out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22));
+ out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
+ out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12));
+ out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21));
+ out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
+ out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11));
+ out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
+ out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
+ out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21));
+ out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
+ out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11));
+ return out;
+};
+
+/**
+ * Calculates the determinant of a mat4
+ *
+ * @param {mat4} a the source matrix
+ * @returns {Number} determinant of a
+ */
+mat4.determinant = function (a) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[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;
+
+ // Calculate the determinant
+ return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+};
+
+/**
+ * Multiplies two mat4's
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the first operand
+ * @param {mat4} b the second operand
+ * @returns {mat4} out
+ */
+mat4.multiply = function (out, a, b) {
+ var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+ a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+ a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+ a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
+
+ // Cache only the current line of the second matrix
+ var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
+ out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+ b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
+ out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+ b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
+ out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+ b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
+ out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+ out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+ out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+ out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+ return out;
+};
+
+/**
+ * Alias for {@link mat4.multiply}
+ * @function
+ */
+mat4.mul = mat4.multiply;
+
+/**
+ * Translate a mat4 by the given vector
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to translate
+ * @param {vec3} v vector to translate by
+ * @returns {mat4} out
+ */
+mat4.translate = function (out, a, v) {
+ var x = v[0], y = v[1], z = v[2],
+ a00, a01, a02, a03,
+ a10, a11, a12, a13,
+ a20, a21, a22, a23;
+
+ if (a === out) {
+ out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
+ out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
+ out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
+ out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
+ } else {
+ a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
+ a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
+ a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
+
+ out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
+ out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
+ out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
+
+ out[12] = a00 * x + a10 * y + a20 * z + a[12];
+ out[13] = a01 * x + a11 * y + a21 * z + a[13];
+ out[14] = a02 * x + a12 * y + a22 * z + a[14];
+ out[15] = a03 * x + a13 * y + a23 * z + a[15];
+ }
+
+ return out;
+};
+
+/**
+ * Scales the mat4 by the dimensions in the given vec3
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to scale
+ * @param {vec3} v the vec3 to scale the matrix by
+ * @returns {mat4} out
+ **/
+mat4.scale = function(out, a, v) {
+ var x = v[0], y = v[1], z = v[2];
+
+ out[0] = a[0] * x;
+ out[1] = a[1] * x;
+ out[2] = a[2] * x;
+ out[3] = a[3] * x;
+ out[4] = a[4] * y;
+ out[5] = a[5] * y;
+ out[6] = a[6] * y;
+ out[7] = a[7] * y;
+ out[8] = a[8] * z;
+ out[9] = a[9] * z;
+ out[10] = a[10] * z;
+ out[11] = a[11] * z;
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ return out;
+};
+
+/**
+ * Rotates a mat4 by the given angle
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @param {vec3} axis the axis to rotate around
+ * @returns {mat4} out
+ */
+mat4.rotate = function (out, a, rad, axis) {
+ 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 (Math.abs(len) < GLMAT_EPSILON) { return null; }
+
+ len = 1 / len;
+ x *= len;
+ y *= len;
+ z *= len;
+
+ s = Math.sin(rad);
+ c = Math.cos(rad);
+ t = 1 - c;
+
+ a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
+ a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
+ a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[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;
+
+ // Perform rotation-specific matrix multiplication
+ out[0] = a00 * b00 + a10 * b01 + a20 * b02;
+ out[1] = a01 * b00 + a11 * b01 + a21 * b02;
+ out[2] = a02 * b00 + a12 * b01 + a22 * b02;
+ out[3] = a03 * b00 + a13 * b01 + a23 * b02;
+ out[4] = a00 * b10 + a10 * b11 + a20 * b12;
+ out[5] = a01 * b10 + a11 * b11 + a21 * b12;
+ out[6] = a02 * b10 + a12 * b11 + a22 * b12;
+ out[7] = a03 * b10 + a13 * b11 + a23 * b12;
+ out[8] = a00 * b20 + a10 * b21 + a20 * b22;
+ out[9] = a01 * b20 + a11 * b21 + a21 * b22;
+ out[10] = a02 * b20 + a12 * b21 + a22 * b22;
+ out[11] = a03 * b20 + a13 * b21 + a23 * b22;
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged last row
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+ return out;
+};
+
+/**
+ * Rotates a matrix by the given angle around the X axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+mat4.rotateX = function (out, a, rad) {
+ var s = Math.sin(rad),
+ c = Math.cos(rad),
+ a10 = a[4],
+ a11 = a[5],
+ a12 = a[6],
+ a13 = a[7],
+ a20 = a[8],
+ a21 = a[9],
+ a22 = a[10],
+ a23 = a[11];
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged rows
+ out[0] = a[0];
+ out[1] = a[1];
+ out[2] = a[2];
+ out[3] = a[3];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+
+ // Perform axis-specific matrix multiplication
+ out[4] = a10 * c + a20 * s;
+ out[5] = a11 * c + a21 * s;
+ out[6] = a12 * c + a22 * s;
+ out[7] = a13 * c + a23 * s;
+ out[8] = a20 * c - a10 * s;
+ out[9] = a21 * c - a11 * s;
+ out[10] = a22 * c - a12 * s;
+ out[11] = a23 * c - a13 * s;
+ return out;
+};
+
+/**
+ * Rotates a matrix by the given angle around the Y axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+mat4.rotateY = function (out, a, rad) {
+ var s = Math.sin(rad),
+ c = Math.cos(rad),
+ a00 = a[0],
+ a01 = a[1],
+ a02 = a[2],
+ a03 = a[3],
+ a20 = a[8],
+ a21 = a[9],
+ a22 = a[10],
+ a23 = a[11];
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged rows
+ out[4] = a[4];
+ out[5] = a[5];
+ out[6] = a[6];
+ out[7] = a[7];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+
+ // Perform axis-specific matrix multiplication
+ out[0] = a00 * c - a20 * s;
+ out[1] = a01 * c - a21 * s;
+ out[2] = a02 * c - a22 * s;
+ out[3] = a03 * c - a23 * s;
+ out[8] = a00 * s + a20 * c;
+ out[9] = a01 * s + a21 * c;
+ out[10] = a02 * s + a22 * c;
+ out[11] = a03 * s + a23 * c;
+ return out;
+};
+
+/**
+ * Rotates a matrix by the given angle around the Z axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+mat4.rotateZ = function (out, a, rad) {
+ var s = Math.sin(rad),
+ c = Math.cos(rad),
+ a00 = a[0],
+ a01 = a[1],
+ a02 = a[2],
+ a03 = a[3],
+ a10 = a[4],
+ a11 = a[5],
+ a12 = a[6],
+ a13 = a[7];
+
+ if (a !== out) { // If the source and destination differ, copy the unchanged last row
+ out[8] = a[8];
+ out[9] = a[9];
+ out[10] = a[10];
+ out[11] = a[11];
+ out[12] = a[12];
+ out[13] = a[13];
+ out[14] = a[14];
+ out[15] = a[15];
+ }
+
+ // Perform axis-specific matrix multiplication
+ out[0] = a00 * c + a10 * s;
+ out[1] = a01 * c + a11 * s;
+ out[2] = a02 * c + a12 * s;
+ out[3] = a03 * c + a13 * s;
+ out[4] = a10 * c - a00 * s;
+ out[5] = a11 * c - a01 * s;
+ out[6] = a12 * c - a02 * s;
+ out[7] = a13 * c - a03 * s;
+ return out;
+};
+
+/**
+ * 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 {mat4} out mat4 receiving operation result
+ * @param {quat4} q Rotation quaternion
+ * @param {vec3} v Translation vector
+ * @returns {mat4} out
+ */
+mat4.fromRotationTranslation = function (out, q, v) {
+ // Quaternion math
+ var x = q[0], y = q[1], z = q[2], w = q[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;
+
+ out[0] = 1 - (yy + zz);
+ out[1] = xy + wz;
+ out[2] = xz - wy;
+ out[3] = 0;
+ out[4] = xy - wz;
+ out[5] = 1 - (xx + zz);
+ out[6] = yz + wx;
+ out[7] = 0;
+ out[8] = xz + wy;
+ out[9] = yz - wx;
+ out[10] = 1 - (xx + yy);
+ out[11] = 0;
+ out[12] = v[0];
+ out[13] = v[1];
+ out[14] = v[2];
+ out[15] = 1;
+
+ return out;
+};
+
+mat4.fromQuat = function (out, q) {
+ var x = q[0], y = q[1], z = q[2], w = q[3],
+ x2 = x + x,
+ y2 = y + y,
+ z2 = z + z,
+
+ xx = x * x2,
+ yx = y * x2,
+ yy = y * y2,
+ zx = z * x2,
+ zy = z * y2,
+ zz = z * z2,
+ wx = w * x2,
+ wy = w * y2,
+ wz = w * z2;
+
+ out[0] = 1 - yy - zz;
+ out[1] = yx + wz;
+ out[2] = zx - wy;
+ out[3] = 0;
+
+ out[4] = yx - wz;
+ out[5] = 1 - xx - zz;
+ out[6] = zy + wx;
+ out[7] = 0;
+
+ out[8] = zx + wy;
+ out[9] = zy - wx;
+ out[10] = 1 - xx - yy;
+ out[11] = 0;
+
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = 0;
+ out[15] = 1;
+
+ return out;
+};
+
+/**
+ * Generates a frustum matrix with the given bounds
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @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
+ * @returns {mat4} out
+ */
+mat4.frustum = function (out, left, right, bottom, top, near, far) {
+ var rl = 1 / (right - left),
+ tb = 1 / (top - bottom),
+ nf = 1 / (near - far);
+ out[0] = (near * 2) * rl;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = (near * 2) * tb;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = (right + left) * rl;
+ out[9] = (top + bottom) * tb;
+ out[10] = (far + near) * nf;
+ out[11] = -1;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = (far * near * 2) * nf;
+ out[15] = 0;
+ return out;
+};
+
+/**
+ * Generates a perspective projection matrix with the given bounds
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @param {number} fovy Vertical field of view in radians
+ * @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
+ * @returns {mat4} out
+ */
+mat4.perspective = function (out, fovy, aspect, near, far) {
+ var f = 1.0 / Math.tan(fovy / 2),
+ nf = 1 / (near - far);
+ out[0] = f / aspect;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = f;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = (far + near) * nf;
+ out[11] = -1;
+ out[12] = 0;
+ out[13] = 0;
+ out[14] = (2 * far * near) * nf;
+ out[15] = 0;
+ return out;
+};
+
+/**
+ * Generates a orthogonal projection matrix with the given bounds
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @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
+ * @returns {mat4} out
+ */
+mat4.ortho = function (out, left, right, bottom, top, near, far) {
+ var lr = 1 / (left - right),
+ bt = 1 / (bottom - top),
+ nf = 1 / (near - far);
+ out[0] = -2 * lr;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ out[4] = 0;
+ out[5] = -2 * bt;
+ out[6] = 0;
+ out[7] = 0;
+ out[8] = 0;
+ out[9] = 0;
+ out[10] = 2 * nf;
+ out[11] = 0;
+ out[12] = (left + right) * lr;
+ out[13] = (top + bottom) * bt;
+ out[14] = (far + near) * nf;
+ out[15] = 1;
+ return out;
+};
+
+/**
+ * Generates a look-at matrix with the given eye position, focal point, and up axis
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @param {vec3} eye Position of the viewer
+ * @param {vec3} center Point the viewer is looking at
+ * @param {vec3} up vec3 pointing up
+ * @returns {mat4} out
+ */
+mat4.lookAt = function (out, eye, center, up) {
+ 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 (Math.abs(eyex - centerx) < GLMAT_EPSILON &&
+ Math.abs(eyey - centery) < GLMAT_EPSILON &&
+ Math.abs(eyez - centerz) < GLMAT_EPSILON) {
+ return mat4.identity(out);
+ }
+
+ z0 = eyex - centerx;
+ z1 = eyey - centery;
+ z2 = eyez - centerz;
+
+ len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
+ z0 *= len;
+ z1 *= len;
+ z2 *= len;
+
+ 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;
+ }
+
+ 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;
+ }
+
+ out[0] = x0;
+ out[1] = y0;
+ out[2] = z0;
+ out[3] = 0;
+ out[4] = x1;
+ out[5] = y1;
+ out[6] = z1;
+ out[7] = 0;
+ out[8] = x2;
+ out[9] = y2;
+ out[10] = z2;
+ out[11] = 0;
+ out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
+ out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
+ out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
+ out[15] = 1;
+
+ return out;
+};
+
+/**
+ * Returns a string representation of a mat4
+ *
+ * @param {mat4} mat matrix to represent as a string
+ * @returns {String} string representation of the matrix
+ */
+mat4.str = function (a) {
+ return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' +
+ a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' +
+ a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' +
+ a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')';
+};
+
+/**
+ * Returns Frobenius norm of a mat4
+ *
+ * @param {mat4} a the matrix to calculate Frobenius norm of
+ * @returns {Number} Frobenius norm
+ */
+mat4.frob = function (a) {
+ return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2) + Math.pow(a[9], 2) + Math.pow(a[10], 2) + Math.pow(a[11], 2) + Math.pow(a[12], 2) + Math.pow(a[13], 2) + Math.pow(a[14], 2) + Math.pow(a[15], 2) ))
+};
+
+
+if(typeof(exports) !== 'undefined') {
+ exports.mat4 = mat4;
+}
+;
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * @class Quaternion
+ * @name quat
+ */
+
+var quat = {};
+
+/**
+ * Creates a new identity quat
+ *
+ * @returns {quat} a new quaternion
+ */
+quat.create = function() {
+ var out = new GLMAT_ARRAY_TYPE(4);
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Sets a quaternion to represent the shortest rotation from one
+ * vector to another.
+ *
+ * Both vectors are assumed to be unit length.
+ *
+ * @param {quat} out the receiving quaternion.
+ * @param {vec3} a the initial vector
+ * @param {vec3} b the destination vector
+ * @returns {quat} out
+ */
+quat.rotationTo = (function() {
+ var tmpvec3 = vec3.create();
+ var xUnitVec3 = vec3.fromValues(1,0,0);
+ var yUnitVec3 = vec3.fromValues(0,1,0);
+
+ return function(out, a, b) {
+ var dot = vec3.dot(a, b);
+ if (dot < -0.999999) {
+ vec3.cross(tmpvec3, xUnitVec3, a);
+ if (vec3.length(tmpvec3) < 0.000001)
+ vec3.cross(tmpvec3, yUnitVec3, a);
+ vec3.normalize(tmpvec3, tmpvec3);
+ quat.setAxisAngle(out, tmpvec3, Math.PI);
+ return out;
+ } else if (dot > 0.999999) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+ } else {
+ vec3.cross(tmpvec3, a, b);
+ out[0] = tmpvec3[0];
+ out[1] = tmpvec3[1];
+ out[2] = tmpvec3[2];
+ out[3] = 1 + dot;
+ return quat.normalize(out, out);
+ }
+ };
+})();
+
+/**
+ * Sets the specified quaternion with values corresponding to the given
+ * axes. Each axis is a vec3 and is expected to be unit length and
+ * perpendicular to all other specified axes.
+ *
+ * @param {vec3} view the vector representing the viewing direction
+ * @param {vec3} right the vector representing the local "right" direction
+ * @param {vec3} up the vector representing the local "up" direction
+ * @returns {quat} out
+ */
+quat.setAxes = (function() {
+ var matr = mat3.create();
+
+ return function(out, view, right, up) {
+ matr[0] = right[0];
+ matr[3] = right[1];
+ matr[6] = right[2];
+
+ matr[1] = up[0];
+ matr[4] = up[1];
+ matr[7] = up[2];
+
+ matr[2] = -view[0];
+ matr[5] = -view[1];
+ matr[8] = -view[2];
+
+ return quat.normalize(out, quat.fromMat3(out, matr));
+ };
+})();
+
+/**
+ * Creates a new quat initialized with values from an existing quaternion
+ *
+ * @param {quat} a quaternion to clone
+ * @returns {quat} a new quaternion
+ * @function
+ */
+quat.clone = vec4.clone;
+
+/**
+ * Creates a new quat initialized with the given values
+ *
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {quat} a new quaternion
+ * @function
+ */
+quat.fromValues = vec4.fromValues;
+
+/**
+ * Copy the values from one quat to another
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the source quaternion
+ * @returns {quat} out
+ * @function
+ */
+quat.copy = vec4.copy;
+
+/**
+ * Set the components of a quat to the given values
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @param {Number} z Z component
+ * @param {Number} w W component
+ * @returns {quat} out
+ * @function
+ */
+quat.set = vec4.set;
+
+/**
+ * Set a quat to the identity quaternion
+ *
+ * @param {quat} out the receiving quaternion
+ * @returns {quat} out
+ */
+quat.identity = function(out) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 1;
+ return out;
+};
+
+/**
+ * Sets a quat from the given angle and rotation axis,
+ * then returns it.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {vec3} axis the axis around which to rotate
+ * @param {Number} rad the angle in radians
+ * @returns {quat} out
+ **/
+quat.setAxisAngle = function(out, axis, rad) {
+ rad = rad * 0.5;
+ var s = Math.sin(rad);
+ out[0] = s * axis[0];
+ out[1] = s * axis[1];
+ out[2] = s * axis[2];
+ out[3] = Math.cos(rad);
+ return out;
+};
+
+/**
+ * Adds two quat's
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @returns {quat} out
+ * @function
+ */
+quat.add = vec4.add;
+
+/**
+ * Multiplies two quat's
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @returns {quat} out
+ */
+quat.multiply = function(out, a, b) {
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bx = b[0], by = b[1], bz = b[2], bw = b[3];
+
+ out[0] = ax * bw + aw * bx + ay * bz - az * by;
+ out[1] = ay * bw + aw * by + az * bx - ax * bz;
+ out[2] = az * bw + aw * bz + ax * by - ay * bx;
+ out[3] = aw * bw - ax * bx - ay * by - az * bz;
+ return out;
+};
+
+/**
+ * Alias for {@link quat.multiply}
+ * @function
+ */
+quat.mul = quat.multiply;
+
+/**
+ * Scales a quat by a scalar number
+ *
+ * @param {quat} out the receiving vector
+ * @param {quat} a the vector to scale
+ * @param {Number} b amount to scale the vector by
+ * @returns {quat} out
+ * @function
+ */
+quat.scale = vec4.scale;
+
+/**
+ * Rotates a quaternion by the given angle about the X axis
+ *
+ * @param {quat} out quat receiving operation result
+ * @param {quat} a quat to rotate
+ * @param {number} rad angle (in radians) to rotate
+ * @returns {quat} out
+ */
+quat.rotateX = function (out, a, rad) {
+ rad *= 0.5;
+
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bx = Math.sin(rad), bw = Math.cos(rad);
+
+ out[0] = ax * bw + aw * bx;
+ out[1] = ay * bw + az * bx;
+ out[2] = az * bw - ay * bx;
+ out[3] = aw * bw - ax * bx;
+ return out;
+};
+
+/**
+ * Rotates a quaternion by the given angle about the Y axis
+ *
+ * @param {quat} out quat receiving operation result
+ * @param {quat} a quat to rotate
+ * @param {number} rad angle (in radians) to rotate
+ * @returns {quat} out
+ */
+quat.rotateY = function (out, a, rad) {
+ rad *= 0.5;
+
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ by = Math.sin(rad), bw = Math.cos(rad);
+
+ out[0] = ax * bw - az * by;
+ out[1] = ay * bw + aw * by;
+ out[2] = az * bw + ax * by;
+ out[3] = aw * bw - ay * by;
+ return out;
+};
+
+/**
+ * Rotates a quaternion by the given angle about the Z axis
+ *
+ * @param {quat} out quat receiving operation result
+ * @param {quat} a quat to rotate
+ * @param {number} rad angle (in radians) to rotate
+ * @returns {quat} out
+ */
+quat.rotateZ = function (out, a, rad) {
+ rad *= 0.5;
+
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bz = Math.sin(rad), bw = Math.cos(rad);
+
+ out[0] = ax * bw + ay * bz;
+ out[1] = ay * bw - ax * bz;
+ out[2] = az * bw + aw * bz;
+ out[3] = aw * bw - az * bz;
+ return out;
+};
+
+/**
+ * Calculates the W component of a quat from the X, Y, and Z components.
+ * Assumes that quaternion is 1 unit in length.
+ * Any existing W component will be ignored.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quat to calculate W component of
+ * @returns {quat} out
+ */
+quat.calculateW = function (out, a) {
+ var x = a[0], y = a[1], z = a[2];
+
+ out[0] = x;
+ out[1] = y;
+ out[2] = z;
+ out[3] = -Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
+ return out;
+};
+
+/**
+ * Calculates the dot product of two quat's
+ *
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @returns {Number} dot product of a and b
+ * @function
+ */
+quat.dot = vec4.dot;
+
+/**
+ * Performs a linear interpolation between two quat's
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {quat} out
+ * @function
+ */
+quat.lerp = vec4.lerp;
+
+/**
+ * Performs a spherical linear interpolation between two quat
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {quat} out
+ */
+quat.slerp = function (out, a, b, t) {
+ // benchmarks:
+ // http://jsperf.com/quaternion-slerp-implementations
+
+ var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+ bx = b[0], by = b[1], bz = b[2], bw = b[3];
+
+ var omega, cosom, sinom, scale0, scale1;
+
+ // calc cosine
+ cosom = ax * bx + ay * by + az * bz + aw * bw;
+ // adjust signs (if necessary)
+ if ( cosom < 0.0 ) {
+ cosom = -cosom;
+ bx = - bx;
+ by = - by;
+ bz = - bz;
+ bw = - bw;
+ }
+ // calculate coefficients
+ if ( (1.0 - cosom) > 0.000001 ) {
+ // standard case (slerp)
+ omega = Math.acos(cosom);
+ sinom = Math.sin(omega);
+ scale0 = Math.sin((1.0 - t) * omega) / sinom;
+ scale1 = Math.sin(t * omega) / sinom;
+ } else {
+ // "from" and "to" quaternions are very close
+ // ... so we can do a linear interpolation
+ scale0 = 1.0 - t;
+ scale1 = t;
+ }
+ // calculate final values
+ out[0] = scale0 * ax + scale1 * bx;
+ out[1] = scale0 * ay + scale1 * by;
+ out[2] = scale0 * az + scale1 * bz;
+ out[3] = scale0 * aw + scale1 * bw;
+
+ return out;
+};
+
+/**
+ * Calculates the inverse of a quat
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quat to calculate inverse of
+ * @returns {quat} out
+ */
+quat.invert = function(out, a) {
+ var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+ dot = a0*a0 + a1*a1 + a2*a2 + a3*a3,
+ invDot = dot ? 1.0/dot : 0;
+
+ // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
+
+ out[0] = -a0*invDot;
+ out[1] = -a1*invDot;
+ out[2] = -a2*invDot;
+ out[3] = a3*invDot;
+ return out;
+};
+
+/**
+ * Calculates the conjugate of a quat
+ * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quat to calculate conjugate of
+ * @returns {quat} out
+ */
+quat.conjugate = function (out, a) {
+ out[0] = -a[0];
+ out[1] = -a[1];
+ out[2] = -a[2];
+ out[3] = a[3];
+ return out;
+};
+
+/**
+ * Calculates the length of a quat
+ *
+ * @param {quat} a vector to calculate length of
+ * @returns {Number} length of a
+ * @function
+ */
+quat.length = vec4.length;
+
+/**
+ * Alias for {@link quat.length}
+ * @function
+ */
+quat.len = quat.length;
+
+/**
+ * Calculates the squared length of a quat
+ *
+ * @param {quat} a vector to calculate squared length of
+ * @returns {Number} squared length of a
+ * @function
+ */
+quat.squaredLength = vec4.squaredLength;
+
+/**
+ * Alias for {@link quat.squaredLength}
+ * @function
+ */
+quat.sqrLen = quat.squaredLength;
+
+/**
+ * Normalize a quat
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a quaternion to normalize
+ * @returns {quat} out
+ * @function
+ */
+quat.normalize = vec4.normalize;
+
+/**
+ * Creates a quaternion from the given 3x3 rotation matrix.
+ *
+ * NOTE: The resultant quaternion is not normalized, so you should be sure
+ * to renormalize the quaternion yourself where necessary.
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {mat3} m rotation matrix
+ * @returns {quat} out
+ * @function
+ */
+quat.fromMat3 = function(out, m) {
+ // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
+ // article "Quaternion Calculus and Fast Animation".
+ var fTrace = m[0] + m[4] + m[8];
+ var fRoot;
+
+ if ( fTrace > 0.0 ) {
+ // |w| > 1/2, may as well choose w > 1/2
+ fRoot = Math.sqrt(fTrace + 1.0); // 2w
+ out[3] = 0.5 * fRoot;
+ fRoot = 0.5/fRoot; // 1/(4w)
+ out[0] = (m[7]-m[5])*fRoot;
+ out[1] = (m[2]-m[6])*fRoot;
+ out[2] = (m[3]-m[1])*fRoot;
+ } else {
+ // |w| <= 1/2
+ var i = 0;
+ if ( m[4] > m[0] )
+ i = 1;
+ if ( m[8] > m[i*3+i] )
+ i = 2;
+ var j = (i+1)%3;
+ var k = (i+2)%3;
+
+ fRoot = Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k] + 1.0);
+ out[i] = 0.5 * fRoot;
+ fRoot = 0.5 / fRoot;
+ out[3] = (m[k*3+j] - m[j*3+k]) * fRoot;
+ out[j] = (m[j*3+i] + m[i*3+j]) * fRoot;
+ out[k] = (m[k*3+i] + m[i*3+k]) * fRoot;
+ }
+
+ return out;
+};
+
+/**
+ * Returns a string representation of a quatenion
+ *
+ * @param {quat} vec vector to represent as a string
+ * @returns {String} string representation of the vector
+ */
+quat.str = function (a) {
+ return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
+};
+
+if(typeof(exports) !== 'undefined') {
+ exports.quat = quat;
+}
+;
+
+
+
+
+
+
+
+
+
+
+
+
+
+ })(shim.exports);
+})(this);
+
+},{}],103:[function(require,module,exports){
+"use strict"
+
+var glm = require("gl-matrix")
+var vec3 = glm.vec3
+var mat3 = glm.mat3
+var mat4 = glm.mat4
+var quat = glm.quat
+
+//Scratch variables
+var scratch0 = new Float32Array(16)
+var scratch1 = new Float32Array(16)
+
+function OrbitCamera(rotation, center, distance) {
+ this.rotation = rotation
+ this.center = center
+ this.distance = distance
+}
+
+var proto = OrbitCamera.prototype
+
+proto.view = function(out) {
+ if(!out) {
+ out = mat4.create()
+ }
+ scratch1[0] = scratch1[1] = 0.0
+ scratch1[2] = -this.distance
+ mat4.fromRotationTranslation(out,
+ quat.conjugate(scratch0, this.rotation),
+ scratch1)
+ mat4.translate(out, out, vec3.negate(scratch0, this.center))
+ return out
+}
+
+proto.lookAt = function(eye, center, up) {
+ mat4.lookAt(scratch0, eye, center, up)
+ mat3.fromMat4(scratch0, scratch0)
+ quat.fromMat3(this.rotation, scratch0)
+ vec3.copy(this.center, center)
+ this.distance = vec3.distance(eye, center)
+}
+
+proto.pan = function(dpan) {
+ var d = this.distance
+ scratch0[0] = -d*(dpan[0]||0)
+ scratch0[1] = d*(dpan[1]||0)
+ scratch0[2] = d*(dpan[2]||0)
+ vec3.transformQuat(scratch0, scratch0, this.rotation)
+ vec3.add(this.center, this.center, scratch0)
+}
+
+proto.zoom = function(d) {
+ this.distance += d
+ if(this.distance < 0.0) {
+ this.distance = 0.0
+ }
+}
+
+function quatFromVec(out, da) {
+ var x = da[0]
+ var y = da[1]
+ var z = da[2]
+ var s = x*x + y*y
+ if(s > 1.0) {
+ s = 1.0
+ }
+ out[0] = -da[0]
+ out[1] = da[1]
+ out[2] = da[2] || Math.sqrt(1.0 - s)
+ out[3] = 0.0
+}
+
+proto.rotate = function(da, db) {
+ quatFromVec(scratch0, da)
+ quatFromVec(scratch1, db)
+ quat.invert(scratch1, scratch1)
+ quat.multiply(scratch0, scratch0, scratch1)
+ if(quat.length(scratch0) < 1e-6) {
+ return
+ }
+ quat.multiply(this.rotation, this.rotation, scratch0)
+ quat.normalize(this.rotation, this.rotation)
+}
+
+function createOrbitCamera(eye, target, up) {
+ eye = eye || [0,0,-1]
+ target = target || [0,0,0]
+ up = up || [0,1,0]
+ var camera = new OrbitCamera(quat.create(), vec3.create(), 1.0)
+ camera.lookAt(eye, target, up)
+ return camera
+}
+
+module.exports = createOrbitCamera
+
+},{"gl-matrix":102}],104:[function(require,module,exports){
+(function (global){
+module.exports =
+ global.performance &&
+ global.performance.now ? function now() {
+ return performance.now()
+ } : Date.now || function now() {
+ return +new Date
+ }
+
+}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],105:[function(require,module,exports){
+module.exports = unindex
+
+function unindex(positions, cells, out) {
+ if (positions.positions && positions.cells) {
+ out = cells
+ cells = positions.cells
+ positions = positions.positions
+ }
+
+ out = out || new Float32Array(cells.length * 9)
+
+ for (var i = 0, n = 0, l = cells.length; i < l; i += 1) {
+ out[n++] = positions[cells[i][0]][0]
+ out[n++] = positions[cells[i][0]][1]
+ out[n++] = positions[cells[i][0]][2]
+ out[n++] = positions[cells[i][1]][0]
+ out[n++] = positions[cells[i][1]][1]
+ out[n++] = positions[cells[i][1]][2]
+ out[n++] = positions[cells[i][2]][0]
+ out[n++] = positions[cells[i][2]][1]
+ out[n++] = positions[cells[i][2]][2]
+ }
+ return out
+}
+
+},{}],106:[function(require,module,exports){
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = Buffer
+exports.INSPECT_MAX_BYTES = 50
+Buffer.poolSize = 8192
+
+/**
+ * If `Buffer._useTypedArrays`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (compatible down to IE6)
+ */
+Buffer._useTypedArrays = (function () {
+ // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
+ // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
+ // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
+ // because we need to be able to add all the node Buffer API methods. This is an issue
+ // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
+ try {
+ var buf = new ArrayBuffer(0)
+ var arr = new Uint8Array(buf)
+ arr.foo = function () { return 42 }
+ return 42 === arr.foo() &&
+ typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
+ } catch (e) {
+ return false
+ }
+})()
+
+/**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+function Buffer (subject, encoding, noZero) {
+ if (!(this instanceof Buffer))
+ return new Buffer(subject, encoding, noZero)
+
+ var type = typeof subject
+
+ // Workaround: node's base64 implementation allows for non-padded strings
+ // while base64-js does not.
+ if (encoding === 'base64' && type === 'string') {
+ subject = stringtrim(subject)
+ while (subject.length % 4 !== 0) {
+ subject = subject + '='
+ }
+ }
+
+ // Find the length
+ var length
+ if (type === 'number')
+ length = coerce(subject)
+ else if (type === 'string')
+ length = Buffer.byteLength(subject, encoding)
+ else if (type === 'object')
+ length = coerce(subject.length) // assume that object is array-like
+ else
+ throw new Error('First argument needs to be a number, array or string.')
+
+ var buf
+ if (Buffer._useTypedArrays) {
+ // Preferred: Return an augmented `Uint8Array` instance for best performance
+ buf = Buffer._augment(new Uint8Array(length))
+ } else {
+ // Fallback: Return THIS instance of Buffer (created by `new`)
+ buf = this
+ buf.length = length
+ buf._isBuffer = true
+ }
+
+ var i
+ if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
+ // Speed optimization -- use set if we're copying from a typed array
+ buf._set(subject)
+ } else if (isArrayish(subject)) {
+ // Treat array-ish objects as a byte array
+ if (Buffer.isBuffer(subject)) {
+ for (i = 0; i < length; i++)
+ buf[i] = subject.readUInt8(i)
+ } else {
+ for (i = 0; i < length; i++)
+ buf[i] = ((subject[i] % 256) + 256) % 256
+ }
+ } else if (type === 'string') {
+ buf.write(subject, 0, encoding)
+ } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
+ for (i = 0; i < length; i++) {
+ buf[i] = 0
+ }
+ }
+
+ return buf
+}
+
+// STATIC METHODS
+// ==============
+
+Buffer.isEncoding = function (encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'binary':
+ case 'base64':
+ case 'raw':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true
+ default:
+ return false
+ }
+}
+
+Buffer.isBuffer = function (b) {
+ return !!(b !== null && b !== undefined && b._isBuffer)
+}
+
+Buffer.byteLength = function (str, encoding) {
+ var ret
+ str = str.toString()
+ switch (encoding || 'utf8') {
+ case 'hex':
+ ret = str.length / 2
+ break
+ case 'utf8':
+ case 'utf-8':
+ ret = utf8ToBytes(str).length
+ break
+ case 'ascii':
+ case 'binary':
+ case 'raw':
+ ret = str.length
+ break
+ case 'base64':
+ ret = base64ToBytes(str).length
+ break
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ ret = str.length * 2
+ break
+ default:
+ throw new Error('Unknown encoding')
+ }
+ return ret
+}
+
+Buffer.concat = function (list, totalLength) {
+ assert(isArray(list), 'Usage: Buffer.concat(list[, length])')
+
+ if (list.length === 0) {
+ return new Buffer(0)
+ } else if (list.length === 1) {
+ return list[0]
+ }
+
+ var i
+ if (totalLength === undefined) {
+ totalLength = 0
+ for (i = 0; i < list.length; i++) {
+ totalLength += list[i].length
+ }
+ }
+
+ var buf = new Buffer(totalLength)
+ var pos = 0
+ for (i = 0; i < list.length; i++) {
+ var item = list[i]
+ item.copy(buf, pos)
+ pos += item.length
+ }
+ return buf
+}
+
+Buffer.compare = function (a, b) {
+ assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers')
+ var x = a.length
+ var y = b.length
+ for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
+ if (i !== len) {
+ x = a[i]
+ y = b[i]
+ }
+ if (x < y) {
+ return -1
+ }
+ if (y < x) {
+ return 1
+ }
+ return 0
+}
+
+// BUFFER INSTANCE METHODS
+// =======================
+
+function hexWrite (buf, string, offset, length) {
+ offset = Number(offset) || 0
+ var remaining = buf.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
+ }
+ }
+
+ // must be an even number of digits
+ var strLen = string.length
+ assert(strLen % 2 === 0, 'Invalid hex string')
+
+ if (length > strLen / 2) {
+ length = strLen / 2
+ }
+ for (var i = 0; i < length; i++) {
+ var byte = parseInt(string.substr(i * 2, 2), 16)
+ assert(!isNaN(byte), 'Invalid hex string')
+ buf[offset + i] = byte
+ }
+ return i
+}
+
+function utf8Write (buf, string, offset, length) {
+ var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
+ return charsWritten
+}
+
+function asciiWrite (buf, string, offset, length) {
+ var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
+ return charsWritten
+}
+
+function binaryWrite (buf, string, offset, length) {
+ return asciiWrite(buf, string, offset, length)
+}
+
+function base64Write (buf, string, offset, length) {
+ var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
+ return charsWritten
+}
+
+function utf16leWrite (buf, string, offset, length) {
+ var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
+ return charsWritten
+}
+
+Buffer.prototype.write = function (string, offset, length, encoding) {
+ // Support both (string, offset, length, encoding)
+ // and the legacy (string, encoding, offset, length)
+ if (isFinite(offset)) {
+ if (!isFinite(length)) {
+ encoding = length
+ length = undefined
+ }
+ } else { // legacy
+ var swap = encoding
+ encoding = offset
+ offset = length
+ length = swap
+ }
+
+ offset = Number(offset) || 0
+ var remaining = this.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
+ }
+ }
+ encoding = String(encoding || 'utf8').toLowerCase()
+
+ var ret
+ switch (encoding) {
+ case 'hex':
+ ret = hexWrite(this, string, offset, length)
+ break
+ case 'utf8':
+ case 'utf-8':
+ ret = utf8Write(this, string, offset, length)
+ break
+ case 'ascii':
+ ret = asciiWrite(this, string, offset, length)
+ break
+ case 'binary':
+ ret = binaryWrite(this, string, offset, length)
+ break
+ case 'base64':
+ ret = base64Write(this, string, offset, length)
+ break
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ ret = utf16leWrite(this, string, offset, length)
+ break
+ default:
+ throw new Error('Unknown encoding')
+ }
+ return ret
+}
+
+Buffer.prototype.toString = function (encoding, start, end) {
+ var self = this
+
+ encoding = String(encoding || 'utf8').toLowerCase()
+ start = Number(start) || 0
+ end = (end === undefined) ? self.length : Number(end)
+
+ // Fastpath empty strings
+ if (end === start)
+ return ''
+
+ var ret
+ switch (encoding) {
+ case 'hex':
+ ret = hexSlice(self, start, end)
+ break
+ case 'utf8':
+ case 'utf-8':
+ ret = utf8Slice(self, start, end)
+ break
+ case 'ascii':
+ ret = asciiSlice(self, start, end)
+ break
+ case 'binary':
+ ret = binarySlice(self, start, end)
+ break
+ case 'base64':
+ ret = base64Slice(self, start, end)
+ break
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ ret = utf16leSlice(self, start, end)
+ break
+ default:
+ throw new Error('Unknown encoding')
+ }
+ return ret
+}
+
+Buffer.prototype.toJSON = function () {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
+ }
+}
+
+Buffer.prototype.equals = function (b) {
+ assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
+ return Buffer.compare(this, b) === 0
+}
+
+Buffer.prototype.compare = function (b) {
+ assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
+ return Buffer.compare(this, b)
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function (target, target_start, start, end) {
+ var source = this
+
+ if (!start) start = 0
+ if (!end && end !== 0) end = this.length
+ if (!target_start) target_start = 0
+
+ // Copy 0 bytes; we're done
+ if (end === start) return
+ if (target.length === 0 || source.length === 0) return
+
+ // Fatal error conditions
+ assert(end >= start, 'sourceEnd < sourceStart')
+ assert(target_start >= 0 && target_start < target.length,
+ 'targetStart out of bounds')
+ assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
+ assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
+
+ // Are we oob?
+ if (end > this.length)
+ end = this.length
+ if (target.length - target_start < end - start)
+ end = target.length - target_start + start
+
+ var len = end - start
+
+ if (len < 100 || !Buffer._useTypedArrays) {
+ for (var i = 0; i < len; i++) {
+ target[i + target_start] = this[i + start]
+ }
+ } else {
+ target._set(this.subarray(start, start + len), target_start)
+ }
+}
+
+function base64Slice (buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return base64.fromByteArray(buf)
+ } else {
+ return base64.fromByteArray(buf.slice(start, end))
+ }
+}
+
+function utf8Slice (buf, start, end) {
+ var res = ''
+ var tmp = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; i++) {
+ if (buf[i] <= 0x7F) {
+ res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
+ tmp = ''
+ } else {
+ tmp += '%' + buf[i].toString(16)
+ }
+ }
+
+ return res + decodeUtf8Char(tmp)
+}
+
+function asciiSlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; i++) {
+ ret += String.fromCharCode(buf[i])
+ }
+ return ret
+}
+
+function binarySlice (buf, start, end) {
+ return asciiSlice(buf, start, end)
+}
+
+function hexSlice (buf, start, end) {
+ var len = buf.length
+
+ if (!start || start < 0) start = 0
+ if (!end || end < 0 || end > len) end = len
+
+ var out = ''
+ for (var i = start; i < end; i++) {
+ out += toHex(buf[i])
+ }
+ return out
+}
+
+function utf16leSlice (buf, start, end) {
+ var bytes = buf.slice(start, end)
+ var res = ''
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
+ }
+ return res
+}
+
+Buffer.prototype.slice = function (start, end) {
+ var len = this.length
+ start = clamp(start, len, 0)
+ end = clamp(end, len, len)
+
+ if (Buffer._useTypedArrays) {
+ return Buffer._augment(this.subarray(start, end))
+ } else {
+ var sliceLen = end - start
+ var newBuf = new Buffer(sliceLen, undefined, true)
+ for (var i = 0; i < sliceLen; i++) {
+ newBuf[i] = this[i + start]
+ }
+ return newBuf
+ }
+}
+
+// `get` will be removed in Node 0.13+
+Buffer.prototype.get = function (offset) {
+ console.log('.get() is deprecated. Access using array indexes instead.')
+ return this.readUInt8(offset)
+}
+
+// `set` will be removed in Node 0.13+
+Buffer.prototype.set = function (v, offset) {
+ console.log('.set() is deprecated. Access using array indexes instead.')
+ return this.writeUInt8(v, offset)
+}
+
+Buffer.prototype.readUInt8 = function (offset, noAssert) {
+ if (!noAssert) {
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset < this.length, 'Trying to read beyond buffer length')
+ }
+
+ if (offset >= this.length)
+ return
+
+ return this[offset]
+}
+
+function readUInt16 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val
+ if (littleEndian) {
+ val = buf[offset]
+ if (offset + 1 < len)
+ val |= buf[offset + 1] << 8
+ } else {
+ val = buf[offset] << 8
+ if (offset + 1 < len)
+ val |= buf[offset + 1]
+ }
+ return val
+}
+
+Buffer.prototype.readUInt16LE = function (offset, noAssert) {
+ return readUInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt16BE = function (offset, noAssert) {
+ return readUInt16(this, offset, false, noAssert)
+}
+
+function readUInt32 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val
+ if (littleEndian) {
+ if (offset + 2 < len)
+ val = buf[offset + 2] << 16
+ if (offset + 1 < len)
+ val |= buf[offset + 1] << 8
+ val |= buf[offset]
+ if (offset + 3 < len)
+ val = val + (buf[offset + 3] << 24 >>> 0)
+ } else {
+ if (offset + 1 < len)
+ val = buf[offset + 1] << 16
+ if (offset + 2 < len)
+ val |= buf[offset + 2] << 8
+ if (offset + 3 < len)
+ val |= buf[offset + 3]
+ val = val + (buf[offset] << 24 >>> 0)
+ }
+ return val
+}
+
+Buffer.prototype.readUInt32LE = function (offset, noAssert) {
+ return readUInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt32BE = function (offset, noAssert) {
+ return readUInt32(this, offset, false, noAssert)
+}
+
+Buffer.prototype.readInt8 = function (offset, noAssert) {
+ if (!noAssert) {
+ assert(offset !== undefined && offset !== null,
+ 'missing offset')
+ assert(offset < this.length, 'Trying to read beyond buffer length')
+ }
+
+ if (offset >= this.length)
+ return
+
+ var neg = this[offset] & 0x80
+ if (neg)
+ return (0xff - this[offset] + 1) * -1
+ else
+ return this[offset]
+}
+
+function readInt16 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val = readUInt16(buf, offset, littleEndian, true)
+ var neg = val & 0x8000
+ if (neg)
+ return (0xffff - val + 1) * -1
+ else
+ return val
+}
+
+Buffer.prototype.readInt16LE = function (offset, noAssert) {
+ return readInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt16BE = function (offset, noAssert) {
+ return readInt16(this, offset, false, noAssert)
+}
+
+function readInt32 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val = readUInt32(buf, offset, littleEndian, true)
+ var neg = val & 0x80000000
+ if (neg)
+ return (0xffffffff - val + 1) * -1
+ else
+ return val
+}
+
+Buffer.prototype.readInt32LE = function (offset, noAssert) {
+ return readInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt32BE = function (offset, noAssert) {
+ return readInt32(this, offset, false, noAssert)
+}
+
+function readFloat (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ return ieee754.read(buf, offset, littleEndian, 23, 4)
+}
+
+Buffer.prototype.readFloatLE = function (offset, noAssert) {
+ return readFloat(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readFloatBE = function (offset, noAssert) {
+ return readFloat(this, offset, false, noAssert)
+}
+
+function readDouble (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ return ieee754.read(buf, offset, littleEndian, 52, 8)
+}
+
+Buffer.prototype.readDoubleLE = function (offset, noAssert) {
+ return readDouble(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readDoubleBE = function (offset, noAssert) {
+ return readDouble(this, offset, false, noAssert)
+}
+
+Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset < this.length, 'trying to write beyond buffer length')
+ verifuint(value, 0xff)
+ }
+
+ if (offset >= this.length) return
+
+ this[offset] = value
+ return offset + 1
+}
+
+function writeUInt16 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
+ verifuint(value, 0xffff)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
+ buf[offset + i] =
+ (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+ (littleEndian ? i : 1 - i) * 8
+ }
+ return offset + 2
+}
+
+Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
+ return writeUInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
+ return writeUInt16(this, value, offset, false, noAssert)
+}
+
+function writeUInt32 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
+ verifuint(value, 0xffffffff)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
+ buf[offset + i] =
+ (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+ }
+ return offset + 4
+}
+
+Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
+ return writeUInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
+ return writeUInt32(this, value, offset, false, noAssert)
+}
+
+Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset < this.length, 'Trying to write beyond buffer length')
+ verifsint(value, 0x7f, -0x80)
+ }
+
+ if (offset >= this.length)
+ return
+
+ if (value >= 0)
+ this.writeUInt8(value, offset, noAssert)
+ else
+ this.writeUInt8(0xff + value + 1, offset, noAssert)
+ return offset + 1
+}
+
+function writeInt16 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
+ verifsint(value, 0x7fff, -0x8000)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ if (value >= 0)
+ writeUInt16(buf, value, offset, littleEndian, noAssert)
+ else
+ writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
+ return offset + 2
+}
+
+Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
+ return writeInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
+ return writeInt16(this, value, offset, false, noAssert)
+}
+
+function writeInt32 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+ verifsint(value, 0x7fffffff, -0x80000000)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ if (value >= 0)
+ writeUInt32(buf, value, offset, littleEndian, noAssert)
+ else
+ writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
+ return offset + 4
+}
+
+Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
+ return writeInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
+ return writeInt32(this, value, offset, false, noAssert)
+}
+
+function writeFloat (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+ verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
+ return offset + 4
+}
+
+Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert)
+}
+
+function writeDouble (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 7 < buf.length,
+ 'Trying to write beyond buffer length')
+ verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+ return offset + 8
+}
+
+Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert)
+}
+
+// fill(value, start=0, end=buffer.length)
+Buffer.prototype.fill = function (value, start, end) {
+ if (!value) value = 0
+ if (!start) start = 0
+ if (!end) end = this.length
+
+ assert(end >= start, 'end < start')
+
+ // Fill 0 bytes; we're done
+ if (end === start) return
+ if (this.length === 0) return
+
+ assert(start >= 0 && start < this.length, 'start out of bounds')
+ assert(end >= 0 && end <= this.length, 'end out of bounds')
+
+ var i
+ if (typeof value === 'number') {
+ for (i = start; i < end; i++) {
+ this[i] = value
+ }
+ } else {
+ var bytes = utf8ToBytes(value.toString())
+ var len = bytes.length
+ for (i = start; i < end; i++) {
+ this[i] = bytes[i % len]
+ }
+ }
+
+ return this
+}
+
+Buffer.prototype.inspect = function () {
+ var out = []
+ var len = this.length
+ for (var i = 0; i < len; i++) {
+ out[i] = toHex(this[i])
+ if (i === exports.INSPECT_MAX_BYTES) {
+ out[i + 1] = '...'
+ break
+ }
+ }
+ return ''
+}
+
+/**
+ * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
+ * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
+ */
+Buffer.prototype.toArrayBuffer = function () {
+ if (typeof Uint8Array !== 'undefined') {
+ if (Buffer._useTypedArrays) {
+ return (new Buffer(this)).buffer
+ } else {
+ var buf = new Uint8Array(this.length)
+ for (var i = 0, len = buf.length; i < len; i += 1) {
+ buf[i] = this[i]
+ }
+ return buf.buffer
+ }
+ } else {
+ throw new Error('Buffer.toArrayBuffer not supported in this browser')
+ }
+}
+
+// HELPER FUNCTIONS
+// ================
+
+var BP = Buffer.prototype
+
+/**
+ * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
+ */
+Buffer._augment = function (arr) {
+ arr._isBuffer = true
+
+ // save reference to original Uint8Array get/set methods before overwriting
+ arr._get = arr.get
+ arr._set = arr.set
+
+ // deprecated, will be removed in node 0.13+
+ arr.get = BP.get
+ arr.set = BP.set
+
+ arr.write = BP.write
+ arr.toString = BP.toString
+ arr.toLocaleString = BP.toString
+ arr.toJSON = BP.toJSON
+ arr.equals = BP.equals
+ arr.compare = BP.compare
+ arr.copy = BP.copy
+ arr.slice = BP.slice
+ arr.readUInt8 = BP.readUInt8
+ arr.readUInt16LE = BP.readUInt16LE
+ arr.readUInt16BE = BP.readUInt16BE
+ arr.readUInt32LE = BP.readUInt32LE
+ arr.readUInt32BE = BP.readUInt32BE
+ arr.readInt8 = BP.readInt8
+ arr.readInt16LE = BP.readInt16LE
+ arr.readInt16BE = BP.readInt16BE
+ arr.readInt32LE = BP.readInt32LE
+ arr.readInt32BE = BP.readInt32BE
+ arr.readFloatLE = BP.readFloatLE
+ arr.readFloatBE = BP.readFloatBE
+ arr.readDoubleLE = BP.readDoubleLE
+ arr.readDoubleBE = BP.readDoubleBE
+ arr.writeUInt8 = BP.writeUInt8
+ arr.writeUInt16LE = BP.writeUInt16LE
+ arr.writeUInt16BE = BP.writeUInt16BE
+ arr.writeUInt32LE = BP.writeUInt32LE
+ arr.writeUInt32BE = BP.writeUInt32BE
+ arr.writeInt8 = BP.writeInt8
+ arr.writeInt16LE = BP.writeInt16LE
+ arr.writeInt16BE = BP.writeInt16BE
+ arr.writeInt32LE = BP.writeInt32LE
+ arr.writeInt32BE = BP.writeInt32BE
+ arr.writeFloatLE = BP.writeFloatLE
+ arr.writeFloatBE = BP.writeFloatBE
+ arr.writeDoubleLE = BP.writeDoubleLE
+ arr.writeDoubleBE = BP.writeDoubleBE
+ arr.fill = BP.fill
+ arr.inspect = BP.inspect
+ arr.toArrayBuffer = BP.toArrayBuffer
+
+ return arr
+}
+
+function stringtrim (str) {
+ if (str.trim) return str.trim()
+ return str.replace(/^\s+|\s+$/g, '')
+}
+
+// slice(start, end)
+function clamp (index, len, defaultValue) {
+ if (typeof index !== 'number') return defaultValue
+ index = ~~index; // Coerce to integer.
+ if (index >= len) return len
+ if (index >= 0) return index
+ index += len
+ if (index >= 0) return index
+ return 0
+}
+
+function coerce (length) {
+ // Coerce length to a number (possibly NaN), round up
+ // in case it's fractional (e.g. 123.456) then do a
+ // double negate to coerce a NaN to 0. Easy, right?
+ length = ~~Math.ceil(+length)
+ return length < 0 ? 0 : length
+}
+
+function isArray (subject) {
+ return (Array.isArray || function (subject) {
+ return Object.prototype.toString.call(subject) === '[object Array]'
+ })(subject)
+}
+
+function isArrayish (subject) {
+ return isArray(subject) || Buffer.isBuffer(subject) ||
+ subject && typeof subject === 'object' &&
+ typeof subject.length === 'number'
+}
+
+function toHex (n) {
+ if (n < 16) return '0' + n.toString(16)
+ return n.toString(16)
+}
+
+function utf8ToBytes (str) {
+ var byteArray = []
+ for (var i = 0; i < str.length; i++) {
+ var b = str.charCodeAt(i)
+ if (b <= 0x7F) {
+ byteArray.push(b)
+ } else {
+ var start = i
+ if (b >= 0xD800 && b <= 0xDFFF) i++
+ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
+ for (var j = 0; j < h.length; j++) {
+ byteArray.push(parseInt(h[j], 16))
+ }
+ }
+ }
+ return byteArray
+}
+
+function asciiToBytes (str) {
+ var byteArray = []
+ for (var i = 0; i < str.length; i++) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF)
+ }
+ return byteArray
+}
+
+function utf16leToBytes (str) {
+ var c, hi, lo
+ var byteArray = []
+ for (var i = 0; i < str.length; i++) {
+ c = str.charCodeAt(i)
+ hi = c >> 8
+ lo = c % 256
+ byteArray.push(lo)
+ byteArray.push(hi)
+ }
+
+ return byteArray
+}
+
+function base64ToBytes (str) {
+ return base64.toByteArray(str)
+}
+
+function blitBuffer (src, dst, offset, length) {
+ for (var i = 0; i < length; i++) {
+ if ((i + offset >= dst.length) || (i >= src.length))
+ break
+ dst[i + offset] = src[i]
+ }
+ return i
+}
+
+function decodeUtf8Char (str) {
+ try {
+ return decodeURIComponent(str)
+ } catch (err) {
+ return String.fromCharCode(0xFFFD) // UTF 8 invalid char
+ }
+}
+
+/*
+ * We have to make sure that the value is a valid integer. This means that it
+ * is non-negative. It has no fractional component and that it does not
+ * exceed the maximum allowed value.
+ */
+function verifuint (value, max) {
+ assert(typeof value === 'number', 'cannot write a non-number as a number')
+ assert(value >= 0, 'specified a negative value for writing an unsigned value')
+ assert(value <= max, 'value is larger than maximum value for type')
+ assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifsint (value, max, min) {
+ assert(typeof value === 'number', 'cannot write a non-number as a number')
+ assert(value <= max, 'value larger than maximum allowed value')
+ assert(value >= min, 'value smaller than minimum allowed value')
+ assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifIEEE754 (value, max, min) {
+ assert(typeof value === 'number', 'cannot write a non-number as a number')
+ assert(value <= max, 'value larger than maximum allowed value')
+ assert(value >= min, 'value smaller than minimum allowed value')
+}
+
+function assert (test, message) {
+ if (!test) throw new Error(message || 'Failed assertion')
+}
+
+},{"base64-js":107,"ieee754":108}],107:[function(require,module,exports){
+var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+;(function (exports) {
+ 'use strict';
+
+ var Arr = (typeof Uint8Array !== 'undefined')
+ ? Uint8Array
+ : Array
+
+ var PLUS = '+'.charCodeAt(0)
+ var SLASH = '/'.charCodeAt(0)
+ var NUMBER = '0'.charCodeAt(0)
+ var LOWER = 'a'.charCodeAt(0)
+ var UPPER = 'A'.charCodeAt(0)
+
+ function decode (elt) {
+ var code = elt.charCodeAt(0)
+ if (code === PLUS)
+ return 62 // '+'
+ if (code === SLASH)
+ return 63 // '/'
+ if (code < NUMBER)
+ return -1 //no match
+ if (code < NUMBER + 10)
+ return code - NUMBER + 26 + 26
+ if (code < UPPER + 26)
+ return code - UPPER
+ if (code < LOWER + 26)
+ return code - LOWER + 26
+ }
+
+ function b64ToByteArray (b64) {
+ var i, j, l, tmp, placeHolders, arr
+
+ if (b64.length % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
+ }
+
+ // the number of equal signs (place holders)
+ // if there are two placeholders, than the two characters before it
+ // represent one byte
+ // if there is only one, then the three characters before it represent 2 bytes
+ // this is just a cheap hack to not do indexOf twice
+ var len = b64.length
+ placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
+
+ // base64 is 4/3 + up to two characters of the original data
+ arr = new Arr(b64.length * 3 / 4 - placeHolders)
+
+ // if there are placeholders, only get up to the last complete 4 chars
+ l = placeHolders > 0 ? b64.length - 4 : b64.length
+
+ var L = 0
+
+ function push (v) {
+ arr[L++] = v
+ }
+
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
+ tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
+ push((tmp & 0xFF0000) >> 16)
+ push((tmp & 0xFF00) >> 8)
+ push(tmp & 0xFF)
+ }
+
+ if (placeHolders === 2) {
+ tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
+ push(tmp & 0xFF)
+ } else if (placeHolders === 1) {
+ tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
+ push((tmp >> 8) & 0xFF)
+ push(tmp & 0xFF)
+ }
+
+ return arr
+ }
+
+ function uint8ToBase64 (uint8) {
+ var i,
+ extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
+ output = "",
+ temp, length
+
+ function encode (num) {
+ return lookup.charAt(num)
+ }
+
+ function tripletToBase64 (num) {
+ return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
+ }
+
+ // go through the array every three bytes, we'll deal with trailing stuff later
+ for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
+ temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
+ output += tripletToBase64(temp)
+ }
+
+ // pad the end with zeros, but make sure to not forget the extra bytes
+ switch (extraBytes) {
+ case 1:
+ temp = uint8[uint8.length - 1]
+ output += encode(temp >> 2)
+ output += encode((temp << 4) & 0x3F)
+ output += '=='
+ break
+ case 2:
+ temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
+ output += encode(temp >> 10)
+ output += encode((temp >> 4) & 0x3F)
+ output += encode((temp << 2) & 0x3F)
+ output += '='
+ break
+ }
+
+ return output
+ }
+
+ exports.toByteArray = b64ToByteArray
+ exports.fromByteArray = uint8ToBase64
+}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
+
+},{}],108:[function(require,module,exports){
+exports.read = function(buffer, offset, isLE, mLen, nBytes) {
+ var e, m,
+ eLen = nBytes * 8 - mLen - 1,
+ eMax = (1 << eLen) - 1,
+ eBias = eMax >> 1,
+ nBits = -7,
+ i = isLE ? (nBytes - 1) : 0,
+ d = isLE ? -1 : 1,
+ s = buffer[offset + i];
+
+ i += d;
+
+ e = s & ((1 << (-nBits)) - 1);
+ s >>= (-nBits);
+ nBits += eLen;
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
+
+ m = e & ((1 << (-nBits)) - 1);
+ e >>= (-nBits);
+ nBits += mLen;
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
+
+ if (e === 0) {
+ e = 1 - eBias;
+ } else if (e === eMax) {
+ return m ? NaN : ((s ? -1 : 1) * Infinity);
+ } else {
+ m = m + Math.pow(2, mLen);
+ e = e - eBias;
+ }
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
+};
+
+exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
+ var e, m, c,
+ eLen = nBytes * 8 - mLen - 1,
+ eMax = (1 << eLen) - 1,
+ eBias = eMax >> 1,
+ rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
+ i = isLE ? 0 : (nBytes - 1),
+ d = isLE ? 1 : -1,
+ s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
+
+ value = Math.abs(value);
+
+ if (isNaN(value) || value === Infinity) {
+ m = isNaN(value) ? 1 : 0;
+ e = eMax;
+ } else {
+ e = Math.floor(Math.log(value) / Math.LN2);
+ if (value * (c = Math.pow(2, -e)) < 1) {
+ e--;
+ c *= 2;
+ }
+ if (e + eBias >= 1) {
+ value += rt / c;
+ } else {
+ value += rt * Math.pow(2, 1 - eBias);
+ }
+ if (value * c >= 2) {
+ e++;
+ c /= 2;
+ }
+
+ if (e + eBias >= eMax) {
+ m = 0;
+ e = eMax;
+ } else if (e + eBias >= 1) {
+ m = (value * c - 1) * Math.pow(2, mLen);
+ e = e + eBias;
+ } else {
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
+ e = 0;
+ }
+ }
+
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
+
+ e = (e << mLen) | m;
+ eLen += mLen;
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
+
+ buffer[offset + i - d] |= s * 128;
+};
+
+},{}],109:[function(require,module,exports){
+// shim for using process in browser
+
+var process = module.exports = {};
+
+process.nextTick = (function () {
+ var canSetImmediate = typeof window !== 'undefined'
+ && window.setImmediate;
+ var canPost = typeof window !== 'undefined'
+ && window.postMessage && window.addEventListener
+ ;
+
+ if (canSetImmediate) {
+ return function (f) { return window.setImmediate(f) };
+ }
+
+ if (canPost) {
+ var queue = [];
+ window.addEventListener('message', function (ev) {
+ var source = ev.source;
+ if ((source === window || source === null) && ev.data === 'process-tick') {
+ ev.stopPropagation();
+ if (queue.length > 0) {
+ var fn = queue.shift();
+ fn();
+ }
+ }
+ }, true);
+
+ return function nextTick(fn) {
+ queue.push(fn);
+ window.postMessage('process-tick', '*');
+ };
+ }
+
+ return function nextTick(fn) {
+ setTimeout(fn, 0);
+ };
+})();
+
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+
+function noop() {}
+
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+}
+
+// TODO(shtylman)
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+};
+
+},{}]},{},[3])
\ No newline at end of file