WebGL – Interleaved Vertex Buffer

Click To Show Running WebGL

fullscreenquad

Updated data and calls to vertexAttribPointer(). The highlighted lines have the relevant changes.


 var squareVertexBuffer;

    function initBuffers() {
      //Create Square Position Buffer
        squareVertexBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexBuffer);
        var vertices = [
             1.0,  1.0,  0.0, 1.0, 1.0, //x, y, z, u, v
            -1.0,  1.0,  0.0, 0.0, 1.0,
             1.0, -1.0,  0.0, 1.0, 0.0,
            -1.0, -1.0,  0.0, 0.0, 0.0
        ];
        gl.bufferData(
                     gl.ARRAY_BUFFER, 
                     new Float32Array(vertices), 
                     gl.STATIC_DRAW
                     );
        squareVertexBuffer.stride = 5*Float32Array.BYTES_PER_ELEMENT;
        squareVertexBuffer.positionElementCount = 3;
        squareVertexBuffer.positionOffset = 0;
        squareVertexBuffer.uvElementCount = 2;
        squareVertexBuffer.uvOffset = 3*Float32Array.BYTES_PER_ELEMENT;
        squareVertexBuffer.numItems = 4;

    }

    function drawScene() {
        gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        pMatrix = identity();
        mvMatrix = identity();

        pMatrix = ortho(-1, 1, -1, 1, 0.01, 10);
        mvMatrix = makeTranslation(0.0, 0.0, -0.01);

        gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexBuffer);
        gl.vertexAttribPointer(
                              shaderProgram.vertexPositionAttribute,
                              squareVertexBuffer.positionElementCount, 
                              gl.FLOAT, 
                              false, 
                              squareVertexBuffer.stride, 
                              squareVertexBuffer.positionOffset
                              );
        gl.vertexAttribPointer(
                              shaderProgram.vertexUVAttribute, 
                              squareVertexBuffer.uvElementCount, 
                              gl.FLOAT, 
                              false, 
                              squareVertexBuffer.stride, 
                              squareVertexBuffer.uvOffset 
                              );
        setUniforms();
        gl.drawArrays(
                      gl.TRIANGLE_STRIP, 
                      0, 
                      squareVertexBuffer.numItems
                      );
    }