user1866990
user1866990

Reputation: 115

Webgl Vector Array

I am trying to make A cube of triangles using JavaScript and Webgl. The cube will use face edge vertex structure using arrays , but when I use arrays there is nothing drawn to screen. This how I declare the array.

function Vector(x,y,z){
this.x = x; 
this.y = y;
this.z = z;
}

var V = new Array;
V[0] = new Vector(0.0,  1.0,  0.0);
V[1] = new Vector(-1.0, -1.0,  0.0);
V[2] = new Vector(1.0, -1.0,  0.0);


function initBuffers() {
    triangleVertexPositionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    var vertices = [
        V[0],
        V[1],
        V[2]
    ];
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 1;
    triangleVertexPositionBuffer.numItems = 3;

I am not sure why it doesn't draw to screen if anyone can help it would be appreciated.

Upvotes: 5

Views: 3502

Answers (1)

Anton
Anton

Reputation: 12435

The problem is the following line:

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

new Float32Array(vertices) is returning [NaN, NaN, NaN]. This is because the Float32Array contructor expects an array of Numbers and not an array of Vectors.

You'll need to pass new Float32Array() a single one dimensional array of Numbers

If you want to fix it you'll have to write a function to convert your array of Vectors into a Float32Array. Something like this:

function vectorsToFloatArray(vertices) {
    var numbers = [];

    for(var i = 0; i < vertices.length; i++) {
        numbers.push(vertices[i].x);
        numbers.push(vertices[i].y);
        numbers.push(vertices[i].z);
    }

    return new Float32Array(numbers);
}

And remember to update the gl.bufferData() and item size:

    gl.bufferData(gl.ARRAY_BUFFER, vectorsToFloatArray(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3;

Upvotes: 3

Related Questions