PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/sdk/demos/google/image-texture-test/demo.js

https://github.com/gabadie/WebGL
JavaScript | 250 lines | 161 code | 18 blank | 71 comment | 11 complexity | 26d76485f4c3c845fc2d8caefde02df5 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  1. /*
  2. * Copyright (c) 2011 The Chromium Authors. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are
  6. * met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above
  11. * copyright notice, this list of conditions and the following disclaimer
  12. * in the documentation and/or other materials provided with the
  13. * distribution.
  14. * * Neither the name of Google Inc. nor the names of its
  15. * contributors may be used to endorse or promote products derived from
  16. * this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. var gl = null;
  31. var g_texture = null;
  32. var g_textureLoc = -1;
  33. var g_programObject = null;
  34. var g_vbo = null;
  35. var g_texCoordOffset=0;
  36. // Main entry point called by the body onload handler.
  37. // Fetches the WebGL rendering context and initializes OpenGL.
  38. function main() {
  39. var c = document.getElementById("c");
  40. //c = WebGLDebugUtils.makeLostContextSimulatingCanvas(c);
  41. // tell the simulator when to lose context.
  42. //c.loseContextInNCalls(15);
  43. c.addEventListener('webglcontextlost', handleContextLost, false);
  44. c.addEventListener('webglcontextrestored', handleContextRestored, false);
  45. gl = WebGLUtils.setupWebGL(c);
  46. if (!gl)
  47. return;
  48. init();
  49. }
  50. function log(msg) {
  51. if (window.console && window.console.log) {
  52. console.log(msg);
  53. }
  54. }
  55. function handleContextLost(e) {
  56. log("handle context lost");
  57. e.preventDefault();
  58. clearLoadingImages();
  59. }
  60. function handleContextRestored() {
  61. log("handle context restored");
  62. init();
  63. }
  64. function init() {
  65. gl.clearColor(0., 0., .7, 1.);
  66. g_texture = loadTexture("test_texture.jpg");
  67. initShaders();
  68. }
  69. function checkGLError() {
  70. var error = gl.getError();
  71. if (error != gl.NO_ERROR && error != gl.CONTEXT_LOST_WEBGL) {
  72. var str = "GL Error: " + error;
  73. document.body.appendChild(document.createTextNode(str));
  74. throw str;
  75. }
  76. }
  77. function loadShader(type, shaderSrc) {
  78. var shader = gl.createShader(type);
  79. // Load the shader source
  80. gl.shaderSource(shader, shaderSrc);
  81. // Compile the shader
  82. gl.compileShader(shader);
  83. // Check the compile status
  84. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) &&
  85. !gl.isContextLost()) {
  86. var infoLog = gl.getShaderInfoLog(shader);
  87. alert("Error compiling shader:\n" + infoLog);
  88. gl.deleteShader(shader);
  89. return null;
  90. }
  91. return shader;
  92. }
  93. function initShaders() {
  94. var vShaderStr = [
  95. "attribute vec3 g_Position;",
  96. "attribute vec2 g_TexCoord0;",
  97. "varying vec2 texCoord;",
  98. "void main()",
  99. "{",
  100. " gl_Position = vec4(g_Position.x, g_Position.y, g_Position.z, 1.0);",
  101. " texCoord = g_TexCoord0;",
  102. "}"
  103. ].join("\n");
  104. var fShaderStr = [
  105. "precision mediump float;\n",
  106. "uniform sampler2D tex;",
  107. "varying vec2 texCoord;",
  108. "void main()",
  109. "{",
  110. " gl_FragColor = texture2D(tex, texCoord);",
  111. "}"
  112. ].join("\n");
  113. var vertexShader = loadShader(gl.VERTEX_SHADER, vShaderStr);
  114. var fragmentShader = loadShader(gl.FRAGMENT_SHADER, fShaderStr);
  115. // Create the program object
  116. var programObject = gl.createProgram();
  117. gl.attachShader(programObject, vertexShader);
  118. gl.attachShader(programObject, fragmentShader);
  119. // Bind g_Position to attribute 0
  120. // Bind g_TexCoord0 to attribute 1
  121. gl.bindAttribLocation(programObject, 0, "g_Position");
  122. gl.bindAttribLocation(programObject, 1, "g_TexCoord0");
  123. // Link the program
  124. gl.linkProgram(programObject);
  125. // Check the link status
  126. var linked = gl.getProgramParameter(programObject, gl.LINK_STATUS);
  127. if (!linked && !gl.isContextLost()) {
  128. var infoLog = gl.getProgramInfoLog(programObject);
  129. alert("Error linking program:\n" + infoLog);
  130. gl.deleteProgram(programObject);
  131. return;
  132. }
  133. g_programObject = programObject;
  134. g_textureLoc = gl.getUniformLocation(g_programObject, "tex");
  135. checkGLError();
  136. g_vbo = gl.createBuffer();
  137. gl.bindBuffer(gl.ARRAY_BUFFER, g_vbo);
  138. var vertices = new Float32Array([
  139. 0.25, 0.75, 0.0,
  140. -0.75, 0.75, 0.0,
  141. -0.75, -0.25, 0.0,
  142. 0.25, 0.75, 0.0,
  143. -0.75, -0.25, 0.0,
  144. 0.25, -0.25, 0.0]);
  145. var texCoords = new Float32Array([
  146. 1.0, 1.0,
  147. 0.0, 1.0,
  148. 0.0, 0.0,
  149. 1.0, 1.0,
  150. 0.0, 0.0,
  151. 1.0, 0.0]);
  152. g_texCoordOffset = vertices.byteLength;
  153. gl.bufferData(gl.ARRAY_BUFFER,
  154. g_texCoordOffset + texCoords.byteLength,
  155. gl.STATIC_DRAW);
  156. gl.bufferSubData(gl.ARRAY_BUFFER, 0, vertices);
  157. gl.bufferSubData(gl.ARRAY_BUFFER, g_texCoordOffset, texCoords);
  158. checkGLError();
  159. }
  160. function draw() {
  161. // Note: the viewport is automatically set up to cover the entire Canvas.
  162. // Clear the color buffer
  163. gl.clear(gl.COLOR_BUFFER_BIT);
  164. checkGLError();
  165. // Use the program object
  166. gl.useProgram(g_programObject);
  167. checkGLError();
  168. // Load the vertex data
  169. gl.bindBuffer(gl.ARRAY_BUFFER, g_vbo);
  170. gl.enableVertexAttribArray(0);
  171. gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 0, 0);
  172. gl.enableVertexAttribArray(1);
  173. gl.vertexAttribPointer(1, 2, gl.FLOAT, gl.FALSE, 0, g_texCoordOffset);
  174. checkGLError();
  175. // Bind the texture to texture unit 0
  176. gl.bindTexture(gl.TEXTURE_2D, g_texture);
  177. checkGLError();
  178. // Point the uniform sampler to texture unit 0
  179. gl.uniform1i(g_textureLoc, 0);
  180. checkGLError();
  181. gl.drawArrays(gl.TRIANGLES, 0, 6);
  182. checkGLError();
  183. }
  184. // Array of images curently loading
  185. var g_loadingImage = [];
  186. // Clears all the images currently loading.
  187. // This is used to handle context lost events.
  188. function clearLoadingImages() {
  189. for (var ii = 0; ii < g_loadingImage.length; ++ii) {
  190. g_loadingImage[ii].onload = undefined;
  191. }
  192. g_loadingImage = [];
  193. }
  194. // Loads a texture from the absolute or relative URL "src".
  195. // Returns a WebGLTexture object.
  196. // The texture is downloaded in the background using the browser's
  197. // built-in image handling. Upon completion of the download, our
  198. // onload event handler will be called which uploads the image into
  199. // the WebGLTexture.
  200. function loadTexture(src) {
  201. // Create and initialize the WebGLTexture object.
  202. var texture = gl.createTexture();
  203. gl.bindTexture(gl.TEXTURE_2D, texture);
  204. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  205. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  206. // Create a DOM image object.
  207. var image = new Image();
  208. // Remember the image so we can stop it if we get lost context.
  209. g_loadingImage.push(image);
  210. // Set up the onload handler for the image, which will be called by
  211. // the browser at some point in the future once the image has
  212. // finished downloading.
  213. image.onload = function() {
  214. // Remove the image from the list of images loading.
  215. g_loadingImage.splice(g_loadingImage.indexOf(image), 1);
  216. // This code is not run immediately, but at some point in the
  217. // future, so we need to re-bind the texture in order to upload
  218. // the image. Note that we use the JavaScript language feature of
  219. // closures to refer to the "texture" and "image" variables in the
  220. // containing function.
  221. gl.bindTexture(gl.TEXTURE_2D, texture);
  222. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  223. gl.texImage2D(
  224. gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  225. checkGLError();
  226. draw();
  227. };
  228. // Start downloading the image by setting its source.
  229. image.src = src;
  230. // Return the WebGLTexture object immediately.
  231. return texture;
  232. }