是什么导致我的绘制数组调用无效操作

What is causing invalid operation on my draw arrays call?

本文关键字:调用 无效 操作 数组 绘制 我的 是什么      更新时间:2023-09-26

使用WebGL,我试图从头开始绘制一个简单的三角形。

我有用C++编写openGL应用程序的经验,并且查看了webGL参考卡来翻译我的代码。

但是,我在调试应用程序时遇到困难。我收到的特定错误消息是:

GL 错误 :GL_INVALID_OPERATION:glDrawArrays:尝试访问属性 0 中的范围外顶点

整个代码在这里: https://github.com/gheshu/webGL_experiments

顶点数据布局为 3 个浮点数的 3 个向量。存在三个属性:位置、法线和颜色,应绑定在索引 0、1、2 上。

一些重要的片段:

网格类:

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);   
}

我将非常感谢您在解决此问题时可能提供的任何帮助或提示。

在 draw.js 文件的底部,您销毁meshprog

mesh.destroy();
prog.destroy();

在 JavaScript 中,window.requestAnimationFrame(onFrame);实际上会在调用这些destroy方法后调用onFrame。因此,当onFrame被执行时,meshprog都不存在。我建议您阅读有关requestAnimationFrame的更多信息,以便稍后销毁它们(即在动画循环停止运行之后)。

您只需删除这些destroy行即可验证行为,它将呈现良好。