如何在 webgl 中定位要绘制的对象?为什么

How to position an object for drawing in webgl? and why

我成功地在一个文件中制作了一个 webgl 示例,没有包含库,只有正在使用的函数:https://jsfiddle.net/vmLab6jr/

我正在绘制一个由 2 个三角形组成的正方形,并使其离相机越来越远。我想了解这部分是如何工作的:

// Now move the drawing position a bit to where we want to start
// drawing the square.
mvMatrix = [
    [1,0,0,0],
    [0,1,0,0],
    [0,0,1,-12+Math.sin(g.loops/6)*4],
    [0,0,0,1]
];

var mvUniform = gl.getUniformLocation(g.shaderProgram, "uMVMatrix");
gl.uniformMatrix4fv(mvUniform, false, g.float32(mvMatrix));

为什么webgl要一个4x4的矩阵来设置绘制对象的位置?或者有没有办法使用 1x3,比如 [x,y,z]?是因为我使用的着色器被任意设置为 4x4 吗? 我找不到有关 uniformMatrix4fv() 的作用、使用时间和原因以及替代方案的信息。 为什么元素[2][3]控制物体的z?

我知道这与平截头体矩阵是 4x4 有关。平截头体矩阵中的同一点有 D,其中 var D = -2*zfar*znear/(zfar-znear);但是要更改我正在绘制的对象的 x,我需要更改 [0][3] 但平截头锥体矩阵中的那个槽只有 0.

function makeFrustum(left, right, bottom, top, znear, zfar)
{
    var X = 2*znear/(right-left);
    var Y = 2*znear/(top-bottom);
    var A = (right+left)/(right-left);
    var B = (top+bottom)/(top-bottom);
    var C = -(zfar+znear)/(zfar-znear);
    var D = -2*zfar*znear/(zfar-znear);

    return [
        [X, 0, A, 0],
        [0, Y, B, 0],
        [0, 0, C, D],
        [0, 0, -1, 0]
    ];
}

我一直在使用这个教程:https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL

WebGL 不需要 4x4 矩阵。 WebGL is just a rasterization library

它所关心的是你提供一个顶点着色器,用剪辑 space 坐标填充一个名为 gl_Position 的特殊变量,然后你还提供一个片段着色器来设置特殊变量 gl_FragColor有颜色。

不需要矩阵来做到这一点。您使用的任何矩阵都是您的,由您提供给您提供的代码。 WebGL 中没有必需的矩阵。

也就是说如果你关注 these tutorials they will eventually lead you to how to use matrices and how the frustum function works

还有这个问答:

关于你的多个问题

Why does webgl want a 4x4 matrix to set the position for drawing an object?

没有。您提供的 着色器 可以。

Or is there a way to use 1x3, like [x,y,z]?

是,提供一个使用 1x3 数学运算的着色器

Is it because the shaders I'm using we're arbitrarily set to 4x4?

I cannot find information on what uniformMatrix4fv() does and when and why it's used and what the alternatives are.

WebGL 1.0 基于 OpenGL ES 2.0,因此 the WebGL spec basically says "look at the OpenGL ES 2.0 spec”。具体地说

1.1 Conventions

...

The remaining sections of this document are intended to be read in conjunction with the OpenGL ES 2.0 specification (2.0.25 at the time of this writing, available from the Khronos OpenGL ES API Registry). Unless otherwise specified, the behavior of each method is defined by the OpenGL ES 2.0 specification.

至于uniformMatrix4fv各种uniform functions are used to set global variables you declared inside the shaders you provided. These global variables are called uniforms because they keep a uniform value from iteration to iteration of your shaders. That's in contrast to 2 other kinds of shader inputs. One called attributes which generally pull the next set of values out of buffers during each iteration of your vertex shader. The other type are called varyings which you set in your vertex shader and are interpolated for each iteration of your fragment shader.