WebGL中的颜色缓冲区滥用



我想为每个顶点单独设置颜色。以下是着色器的代码:

const VERTEX_SHADER_SOURCE = `
precision mediump float;
attribute vec3 aPosition;
attribute vec4 aColor;
varying vec4 vColor;
uniform mat4 uMatrix;
void main() {
vColor = aColor;
gl_Position = uMatrix * vec4(aPosition, 1);
}
`
const FRAGMENT_SHADER_SOURCE = `
precision mediump float;
varying vec4 vColor;
void main() {
gl_FragColor = vColor;
}`

有了这个代码,就可以标注:

const attrLocations = {
position: gl.getAttribLocation(this.#program, 'aPosition'),
color: gl.getAttribLocation(this.#program, 'aColor')
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.#vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.#sphere.getVertices()), gl.STATIC_DRAW)
gl.vertexAttribPointer(attrLocations.position, 3, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(attrLocations.position)
gl.bindBuffer(gl.ARRAY_BUFFER, this.#colorBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.#drawMode.getColors.call()), gl.STATIC_DRAW)
gl.vertexAttribPointer(attrLocations.color, 4, gl.FLOAT, false, 0 , 0)
gl.enableVertexAttribArray(attrLocations.color)
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.#indicesBuffer)
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(this.#drawMode.getIndices.call()), gl.STATIC_DRAW)

如果将片段着色器更改为gl_FragColor = vec4(1, 0, 0, 1);,则会使用指定的颜色正确绘制对象。

如果我更改

gl.vertexAttribPointer(attrLocations.color, 4, gl.FLOAT, false, 0 , 0) 

gl.vertexAttribPointer(attrLocations.color, 3, gl.FLOAT, false, 0 , 0)

(4=>3(,则绘制对象(但显然使用了错误的颜色(。

但是this.#sphere.getVertices().length / 3 === this.#drawMode.getColors.call().length / 4true,所以每个vec3顶点都有vec4颜色。例如,有100个顶点,因此将有长度为300的顶点阵列和长度为400

那么,问题出在哪里呢?

透明度还可以,但rgb不可以。我使用了黄白色,当启用蓝色滤镜时,我看不到它。。。

最新更新