【发布时间】:2014-07-15 09:31:16
【问题描述】:
我正在编写一个网页,它使用 WebGL 在视口中呈现 3d 模型,但我很困惑为什么在加载 3d 模型后需要延迟。 3d 模型是一个 .OBJ 文件,我使用库 (K3D.js) 来加载和解析 .OBJ 文件。
我意识到文件必须异步加载到浏览器中。但据我了解,图书馆处理这部分。下面是 K3D 加载函数的样子:
K3D.load = function(path, resp)
{
var request = new XMLHttpRequest();
request.open("GET", path, true);
request.responseType = "arraybuffer";
request.onload = function(e){resp(e.target.response);};
request.send();
}
因此,当 K3D 完成加载文件时,它可能会执行存储在 request.onload 中的函数,这是我在我的 Mesh 类中提供的(在 meshFromOBJ 方法中):
Mesh.prototype.meshFromArray = function( vertexArray, normalArray ) {
this.vbo = this.gl.createBuffer();
//normals are left out for now
this.numVertices = vertexArray.length / 3.0;
this.gl.bindBuffer( this.gl.ARRAY_BUFFER, this.vbo );
this.gl.bufferData( this.gl.ARRAY_BUFFER,
new Float32Array( vertexArray ),
this.gl.STATIC_DRAW
);
this.gl.bindBuffer( this.gl.ARRAY_BUFFER, null );
};
Mesh.prototype.meshFromOBJ = function( file ) {
var that = this;
var loader = function( data ) {
var model = K3D.parse.fromOBJ( data );
var array = K3D.edit.unwrap( model.i_verts, model.c_verts, 3 );
var norms = K3D.edit.unwrap( model.i_norms, model.c_norms, 3 );
that.meshFromArray( array, model.c_norms );
}
K3D.load( file, loader );
};
在我的主脚本中,我加载了网格,并设置了顶点属性指针。我注意到我必须在加载网格和设置指针之间发出警报,否则浏览器会抛出 vertexAttribPointer: must have valid GL_ARRAY_BUFFER binding 错误等。我脚本的相关部分:
mesh = new ngl.Mesh( webgl );
mesh.meshFromOBJ( "cow.obj" );
//set the vertex attribute pointer with a delay
//otherwise, the mesh doesn't seem to exist yet :S
setTimeout( function() {
mesh.bind();
webgl.vertexAttribPointer( program.attribute( "vert" ),
3, webgl.FLOAT, false, 12, 0
);
mesh.unbind();
}, 10 );
为什么需要延迟?
【问题讨论】:
标签: javascript ajax