Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(495)

Side by Side Diff: conformance/resources/webgl-test-utils.js

Issue 8342021: Add webgl conformance tests r15841. (Closed) Base URL: svn://chrome-svn/chrome/trunk/deps/third_party/webgl/sdk/tests/
Patch Set: Created 9 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « conformance/resources/webgl-test.js ('k') | conformance/resources/zero-alpha.png » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 WebGLTestUtils = (function() {
6
7 /**
8 * Wrapped logging function.
9 * @param {string} msg The message to log.
10 */
11 var log = function(msg) {
12 if (window.console && window.console.log) {
13 window.console.log(msg);
14 }
15 };
16
17 /**
18 * Wrapped logging function.
19 * @param {string} msg The message to log.
20 */
21 var error = function(msg) {
22 if (window.console) {
23 if (window.console.error) {
24 window.console.error(msg);
25 }
26 else if (window.console.log) {
27 window.console.log(msg);
28 }
29 }
30 };
31
32 /**
33 * Turn off all logging.
34 */
35 var loggingOff = function() {
36 log = function() {};
37 error = function() {};
38 };
39
40 /**
41 * Converts a WebGL enum to a string
42 * @param {!WebGLContext} gl The WebGLContext to use.
43 * @param {number} value The enum value.
44 * @return {string} The enum as a string.
45 */
46 var glEnumToString = function(gl, value) {
47 for (var p in gl) {
48 if (gl[p] == value) {
49 return p;
50 }
51 }
52 return "0x" + value.toString(16);
53 };
54
55 var lastError = "";
56
57 /**
58 * Returns the last compiler/linker error.
59 * @return {string} The last compiler/linker error.
60 */
61 var getLastError = function() {
62 return lastError;
63 };
64
65 /**
66 * Whether a haystack ends with a needle.
67 * @param {string} haystack String to search
68 * @param {string} needle String to search for.
69 * @param {boolean} True if haystack ends with needle.
70 */
71 var endsWith = function(haystack, needle) {
72 return haystack.substr(haystack.length - needle.length) === needle;
73 };
74
75 /**
76 * Whether a haystack starts with a needle.
77 * @param {string} haystack String to search
78 * @param {string} needle String to search for.
79 * @param {boolean} True if haystack starts with needle.
80 */
81 var startsWith = function(haystack, needle) {
82 return haystack.substr(0, needle.length) === needle;
83 };
84
85 /**
86 * A vertex shader for a single texture.
87 * @type {string}
88 */
89 var simpleTextureVertexShader = [
90 'attribute vec4 vPosition;',
91 'attribute vec2 texCoord0;',
92 'varying vec2 texCoord;',
93 'void main() {',
94 ' gl_Position = vPosition;',
95 ' texCoord = texCoord0;',
96 '}'].join('\n');
97
98 /**
99 * A fragment shader for a single texture.
100 * @type {string}
101 */
102 var simpleTextureFragmentShader = [
103 'precision mediump float;',
104 'uniform sampler2D tex;',
105 'varying vec2 texCoord;',
106 'void main() {',
107 ' gl_FragData[0] = texture2D(tex, texCoord);',
108 '}'].join('\n');
109
110 /**
111 * Creates a simple texture vertex shader.
112 * @param {!WebGLContext} gl The WebGLContext to use.
113 * @return {!WebGLShader}
114 */
115 var setupSimpleTextureVertexShader = function(gl) {
116 return loadShader(gl, simpleTextureVertexShader, gl.VERTEX_SHADER);
117 };
118
119 /**
120 * Creates a simple texture fragment shader.
121 * @param {!WebGLContext} gl The WebGLContext to use.
122 * @return {!WebGLShader}
123 */
124 var setupSimpleTextureFragmentShader = function(gl) {
125 return loadShader(
126 gl, simpleTextureFragmentShader, gl.FRAGMENT_SHADER);
127 };
128
129 /**
130 * Creates a program, attaches shaders, binds attrib locations, links the
131 * program and calls useProgram.
132 * @param {!Array.<!WebGLShader>} shaders The shaders to attach .
133 * @param {!Array.<string>} opt_attribs The attribs names.
134 * @param {!Array.<number>} opt_locations The locations for the attribs.
135 */
136 var setupProgram = function(gl, shaders, opt_attribs, opt_locations) {
137 var program = gl.createProgram();
138 for (var ii = 0; ii < shaders.length; ++ii) {
139 gl.attachShader(program, shaders[ii]);
140 }
141 if (opt_attribs) {
142 for (var ii = 0; ii < opt_attribs.length; ++ii) {
143 gl.bindAttribLocation(
144 program,
145 opt_locations ? opt_locations[ii] : ii,
146 opt_attribs[ii]);
147 }
148 }
149 gl.linkProgram(program);
150
151 // Check the link status
152 var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
153 if (!linked) {
154 // something went wrong with the link
155 lastError = gl.getProgramInfoLog (program);
156 error("Error in program linking:" + lastError);
157
158 gl.deleteProgram(program);
159 return null;
160 }
161
162 gl.useProgram(program);
163 return program;
164 };
165
166 /**
167 * Creates a simple texture program.
168 * @param {!WebGLContext} gl The WebGLContext to use.
169 * @param {number} opt_positionLocation The attrib location for position.
170 * @param {number} opt_texcoordLocation The attrib location for texture coords.
171 * @return {WebGLProgram}
172 */
173 var setupSimpleTextureProgram = function(
174 gl, opt_positionLocation, opt_texcoordLocation) {
175 opt_positionLocation = opt_positionLocation || 0;
176 opt_texcoordLocation = opt_texcoordLocation || 1;
177 var vs = setupSimpleTextureVertexShader(gl);
178 var fs = setupSimpleTextureFragmentShader(gl);
179 if (!vs || !fs) {
180 return null;
181 }
182 var program = setupProgram(
183 gl,
184 [vs, fs],
185 ['vPosition', 'texCoord0'],
186 [opt_positionLocation, opt_texcoordLocation]);
187 if (!program) {
188 gl.deleteShader(fs);
189 gl.deleteShader(vs);
190 }
191 gl.useProgram(program);
192 return program;
193 };
194
195 /**
196 * Creates buffers for a textured unit quad and attaches them to vertex attribs.
197 * @param {!WebGLContext} gl The WebGLContext to use.
198 * @param {number} opt_positionLocation The attrib location for position.
199 * @param {number} opt_texcoordLocation The attrib location for texture coords.
200 * @return {!Array.<WebGLBuffer>} The buffer objects that were
201 * created.
202 */
203 var setupUnitQuad = function(gl, opt_positionLocation, opt_texcoordLocation) {
204 opt_positionLocation = opt_positionLocation || 0;
205 opt_texcoordLocation = opt_texcoordLocation || 1;
206 var objects = [];
207
208 var vertexObject = gl.createBuffer();
209 gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject);
210 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
211 1.0, 1.0, 0.0,
212 -1.0, 1.0, 0.0,
213 -1.0, -1.0, 0.0,
214 1.0, 1.0, 0.0,
215 -1.0, -1.0, 0.0,
216 1.0, -1.0, 0.0]), gl.STATIC_DRAW);
217 gl.enableVertexAttribArray(opt_positionLocation);
218 gl.vertexAttribPointer(opt_positionLocation, 3, gl.FLOAT, false, 0, 0);
219 objects.push(vertexObject);
220
221 var vertexObject = gl.createBuffer();
222 gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject);
223 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
224 1.0, 1.0,
225 0.0, 1.0,
226 0.0, 0.0,
227 1.0, 1.0,
228 0.0, 0.0,
229 1.0, 0.0]), gl.STATIC_DRAW);
230 gl.enableVertexAttribArray(opt_texcoordLocation);
231 gl.vertexAttribPointer(opt_texcoordLocation, 2, gl.FLOAT, false, 0, 0);
232 objects.push(vertexObject);
233 return objects;
234 };
235
236 /**
237 * Creates a program and buffers for rendering a textured quad.
238 * @param {!WebGLContext} gl The WebGLContext to use.
239 * @param {number} opt_positionLocation The attrib location for position.
240 * @param {number} opt_texcoordLocation The attrib location for texture coords.
241 * @return {!WebGLProgram}
242 */
243 var setupTexturedQuad = function(
244 gl, opt_positionLocation, opt_texcoordLocation) {
245 var program = setupSimpleTextureProgram(
246 gl, opt_positionLocation, opt_texcoordLocation);
247 setupUnitQuad(gl, opt_positionLocation, opt_texcoordLocation);
248 return program;
249 };
250
251 /**
252 * Creates a unit quad with only positions of a given rez
253 * @param {!WebGLContext} gl The WebGLContext to use.
254 * @param {number} gridRez The resolution of the mesh grid.
255 * @param {number} opt_positionLocation The attrib location for position.
256 */
257 var setupQuad = function (
258 gl, gridRes, opt_positionLocation, opt_flipOddTriangles) {
259 var positionLocation = opt_positionLocation || 0;
260 var objects = [];
261
262 var vertsAcross = gridRes + 1;
263 var numVerts = vertsAcross * vertsAcross;
264 var positions = new Float32Array(numVerts * 3);
265 var indices = new Uint16Array(6 * gridRes * gridRes);
266
267 var poffset = 0;
268
269 for (var yy = 0; yy <= gridRes; ++yy) {
270 for (var xx = 0; xx <= gridRes; ++xx) {
271 positions[poffset + 0] = -1 + 2 * xx / gridRes;
272 positions[poffset + 1] = -1 + 2 * yy / gridRes;
273 positions[poffset + 2] = 0;
274
275 poffset += 3;
276 }
277 }
278
279 var tbase = 0;
280 for (var yy = 0; yy < gridRes; ++yy) {
281 var index = yy * vertsAcross;
282 for (var xx = 0; xx < gridRes; ++xx) {
283 indices[tbase + 0] = index + 0;
284 indices[tbase + 1] = index + 1;
285 indices[tbase + 2] = index + vertsAcross;
286 indices[tbase + 3] = index + vertsAcross;
287 indices[tbase + 4] = index + 1;
288 indices[tbase + 5] = index + vertsAcross + 1;
289
290 if (opt_flipOddTriangles) {
291 indices[tbase + 4] = index + vertsAcross + 1;
292 indices[tbase + 5] = index + 1;
293 }
294
295 index += 1;
296 tbase += 6;
297 }
298 }
299
300 var buf = gl.createBuffer();
301 gl.bindBuffer(gl.ARRAY_BUFFER, buf);
302 gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
303 gl.enableVertexAttribArray(positionLocation);
304 gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);
305 objects.push(buf);
306
307 var buf = gl.createBuffer();
308 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf);
309 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
310 objects.push(buf);
311
312 return objects;
313 };
314
315 /**
316 * Fills the given texture with a solid color
317 * @param {!WebGLContext} gl The WebGLContext to use.
318 * @param {!WebGLTexture} tex The texture to fill.
319 * @param {number} width The width of the texture to create.
320 * @param {number} height The height of the texture to create.
321 * @param {!Array.<number>} color The color to fill with. A 4 element array
322 * where each element is in the range 0 to 255.
323 * @param {number} opt_level The level of the texture to fill. Default = 0.
324 */
325 var fillTexture = function(gl, tex, width, height, color, opt_level) {
326 opt_level = opt_level || 0;
327 var numPixels = width * height;
328 var size = numPixels * 4;
329 var buf = new Uint8Array(size);
330 for (var ii = 0; ii < numPixels; ++ii) {
331 var off = ii * 4;
332 buf[off + 0] = color[0];
333 buf[off + 1] = color[1];
334 buf[off + 2] = color[2];
335 buf[off + 3] = color[3];
336 }
337 gl.bindTexture(gl.TEXTURE_2D, tex);
338 gl.texImage2D(
339 gl.TEXTURE_2D, opt_level, gl.RGBA, width, height, 0,
340 gl.RGBA, gl.UNSIGNED_BYTE, buf);
341 };
342
343 /**
344 * Creates a textures and fills it with a solid color
345 * @param {!WebGLContext} gl The WebGLContext to use.
346 * @param {number} width The width of the texture to create.
347 * @param {number} height The height of the texture to create.
348 * @param {!Array.<number>} color The color to fill with. A 4 element array
349 * where each element is in the range 0 to 255.
350 * @return {!WebGLTexture}
351 */
352 var createColoredTexture = function(gl, width, height, color) {
353 var tex = gl.createTexture();
354 fillTexture(gl, tex, width, height, color);
355 return tex;
356 };
357
358 /**
359 * Draws a previously setup quad.
360 * @param {!WebGLContext} gl The WebGLContext to use.
361 * @param {!Array.<number>} opt_color The color to fill clear with before
362 * drawing. A 4 element array where each element is in the range 0 to
363 * 255. Default [255, 255, 255, 255]
364 */
365 var drawQuad = function(gl, opt_color) {
366 opt_color = opt_color || [255, 255, 255, 255];
367 gl.clearColor(
368 opt_color[0] / 255,
369 opt_color[1] / 255,
370 opt_color[2] / 255,
371 opt_color[3] / 255);
372 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
373 gl.drawArrays(gl.TRIANGLES, 0, 6);
374 };
375
376 /**
377 * Checks that a portion of a canvas is 1 color.
378 * @param {!WebGLContext} gl The WebGLContext to use.
379 * @param {number} x left corner of region to check.
380 * @param {number} y bottom corner of region to check.
381 * @param {number} width width of region to check.
382 * @param {number} height width of region to check.
383 * @param {!Array.<number>} color The color to fill clear with before drawing. A
384 * 4 element array where each element is in the range 0 to 255.
385 * @param {string} msg Message to associate with success. Eg ("should be red").
386 * @param {number} errorRange Optional. Acceptable error in
387 * color checking. 0 by default.
388 */
389 var checkCanvasRect = function(gl, x, y, width, height, color, msg, errorRange) {
390 errorRange = errorRange || 0;
391 var buf = new Uint8Array(width * height * 4);
392 gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, buf);
393 for (var i = 0; i < width * height; ++i) {
394 var offset = i * 4;
395 for (var j = 0; j < color.length; ++j) {
396 if (Math.abs(buf[offset + j] - color[j]) > errorRange) {
397 testFailed(msg);
398 var was = buf[offset + 0].toString();
399 for (j = 1; j < color.length; ++j) {
400 was += "," + buf[offset + j];
401 }
402 debug('expected: ' + color + ' was ' + was);
403 return;
404 }
405 }
406 }
407 testPassed(msg);
408 };
409
410 /**
411 * Checks that an entire canvas is 1 color.
412 * @param {!WebGLContext} gl The WebGLContext to use.
413 * @param {!Array.<number>} color The color to fill clear with before drawing. A
414 * 4 element array where each element is in the range 0 to 255.
415 * @param {string} msg Message to associate with success. Eg ("should be red").
416 * @param {number} errorRange Optional. Acceptable error in
417 * color checking. 0 by default.
418 */
419 var checkCanvas = function(gl, color, msg, errorRange) {
420 checkCanvasRect(gl, 0, 0, gl.canvas.width, gl.canvas.height, color, msg, error Range);
421 };
422
423 /**
424 * Loads a texture, calls callback when finished.
425 * @param {!WebGLContext} gl The WebGLContext to use.
426 * @param {string} url URL of image to load
427 * @param {function(!Image): void} callback Function that gets called after
428 * image has loaded
429 * @return {!WebGLTexture} The created texture.
430 */
431 var loadTexture = function(gl, url, callback) {
432 var texture = gl.createTexture();
433 gl.bindTexture(gl.TEXTURE_2D, texture);
434 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
435 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
436 var image = new Image();
437 image.onload = function() {
438 gl.bindTexture(gl.TEXTURE_2D, texture);
439 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
440 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imag e);
441 callback(image);
442 };
443 image.src = url;
444 return texture;
445 };
446
447 /**
448 * Creates a webgl context.
449 * @param {!Canvas} opt_canvas The canvas tag to get context from. If one is not
450 * passed in one will be created.
451 * @return {!WebGLContext} The created context.
452 */
453 var create3DContext = function(opt_canvas, opt_attributes) {
454 opt_canvas = opt_canvas || document.createElement("canvas");
455 var context = null;
456 try {
457 context = opt_canvas.getContext("webgl", opt_attributes);
458 } catch(e) {}
459 if (!context) {
460 try {
461 context = opt_canvas.getContext("experimental-webgl", opt_attributes);
462 } catch(e) {}
463 }
464 if (!context) {
465 testFailed("Unable to fetch WebGL rendering context for Canvas");
466 }
467 return context;
468 }
469
470 /**
471 * Gets a GLError value as a string.
472 * @param {!WebGLContext} gl The WebGLContext to use.
473 * @param {number} err The webgl error as retrieved from gl.getError().
474 * @return {string} the error as a string.
475 */
476 var getGLErrorAsString = function(gl, err) {
477 if (err === gl.NO_ERROR) {
478 return "NO_ERROR";
479 }
480 for (var name in gl) {
481 if (gl[name] === err) {
482 return name;
483 }
484 }
485 return err.toString();
486 };
487
488 /**
489 * Wraps a WebGL function with a function that throws an exception if there is
490 * an error.
491 * @param {!WebGLContext} gl The WebGLContext to use.
492 * @param {string} fname Name of function to wrap.
493 * @return {function} The wrapped function.
494 */
495 var createGLErrorWrapper = function(context, fname) {
496 return function() {
497 var rv = context[fname].apply(context, arguments);
498 var err = context.getError();
499 if (err != 0)
500 throw "GL error " + getGLErrorAsString(err) + " in " + fname;
501 return rv;
502 };
503 };
504
505 /**
506 * Creates a WebGL context where all functions are wrapped to throw an exception
507 * if there is an error.
508 * @param {!Canvas} canvas The HTML canvas to get a context from.
509 * @return {!Object} The wrapped context.
510 */
511 function create3DContextWithWrapperThatThrowsOnGLError(canvas) {
512 var context = create3DContext(canvas);
513 var wrap = {};
514 for (var i in context) {
515 try {
516 if (typeof context[i] == 'function') {
517 wrap[i] = createGLErrorWrapper(context, i);
518 } else {
519 wrap[i] = context[i];
520 }
521 } catch (e) {
522 error("createContextWrapperThatThrowsOnGLError: Error accessing " + i);
523 }
524 }
525 wrap.getError = function() {
526 return context.getError();
527 };
528 return wrap;
529 };
530
531 /**
532 * Tests that an evaluated expression generates a specific GL error.
533 * @param {!WebGLContext} gl The WebGLContext to use.
534 * @param {number} glError The expected gl error.
535 * @param {string} evalSTr The string to evaluate.
536 */
537 var shouldGenerateGLError = function(gl, glError, evalStr) {
538 var exception;
539 try {
540 eval(evalStr);
541 } catch (e) {
542 exception = e;
543 }
544 if (exception) {
545 testFailed(evalStr + " threw exception " + exception);
546 } else {
547 var err = gl.getError();
548 if (err != glError) {
549 testFailed(evalStr + " expected: " + getGLErrorAsString(gl, glError) + ". Was " + getGLErrorAsString(gl, err) + ".");
550 } else {
551 testPassed(evalStr + " was expected value: " + getGLErrorAsString(gl, glEr ror) + ".");
552 }
553 }
554 };
555
556 /**
557 * Tests that the first error GL returns is the specified error.
558 * @param {!WebGLContext} gl The WebGLContext to use.
559 * @param {number} glError The expected gl error.
560 * @param {string} opt_msg
561 */
562 var glErrorShouldBe = function(gl, glError, opt_msg) {
563 opt_msg = opt_msg || "";
564 var err = gl.getError();
565 if (err != glError) {
566 testFailed("getError expected: " + getGLErrorAsString(gl, glError) +
567 ". Was " + getGLErrorAsString(gl, err) + " : " + opt_msg);
568 } else {
569 testPassed("getError was expected value: " +
570 getGLErrorAsString(gl, glError) + " : " + opt_msg);
571 }
572 };
573
574 /**
575 * Links a WebGL program, throws if there are errors.
576 * @param {!WebGLContext} gl The WebGLContext to use.
577 * @param {!WebGLProgram} program The WebGLProgram to link.
578 * @param {function(string): void) opt_errorCallback callback for errors.
579 */
580 var linkProgram = function(gl, program, opt_errorCallback) {
581 // Link the program
582 gl.linkProgram(program);
583
584 // Check the link status
585 var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
586 if (!linked) {
587 // something went wrong with the link
588 var error = gl.getProgramInfoLog (program);
589
590 testFailed("Error in program linking:" + error);
591
592 gl.deleteProgram(program);
593 //gl.deleteProgram(fragmentShader);
594 //gl.deleteProgram(vertexShader);
595 }
596 };
597
598 /**
599 * Sets up WebGL with shaders.
600 * @param {string} canvasName The id of the canvas.
601 * @param {string} vshader The id of the script tag that contains the vertex
602 * shader source.
603 * @param {string} fshader The id of the script tag that contains the fragment
604 * shader source.
605 * @param {!Array.<string>} attribs An array of attrib names used to bind
606 * attribs to the ordinal of the name in this array.
607 * @param {!Array.<number>} opt_clearColor The color to cla
608 * @return {!WebGLContext} The created WebGLContext.
609 */
610 var setupWebGLWithShaders = function(
611 canvasName, vshader, fshader, attribs) {
612 var canvas = document.getElementById(canvasName);
613 var gl = create3DContext(canvas);
614 if (!gl) {
615 testFailed("No WebGL context found");
616 }
617
618 // create our shaders
619 var vertexShader = loadShaderFromScript(gl, vshader);
620 var fragmentShader = loadShaderFromScript(gl, fshader);
621
622 if (!vertexShader || !fragmentShader) {
623 return null;
624 }
625
626 // Create the program object
627 program = gl.createProgram();
628
629 if (!program) {
630 return null;
631 }
632
633 // Attach our two shaders to the program
634 gl.attachShader (program, vertexShader);
635 gl.attachShader (program, fragmentShader);
636
637 // Bind attributes
638 for (var i in attribs) {
639 gl.bindAttribLocation (program, i, attribs[i]);
640 }
641
642 linkProgram(gl, program);
643
644 gl.useProgram(program);
645
646 gl.clearColor(0,0,0,1);
647 gl.clearDepth(1);
648
649 gl.enable(gl.DEPTH_TEST);
650 gl.enable(gl.BLEND);
651 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
652
653 gl.program = program;
654 return gl;
655 };
656
657 /**
658 * Loads text from an external file. This function is synchronous.
659 * @param {string} url The url of the external file.
660 * @param {!function(bool, string): void} callback that is sent a bool for
661 * success and the string.
662 */
663 var loadTextFileAsync = function(url, callback) {
664 log ("loading: " + url);
665 var error = 'loadTextFileSynchronous failed to load url "' + url + '"';
666 var request;
667 if (window.XMLHttpRequest) {
668 request = new XMLHttpRequest();
669 if (request.overrideMimeType) {
670 request.overrideMimeType('text/plain');
671 }
672 } else {
673 throw 'XMLHttpRequest is disabled';
674 }
675 try {
676 request.open('GET', url, true);
677 request.onreadystatechange = function() {
678 if (request.readyState == 4) {
679 var text = '';
680 // HTTP reports success with a 200 status. The file protocol reports
681 // success with zero. HTTP does not use zero as a status code (they
682 // start at 100).
683 // https://developer.mozilla.org/En/Using_XMLHttpRequest
684 var success = request.status == 200 || request.status == 0;
685 if (success) {
686 text = request.responseText;
687 }
688 log("loaded: " + url);
689 callback(success, text);
690 }
691 };
692 request.send(null);
693 } catch (e) {
694 log("failed to load: " + url);
695 callback(false, '');
696 }
697 };
698
699 /**
700 * Recursively loads a file as a list. Each line is parsed for a relative
701 * path. If the file ends in .txt the contents of that file is inserted in
702 * the list.
703 *
704 * @param {string} url The url of the external file.
705 * @param {!function(bool, Array<string>): void} callback that is sent a bool
706 * for success and the array of strings.
707 */
708 var getFileListAsync = function(url, callback) {
709 var files = [];
710
711 var getFileListImpl = function(url, callback) {
712 var files = [];
713 if (url.substr(url.length - 4) == '.txt') {
714 loadTextFileAsync(url, function() {
715 return function(success, text) {
716 if (!success) {
717 callback(false, '');
718 return;
719 }
720 var lines = text.split('\n');
721 var prefix = '';
722 var lastSlash = url.lastIndexOf('/');
723 if (lastSlash >= 0) {
724 prefix = url.substr(0, lastSlash + 1);
725 }
726 var fail = false;
727 var count = 1;
728 var index = 0;
729 for (var ii = 0; ii < lines.length; ++ii) {
730 var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
731 if (str.length > 4 &&
732 str[0] != '#' &&
733 str[0] != ";" &&
734 str.substr(0, 2) != "//") {
735 var names = str.split(/ +/);
736 new_url = prefix + str;
737 if (names.length == 1) {
738 new_url = prefix + str;
739 ++count;
740 getFileListImpl(new_url, function(index) {
741 return function(success, new_files) {
742 log("got files: " + new_files.length);
743 if (success) {
744 files[index] = new_files;
745 }
746 finish(success);
747 };
748 }(index++));
749 } else {
750 var s = "";
751 var p = "";
752 for (var jj = 0; jj < names.length; ++jj) {
753 s += p + prefix + names[jj];
754 p = " ";
755 }
756 files[index++] = s;
757 }
758 }
759 }
760 finish(true);
761
762 function finish(success) {
763 if (!success) {
764 fail = true;
765 }
766 --count;
767 log("count: " + count);
768 if (!count) {
769 callback(!fail, files);
770 }
771 }
772 }
773 }());
774
775 } else {
776 files.push(url);
777 callback(true, files);
778 }
779 };
780
781 getFileListImpl(url, function(success, files) {
782 // flatten
783 var flat = [];
784 flatten(files);
785 function flatten(files) {
786 for (var ii = 0; ii < files.length; ++ii) {
787 var value = files[ii];
788 if (typeof(value) == "string") {
789 flat.push(value);
790 } else {
791 flatten(value);
792 }
793 }
794 }
795 callback(success, flat);
796 });
797 };
798
799 /**
800 * Gets a file from a file/URL
801 * @param {string} file the URL of the file to get.
802 * @return {string} The contents of the file.
803 */
804 var readFile = function(file) {
805 var xhr = new XMLHttpRequest();
806 xhr.open("GET", file, false);
807 xhr.send();
808 return xhr.responseText.replace(/\r/g, "");
809 };
810
811 var readFileList = function(url) {
812 var files = [];
813 if (url.substr(url.length - 4) == '.txt') {
814 var lines = readFile(url).split('\n');
815 var prefix = '';
816 var lastSlash = url.lastIndexOf('/');
817 if (lastSlash >= 0) {
818 prefix = url.substr(0, lastSlash + 1);
819 }
820 for (var ii = 0; ii < lines.length; ++ii) {
821 var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
822 if (str.length > 4 &&
823 str[0] != '#' &&
824 str[0] != ";" &&
825 str.substr(0, 2) != "//") {
826 var names = str.split(/ +/);
827 if (names.length == 1) {
828 new_url = prefix + str;
829 files = files.concat(readFileList(new_url));
830 } else {
831 var s = "";
832 var p = "";
833 for (var jj = 0; jj < names.length; ++jj) {
834 s += p + prefix + names[jj];
835 p = " ";
836 }
837 files.push(s);
838 }
839 }
840 }
841 } else {
842 files.push(url);
843 }
844 return files;
845 };
846
847 /**
848 * Loads a shader.
849 * @param {!WebGLContext} gl The WebGLContext to use.
850 * @param {string} shaderSource The shader source.
851 * @param {number} shaderType The type of shader.
852 * @param {function(string): void) opt_errorCallback callback for errors.
853 * @return {!WebGLShader} The created shader.
854 */
855 var loadShader = function(gl, shaderSource, shaderType, opt_errorCallback) {
856 var errFn = opt_errorCallback || error;
857 // Create the shader object
858 var shader = gl.createShader(shaderType);
859 if (shader == null) {
860 errFn("*** Error: unable to create shader '"+shaderSource+"'");
861 return null;
862 }
863
864 // Load the shader source
865 gl.shaderSource(shader, shaderSource);
866 var err = gl.getError();
867 if (err != gl.NO_ERROR) {
868 errFn("*** Error loading shader '" + shader + "':" + glEnumToString(gl, err) );
869 return null;
870 }
871
872 // Compile the shader
873 gl.compileShader(shader);
874
875 // Check the compile status
876 var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
877 if (!compiled) {
878 // Something went wrong during compilation; get the error
879 lastError = gl.getShaderInfoLog(shader);
880 errFn("*** Error compiling shader '" + shader + "':" + lastError);
881 gl.deleteShader(shader);
882 return null;
883 }
884
885 return shader;
886 }
887
888 /**
889 * Loads a shader from a URL.
890 * @param {!WebGLContext} gl The WebGLContext to use.
891 * @param {file} file The URL of the shader source.
892 * @param {number} type The type of shader.
893 * @param {function(string): void) opt_errorCallback callback for errors.
894 * @return {!WebGLShader} The created shader.
895 */
896 var loadShaderFromFile = function(gl, file, type, opt_errorCallback) {
897 var shaderSource = readFile(file);
898 return loadShader(gl, shaderSource, type, opt_errorCallback);
899 };
900
901 /**
902 * Loads a shader from a script tag.
903 * @param {!WebGLContext} gl The WebGLContext to use.
904 * @param {string} scriptId The id of the script tag.
905 * @param {number} opt_shaderType The type of shader. If not passed in it will
906 * be derived from the type of the script tag.
907 * @param {function(string): void) opt_errorCallback callback for errors.
908 * @return {!WebGLShader} The created shader.
909 */
910 var loadShaderFromScript = function(
911 gl, scriptId, opt_shaderType, opt_errorCallback) {
912 var shaderSource = "";
913 var shaderType;
914 var shaderScript = document.getElementById(scriptId);
915 if (!shaderScript) {
916 throw("*** Error: unknown script element" + scriptId);
917 }
918 shaderSource = shaderScript.text;
919
920 if (!opt_shaderType) {
921 if (shaderScript.type == "x-shader/x-vertex") {
922 shaderType = gl.VERTEX_SHADER;
923 } else if (shaderScript.type == "x-shader/x-fragment") {
924 shaderType = gl.FRAGMENT_SHADER;
925 } else if (shaderType != gl.VERTEX_SHADER && shaderType != gl.FRAGMENT_SHADE R) {
926 throw("*** Error: unknown shader type");
927 return null;
928 }
929 }
930
931 return loadShader(
932 gl, shaderSource, opt_shaderType ? opt_shaderType : shaderType,
933 opt_errorCallback);
934 };
935
936 var loadStandardProgram = function(gl) {
937 var program = gl.createProgram();
938 gl.attachShader(program, loadStandardVertexShader(gl));
939 gl.attachShader(program, loadStandardFragmentShader(gl));
940 linkProgram(gl, program);
941 return program;
942 };
943
944 /**
945 * Loads shaders from files, creates a program, attaches the shaders and links.
946 * @param {!WebGLContext} gl The WebGLContext to use.
947 * @param {string} vertexShaderPath The URL of the vertex shader.
948 * @param {string} fragmentShaderPath The URL of the fragment shader.
949 * @param {function(string): void) opt_errorCallback callback for errors.
950 * @return {!WebGLProgram} The created program.
951 */
952 var loadProgramFromFile = function(
953 gl, vertexShaderPath, fragmentShaderPath, opt_errorCallback) {
954 var program = gl.createProgram();
955 gl.attachShader(
956 program,
957 loadShaderFromFile(
958 gl, vertexShaderPath, gl.VERTEX_SHADER, opt_errorCallback));
959 gl.attachShader(
960 program,
961 loadShaderFromFile(
962 gl, fragmentShaderPath, gl.FRAGMENT_SHADER, opt_errorCallback));
963 linkProgram(gl, program, opt_errorCallback);
964 return program;
965 };
966
967 /**
968 * Loads shaders from script tags, creates a program, attaches the shaders and
969 * links.
970 * @param {!WebGLContext} gl The WebGLContext to use.
971 * @param {string} vertexScriptId The id of the script tag that contains the
972 * vertex shader.
973 * @param {string} fragmentScriptId The id of the script tag that contains the
974 * fragment shader.
975 * @param {function(string): void) opt_errorCallback callback for errors.
976 * @return {!WebGLProgram} The created program.
977 */
978 var loadProgramFromScript = function loadProgramFromScript(
979 gl, vertexScriptId, fragmentScriptId, opt_errorCallback) {
980 var program = gl.createProgram();
981 gl.attachShader(
982 program,
983 loadShaderFromScript(
984 gl, vertexScriptId, gl.VERTEX_SHADER, opt_errorCallback));
985 gl.attachShader(
986 program,
987 loadShaderFromScript(
988 gl, fragmentScriptId, gl.FRAGMENT_SHADER, opt_errorCallback));
989 linkProgram(gl, program, opt_errorCallback);
990 return program;
991 };
992
993 /**
994 * Loads shaders from source, creates a program, attaches the shaders and
995 * links.
996 * @param {!WebGLContext} gl The WebGLContext to use.
997 * @param {string} vertexShader The vertex shader.
998 * @param {string} fragmentShader The fragment shader.
999 * @param {function(string): void) opt_errorCallback callback for errors.
1000 * @return {!WebGLProgram} The created program.
1001 */
1002 var loadProgram = function(
1003 gl, vertexShader, fragmentShader, opt_errorCallback) {
1004 var program = gl.createProgram();
1005 gl.attachShader(
1006 program,
1007 loadShader(
1008 gl, vertexShader, gl.VERTEX_SHADER, opt_errorCallback));
1009 gl.attachShader(
1010 program,
1011 loadShader(
1012 gl, fragmentShader, gl.FRAGMENT_SHADER, opt_errorCallback));
1013 linkProgram(gl, program, opt_errorCallback);
1014 return program;
1015 };
1016
1017 var basePath;
1018 var getBasePath = function() {
1019 if (!basePath) {
1020 var expectedBase = "webgl-test-utils.js";
1021 var scripts = document.getElementsByTagName('script');
1022 for (var script, i = 0; script = scripts[i]; i++) {
1023 var src = script.src;
1024 var l = src.length;
1025 if (src.substr(l - expectedBase.length) == expectedBase) {
1026 basePath = src.substr(0, l - expectedBase.length);
1027 }
1028 }
1029 }
1030 return basePath;
1031 };
1032
1033 var loadStandardVertexShader = function(gl) {
1034 return loadShaderFromFile(
1035 gl, getBasePath() + "vertexShader.vert", gl.VERTEX_SHADER);
1036 };
1037
1038 var loadStandardFragmentShader = function(gl) {
1039 return loadShaderFromFile(
1040 gl, getBasePath() + "fragmentShader.frag", gl.FRAGMENT_SHADER);
1041 };
1042
1043 /**
1044 * Loads an image asynchronously.
1045 * @param {string} url URL of image to load.
1046 * @param {!function(!Element): void} callback Function to call
1047 * with loaded image.
1048 */
1049 var loadImageAsync = function(url, callback) {
1050 var img = document.createElement('img');
1051 img.onload = function() {
1052 callback(img);
1053 };
1054 img.src = url;
1055 };
1056
1057 /**
1058 * Loads an array of images.
1059 * @param {!Array.<string>} urls URLs of images to load.
1060 * @param {!function(!{string, img}): void} callback. Callback
1061 * that gets passed map of urls to img tags.
1062 */
1063 var loadImagesAsync = function(urls, callback) {
1064 var count = 1;
1065 var images = { };
1066 function countDown() {
1067 --count;
1068 if (count == 0) {
1069 callback(images);
1070 }
1071 }
1072 function imageLoaded(url) {
1073 return function(img) {
1074 images[url] = img;
1075 countDown();
1076 }
1077 }
1078 for (var ii = 0; ii < urls.length; ++ii) {
1079 ++count;
1080 loadImageAsync(urls[ii], imageLoaded(urls[ii]));
1081 }
1082 countDown();
1083 };
1084
1085 var getUrlArguments = function() {
1086 var args = {};
1087 try {
1088 var s = window.location.href;
1089 var q = s.indexOf("?");
1090 var e = s.indexOf("#");
1091 if (e < 0) {
1092 e = s.length;
1093 }
1094 var query = s.substring(q + 1, e);
1095 var pairs = query.split("&");
1096 for (var ii = 0; ii < pairs.length; ++ii) {
1097 var keyValue = pairs[ii].split("=");
1098 var key = keyValue[0];
1099 var value = decodeURIComponent(keyValue[1]);
1100 args[key] = value;
1101 }
1102 } catch (e) {
1103 throw "could not parse url";
1104 }
1105 return args;
1106 };
1107
1108 return {
1109 create3DContext: create3DContext,
1110 create3DContextWithWrapperThatThrowsOnGLError:
1111 create3DContextWithWrapperThatThrowsOnGLError,
1112 checkCanvas: checkCanvas,
1113 checkCanvasRect: checkCanvasRect,
1114 createColoredTexture: createColoredTexture,
1115 drawQuad: drawQuad,
1116 endsWith: endsWith,
1117 getFileListAsync: getFileListAsync,
1118 getLastError: getLastError,
1119 getUrlArguments: getUrlArguments,
1120 glEnumToString: glEnumToString,
1121 glErrorShouldBe: glErrorShouldBe,
1122 fillTexture: fillTexture,
1123 loadImageAsync: loadImageAsync,
1124 loadImagesAsync: loadImagesAsync,
1125 loadProgram: loadProgram,
1126 loadProgramFromFile: loadProgramFromFile,
1127 loadProgramFromScript: loadProgramFromScript,
1128 loadShader: loadShader,
1129 loadShaderFromFile: loadShaderFromFile,
1130 loadShaderFromScript: loadShaderFromScript,
1131 loadStandardProgram: loadStandardProgram,
1132 loadStandardVertexShader: loadStandardVertexShader,
1133 loadStandardFragmentShader: loadStandardFragmentShader,
1134 loadTextFileAsync: loadTextFileAsync,
1135 loadTexture: loadTexture,
1136 log: log,
1137 loggingOff: loggingOff,
1138 error: error,
1139 setupProgram: setupProgram,
1140 setupQuad: setupQuad,
1141 setupSimpleTextureFragmentShader: setupSimpleTextureFragmentShader,
1142 setupSimpleTextureProgram: setupSimpleTextureProgram,
1143 setupSimpleTextureVertexShader: setupSimpleTextureVertexShader,
1144 setupTexturedQuad: setupTexturedQuad,
1145 setupUnitQuad: setupUnitQuad,
1146 setupWebGLWithShaders: setupWebGLWithShaders,
1147 startsWith: startsWith,
1148 shouldGenerateGLError: shouldGenerateGLError,
1149 readFile: readFile,
1150 readFileList: readFileList,
1151
1152 none: false
1153 };
1154
1155 }());
1156
1157
OLDNEW
« no previous file with comments | « conformance/resources/webgl-test.js ('k') | conformance/resources/zero-alpha.png » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698