【发布时间】:2019-10-15 15:29:20
【问题描述】:
我是 WebGL 的新手,我正在努力学习 WebGL2。但我真的不明白如何使用 WebGL。尤其是 VAO 和 VBO。我查找了有关内存工作原理的图表,但找不到。我已经给出了以下示例,我将尝试解释该示例的工作原理。
function main(){
// initialize GL
// create vertex shader and fragment shader
// create program
var positionAttributeLocation = gl.getAttribLocation(program, "a_position");
var positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// define positions with array
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
var vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.enableVertexAttribArray(positionAttributeLocation);
// ....
gl.vertexAttribPointer(
positionAttributeLocation, size, type, normalize, stride, offset
);
gl.viewport(0, 0, 400, 300);
// clear canvas
// use program
gl.bindVertexArray(vao); // why we use that here ?
var primitiveType = gl.TRIANGLES;
var offset = 0;
var count = 3;
gl.drawArrays(primitiveType, offset, count);
}
- 首先,我在顶点着色器程序中获得了属性,我们将用于VAO。我可以认为它是插槽 0。
- 然后我为位置(数组)创建了缓冲区。
- 使用
bindBuffer()函数激活缓冲区。 - 然后将位置添加到缓冲区中。
- 创建了 VAO 并使用
bindVertexArray()激活。 - 启用 slot 0,我将在 slot 0 中添加数据(位置)。它作为
vertexAttribFunction()的参数。
这是我能理解的情况。然后情况变得混乱。为什么要再次调用 bindVertexArray(vao)?是否还有关于 VAO 和 VBO 如何在 WebGL 中工作的详细方案?
【问题讨论】:
-
OpenGL 作为 WebGL 是一个状态引擎。
gl.bindVertexArray(vao)绑定顶点数组对象,打破现有的顶点数组对象绑定。再次绑定相同的VAO是没有用的。但请注意,如果您有不同的顶点数组对象,那么您必须在绘制调用之前绑定正确的 VAO。
标签: webgl