为什么我不能使用 uniform1f 而不是 uniform4f 来设置 vec4 制服?

Why I can't use uniform1f instead of uniform4f for setting a vec4 uniform?

我通过 this book 逐步学习 WebGL。我尝试通过使用缓冲区 (gl.ARRAY_BUFFER) 而不是循环来绘制三个点(正如我之前在本书的其他示例中所做的一样)。

  var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
  if(!u_FragColor){
    console.log('Can\'t to get the "u_FragColor" variable.');
    return -1;
  }

  // gl.uniform1f(u_FragColor, 1.0); // <- this variant doesn't work! Why?
  gl.uniform4f(u_FragColor, 1.0, 0.0, 0.0, 1.0);

它工作正常,但我有一个关于 gl_FragColor 初始化的问题:为什么我不能替换

gl.uniform4f(u_FragColor, 1.0, 0.0, 0.0, 1.0);

gl.uniform1f(u_FragColor, 1.0);

?我希望这是一样的。但是在这种情况下,我在控制台中收到错误消息:

您必须使用正确的类型来设置制服。如果你的制服是 vec4 那么你必须使用 gl.uniform4fgl.uniform4fv.

uniform       valid
type          functions
----------------------------------------------
float         gl.uniform1f    gl.uniform1fv
vec2          gl.uniform2f    gl.uniform2fv
vec3          gl.uniform3f    gl.uniform3fv
vec4          gl.uniform4f    gl.uniform4fv
int           gl.uniform1i    gl.uniform1iv
ivec2         gl.uniform2i    gl.uniform2iv
ivec3         gl.uniform3i    gl.uniform3iv
ivec4         gl.uniform4i    gl.uniform4iv
sampler2D     gl.uniform1i    gl.uniform1iv
samplerCube   gl.uniform1i    gl.uniform1iv

mat2          gl.uniformMatrix2fv
mat3          gl.uniformMatrix3fv
mat4          gl.uniformMatrix4fv

bool          gl.uniform1i gl.uniform1f gl.uniform1iv gl.uniform1fv
bvec2         gl.uniform2i gl.uniform2f gl.uniform2iv gl.uniform2fv
bvec3         gl.uniform3i gl.uniform3f gl.uniform3iv gl.uniform3fv
bvec4         gl.uniform4i gl.uniform4f gl.uniform4iv gl.uniform4fv

From the OpenGL ES 2.0 spec 第 2.10.4 节

The Uniform* command used must match the size of the uniform, as declared in the shader. For example, to load a uniform declared as a bvec2, either Uniform2i{v} or Uniform2f{v} can be used. An INVALID_OPERATION error will be generated if an attempt is made to use a non-matching Uniform* command. In this example using Uniform1iv would generate an error

For all other uniform types the Uniform* command used must match the size and type of the uniform, as declared in the shader. No type conversions are done. For example, to load a uniform declared as a vec4, Uniform4f{v} must be used. To load a 3x3 matrix, UniformMatrix3fv must be used. An INVALID_OPERATION error will be generated if an attempt is made to use a non-matching Uniform* command. In this example, using Uniform4i{v} would generate an error