0
votes

I have a WebGL program that is supposed to draw a triangle using indexed buffers. A custom shader is used that uses the attributes a_position and a_color; for the vertex postion, and vertex color respectively.

The relevant JavaScript code:

var gl = // initialized elsewhere

var vertexArray      = new Float32Array( 3 * 3 ); // 3 vec3's
var vertexIndexArray = new Uint16Array( 3 );      // 3 vertices

var colorArray      = new Float32Array( 1 * 4 );  // 1 vec4
var colorIndexArray = new Uint16Array( 3 );       // 3 vertices

// # Omitted: Fill buffers #

// -- Setup the GL buffers --
var vertexBuffer      = setupGLArrayBuffer( vertexArray );
var vertexIndexBuffer = setupGLIndexBuffer( vertexIndexArray );
var colorBuffer       = setupGLArrayBuffer( colorArray );
var colorIndexBuffer  = setupGLIndexBuffer( colorIndexArray );

// -- "Link" buffers to shader attributes --
var aColor    = gl.getAttribLocation( privateVariables.shaderProgram, "a_color" );
var aPosition = gl.getAttribLocation( privateVariables.shaderProgram, "a_position" );

gl.bindBuffer( gl.ARRAY_BUFFER, colorBuffer ); 
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, colorIndexBuffer ); 
gl.vertexAttribPointer( aColor, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( aColor );

gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, vertexIndexBuffer );
gl.vertexAttribPointer( aPosition, 2, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( aPosition );

// # Omitted: Setting up viewport etc. #

gl.drawElements( gl.TRIANGLES, 3, gl.UNSIGNED_SHORT, 0 );

This doesn't display anything at all. However, when the color part is removed and the a_color attribute set to white, then it works. (Without custom colors, that is)
So, I believe it has something to do with the index-referenced color buffer.

Hopefully someone could tell what is going wrong here, and why.

1

1 Answers

0
votes

Element array buffer doesn't work the way you think. There should only be one element array and multiple array buffers with the same number of vertices in each. So in your case, the data you upload is incomplete because you sent in 3 position vertices but only the first vertex has color data.

So your var colorArray = new Float32Array( 1 * 4 ); should be new Float32Array(3 * 4);