【发布时间】:2016-02-10 14:52:58
【问题描述】:
我正在尝试使用 WebGL 从头开始绘制一个简单的三角形。
我有使用 C++ 编写 openGL 应用程序的经验,并查看了 webGL 参考卡来翻译我的代码。
但是,我在调试应用程序时遇到了困难。 我收到的特定错误消息是:
GL ERROR :GL_INVALID_OPERATION : glDrawArrays: 尝试访问属性 0 中超出范围的顶点
完整代码在这里:https://github.com/gheshu/webGL_experiments
顶点数据布局为 3 个浮点数的 3 个向量。 存在三个属性:位置、法线和颜色,应绑定在索引 0、1、2 上。
一些重要的sn-ps:
网格类:
class Mesh{
constructor(){
this.num_vertices = 0;
this.vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 4*3*3, 0);
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 4*3*3, 4*3);
gl.enableVertexAttribArray(2);
gl.vertexAttribPointer(2, 3, gl.FLOAT, false, 4*3*3, 4*3*2);
}
upload(buffer){
console.log(buffer);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
gl.bufferData(gl.ARRAY_BUFFER, buffer, gl.STATIC_DRAW);
this.num_vertices = buffer.length / 9;
}
draw(){
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
gl.drawArrays(gl.TRIANGLES, 0, this.num_vertices);
}
destroy(){
gl.deleteBuffer(this.vbo);
}
}
程序类:
class GLProgram{
constructor(vertShader, fragShader){
this.prog = gl.createProgram();
gl.attachShader(this.prog, vertShader.id);
gl.attachShader(this.prog, fragShader.id);
gl.bindAttribLocation(this.prog, 0, "position");
gl.bindAttribLocation(this.prog, 1, "normal");
gl.bindAttribLocation(this.prog, 2, "color");
gl.linkProgram(this.prog);
var log = gl.getProgramInfoLog(this.prog);
if(log.length){
console.log();
}
gl.detachShader(this.prog, vertShader.id);
vertShader.destroy();
gl.detachShader(this.prog, fragShader.id);
fragShader.destroy();
}
bind(){
gl.useProgram(this.prog);
}
destroy(){
gl.deleteProgram(this.prog);
}
}
顶点着色器:
attribute vec3 position;
attribute vec3 normal;
attribute vec3 color;
varying vec3 vColor;
void main(){
gl_Position = vec4(position, 1.0);
vColor = color;
}
片段着色器:
precision mediump float;
varying vec3 vColor;
void main(){
gl_FragColor = vec4(vColor, 1.0);
}
非常感谢您在解决此问题时提供的任何帮助或提示。
【问题讨论】:
标签: javascript webgl