2016-02-10 22 views
2

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

我將不勝感激任何幫助,或者你可能在解決這個問題的技巧。

回答

2

在你draw.js文件的底部,你破壞meshprog

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

在JavaScript window.requestAnimationFrame(onFrame);實際上將調用onFrame被稱爲那些destroy方法之後。所以在執行onFramemeshprog都不存在。我建議閱讀更多關於requestAnimationFrame的內容,以便稍後可以銷燬它們(即在動畫循環停止運行後)。

您可以通過刪除那些destroy行來驗證行爲,並且它會呈現正常。

+0

這是解決方案。我可以發誓我曾嘗試刪除這兩條線。我一定會深入研究該函數背後的更多細節以及js的異步特性。非常感謝你。這是三角形:http://i.imgur.com/GVOHe2x.png –

相關問題