DanAlucard

Implementación Final

Jan 25th, 2012
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 19.57 KB | None | 0 0
  1. <html><head>
  2.     <title>Computación Gráfica LCC - Cubo Texturizado con "vertex shading"</title>
  3.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4.    
  5.     <!-- External Mozilla Libraries to help with some matrix operations -->
  6.     <script src="archivos/sylvester.js" type="text/javascript"></script>
  7.     <script src="archivos/glUtils.js" type="text/javascript"></script>
  8.    
  9.     <!-- Canvas styler (in css) -->
  10.    
  11.     <style type='text/css'>
  12.       canvas {
  13.         border: 1px solid black;
  14.         -moz-box-shadow: black 2px 2px 2px;
  15.         background-color: black;
  16.       }
  17.     </style>
  18.    
  19.     <!-- WebGL functions to draw the animated cube -->
  20.    
  21.     <script type='text/javascript'>
  22.    
  23.       // global variables
  24.       var canvas;
  25.       var gl;
  26.  
  27.       var cubeVerticesBuffer;
  28.       var cubeVerticesTextureCoordBuffer;
  29.       var cubeVerticesIndexBuffer;
  30.       var cubeVerticesIndexBuffer;
  31.       var cubeRotation = 0.0;
  32.       var lastCubeUpdateTime = 0;
  33.  
  34.       var cubeImage;
  35.       var cubeTexture;
  36.  
  37.       var mvMatrix;
  38.       var shaderProgram;
  39.       var vertexPositionAttribute;
  40.       var vertexNormalAttribute;
  41.       var textureCoordAttribute;
  42.       var perspectiveMatrix;
  43.  
  44.       //
  45.       // start
  46.       //
  47.       // Called when the canvas is created
  48.       //
  49.       function start() {
  50.         canvas = document.getElementById("glcanvas");
  51.  
  52.         initWebGL(canvas);      // Initialize the GL context
  53.        
  54.         // Only continue if WebGL is available and working
  55.        
  56.         if (gl) {
  57.           gl.clearColor(1.0, 1.0, 1.0, 1.0);  // Clear to black, fully opaque
  58.           gl.clearDepth(1.0);                 // Clear everything
  59.           gl.enable(gl.DEPTH_TEST);           // Enable depth testing
  60.           gl.depthFunc(gl.LEQUAL);            // Near things obscure far things
  61.          
  62.           // Initialize the shaders; this is where all the lighting for the
  63.           // vertices and so forth is established.
  64.          
  65.           initShaders();
  66.          
  67.           // Here's where we call the routine that builds all the objects
  68.           // we'll be drawing.
  69.          
  70.           initBuffers();
  71.          
  72.           // Next, load and set up the textures we'll be using.
  73.          
  74.           initTextures();
  75.          
  76.           // Set up to draw the scene periodically.
  77.          
  78.           setInterval(drawScene, 15);
  79.         }
  80.       }
  81.  
  82.       //
  83.       // initWebGL
  84.       //
  85.       // Initialize WebGL, returning the GL context or null if
  86.       // WebGL isn't available or could not be initialized.
  87.       //
  88.       function initWebGL() {
  89.         gl = null;
  90.        
  91.         try {
  92.           gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
  93.           // if we can't start the "normal" webgl context, try the experimental-webgl context
  94.         }
  95.         catch(e) {
  96.         }
  97.        
  98.         // If we don't have a GL context, give up now
  99.        
  100.         if (!gl) {
  101.           alert("Unable to initialize WebGL. Your browser may not support it.");
  102.         }
  103.       }
  104.  
  105.       //
  106.       // initBuffers
  107.       //
  108.       // Initialize the buffers we'll need. For instance, a simple cube.
  109.       //
  110.       function initBuffers() {
  111.        
  112.         // Create a buffer for the cube's vertices.
  113.        
  114.         cubeVerticesBuffer = gl.createBuffer();
  115.        
  116.         // Select the cubeVerticesBuffer as the one to apply vertex
  117.         // operations to from here out.
  118.        
  119.         gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer);
  120.        
  121.         // Now create an array of vertices for the cube.
  122.        
  123.         var vertices = [
  124.           // Front face
  125.           -1.0, -1.0,  1.0,
  126.           1.0, -1.0,  1.0,
  127.           1.0,  1.0,  1.0,
  128.           -1.0,  1.0,  1.0,
  129.          
  130.           // Back face
  131.           -1.0, -1.0, -1.0,
  132.           -1.0,  1.0, -1.0,
  133.           1.0,  1.0, -1.0,
  134.           1.0, -1.0, -1.0,
  135.          
  136.           // Top face
  137.           -1.0,  1.0, -1.0,
  138.           -1.0,  1.0,  1.0,
  139.           1.0,  1.0,  1.0,
  140.           1.0,  1.0, -1.0,
  141.          
  142.           // Bottom face
  143.           -1.0, -1.0, -1.0,
  144.           1.0, -1.0, -1.0,
  145.           1.0, -1.0,  1.0,
  146.           -1.0, -1.0,  1.0,
  147.          
  148.           // Right face
  149.           1.0, -1.0, -1.0,
  150.           1.0,  1.0, -1.0,
  151.           1.0,  1.0,  1.0,
  152.           1.0, -1.0,  1.0,
  153.          
  154.           // Left face
  155.           -1.0, -1.0, -1.0,
  156.           -1.0, -1.0,  1.0,
  157.           -1.0,  1.0,  1.0,
  158.           -1.0,  1.0, -1.0
  159.         ];
  160.        
  161.         // Now pass the list of vertices into WebGL to build the shape. We
  162.         // do this by creating a Float32Array from the JavaScript array,
  163.         // then use it to fill the current vertex buffer.
  164.        
  165.         gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  166.  
  167.         // Set up the normals for the vertices, so that we can compute lighting.
  168.        
  169.         cubeVerticesNormalBuffer = gl.createBuffer();
  170.         gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
  171.        
  172.         var vertexNormals = [
  173.           // Front
  174.           0.0,  0.0,  1.0,
  175.           0.0,  0.0,  1.0,
  176.           0.0,  0.0,  1.0,
  177.           0.0,  0.0,  1.0,
  178.          
  179.           // Back
  180.           0.0,  0.0, -1.0,
  181.           0.0,  0.0, -1.0,
  182.           0.0,  0.0, -1.0,
  183.           0.0,  0.0, -1.0,
  184.          
  185.           // Top
  186.           0.0,  1.0,  0.0,
  187.           0.0,  1.0,  0.0,
  188.           0.0,  1.0,  0.0,
  189.           0.0,  1.0,  0.0,
  190.          
  191.           // Bottom
  192.           0.0, -1.0,  0.0,
  193.           0.0, -1.0,  0.0,
  194.           0.0, -1.0,  0.0,
  195.           0.0, -1.0,  0.0,
  196.          
  197.           // Right
  198.           1.0,  0.0,  0.0,
  199.           1.0,  0.0,  0.0,
  200.           1.0,  0.0,  0.0,
  201.           1.0,  0.0,  0.0,
  202.          
  203.           // Left
  204.           -1.0,  0.0,  0.0,
  205.           -1.0,  0.0,  0.0,
  206.           -1.0,  0.0,  0.0,
  207.           -1.0,  0.0,  0.0
  208.         ];
  209.        
  210.         gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexNormals),
  211.                       gl.STATIC_DRAW);
  212.        
  213.         // Map the texture onto the cube's faces.
  214.        
  215.         cubeVerticesTextureCoordBuffer = gl.createBuffer();
  216.         gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
  217.        
  218.         var textureCoordinates = [
  219.           // Front
  220.           0.0,  0.0,
  221.           1.0,  0.0,
  222.           1.0,  1.0,
  223.           0.0,  1.0,
  224.           // Back
  225.           0.0,  0.0,
  226.           1.0,  0.0,
  227.           1.0,  1.0,
  228.           0.0,  1.0,
  229.           // Top
  230.           0.0,  0.0,
  231.           1.0,  0.0,
  232.           1.0,  1.0,
  233.           0.0,  1.0,
  234.           // Bottom
  235.           0.0,  0.0,
  236.           1.0,  0.0,
  237.           1.0,  1.0,
  238.           0.0,  1.0,
  239.           // Right
  240.           0.0,  0.0,
  241.           1.0,  0.0,
  242.           1.0,  1.0,
  243.           0.0,  1.0,
  244.           // Left
  245.           0.0,  0.0,
  246.           1.0,  0.0,
  247.           1.0,  1.0,
  248.           0.0,  1.0
  249.         ];
  250.  
  251.         gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates),
  252.                       gl.STATIC_DRAW);
  253.  
  254.         // Build the element array buffer; this specifies the indices
  255.         // into the vertex array for each face's vertices.
  256.        
  257.         cubeVerticesIndexBuffer = gl.createBuffer();
  258.         gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
  259.        
  260.         // This array defines each face as two triangles, using the
  261.         // indices into the vertex array to specify each triangle's
  262.         // position.
  263.        
  264.         var cubeVertexIndices = [
  265.           0,  1,  2,      0,  2,  3,    // front
  266.           4,  5,  6,      4,  6,  7,    // back
  267.           8,  9,  10,     8,  10, 11,   // top
  268.           12, 13, 14,     12, 14, 15,   // bottom
  269.           16, 17, 18,     16, 18, 19,   // right
  270.           20, 21, 22,     20, 22, 23    // left
  271.         ]
  272.        
  273.         // Now send the element array to GL
  274.        
  275.         gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
  276.             new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
  277.       }
  278.  
  279.       //
  280.       // initTextures
  281.       //
  282.       // Initialize the textures we'll be using, then initiate a load of
  283.       // the texture images. The handleTextureLoaded() callback will finish
  284.       // the job; it gets called each time a texture finishes loading.
  285.       //
  286.       // The texture image gets turned horizontally for some reason, so we
  287.       // use an already mirrored image as texture.
  288.       //
  289.       function initTextures() {
  290.         cubeTexture = gl.createTexture();
  291.         cubeImage = new Image();
  292.         cubeImage.onload = function() { handleTextureLoaded(cubeImage, cubeTexture); }
  293.         cubeImage.src = "archivos/USACH_logo.png";
  294.       }
  295.  
  296.       function handleTextureLoaded(image, texture) {
  297.         gl.bindTexture(gl.TEXTURE_2D, texture);
  298.         gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  299.         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  300.         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  301.         gl.generateMipmap(gl.TEXTURE_2D);
  302.         gl.bindTexture(gl.TEXTURE_2D, null);
  303.       }
  304.  
  305.       //
  306.       // drawScene
  307.       //
  308.       // Draw the scene.
  309.       //
  310.       function drawScene() {
  311.         // Clear the canvas before we start drawing on it.
  312.  
  313.         gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  314.        
  315.         // Establish the perspective with which we want to view the
  316.         // scene. Our field of view is 45 degrees, with a width/height
  317.         // ratio of 640:480, and we only want to see objects between 0.1 units
  318.         // and 100 units away from the camera.
  319.        
  320.         perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
  321.        
  322.         // Set the drawing position to the "identity" point, which is
  323.         // the center of the scene.
  324.        
  325.         loadIdentity();
  326.        
  327.         // Now move the drawing position a bit to where we want to start
  328.         // drawing the cube.
  329.        
  330.         mvTranslate([0.0, 0.0, -6.0]);
  331.        
  332.         // Save the current matrix, then rotate before we draw.
  333.        
  334.         mvPushMatrix();
  335.         mvRotate(cubeRotation, [1, 0, 1]);
  336.        
  337.         // Draw the cube by binding the array buffer to the cube's vertices
  338.         // array, setting attributes, and pushing it to GL.
  339.        
  340.         gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer);
  341.         gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
  342.        
  343.         // Set the texture coordinates attribute for the vertices.
  344.        
  345.         gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
  346.         gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
  347.        
  348.         // Bind the normals buffer to the shader attribute.
  349.        
  350.         gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
  351.         gl.vertexAttribPointer(vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);
  352.        
  353.         // Specify the texture to map onto the faces.
  354.        
  355.         gl.activeTexture(gl.TEXTURE0);
  356.         gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
  357.         gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
  358.        
  359.         // Draw the cube.
  360.        
  361.         gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
  362.         setMatrixUniforms();
  363.         gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
  364.        
  365.         // Restore the original matrix
  366.        
  367.         mvPopMatrix();
  368.        
  369.         // Update the rotation for the next draw, if it's time to do so.
  370.        
  371.         var currentTime = (new Date).getTime();
  372.         if (lastCubeUpdateTime) {
  373.           var delta = currentTime - lastCubeUpdateTime;
  374.          
  375.           cubeRotation += (30 * delta) / 1000.0;
  376.         }
  377.        
  378.         lastCubeUpdateTime = currentTime;
  379.       }
  380.  
  381.       //
  382.       // initShaders
  383.       //
  384.       // Initialize the shaders, so WebGL knows how to light our scene.
  385.       //
  386.       function initShaders() {
  387.         var fragmentShader = getShader(gl, "shader-fs");
  388.         var vertexShader = getShader(gl, "shader-vs");
  389.        
  390.         // Create the shader program
  391.        
  392.         shaderProgram = gl.createProgram();
  393.         gl.attachShader(shaderProgram, vertexShader);
  394.         gl.attachShader(shaderProgram, fragmentShader);
  395.         gl.linkProgram(shaderProgram);
  396.        
  397.         // If creating the shader program failed, alert
  398.        
  399.         if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
  400.           alert("Unable to initialize the shader program.");
  401.         }
  402.        
  403.         gl.useProgram(shaderProgram);
  404.        
  405.         vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  406.         gl.enableVertexAttribArray(vertexPositionAttribute);
  407.        
  408.         textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
  409.         gl.enableVertexAttribArray(textureCoordAttribute);
  410.        
  411.         vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
  412.         gl.enableVertexAttribArray(vertexNormalAttribute);
  413.       }
  414.  
  415.       //
  416.       // getShader
  417.       //
  418.       // Loads a shader program by scouring the current document,
  419.       // looking for a script with the specified ID.
  420.       //
  421.       function getShader(gl, id) {
  422.         var shaderScript = document.getElementById(id);
  423.        
  424.         // Didn't find an element with the specified ID; abort.
  425.        
  426.         if (!shaderScript) {
  427.           return null;
  428.         }
  429.        
  430.         // Walk through the source element's children, building the
  431.         // shader source string.
  432.        
  433.         var theSource = "";
  434.         var currentChild = shaderScript.firstChild;
  435.        
  436.         while(currentChild) {
  437.           if (currentChild.nodeType == 3) {
  438.             theSource += currentChild.textContent;
  439.           }
  440.          
  441.           currentChild = currentChild.nextSibling;
  442.         }
  443.        
  444.         // Now figure out what type of shader script we have,
  445.         // based on its MIME type.
  446.        
  447.         var shader;
  448.        
  449.         if (shaderScript.type == "x-shader/x-fragment") {
  450.           shader = gl.createShader(gl.FRAGMENT_SHADER);
  451.         } else if (shaderScript.type == "x-shader/x-vertex") {
  452.           shader = gl.createShader(gl.VERTEX_SHADER);
  453.         } else {
  454.           return null;  // Unknown shader type
  455.         }
  456.        
  457.         // Send the source to the shader object
  458.        
  459.         gl.shaderSource(shader, theSource);
  460.        
  461.         // Compile the shader program
  462.        
  463.         gl.compileShader(shader);
  464.        
  465.         // See if it compiled successfully
  466.        
  467.         if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  468.           alert("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader));
  469.           return null;
  470.         }
  471.        
  472.         return shader;
  473.       }
  474.  
  475.       //
  476.       // Matrix utility functions
  477.       //
  478.  
  479.       function loadIdentity() {
  480.         mvMatrix = Matrix.I(4);
  481.       }
  482.  
  483.       function multMatrix(m) {
  484.         mvMatrix = mvMatrix.x(m);
  485.       }
  486.  
  487.       function mvTranslate(v) {
  488.         multMatrix(Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4());
  489.       }
  490.  
  491.       function setMatrixUniforms() {
  492.         var pUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
  493.         gl.uniformMatrix4fv(pUniform, false, new Float32Array(perspectiveMatrix.flatten()));
  494.  
  495.         var mvUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
  496.         gl.uniformMatrix4fv(mvUniform, false, new Float32Array(mvMatrix.flatten()));
  497.        
  498.         var normalMatrix = mvMatrix.inverse();
  499.         normalMatrix = normalMatrix.transpose();
  500.         var nUniform = gl.getUniformLocation(shaderProgram, "uNormalMatrix");
  501.         gl.uniformMatrix4fv(nUniform, false, new Float32Array(normalMatrix.flatten()));
  502.       }
  503.  
  504.       var mvMatrixStack = [];
  505.  
  506.       function mvPushMatrix(m) {
  507.         if (m) {
  508.           mvMatrixStack.push(m.dup());
  509.           mvMatrix = m.dup();
  510.         } else {
  511.           mvMatrixStack.push(mvMatrix.dup());
  512.         }
  513.       }
  514.  
  515.       function mvPopMatrix() {
  516.         if (!mvMatrixStack.length) {
  517.           throw("Can't pop from an empty matrix stack.");
  518.         }
  519.        
  520.         mvMatrix = mvMatrixStack.pop();
  521.         return mvMatrix;
  522.       }
  523.  
  524.       function mvRotate(angle, v) {
  525.         var inRadians = angle * Math.PI / 180.0;
  526.        
  527.         var m = Matrix.Rotation(inRadians, $V([v[0], v[1], v[2]])).ensure4x4();
  528.         multMatrix(m);
  529.       }
  530.    
  531.     </script>
  532.  
  533.     <!-- Fragment shader program -->
  534.  
  535.     <script id="shader-fs" type="x-shader/x-fragment">
  536.       varying highp vec2 vTextureCoord;
  537.       varying highp vec3 vLighting;
  538.      
  539.       uniform sampler2D uSampler;
  540.      
  541.       void main(void) {
  542.         highp vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
  543.        
  544.         gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);
  545.       }
  546.     </script>
  547.    
  548.     <!-- Vertex shader program -->
  549.    
  550.     <script id="shader-vs" type="x-shader/x-vertex">
  551.       attribute highp vec3 aVertexNormal;
  552.       attribute highp vec3 aVertexPosition;
  553.       attribute highp vec2 aTextureCoord;
  554.    
  555.       uniform highp mat4 uNormalMatrix;
  556.       uniform highp mat4 uMVMatrix;
  557.       uniform highp mat4 uPMatrix;
  558.      
  559.       varying highp vec2 vTextureCoord;
  560.       varying highp vec3 vLighting;
  561.    
  562.       void main(void) {
  563.         gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  564.         vTextureCoord = aTextureCoord;
  565.        
  566.         // Apply lighting effect
  567.        
  568.         highp vec3 ambientLight = vec3(0.6, 0.6, 0.6);
  569.         highp vec3 directionalLightColor = vec3(0.5, 0.5, 0.75);
  570.         highp vec3 directionalVector = vec3(0.85, 0.8, 0.75);
  571.        
  572.         highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
  573.        
  574.         highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
  575.         vLighting = ambientLight + (directionalLightColor * directional);
  576.       }
  577.     </script>
  578.   </head>
  579.  
  580.   <body onload="start()">
  581.     <canvas id="glcanvas" width="640" height="480">
  582.       Your browser doesn't appear to support the HTML5 <code>&lt;canvas&gt;</code> element.
  583.     </canvas>
  584.    
  585.     <br>
  586.     <br>
  587.     Alumno: Danilo I. J. Riffo Cerda <br>
  588.     Profesora: Lorna Figueroa Morales<br>
  589.     Computación Gráfica <br>
  590.     Licenciatura en Ciencia de la Computación <br>
  591.     Facultad de Ciencia - USACH <br>
  592.     Enero de 2012
  593.  
  594.     <br>
  595.     <br>
  596.     Puede acceder a los archivos que utiliza este sitio mediante <a href='http://danriffo.net63.net/archivos/' target='_blank'>este link</a>.  <br>
  597.     Dichos archivos son:
  598.     <DL>
  599.       <DT><STRONG>USACH_logo.png</STRONG>
  600.         <DD>Is the texture used.
  601.       <DT><STRONG>glUtils.js</STRONG>
  602.         <DD>Mozilla's library to help with some Matrix operations (transpose, inverse, etc).
  603.       <DT><STRONG>sylvester.js</STRONG>
  604.         <DD>A useful JavaScript Engine to do some Matrix arithmetics such as addition, multiplication, etc.
  605.     </DL>
  606.  
  607.   </body>
  608.  
  609.  
  610. <!-- Start of StatCounter Code -->
  611. <script type="text/javascript">
  612. var sc_project=7571834;
  613. var sc_invisible=0;
  614. var sc_security="fd7f93df";
  615. </script>
  616. <script type="text/javascript" src="http://www.statcounter.com/counter/counter_xhtml.js"></script>
  617. <noscript><div class="statcounter"><a title=" -> " href="http://statcounter.com/blogger/" class="statcounter"><img class="statcounter" src="http://c.statcounter.com/7571834/0/fd7f93df/0/" alt="counter" /></a></div></noscript>
  618. <!-- End of StatCounter Code -->
  619.  
  620.  
  621. </html>
Add Comment
Please, Sign In to add comment