【发布时间】:2020-05-26 13:31:44
【问题描述】:
我正在研究 WebGL,并且我制作了一些类来简化渲染。问题是,只有第一个类可以被渲染,而所有其他类都不能被渲染。我查找了每个数组缓冲区,并在需要时绑定和取消绑定它们,但它仍然不起作用。这是我的 triangleElementCluster 类:
function TriangleElementCluster(vertices, uvs, normals, indices, indicesLenght, shader, gl) {
shader.use();
var verticesBuffer = new ArrayBufferFloat(vertices, gl);
var verticesAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "vertex", 3, 3, 0, gl);
var uvsBuffer = new ArrayBufferFloat(uvs, gl);
var uvsAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "uv", 2, 2, 0, gl);
var normalsBuffer = new ArrayBufferFloat(normals, gl);
var normalsAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "normal", 3, 3, 0, gl);
var indicesBuffer = new ElementArrayBuffer16(indices, gl);
verticesBuffer.unbind();
verticesAttribLocation.unbind();
uvsBuffer.unbind();
uvsAttribLocation.unbind();
normalsBuffer.unbind();
normalsAttribLocation.unbind();
indicesBuffer.unbind();
this.setTexture = function(texture) {
this.texture = texture;
}
this.render = function() {
verticesBuffer.bind();
verticesAttribLocation.bind();
uvsBuffer.bind();
uvsAttribLocation.bind();
normalsBuffer.bind();
normalsAttribLocation.bind();
indicesBuffer.bind();
this.texture.activate(gl.TEXTURE0);
gl.drawElements(gl.TRIANGLES, indicesLenght, gl.UNSIGNED_SHORT, 0);
verticesBuffer.unbind();
verticesAttribLocation.unbind();
uvsBuffer.unbind();
uvsAttribLocation.unbind();
normalsBuffer.unbind();
normalsAttribLocation.unbind();
indicesBuffer.unbind();
}
}
这些是 ArrayBuffers 和 VertexAttribPoints 的类:
function ArrayBufferFloat(array, gl) {
this.arrayBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.arrayBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(array), gl.STATIC_DRAW);
this.unbind = function() {
gl.bindBuffer(gl.ARRAY_BUFFER, null);
}
this.bind = function() {
gl.bindBuffer(gl.ARRAY_BUFFER, this.arrayBuffer);
}
}
function VertexAttribPointerFloat(shaderProgram, shaderVariableName, elementLenght, stepSize, offset, gl) {
var attribLocation = gl.getAttribLocation(shaderProgram, shaderVariableName);
gl.vertexAttribPointer(attribLocation, elementLenght, gl.FLOAT, gl.FALSE, stepSize * Float32Array.BYTES_PER_ELEMENT, offset);
gl.enableVertexAttribArray(attribLocation);
console.log(attribLocation);
this.bind = function() {
gl.enableVertexAttribArray(attribLocation);
}
this.unbind = function() {
gl.disableVertexAttribArray(attribLocation);
}
}
您可能已经注意到,我打印了 VertexAttribPointer 的 ID 并得到:2 0 1 2 0 1 我有两个类,并且它们都使用相同的指针,这不应该发生,可能导致这种情况?
根据我对 OpenGL 的理解,在绘制三角形后,每个缓冲区等都会被停用。导致只画第一类的错误在哪里?
【问题讨论】:
-
你能发布整个代码,包括 html 和至少最小的工作脚本,这样我就可以在不自己构建的情况下测试它吗?
-
在 stackoverflow 上发布最少的代码会非常大,但这是我的 github 存储库:github.com/Kuechenzwiebel/WebGL-Tests
标签: javascript webgl