Error: WebGL warning: vertexAttribPointer: -1 is not a valid `index`

Error: WebGL warning: vertexAttribPointer: -1 is not a valid `index`

我最近遇到了一个非常奇怪的错误。在我的顶点着色器中,我有三个属性:

attribute vec3 vPosition;
attribute vec3 vNormal;
attribute vec3 vColor;

我以相同的方式初始化与所有缓冲区关联的缓冲区,一切看起来都很好。但是,在我的渲染周期中,当我将属性绑定到缓冲区时,第一个和第三个属性工作正常,而第二个属性给我一个奇怪的错误。这让我很烦恼,因为我对所有 3 个属性使用相同的代码。

这是我的绑定代码:

gl.bindBuffer(gl.ARRAY_BUFFER, this.vBuffer);
gl.vertexAttribPointer(gl.getAttribLocation(program, "vPosition"), 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(gl.getAttribLocation(program, "vPosition"));

gl.bindBuffer(gl.ARRAY_BUFFER, this.nBuffer);
gl.vertexAttribPointer(gl.getAttribLocation(program, "vNormal"), 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(gl.getAttribLocation(program, "vNormal"));

gl.bindBuffer(gl.ARRAY_BUFFER, this.cBuffer);
gl.vertexAttribPointer(gl.getAttribLocation(program, "vColor"), 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(gl.getAttribLocation(program, "vColor"));

这是我得到的错误代码(我得到了两次,每行一次调用 getAttribLocation(program, "vNormal"):

Error: WebGL warning: vertexAttribPointer: -1 is not a valid `index`. This value probably comes from a getAttribLocation() call, where this return value -1 means that the passed name didn't correspond to an active attribute in the specified program.

这似乎表明我对 getAttribLocation 做错了什么,但我将我在着色器中的变量的实际名称传递给它,就像我对其他两个变量所做的那样。有什么很明显我想念的吗?我该如何解决这个问题?

getAttribLocation 获取活动属性的属性索引。一个属性就是一个程序资源。

WebGL 1.0 Specification for 5.14.10 Uniforms and attributes - getAttribLocation points to OpenGL ES 2.0 Specification - 2.10.4 Shader Variables,其中指定:

A generic attribute variable is considered active if it is determined by the compiler and linker that the attribute may be accessed when the shader is executed. Attribute variables that are declared in a vertex shader but never used are not considered active. [...]

这意味着,顶点着色器程序中不是 "used" 的属性变量不会变为活动状态。因此,当查询变量的索引时,变量未关联到属性索引和 getAttribLocation returns -1。