PDA

View Full Version : Moving vertex buffers to prototype scope



zagibu
07-14-2010, 12:24 PM
I know it's more of a javascript-problem, but I have troubles moving the global "vertexBlaBuffer" variables over to the scope of the Geometry prototype:


function Geometry(position, rotation, path) {
this.position = position;
this.rotation = rotation;
this.path = path;

var request = new XMLHttpRequest();
request.open("GET", path);
request.onreadystatechange = function() {
if (request.readyState == 4) {
handleLoadedModel(JSON.parse(request.responseText) );
}
}
request.send();

initTextures();
}

/************************************************** ****************************
* FUNCTION: handleLoadedModel
* Load extracted model data into GL buffers
************************************************** ****************************/
var vertexPositionBuffer;
var vertexNormalBuffer;
var vertexTextureCoordBuffer;
var vertexIndexBuffer;
function handleLoadedModel(modelData) {
vertexNormalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexNormalBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(modelData.vertexNormals), gl.STATIC_DRAW);
vertexNormalBuffer.itemSize = 3;
vertexNormalBuffer.numItems = modelData.vertexNormals.length / 3;

vertexTextureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexTextureCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(modelData.vertexTextureCoords), gl.STATIC_DRAW);
vertexTextureCoordBuffer.itemSize = 2;
vertexTextureCoordBuffer.numItems = modelData.vertexTextureCoords.length / 2;

vertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(modelData.vertexPositions), gl.STATIC_DRAW);
vertexPositionBuffer.itemSize = 3;
vertexPositionBuffer.numItems = modelData.vertexPositions.length / 3;

vertexIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vertexIndexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new WebGLUnsignedShortArray(modelData.indices), gl.STREAM_DRAW);
vertexIndexBuffer.itemSize = 1;
vertexIndexBuffer.numItems = modelData.indices.length;
}


I already tried binding the buffers in the anonymous onreadystatechange function of the request, but in that scope, "this" doesn't seem to refer to Geometry.
Any tips?

zagibu
07-15-2010, 04:21 AM
I've managed to do it by saving the this reference in a var, which is accessible within the anonymous function.

giles
07-21-2010, 02:41 AM
I've managed to do it by saving the this reference in a var, which is accessible within the anonymous function.

Yup, that's the standard way to do it in JavaScript. I think people normally call the var they use "that" :-)