webglopengl-es-2.0index-buffer

Render several graphs from single vertex buffer


I have a vertex buffer containing several (in this case 2) graphs in the following structure:

var vertices = [ 
  x0, y00, y10,
  x1, y01, y11,
  x2, y02, y12,
  ...
  xn, y0n, y1n
];

and its indices

var indices = [0, 1, 2, 3, ... n-1];

You can notice that for each x value there is 2 y values each determining the graph.

What I want is to render those 2 graphs using this single buffer without any duplication of the x values.

Currently in the render loop I have this:

    function render() {         
        gl.bindBuffer(gl.ARRAY_BUFFER, vBuff);  // bind our buffer                                                      

        // with this setup it renders only first graph:
        // x0, y00,  
        // x1, y01, 
        // x2, y02, 
        // ... 
        // xn, y0n
        gl.vertexAttribPointer(vertexPositionLocation, 2, gl.FLOAT, false, 4*3, 0);     
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);                                            
        gl.drawElements(gl.LINE_STRIP, indices.length, gl.UNSIGNED_SHORT, 0);

        // now how do I set up the vertexAttribPointer such that next draw call here 
        // would render second graph containing these points
        // x0, y10,  
        // x1, y11, 
        // x2, y12, 
        // ... 
        // xn, y1n      
        // ?
    }

Solution

  • If you were to strictly wanting to do it via attribute pointers you could split your position into two attributes referring to the same buffer:

        // first call
        gl.vertexAttribPointer(vertexPositionXLocation, 1, gl.FLOAT, false, 4*3, 0);
        gl.vertexAttribPointer(vertexPositionYLocation, 1, gl.FLOAT, false, 4*3, 4);
        gl.drawArrays(gl.LINE_STRIP, 0, numDataPoints);
    
        // second call
        gl.vertexAttribPointer(vertexPositionYLocation, 1, gl.FLOAT, false, 4*3, 8);
        gl.drawArrays(gl.LINE_STRIP, 0, numDataPoints);
    

    You vertex shader would then look something like this:

    attribute float vX;
    attribute float vY;
    void main () { gl_Position=vec4(vX,vY,0,1); }
    

    Also note that I used drawArrays instead of drawElements since you're implying that you have a linear index buffer anyways.