简体   繁体   English

使用相同的着色器更改不同形状的缓冲区在渲染时失败-WebGL

[英]Changing buffers of different shapes with same shader fails at rendering - WebGL

I am trying to render different shapes of objects with the same shader. 我正在尝试使用相同的着色器渲染不同形状的对象。

If I try the following code with only one shape, the code works. 如果我尝试仅使用一种形状的以下代码,则该代码有效。 If I try the following code with 2 identical shapes, code works. 如果我尝试以下具有2个相同形状的代码,则该代码有效。 But if I try with 2 different shapes, using the same shader, I get the following error: glDrawElements: attempt to access out of range vertices in attribute 0 and only one, disfigured object is shown. 但是,如果我尝试使用相同的着色器使用2种不同的形状, glDrawElements: attempt to access out of range vertices in attribute 0出现以下错误: glDrawElements: attempt to access out of range vertices in attribute 0并且仅显示一个变形的对象。

For every uploaded shape, I save its vertices ( positions ) and indices( positions_indices ). 对于每个上载的形状,我保存其顶点( positions )和索引( positions_indices )。 After that I create vertex_buffer and index_buffer and save those in the model object. 之后,我创建vertex_bufferindex_buffer并将它们保存在model对象中。 Here is the code: 这是代码:

var model = new Model(positions,positions_indices);

You have forgotten to bind the element array buffer before you draw the elements: 在绘制元素之前,您已经忘记绑定元素数组缓冲区了:

gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, models[i].index_buffer);

Further you have to bind the array buffer, before you define an array of generic vertex attribute data. 此外,在定义通用顶点属性数据的数组之前,必须绑定数组缓冲区。

Your code should look somehow like this: 您的代码应如下所示:

for(var i = 0;i<models.length;i++) {
    //creating and setting model matrix and setting color uniform property to shader

   gl.bindBuffer(gl.ARRAY_BUFFER, models[i].vertex_buffer);
   gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0);
   gl.enableVertexAttribArray(position);

   gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, models[i].index_buffer);

   gl.drawElements(gl.TRIANGLES, models[i].positions_indices.length, gl.UNSIGNED_INT, 0); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM