Dave
Dave

Reputation: 65

WebGL error when attempting to get color data from vec4

I'm having an issue while rendering a square in WebGL. When I run the program in Chrome, I'm getting the error:

GL ERROR :GL_INVALID_OPERATION : glDrawArrays: attempt to access out of range vertices in attribute 0

I've assumed this is because, at some point, the buffers are looking at the wrong arrays when trying to get data. I've pinpointed the issue to the

gl.vertexAttribPointer(pColorIndex, 4, gl.FLOAT, false, 0, 0);

line in the code below. i.e. if I change the 4 to a 2, the code will run, but not properly (as I'm looking at a vec4 for color data here). Is there an issue with the way my arrays are bound?

    bindColorDisplayShaders();
// clear the framebuffer
gl.clear(gl.COLOR_BUFFER_BIT);

// bind the shader
gl.useProgram(shader);

// set the value of the uniform variable in the shader
var shift_loc = gl.getUniformLocation(shader, "shift");
gl.uniform1f(shift_loc, .5);

// bind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, vertexbuffer);

// get the index for the a_Position attribute defined in the vertex shader
var positionIndex = gl.getAttribLocation(shader, 'a_Position');
if (positionIndex < 0) {
    console.log('Failed to get the storage location of a_Position');
    return;
}

// "enable" the a_position attribute
gl.enableVertexAttribArray(positionIndex);

// associate the data in the currently bound buffer with the a_position attribute
// (The '2' specifies there are 2 floats per vertex in the buffer.  Don't worry about
// the last three args just yet.)
gl.vertexAttribPointer(positionIndex, 2, gl.FLOAT, false, 0, 0);

gl.bindBuffer(gl.ARRAY_BUFFER, null);

// bind the buffer with the color data
gl.bindBuffer(gl.ARRAY_BUFFER, chosencolorbuffer);

var pColorIndex = gl.getUniformLocation(shader, 'a_ChosenColor');
if(pColorIndex < 0){
    console.log('Failed to get the storage location of a_ChosenColor');
}

gl.enableVertexAttribArray(pColorIndex);

gl.vertexAttribPointer(pColorIndex, 4, gl.FLOAT, false, 0, 0);

gl.bindBuffer(gl.ARRAY_BUFFER, null);

// draw, specifying the type of primitive to assemble from the vertices
gl.drawArrays(gl.TRIANGLES, 0, numPoints);

Upvotes: 0

Views: 279

Answers (1)

LJᛃ
LJᛃ

Reputation: 8153

You can only use either a uniform or a vertex attribute, this are two different things.

When using a vertex attribute you have to match the amount of vertices in your position buffer, and get the location using gl.getAttribLocation.

When using a uniform you're not supplying its data via array buffers but using the gl.uniform* methods to set their value.

In your example gl.uniform4fv(pColorIndex, yourColorVector).

Upvotes: 3

Related Questions