在 WebGL 中翻译 3d 对象

Translate a 3d object in WebGL

我正在尝试在 WebGL 应用程序中移动 3d 对象,问题是我遇到了错误:

GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type

// Vertex Shader

    var vertCode =
        'attribute vec4 coordinates;' + 
        'uniform vec4 translation;'+
        'void main(void) {' +
        'gl_Position = coordinates * translation;' +
    '}';

...

// Associating shaders to buffer objects 

         gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);    
         var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates");
         gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0);   
         gl.enableVertexAttribArray(coordinatesVar); 

// Translation
        var Tx = 0.5, Ty = 0.5, Tz =-0.5;
        var translationMatrix = new Float32Array([
            1,0,0,0,
            0,1,0,0,
            0,0,1,0,
            Tx,Ty,Tz,1
         ]);

         var translation = gl.getUniformLocation(shaderProgram, 'translation');
         gl.uniformMatrix4fv(translation, false, translationMatrix);

// Draw

    gl.clearColor(0.5, 0.5, 0.5, 0.9);
    gl.enable(gl.DEPTH_TEST);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.viewport(0,0,canvas.width,canvas.height);
    gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);

制服的类型 translation 必须是 mat4 而不是 vec4。 这会导致 GL_INVALID_OPERATION 错误,因为 glUniformMatrix4fv 与类型 vec4 不匹配。

此外,向量必须在顶点着色器中从右边乘以矩阵:

attribute vec4 coordinates; 
uniform mat translation;
void main(void) {
    gl_Position = translation * coordinates; 
}

参见GLSL Programming/Vector and Matrix Operations

Furthermore, the *-operator can be used for matrix-vector products of the corresponding dimension, e.g.:

vec2 v = vec2(10., 20.);
mat2 m = mat2(1., 2.,  3., 4.);
vec2 w = m * v; // = vec2(1. * 10. + 3. * 20., 2. * 10. + 4. * 20.)

Note that the vector has to be multiplied to the matrix from the right.

If a vector is multiplied to a matrix from the left, the result corresponds to to multiplying a column vector to the transposed matrix from the right. This corresponds to multiplying a column vector to the transposed matrix from the right:

Thus, multiplying a vector from the left to a matrix corresponds to multiplying it from the right to the transposed matrix:

vec2 v = vec2(10., 20.);
mat2 m = mat2(1., 2.,  3., 4.);
vec2 w = v * m; // = vec2(1. * 10. + 2. * 20., 3. * 10. + 4. * 20.)

注意,如果要将向量与右边的矩阵相乘,

gl_Position = coordinates * translation; 

然后你必须转置矩阵。 uniformMatrix4fv 将转置矩阵,如果第二个参数设置为 true:

gl.uniformMatrix4fv(translation, true, translationMatrix);