michael@0: // Copyright (c) 2011 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: WebGLTestUtils = (function() { michael@0: michael@0: /** michael@0: * Wrapped logging function. michael@0: * @param {string} msg The message to log. michael@0: */ michael@0: var log = function(msg) { michael@0: if (window.console && window.console.log) { michael@0: window.console.log(msg); michael@0: } michael@0: }; michael@0: michael@0: /** michael@0: * Wrapped logging function. michael@0: * @param {string} msg The message to log. michael@0: */ michael@0: var error = function(msg) { michael@0: if (window.console) { michael@0: if (window.console.error) { michael@0: window.console.error(msg); michael@0: } michael@0: else if (window.console.log) { michael@0: window.console.log(msg); michael@0: } michael@0: } michael@0: }; michael@0: michael@0: /** michael@0: * Turn off all logging. michael@0: */ michael@0: var loggingOff = function() { michael@0: log = function() {}; michael@0: error = function() {}; michael@0: }; michael@0: michael@0: /** michael@0: * Converts a WebGL enum to a string michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} value The enum value. michael@0: * @return {string} The enum as a string. michael@0: */ michael@0: var glEnumToString = function(gl, value) { michael@0: for (var p in gl) { michael@0: if (gl[p] == value) { michael@0: return p; michael@0: } michael@0: } michael@0: return "0x" + value.toString(16); michael@0: }; michael@0: michael@0: var lastError = ""; michael@0: michael@0: /** michael@0: * Returns the last compiler/linker error. michael@0: * @return {string} The last compiler/linker error. michael@0: */ michael@0: var getLastError = function() { michael@0: return lastError; michael@0: }; michael@0: michael@0: /** michael@0: * Whether a haystack ends with a needle. michael@0: * @param {string} haystack String to search michael@0: * @param {string} needle String to search for. michael@0: * @param {boolean} True if haystack ends with needle. michael@0: */ michael@0: var endsWith = function(haystack, needle) { michael@0: return haystack.substr(haystack.length - needle.length) === needle; michael@0: }; michael@0: michael@0: /** michael@0: * Whether a haystack starts with a needle. michael@0: * @param {string} haystack String to search michael@0: * @param {string} needle String to search for. michael@0: * @param {boolean} True if haystack starts with needle. michael@0: */ michael@0: var startsWith = function(haystack, needle) { michael@0: return haystack.substr(0, needle.length) === needle; michael@0: }; michael@0: michael@0: /** michael@0: * A vertex shader for a single texture. michael@0: * @type {string} michael@0: */ michael@0: var simpleTextureVertexShader = [ michael@0: 'attribute vec4 vPosition;', michael@0: 'attribute vec2 texCoord0;', michael@0: 'varying vec2 texCoord;', michael@0: 'void main() {', michael@0: ' gl_Position = vPosition;', michael@0: ' texCoord = texCoord0;', michael@0: '}'].join('\n'); michael@0: michael@0: /** michael@0: * A fragment shader for a single texture. michael@0: * @type {string} michael@0: */ michael@0: var simpleTextureFragmentShader = [ michael@0: 'precision mediump float;', michael@0: 'uniform sampler2D tex;', michael@0: 'varying vec2 texCoord;', michael@0: 'void main() {', michael@0: ' gl_FragData[0] = texture2D(tex, texCoord);', michael@0: '}'].join('\n'); michael@0: michael@0: /** michael@0: * Creates a simple texture vertex shader. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @return {!WebGLShader} michael@0: */ michael@0: var setupSimpleTextureVertexShader = function(gl) { michael@0: return loadShader(gl, simpleTextureVertexShader, gl.VERTEX_SHADER); michael@0: }; michael@0: michael@0: /** michael@0: * Creates a simple texture fragment shader. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @return {!WebGLShader} michael@0: */ michael@0: var setupSimpleTextureFragmentShader = function(gl) { michael@0: return loadShader( michael@0: gl, simpleTextureFragmentShader, gl.FRAGMENT_SHADER); michael@0: }; michael@0: michael@0: /** michael@0: * Creates a program, attaches shaders, binds attrib locations, links the michael@0: * program and calls useProgram. michael@0: * @param {!Array.} shaders The shaders to michael@0: * attach, or the source, or the id of a script to get michael@0: * the source from. michael@0: * @param {!Array.} opt_attribs The attribs names. michael@0: * @param {!Array.} opt_locations The locations for the attribs. michael@0: */ michael@0: var setupProgram = function(gl, shaders, opt_attribs, opt_locations) { michael@0: var realShaders = []; michael@0: var program = gl.createProgram(); michael@0: for (var ii = 0; ii < shaders.length; ++ii) { michael@0: var shader = shaders[ii]; michael@0: if (typeof shader == 'string') { michael@0: var element = document.getElementById(shader); michael@0: if (element) { michael@0: shader = loadShaderFromScript(gl, shader); michael@0: } else { michael@0: shader = loadShader(gl, shader, ii ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER); michael@0: } michael@0: } michael@0: gl.attachShader(program, shader); michael@0: } michael@0: if (opt_attribs) { michael@0: for (var ii = 0; ii < opt_attribs.length; ++ii) { michael@0: gl.bindAttribLocation( michael@0: program, michael@0: opt_locations ? opt_locations[ii] : ii, michael@0: opt_attribs[ii]); michael@0: } michael@0: } michael@0: gl.linkProgram(program); michael@0: michael@0: // Check the link status michael@0: var linked = gl.getProgramParameter(program, gl.LINK_STATUS); michael@0: if (!linked) { michael@0: // something went wrong with the link michael@0: lastError = gl.getProgramInfoLog (program); michael@0: error("Error in program linking:" + lastError); michael@0: michael@0: gl.deleteProgram(program); michael@0: return null; michael@0: } michael@0: michael@0: gl.useProgram(program); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Creates a simple texture program. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} opt_positionLocation The attrib location for position. michael@0: * @param {number} opt_texcoordLocation The attrib location for texture coords. michael@0: * @return {WebGLProgram} michael@0: */ michael@0: var setupSimpleTextureProgram = function( michael@0: gl, opt_positionLocation, opt_texcoordLocation) { michael@0: opt_positionLocation = opt_positionLocation || 0; michael@0: opt_texcoordLocation = opt_texcoordLocation || 1; michael@0: var vs = setupSimpleTextureVertexShader(gl); michael@0: var fs = setupSimpleTextureFragmentShader(gl); michael@0: if (!vs || !fs) { michael@0: return null; michael@0: } michael@0: var program = setupProgram( michael@0: gl, michael@0: [vs, fs], michael@0: ['vPosition', 'texCoord0'], michael@0: [opt_positionLocation, opt_texcoordLocation]); michael@0: if (!program) { michael@0: gl.deleteShader(fs); michael@0: gl.deleteShader(vs); michael@0: } michael@0: gl.useProgram(program); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Creates buffers for a textured unit quad and attaches them to vertex attribs. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} opt_positionLocation The attrib location for position. michael@0: * @param {number} opt_texcoordLocation The attrib location for texture coords. michael@0: * @return {!Array.} The buffer objects that were michael@0: * created. michael@0: */ michael@0: var setupUnitQuad = function(gl, opt_positionLocation, opt_texcoordLocation) { michael@0: return setupUnitQuadWithTexCoords(gl, [ 0.0, 0.0 ], [ 1.0, 1.0 ], michael@0: opt_positionLocation, opt_texcoordLocation); michael@0: }; michael@0: michael@0: /** michael@0: * Draws a previously setupUnitQuad. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: */ michael@0: var drawUnitQuad = function(gl) { michael@0: gl.drawArrays(gl.TRIANGLES, 0, 6); michael@0: }; michael@0: michael@0: /** michael@0: * Clears then Draws a previously setupUnitQuad. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {!Array.} opt_color The color to fill clear with before michael@0: * drawing. A 4 element array where each element is in the range 0 to michael@0: * 255. Default [255, 255, 255, 255] michael@0: */ michael@0: var clearAndDrawUnitQuad = function(gl, opt_color) { michael@0: opt_color = opt_color || [255, 255, 255, 255]; michael@0: michael@0: // Save and restore. michael@0: var prevClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE); michael@0: michael@0: gl.clearColor(opt_color[0] / 255, michael@0: opt_color[1] / 255, michael@0: opt_color[2] / 255, michael@0: opt_color[3] / 255); michael@0: gl.clear(gl.COLOR_BUFFER_BIT); michael@0: drawUnitQuad(gl); michael@0: michael@0: gl.clearColor(prevClearColor[0], michael@0: prevClearColor[1], michael@0: prevClearColor[2], michael@0: prevClearColor[3]); michael@0: }; michael@0: michael@0: /** michael@0: * Creates buffers for a textured unit quad with specified lower left michael@0: * and upper right texture coordinates, and attaches them to vertex michael@0: * attribs. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {!Array.} lowerLeftTexCoords The texture coordinates for the lower left corner. michael@0: * @param {!Array.} upperRightTexCoords The texture coordinates for the upper right corner. michael@0: * @param {number} opt_positionLocation The attrib location for position. michael@0: * @param {number} opt_texcoordLocation The attrib location for texture coords. michael@0: * @return {!Array.} The buffer objects that were michael@0: * created. michael@0: */ michael@0: var setupUnitQuadWithTexCoords = function( michael@0: gl, lowerLeftTexCoords, upperRightTexCoords, michael@0: opt_positionLocation, opt_texcoordLocation) { michael@0: opt_positionLocation = opt_positionLocation || 0; michael@0: opt_texcoordLocation = opt_texcoordLocation || 1; michael@0: var objects = []; michael@0: michael@0: var vertexObject = gl.createBuffer(); michael@0: gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject); michael@0: gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ michael@0: 1.0, 1.0, 0.0, michael@0: -1.0, 1.0, 0.0, michael@0: -1.0, -1.0, 0.0, michael@0: 1.0, 1.0, 0.0, michael@0: -1.0, -1.0, 0.0, michael@0: 1.0, -1.0, 0.0]), gl.STATIC_DRAW); michael@0: gl.enableVertexAttribArray(opt_positionLocation); michael@0: gl.vertexAttribPointer(opt_positionLocation, 3, gl.FLOAT, false, 0, 0); michael@0: objects.push(vertexObject); michael@0: michael@0: var llx = lowerLeftTexCoords[0]; michael@0: var lly = lowerLeftTexCoords[1]; michael@0: var urx = upperRightTexCoords[0]; michael@0: var ury = upperRightTexCoords[1]; michael@0: michael@0: var vertexObject = gl.createBuffer(); michael@0: gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject); michael@0: gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ michael@0: urx, ury, michael@0: llx, ury, michael@0: llx, lly, michael@0: urx, ury, michael@0: llx, lly, michael@0: urx, lly]), gl.STATIC_DRAW); michael@0: gl.enableVertexAttribArray(opt_texcoordLocation); michael@0: gl.vertexAttribPointer(opt_texcoordLocation, 2, gl.FLOAT, false, 0, 0); michael@0: objects.push(vertexObject); michael@0: return objects; michael@0: }; michael@0: michael@0: /** michael@0: * Creates a program and buffers for rendering a textured quad. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} opt_positionLocation The attrib location for position. michael@0: * @param {number} opt_texcoordLocation The attrib location for texture coords. michael@0: * @return {!WebGLProgram} michael@0: */ michael@0: var setupTexturedQuad = function( michael@0: gl, opt_positionLocation, opt_texcoordLocation) { michael@0: var program = setupSimpleTextureProgram( michael@0: gl, opt_positionLocation, opt_texcoordLocation); michael@0: setupUnitQuad(gl, opt_positionLocation, opt_texcoordLocation); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Creates a program and buffers for rendering a textured quad with michael@0: * specified lower left and upper right texture coordinates. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {!Array.} lowerLeftTexCoords The texture coordinates for the lower left corner. michael@0: * @param {!Array.} upperRightTexCoords The texture coordinates for the upper right corner. michael@0: * @param {number} opt_positionLocation The attrib location for position. michael@0: * @param {number} opt_texcoordLocation The attrib location for texture coords. michael@0: * @return {!WebGLProgram} michael@0: */ michael@0: var setupTexturedQuadWithTexCoords = function( michael@0: gl, lowerLeftTexCoords, upperRightTexCoords, michael@0: opt_positionLocation, opt_texcoordLocation) { michael@0: var program = setupSimpleTextureProgram( michael@0: gl, opt_positionLocation, opt_texcoordLocation); michael@0: setupUnitQuadWithTexCoords(gl, lowerLeftTexCoords, upperRightTexCoords, michael@0: opt_positionLocation, opt_texcoordLocation); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Creates a unit quad with only positions of a given resolution. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} gridRes The resolution of the mesh grid, expressed in the number of triangles across and down. michael@0: * @param {number} opt_positionLocation The attrib location for position. michael@0: */ michael@0: var setupQuad = function ( michael@0: gl, gridRes, opt_positionLocation, opt_flipOddTriangles) { michael@0: var positionLocation = opt_positionLocation || 0; michael@0: var objects = []; michael@0: michael@0: var vertsAcross = gridRes + 1; michael@0: var numVerts = vertsAcross * vertsAcross; michael@0: var positions = new Float32Array(numVerts * 3); michael@0: var indices = new Uint16Array(6 * gridRes * gridRes); michael@0: michael@0: var poffset = 0; michael@0: michael@0: for (var yy = 0; yy <= gridRes; ++yy) { michael@0: for (var xx = 0; xx <= gridRes; ++xx) { michael@0: positions[poffset + 0] = -1 + 2 * xx / gridRes; michael@0: positions[poffset + 1] = -1 + 2 * yy / gridRes; michael@0: positions[poffset + 2] = 0; michael@0: michael@0: poffset += 3; michael@0: } michael@0: } michael@0: michael@0: var tbase = 0; michael@0: for (var yy = 0; yy < gridRes; ++yy) { michael@0: var index = yy * vertsAcross; michael@0: for (var xx = 0; xx < gridRes; ++xx) { michael@0: indices[tbase + 0] = index + 0; michael@0: indices[tbase + 1] = index + 1; michael@0: indices[tbase + 2] = index + vertsAcross; michael@0: indices[tbase + 3] = index + vertsAcross; michael@0: indices[tbase + 4] = index + 1; michael@0: indices[tbase + 5] = index + vertsAcross + 1; michael@0: michael@0: if (opt_flipOddTriangles) { michael@0: indices[tbase + 4] = index + vertsAcross + 1; michael@0: indices[tbase + 5] = index + 1; michael@0: } michael@0: michael@0: index += 1; michael@0: tbase += 6; michael@0: } michael@0: } michael@0: michael@0: var buf = gl.createBuffer(); michael@0: gl.bindBuffer(gl.ARRAY_BUFFER, buf); michael@0: gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); michael@0: gl.enableVertexAttribArray(positionLocation); michael@0: gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0); michael@0: objects.push(buf); michael@0: michael@0: var buf = gl.createBuffer(); michael@0: gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf); michael@0: gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW); michael@0: objects.push(buf); michael@0: michael@0: return objects; michael@0: }; michael@0: michael@0: /** michael@0: * Fills the given texture with a solid color michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {!WebGLTexture} tex The texture to fill. michael@0: * @param {number} width The width of the texture to create. michael@0: * @param {number} height The height of the texture to create. michael@0: * @param {!Array.} color The color to fill with. A 4 element array michael@0: * where each element is in the range 0 to 255. michael@0: * @param {number} opt_level The level of the texture to fill. Default = 0. michael@0: */ michael@0: var fillTexture = function(gl, tex, width, height, color, opt_level) { michael@0: opt_level = opt_level || 0; michael@0: var numPixels = width * height; michael@0: var size = numPixels * 4; michael@0: var buf = new Uint8Array(size); michael@0: for (var ii = 0; ii < numPixels; ++ii) { michael@0: var off = ii * 4; michael@0: buf[off + 0] = color[0]; michael@0: buf[off + 1] = color[1]; michael@0: buf[off + 2] = color[2]; michael@0: buf[off + 3] = color[3]; michael@0: } michael@0: gl.bindTexture(gl.TEXTURE_2D, tex); michael@0: gl.texImage2D( michael@0: gl.TEXTURE_2D, opt_level, gl.RGBA, width, height, 0, michael@0: gl.RGBA, gl.UNSIGNED_BYTE, buf); michael@0: }; michael@0: michael@0: /** michael@0: * Creates a textures and fills it with a solid color michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} width The width of the texture to create. michael@0: * @param {number} height The height of the texture to create. michael@0: * @param {!Array.} color The color to fill with. A 4 element array michael@0: * where each element is in the range 0 to 255. michael@0: * @return {!WebGLTexture} michael@0: */ michael@0: var createColoredTexture = function(gl, width, height, color) { michael@0: var tex = gl.createTexture(); michael@0: fillTexture(gl, tex, width, height, color); michael@0: return tex; michael@0: }; michael@0: michael@0: /** michael@0: * Draws a previously setup quad. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {!Array.} opt_color The color to fill clear with before michael@0: * drawing. A 4 element array where each element is in the range 0 to michael@0: * 255. Default [255, 255, 255, 255] michael@0: */ michael@0: var drawQuad = function(gl, opt_color) { michael@0: opt_color = opt_color || [255, 255, 255, 255]; michael@0: gl.clearColor( michael@0: opt_color[0] / 255, michael@0: opt_color[1] / 255, michael@0: opt_color[2] / 255, michael@0: opt_color[3] / 255); michael@0: gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); michael@0: gl.drawArrays(gl.TRIANGLES, 0, 6); michael@0: }; michael@0: michael@0: /** michael@0: * Checks that a portion of a canvas is 1 color. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} x left corner of region to check. michael@0: * @param {number} y bottom corner of region to check. michael@0: * @param {number} width width of region to check. michael@0: * @param {number} height width of region to check. michael@0: * @param {!Array.} color The color to fill clear with before drawing. A michael@0: * 4 element array where each element is in the range 0 to 255. michael@0: * @param {string} msg Message to associate with success. Eg ("should be red"). michael@0: * @param {number} errorRange Optional. Acceptable error in michael@0: * color checking. 0 by default. michael@0: */ michael@0: var checkCanvasRect = function(gl, x, y, width, height, color, msg, errorRange) { michael@0: errorRange = errorRange || 0; michael@0: var buf = new Uint8Array(width * height * 4); michael@0: gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, buf); michael@0: for (var i = 0; i < width * height; ++i) { michael@0: var offset = i * 4; michael@0: for (var j = 0; j < color.length; ++j) { michael@0: if (Math.abs(buf[offset + j] - color[j]) > errorRange) { michael@0: var was = buf[offset + 0].toString(); michael@0: for (j = 1; j < color.length; ++j) { michael@0: was += "," + buf[offset + j]; michael@0: } michael@0: michael@0: var cv = document.createElement('canvas'); michael@0: cv.height = height; michael@0: cv.width = width; michael@0: var ctx = cv.getContext('2d'); michael@0: ctx.fillStyle="rgba(" + color[0] + ", " + color[1] + ", " + color[2] + ", 255)"; michael@0: ctx.fillRect(0, 0, width, height); michael@0: testFailedRender(msg, ctx, buf, width, height); michael@0: michael@0: debug('at (' + (i % width) + ', ' + Math.floor(i / width) + michael@0: ') expected: ' + color + ' was ' + was); michael@0: return; michael@0: } michael@0: } michael@0: } michael@0: testPassed(msg); michael@0: }; michael@0: michael@0: /** michael@0: * Checks that an entire canvas is 1 color. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {!Array.} color The color to fill clear with before drawing. A michael@0: * 4 element array where each element is in the range 0 to 255. michael@0: * @param {string} msg Message to associate with success. Eg ("should be red"). michael@0: * @param {number} errorRange Optional. Acceptable error in michael@0: * color checking. 0 by default. michael@0: */ michael@0: var checkCanvas = function(gl, color, msg, errorRange) { michael@0: checkCanvasRect(gl, 0, 0, gl.canvas.width, gl.canvas.height, color, msg, errorRange); michael@0: }; michael@0: michael@0: /** michael@0: * Loads a texture, calls callback when finished. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} url URL of image to load michael@0: * @param {function(!Image): void} callback Function that gets called after michael@0: * image has loaded michael@0: * @return {!WebGLTexture} The created texture. michael@0: */ michael@0: var loadTexture = function(gl, url, callback) { michael@0: var texture = gl.createTexture(); michael@0: gl.bindTexture(gl.TEXTURE_2D, texture); michael@0: gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); michael@0: gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); michael@0: var image = new Image(); michael@0: image.onload = function() { michael@0: gl.bindTexture(gl.TEXTURE_2D, texture); michael@0: gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); michael@0: gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); michael@0: callback(image); michael@0: }; michael@0: image.src = url; michael@0: return texture; michael@0: }; michael@0: michael@0: /** michael@0: * Creates a webgl context. michael@0: * @param {!Canvas|string} opt_canvas The canvas tag to get michael@0: * context from. If one is not passed in one will be michael@0: * created. If it's a string it's assumed to be the id of a michael@0: * canvas. michael@0: * @return {!WebGLContext} The created context. michael@0: */ michael@0: var create3DContext = function(opt_canvas, opt_attributes) { michael@0: opt_canvas = opt_canvas || document.createElement("canvas"); michael@0: if (typeof opt_canvas == 'string') { michael@0: opt_canvas = document.getElementById(opt_canvas); michael@0: } michael@0: var context = null; michael@0: var names = ["webgl", "experimental-webgl"]; michael@0: for (var i = 0; i < names.length; ++i) { michael@0: try { michael@0: context = opt_canvas.getContext(names[i], opt_attributes); michael@0: } catch (e) { michael@0: } michael@0: if (context) { michael@0: break; michael@0: } michael@0: } michael@0: if (!context) { michael@0: testFailed("Unable to fetch WebGL rendering context for Canvas"); michael@0: } michael@0: return context; michael@0: } michael@0: michael@0: /** michael@0: * Gets a GLError value as a string. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} err The webgl error as retrieved from gl.getError(). michael@0: * @return {string} the error as a string. michael@0: */ michael@0: var getGLErrorAsString = function(gl, err) { michael@0: if (err === gl.NO_ERROR) { michael@0: return "NO_ERROR"; michael@0: } michael@0: for (var name in gl) { michael@0: if (gl[name] === err) { michael@0: return name; michael@0: } michael@0: } michael@0: return err.toString(); michael@0: }; michael@0: michael@0: /** michael@0: * Wraps a WebGL function with a function that throws an exception if there is michael@0: * an error. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} fname Name of function to wrap. michael@0: * @return {function} The wrapped function. michael@0: */ michael@0: var createGLErrorWrapper = function(context, fname) { michael@0: return function() { michael@0: var rv = context[fname].apply(context, arguments); michael@0: var err = context.getError(); michael@0: if (err != 0) michael@0: throw "GL error " + getGLErrorAsString(err) + " in " + fname; michael@0: return rv; michael@0: }; michael@0: }; michael@0: michael@0: /** michael@0: * Creates a WebGL context where all functions are wrapped to throw an exception michael@0: * if there is an error. michael@0: * @param {!Canvas} canvas The HTML canvas to get a context from. michael@0: * @return {!Object} The wrapped context. michael@0: */ michael@0: function create3DContextWithWrapperThatThrowsOnGLError(canvas) { michael@0: var context = create3DContext(canvas); michael@0: var wrap = {}; michael@0: for (var i in context) { michael@0: try { michael@0: if (typeof context[i] == 'function') { michael@0: wrap[i] = createGLErrorWrapper(context, i); michael@0: } else { michael@0: wrap[i] = context[i]; michael@0: } michael@0: } catch (e) { michael@0: error("createContextWrapperThatThrowsOnGLError: Error accessing " + i); michael@0: } michael@0: } michael@0: wrap.getError = function() { michael@0: return context.getError(); michael@0: }; michael@0: return wrap; michael@0: }; michael@0: michael@0: /** michael@0: * Tests that an evaluated expression generates a specific GL error. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} glError The expected gl error. michael@0: * @param {string} evalSTr The string to evaluate. michael@0: */ michael@0: var shouldGenerateGLError = function(gl, glError, evalStr) { michael@0: var exception; michael@0: try { michael@0: eval(evalStr); michael@0: } catch (e) { michael@0: exception = e; michael@0: } michael@0: if (exception) { michael@0: testFailed(evalStr + " threw exception " + exception); michael@0: } else { michael@0: var err = gl.getError(); michael@0: if (err != glError) { michael@0: testFailed(evalStr + " expected: " + getGLErrorAsString(gl, glError) + ". Was " + getGLErrorAsString(gl, err) + "."); michael@0: } else { michael@0: testPassed(evalStr + " was expected value: " + getGLErrorAsString(gl, glError) + "."); michael@0: } michael@0: } michael@0: }; michael@0: michael@0: /** michael@0: * Tests that the first error GL returns is the specified error. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {number} glError The expected gl error. michael@0: * @param {string} opt_msg michael@0: */ michael@0: var glErrorShouldBe = function(gl, glError, opt_msg) { michael@0: opt_msg = opt_msg || ""; michael@0: var err = gl.getError(); michael@0: if (err != glError) { michael@0: testFailed("getError expected: " + getGLErrorAsString(gl, glError) + michael@0: ". Was " + getGLErrorAsString(gl, err) + " : " + opt_msg); michael@0: } else { michael@0: testPassed("getError was expected value: " + michael@0: getGLErrorAsString(gl, glError) + " : " + opt_msg); michael@0: } michael@0: }; michael@0: michael@0: /** michael@0: * Links a WebGL program, throws if there are errors. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {!WebGLProgram} program The WebGLProgram to link. michael@0: * @param {function(string): void) opt_errorCallback callback for errors. michael@0: */ michael@0: var linkProgram = function(gl, program, opt_errorCallback) { michael@0: errFn = opt_errorCallback || testFailed; michael@0: // Link the program michael@0: gl.linkProgram(program); michael@0: michael@0: // Check the link status michael@0: var linked = gl.getProgramParameter(program, gl.LINK_STATUS); michael@0: if (!linked) { michael@0: // something went wrong with the link michael@0: var error = gl.getProgramInfoLog (program); michael@0: michael@0: errFn("Error in program linking:" + error); michael@0: michael@0: gl.deleteProgram(program); michael@0: } michael@0: }; michael@0: michael@0: /** michael@0: * Sets up WebGL with shaders. michael@0: * @param {string} canvasName The id of the canvas. michael@0: * @param {string} vshader The id of the script tag that contains the vertex michael@0: * shader source. michael@0: * @param {string} fshader The id of the script tag that contains the fragment michael@0: * shader source. michael@0: * @param {!Array.} attribs An array of attrib names used to bind michael@0: * attribs to the ordinal of the name in this array. michael@0: * @param {!Array.} opt_clearColor The color to cla michael@0: * @return {!WebGLContext} The created WebGLContext. michael@0: */ michael@0: var setupWebGLWithShaders = function( michael@0: canvasName, vshader, fshader, attribs) { michael@0: var canvas = document.getElementById(canvasName); michael@0: var gl = create3DContext(canvas); michael@0: if (!gl) { michael@0: testFailed("No WebGL context found"); michael@0: } michael@0: michael@0: // create our shaders michael@0: var vertexShader = loadShaderFromScript(gl, vshader); michael@0: var fragmentShader = loadShaderFromScript(gl, fshader); michael@0: michael@0: if (!vertexShader || !fragmentShader) { michael@0: return null; michael@0: } michael@0: michael@0: // Create the program object michael@0: program = gl.createProgram(); michael@0: michael@0: if (!program) { michael@0: return null; michael@0: } michael@0: michael@0: // Attach our two shaders to the program michael@0: gl.attachShader (program, vertexShader); michael@0: gl.attachShader (program, fragmentShader); michael@0: michael@0: // Bind attributes michael@0: for (var i in attribs) { michael@0: gl.bindAttribLocation (program, i, attribs[i]); michael@0: } michael@0: michael@0: linkProgram(gl, program); michael@0: michael@0: gl.useProgram(program); michael@0: michael@0: gl.clearColor(0,0,0,1); michael@0: gl.clearDepth(1); michael@0: michael@0: gl.enable(gl.DEPTH_TEST); michael@0: gl.enable(gl.BLEND); michael@0: gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); michael@0: michael@0: gl.program = program; michael@0: return gl; michael@0: }; michael@0: michael@0: /** michael@0: * Loads text from an external file. This function is synchronous. michael@0: * @param {string} url The url of the external file. michael@0: * @param {!function(bool, string): void} callback that is sent a bool for michael@0: * success and the string. michael@0: */ michael@0: var loadTextFileAsync = function(url, callback) { michael@0: log ("loading: " + url); michael@0: var error = 'loadTextFileSynchronous failed to load url "' + url + '"'; michael@0: var request; michael@0: if (window.XMLHttpRequest) { michael@0: request = new XMLHttpRequest(); michael@0: if (request.overrideMimeType) { michael@0: request.overrideMimeType('text/plain'); michael@0: } michael@0: } else { michael@0: throw 'XMLHttpRequest is disabled'; michael@0: } michael@0: try { michael@0: request.open('GET', url, true); michael@0: request.onreadystatechange = function() { michael@0: if (request.readyState == 4) { michael@0: var text = ''; michael@0: // HTTP reports success with a 200 status. The file protocol reports michael@0: // success with zero. HTTP does not use zero as a status code (they michael@0: // start at 100). michael@0: // https://developer.mozilla.org/En/Using_XMLHttpRequest michael@0: var success = request.status == 200 || request.status == 0; michael@0: if (success) { michael@0: text = request.responseText; michael@0: } michael@0: log("loaded: " + url); michael@0: callback(success, text); michael@0: } michael@0: }; michael@0: request.send(null); michael@0: } catch (e) { michael@0: log("failed to load: " + url); michael@0: callback(false, ''); michael@0: } michael@0: }; michael@0: michael@0: // Add your prefix here. michael@0: var browserPrefixes = [ michael@0: "", michael@0: "MOZ_", michael@0: "OP_", michael@0: "WEBKIT_" michael@0: ]; michael@0: michael@0: /** michael@0: * Given an extension name like WEBGL_compressed_texture_s3tc michael@0: * returns the name of the supported version extension, like michael@0: * WEBKIT_WEBGL_compressed_teture_s3tc michael@0: * @param {string} name Name of extension to look for michael@0: * @return {string} name of extension found or undefined if not michael@0: * found. michael@0: */ michael@0: var getSupportedExtensionWithKnownPrefixes = function(gl, name) { michael@0: var supported = gl.getSupportedExtensions(); michael@0: for (var ii = 0; ii < browserPrefixes.length; ++ii) { michael@0: var prefixedName = browserPrefixes[ii] + name; michael@0: if (supported.indexOf(prefixedName) >= 0) { michael@0: return prefixedName; michael@0: } michael@0: } michael@0: }; michael@0: michael@0: /** michael@0: * Given an extension name like WEBGL_compressed_texture_s3tc michael@0: * returns the supported version extension, like michael@0: * WEBKIT_WEBGL_compressed_teture_s3tc michael@0: * @param {string} name Name of extension to look for michael@0: * @return {WebGLExtension} The extension or undefined if not michael@0: * found. michael@0: */ michael@0: var getExtensionWithKnownPrefixes = function(gl, name) { michael@0: for (var ii = 0; ii < browserPrefixes.length; ++ii) { michael@0: var prefixedName = browserPrefixes[ii] + name; michael@0: var ext = gl.getExtension(prefixedName); michael@0: if (ext) { michael@0: return ext; michael@0: } michael@0: } michael@0: }; michael@0: michael@0: /** michael@0: * Recursively loads a file as a list. Each line is parsed for a relative michael@0: * path. If the file ends in .txt the contents of that file is inserted in michael@0: * the list. michael@0: * michael@0: * @param {string} url The url of the external file. michael@0: * @param {!function(bool, Array): void} callback that is sent a bool michael@0: * for success and the array of strings. michael@0: */ michael@0: var getFileListAsync = function(url, callback) { michael@0: var files = []; michael@0: michael@0: var getFileListImpl = function(url, callback) { michael@0: var files = []; michael@0: if (url.substr(url.length - 4) == '.txt') { michael@0: loadTextFileAsync(url, function() { michael@0: return function(success, text) { michael@0: if (!success) { michael@0: callback(false, ''); michael@0: return; michael@0: } michael@0: var lines = text.split('\n'); michael@0: var prefix = ''; michael@0: var lastSlash = url.lastIndexOf('/'); michael@0: if (lastSlash >= 0) { michael@0: prefix = url.substr(0, lastSlash + 1); michael@0: } michael@0: var fail = false; michael@0: var count = 1; michael@0: var index = 0; michael@0: for (var ii = 0; ii < lines.length; ++ii) { michael@0: var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, ''); michael@0: if (str.length > 4 && michael@0: str[0] != '#' && michael@0: str[0] != ";" && michael@0: str.substr(0, 2) != "//") { michael@0: var names = str.split(/ +/); michael@0: new_url = prefix + str; michael@0: if (names.length == 1) { michael@0: new_url = prefix + str; michael@0: ++count; michael@0: getFileListImpl(new_url, function(index) { michael@0: return function(success, new_files) { michael@0: log("got files: " + new_files.length); michael@0: if (success) { michael@0: files[index] = new_files; michael@0: } michael@0: finish(success); michael@0: }; michael@0: }(index++)); michael@0: } else { michael@0: var s = ""; michael@0: var p = ""; michael@0: for (var jj = 0; jj < names.length; ++jj) { michael@0: s += p + prefix + names[jj]; michael@0: p = " "; michael@0: } michael@0: files[index++] = s; michael@0: } michael@0: } michael@0: } michael@0: finish(true); michael@0: michael@0: function finish(success) { michael@0: if (!success) { michael@0: fail = true; michael@0: } michael@0: --count; michael@0: log("count: " + count); michael@0: if (!count) { michael@0: callback(!fail, files); michael@0: } michael@0: } michael@0: } michael@0: }()); michael@0: michael@0: } else { michael@0: files.push(url); michael@0: callback(true, files); michael@0: } michael@0: }; michael@0: michael@0: getFileListImpl(url, function(success, files) { michael@0: // flatten michael@0: var flat = []; michael@0: flatten(files); michael@0: function flatten(files) { michael@0: for (var ii = 0; ii < files.length; ++ii) { michael@0: var value = files[ii]; michael@0: if (typeof(value) == "string") { michael@0: flat.push(value); michael@0: } else { michael@0: flatten(value); michael@0: } michael@0: } michael@0: } michael@0: callback(success, flat); michael@0: }); michael@0: }; michael@0: michael@0: /** michael@0: * Gets a file from a file/URL michael@0: * @param {string} file the URL of the file to get. michael@0: * @return {string} The contents of the file. michael@0: */ michael@0: var readFile = function(file) { michael@0: var xhr = new XMLHttpRequest(); michael@0: xhr.open("GET", file, false); michael@0: xhr.send(); michael@0: return xhr.responseText.replace(/\r/g, ""); michael@0: }; michael@0: michael@0: var readFileList = function(url) { michael@0: var files = []; michael@0: if (url.substr(url.length - 4) == '.txt') { michael@0: var lines = readFile(url).split('\n'); michael@0: var prefix = ''; michael@0: var lastSlash = url.lastIndexOf('/'); michael@0: if (lastSlash >= 0) { michael@0: prefix = url.substr(0, lastSlash + 1); michael@0: } michael@0: for (var ii = 0; ii < lines.length; ++ii) { michael@0: var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, ''); michael@0: if (str.length > 4 && michael@0: str[0] != '#' && michael@0: str[0] != ";" && michael@0: str.substr(0, 2) != "//") { michael@0: var names = str.split(/ +/); michael@0: if (names.length == 1) { michael@0: new_url = prefix + str; michael@0: files = files.concat(readFileList(new_url)); michael@0: } else { michael@0: var s = ""; michael@0: var p = ""; michael@0: for (var jj = 0; jj < names.length; ++jj) { michael@0: s += p + prefix + names[jj]; michael@0: p = " "; michael@0: } michael@0: files.push(s); michael@0: } michael@0: } michael@0: } michael@0: } else { michael@0: files.push(url); michael@0: } michael@0: return files; michael@0: }; michael@0: michael@0: /** michael@0: * Loads a shader. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} shaderSource The shader source. michael@0: * @param {number} shaderType The type of shader. michael@0: * @param {function(string): void) opt_errorCallback callback for errors. michael@0: * @return {!WebGLShader} The created shader. michael@0: */ michael@0: var loadShader = function(gl, shaderSource, shaderType, opt_errorCallback) { michael@0: var errFn = opt_errorCallback || error; michael@0: // Create the shader object michael@0: var shader = gl.createShader(shaderType); michael@0: if (shader == null) { michael@0: errFn("*** Error: unable to create shader '"+shaderSource+"'"); michael@0: return null; michael@0: } michael@0: michael@0: // Load the shader source michael@0: gl.shaderSource(shader, shaderSource); michael@0: var err = gl.getError(); michael@0: if (err != gl.NO_ERROR) { michael@0: errFn("*** Error loading shader '" + shader + "':" + glEnumToString(gl, err)); michael@0: return null; michael@0: } michael@0: michael@0: // Compile the shader michael@0: gl.compileShader(shader); michael@0: michael@0: // Check the compile status michael@0: var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); michael@0: if (!compiled) { michael@0: // Something went wrong during compilation; get the error michael@0: lastError = gl.getShaderInfoLog(shader); michael@0: errFn("*** Error compiling shader '" + shader + "':" + lastError); michael@0: gl.deleteShader(shader); michael@0: return null; michael@0: } michael@0: michael@0: return shader; michael@0: } michael@0: michael@0: /** michael@0: * Loads a shader from a URL. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {file} file The URL of the shader source. michael@0: * @param {number} type The type of shader. michael@0: * @param {function(string): void) opt_errorCallback callback for errors. michael@0: * @return {!WebGLShader} The created shader. michael@0: */ michael@0: var loadShaderFromFile = function(gl, file, type, opt_errorCallback) { michael@0: var shaderSource = readFile(file); michael@0: return loadShader(gl, shaderSource, type, opt_errorCallback); michael@0: }; michael@0: michael@0: /** michael@0: * Gets the content of script. michael@0: */ michael@0: var getScript = function(scriptId) { michael@0: var shaderScript = document.getElementById(scriptId); michael@0: if (!shaderScript) { michael@0: throw("*** Error: unknown script element" + scriptId); michael@0: } michael@0: return shaderScript.text; michael@0: }; michael@0: michael@0: /** michael@0: * Loads a shader from a script tag. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} scriptId The id of the script tag. michael@0: * @param {number} opt_shaderType The type of shader. If not passed in it will michael@0: * be derived from the type of the script tag. michael@0: * @param {function(string): void) opt_errorCallback callback for errors. michael@0: * @return {!WebGLShader} The created shader. michael@0: */ michael@0: var loadShaderFromScript = function( michael@0: gl, scriptId, opt_shaderType, opt_errorCallback) { michael@0: var shaderSource = ""; michael@0: var shaderType; michael@0: var shaderScript = document.getElementById(scriptId); michael@0: if (!shaderScript) { michael@0: throw("*** Error: unknown script element " + scriptId); michael@0: } michael@0: shaderSource = shaderScript.text; michael@0: michael@0: if (!opt_shaderType) { michael@0: if (shaderScript.type == "x-shader/x-vertex") { michael@0: shaderType = gl.VERTEX_SHADER; michael@0: } else if (shaderScript.type == "x-shader/x-fragment") { michael@0: shaderType = gl.FRAGMENT_SHADER; michael@0: } else if (shaderType != gl.VERTEX_SHADER && shaderType != gl.FRAGMENT_SHADER) { michael@0: throw("*** Error: unknown shader type"); michael@0: return null; michael@0: } michael@0: } michael@0: michael@0: return loadShader( michael@0: gl, shaderSource, opt_shaderType ? opt_shaderType : shaderType, michael@0: opt_errorCallback); michael@0: }; michael@0: michael@0: var loadStandardProgram = function(gl) { michael@0: var program = gl.createProgram(); michael@0: gl.attachShader(program, loadStandardVertexShader(gl)); michael@0: gl.attachShader(program, loadStandardFragmentShader(gl)); michael@0: linkProgram(gl, program); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Loads shaders from files, creates a program, attaches the shaders and links. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} vertexShaderPath The URL of the vertex shader. michael@0: * @param {string} fragmentShaderPath The URL of the fragment shader. michael@0: * @param {function(string): void) opt_errorCallback callback for errors. michael@0: * @return {!WebGLProgram} The created program. michael@0: */ michael@0: var loadProgramFromFile = function( michael@0: gl, vertexShaderPath, fragmentShaderPath, opt_errorCallback) { michael@0: var program = gl.createProgram(); michael@0: gl.attachShader( michael@0: program, michael@0: loadShaderFromFile( michael@0: gl, vertexShaderPath, gl.VERTEX_SHADER, opt_errorCallback)); michael@0: gl.attachShader( michael@0: program, michael@0: loadShaderFromFile( michael@0: gl, fragmentShaderPath, gl.FRAGMENT_SHADER, opt_errorCallback)); michael@0: linkProgram(gl, program, opt_errorCallback); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Loads shaders from script tags, creates a program, attaches the shaders and michael@0: * links. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} vertexScriptId The id of the script tag that contains the michael@0: * vertex shader. michael@0: * @param {string} fragmentScriptId The id of the script tag that contains the michael@0: * fragment shader. michael@0: * @param {function(string): void) opt_errorCallback callback for errors. michael@0: * @return {!WebGLProgram} The created program. michael@0: */ michael@0: var loadProgramFromScript = function loadProgramFromScript( michael@0: gl, vertexScriptId, fragmentScriptId, opt_errorCallback) { michael@0: var program = gl.createProgram(); michael@0: gl.attachShader( michael@0: program, michael@0: loadShaderFromScript( michael@0: gl, vertexScriptId, gl.VERTEX_SHADER, opt_errorCallback)); michael@0: gl.attachShader( michael@0: program, michael@0: loadShaderFromScript( michael@0: gl, fragmentScriptId, gl.FRAGMENT_SHADER, opt_errorCallback)); michael@0: linkProgram(gl, program, opt_errorCallback); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Loads shaders from source, creates a program, attaches the shaders and michael@0: * links. michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} vertexShader The vertex shader. michael@0: * @param {string} fragmentShader The fragment shader. michael@0: * @param {function(string): void) opt_errorCallback callback for errors. michael@0: * @return {!WebGLProgram} The created program. michael@0: */ michael@0: var loadProgram = function( michael@0: gl, vertexShader, fragmentShader, opt_errorCallback) { michael@0: var program = gl.createProgram(); michael@0: gl.attachShader( michael@0: program, michael@0: loadShader( michael@0: gl, vertexShader, gl.VERTEX_SHADER, opt_errorCallback)); michael@0: gl.attachShader( michael@0: program, michael@0: loadShader( michael@0: gl, fragmentShader, gl.FRAGMENT_SHADER, opt_errorCallback)); michael@0: linkProgram(gl, program, opt_errorCallback); michael@0: return program; michael@0: }; michael@0: michael@0: /** michael@0: * Loads shaders from source, creates a program, attaches the shaders and michael@0: * links but expects error. michael@0: * michael@0: * GLSL 1.0.17 10.27 effectively says that compileShader can michael@0: * always succeed as long as linkProgram fails so we can't michael@0: * rely on compileShader failing. This function expects michael@0: * one of the shader to fail OR linking to fail. michael@0: * michael@0: * @param {!WebGLContext} gl The WebGLContext to use. michael@0: * @param {string} vertexShaderScriptId The vertex shader. michael@0: * @param {string} fragmentShaderScriptId The fragment shader. michael@0: * @return {WebGLProgram} The created program. michael@0: */ michael@0: var loadProgramFromScriptExpectError = function( michael@0: gl, vertexShaderScriptId, fragmentShaderScriptId) { michael@0: var vertexShader = loadShaderFromScript(gl, vertexShaderScriptId); michael@0: if (!vertexShader) { michael@0: return null; michael@0: } michael@0: var fragmentShader = loadShaderFromScript(gl, fragmentShaderScriptId); michael@0: if (!fragmentShader) { michael@0: return null; michael@0: } michael@0: var linkSuccess = true; michael@0: var program = gl.createProgram(); michael@0: gl.attachShader(program, vertexShader); michael@0: gl.attachShader(program, fragmentShader); michael@0: linkSuccess = true; michael@0: linkProgram(gl, program, function() { michael@0: linkSuccess = false; michael@0: }); michael@0: return linkSuccess ? program : null; michael@0: }; michael@0: michael@0: var basePath; michael@0: var getBasePath = function() { michael@0: if (!basePath) { michael@0: var expectedBase = "webgl-test-utils.js"; michael@0: var scripts = document.getElementsByTagName('script'); michael@0: for (var script, i = 0; script = scripts[i]; i++) { michael@0: var src = script.src; michael@0: var l = src.length; michael@0: if (src.substr(l - expectedBase.length) == expectedBase) { michael@0: basePath = src.substr(0, l - expectedBase.length); michael@0: } michael@0: } michael@0: } michael@0: return basePath; michael@0: }; michael@0: michael@0: var loadStandardVertexShader = function(gl) { michael@0: return loadShaderFromFile( michael@0: gl, getBasePath() + "vertexShader.vert", gl.VERTEX_SHADER); michael@0: }; michael@0: michael@0: var loadStandardFragmentShader = function(gl) { michael@0: return loadShaderFromFile( michael@0: gl, getBasePath() + "fragmentShader.frag", gl.FRAGMENT_SHADER); michael@0: }; michael@0: michael@0: /** michael@0: * Loads an image asynchronously. michael@0: * @param {string} url URL of image to load. michael@0: * @param {!function(!Element): void} callback Function to call michael@0: * with loaded image. michael@0: */ michael@0: var loadImageAsync = function(url, callback) { michael@0: var img = document.createElement('img'); michael@0: img.onload = function() { michael@0: callback(img); michael@0: }; michael@0: img.src = url; michael@0: }; michael@0: michael@0: /** michael@0: * Loads an array of images. michael@0: * @param {!Array.} urls URLs of images to load. michael@0: * @param {!function(!{string, img}): void} callback. Callback michael@0: * that gets passed map of urls to img tags. michael@0: */ michael@0: var loadImagesAsync = function(urls, callback) { michael@0: var count = 1; michael@0: var images = { }; michael@0: function countDown() { michael@0: --count; michael@0: if (count == 0) { michael@0: callback(images); michael@0: } michael@0: } michael@0: function imageLoaded(url) { michael@0: return function(img) { michael@0: images[url] = img; michael@0: countDown(); michael@0: } michael@0: } michael@0: for (var ii = 0; ii < urls.length; ++ii) { michael@0: ++count; michael@0: loadImageAsync(urls[ii], imageLoaded(urls[ii])); michael@0: } michael@0: countDown(); michael@0: }; michael@0: michael@0: var getUrlArguments = function() { michael@0: var args = {}; michael@0: try { michael@0: var s = window.location.href; michael@0: var q = s.indexOf("?"); michael@0: var e = s.indexOf("#"); michael@0: if (e < 0) { michael@0: e = s.length; michael@0: } michael@0: var query = s.substring(q + 1, e); michael@0: var pairs = query.split("&"); michael@0: for (var ii = 0; ii < pairs.length; ++ii) { michael@0: var keyValue = pairs[ii].split("="); michael@0: var key = keyValue[0]; michael@0: var value = decodeURIComponent(keyValue[1]); michael@0: args[key] = value; michael@0: } michael@0: } catch (e) { michael@0: throw "could not parse url"; michael@0: } michael@0: return args; michael@0: }; michael@0: michael@0: var makeImage = function(canvas) { michael@0: var img = document.createElement('img'); michael@0: img.src = canvas.toDataURL(); michael@0: return img; michael@0: }; michael@0: michael@0: var insertImage = function(element, caption, img) { michael@0: var div = document.createElement("div"); michael@0: div.appendChild(img); michael@0: var label = document.createElement("div"); michael@0: label.appendChild(document.createTextNode(caption)); michael@0: div.appendChild(label); michael@0: element.appendChild(div); michael@0: }; michael@0: michael@0: var addShaderSource = function(element, label, source) { michael@0: var div = document.createElement("div"); michael@0: var s = document.createElement("pre"); michael@0: s.className = "shader-source"; michael@0: s.style.display = "none"; michael@0: var ol = document.createElement("ol"); michael@0: //s.appendChild(document.createTextNode(source)); michael@0: var lines = source.split("\n"); michael@0: for (var ii = 0; ii < lines.length; ++ii) { michael@0: var line = lines[ii]; michael@0: var li = document.createElement("li"); michael@0: li.appendChild(document.createTextNode(line)); michael@0: ol.appendChild(li); michael@0: } michael@0: s.appendChild(ol); michael@0: var l = document.createElement("a"); michael@0: l.href = "show-shader-source"; michael@0: l.appendChild(document.createTextNode(label)); michael@0: l.addEventListener('click', function(event) { michael@0: if (event.preventDefault) { michael@0: event.preventDefault(); michael@0: } michael@0: s.style.display = (s.style.display == 'none') ? 'block' : 'none'; michael@0: return false; michael@0: }, false); michael@0: div.appendChild(l); michael@0: div.appendChild(s); michael@0: element.appendChild(div); michael@0: } michael@0: michael@0: return { michael@0: addShaderSource: addShaderSource, michael@0: clearAndDrawUnitQuad : clearAndDrawUnitQuad, michael@0: create3DContext: create3DContext, michael@0: create3DContextWithWrapperThatThrowsOnGLError: michael@0: create3DContextWithWrapperThatThrowsOnGLError, michael@0: checkCanvas: checkCanvas, michael@0: checkCanvasRect: checkCanvasRect, michael@0: createColoredTexture: createColoredTexture, michael@0: drawQuad: drawQuad, michael@0: drawUnitQuad: drawUnitQuad, michael@0: endsWith: endsWith, michael@0: getExtensionWithKnownPrefixes: getExtensionWithKnownPrefixes, michael@0: getFileListAsync: getFileListAsync, michael@0: getLastError: getLastError, michael@0: getScript: getScript, michael@0: getSupportedExtensionWithKnownPrefixes: getSupportedExtensionWithKnownPrefixes, michael@0: getUrlArguments: getUrlArguments, michael@0: glEnumToString: glEnumToString, michael@0: glErrorShouldBe: glErrorShouldBe, michael@0: fillTexture: fillTexture, michael@0: insertImage: insertImage, michael@0: loadImageAsync: loadImageAsync, michael@0: loadImagesAsync: loadImagesAsync, michael@0: loadProgram: loadProgram, michael@0: loadProgramFromFile: loadProgramFromFile, michael@0: loadProgramFromScript: loadProgramFromScript, michael@0: loadProgramFromScriptExpectError: loadProgramFromScriptExpectError, michael@0: loadShader: loadShader, michael@0: loadShaderFromFile: loadShaderFromFile, michael@0: loadShaderFromScript: loadShaderFromScript, michael@0: loadStandardProgram: loadStandardProgram, michael@0: loadStandardVertexShader: loadStandardVertexShader, michael@0: loadStandardFragmentShader: loadStandardFragmentShader, michael@0: loadTextFileAsync: loadTextFileAsync, michael@0: loadTexture: loadTexture, michael@0: log: log, michael@0: loggingOff: loggingOff, michael@0: makeImage: makeImage, michael@0: error: error, michael@0: setupProgram: setupProgram, michael@0: setupQuad: setupQuad, michael@0: setupSimpleTextureFragmentShader: setupSimpleTextureFragmentShader, michael@0: setupSimpleTextureProgram: setupSimpleTextureProgram, michael@0: setupSimpleTextureVertexShader: setupSimpleTextureVertexShader, michael@0: setupTexturedQuad: setupTexturedQuad, michael@0: setupTexturedQuadWithTexCoords: setupTexturedQuadWithTexCoords, michael@0: setupUnitQuad: setupUnitQuad, michael@0: setupUnitQuadWithTexCoords: setupUnitQuadWithTexCoords, michael@0: setupWebGLWithShaders: setupWebGLWithShaders, michael@0: startsWith: startsWith, michael@0: shouldGenerateGLError: shouldGenerateGLError, michael@0: readFile: readFile, michael@0: readFileList: readFileList, michael@0: michael@0: none: false michael@0: }; michael@0: michael@0: }()); michael@0: michael@0: