gpt4 book ai didi

javascript - 如何在 webgl 中定位对象以进行绘图?以及为什么

转载 作者:行者123 更新时间:2023-11-28 18:13:46 25 4
gpt4 key购买 nike

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

我正在绘制一个由 2 个三 Angular 形组成的正方形,并让它远离相机并靠近相机。我想了解这部分是如何工作的:

// 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

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

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

也就是说,如果您关注 these tutorials他们最终将引导您如何使用矩阵和 how the frustum function works

还有这个问答:Trying to understand the math behind the perspective matrix in WebGL

至于你的多个问题

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基本上是说“看看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用于设置您在提供的着色器内声明的全局变量。这些全局变量称为“uniforms”,因为它们在着色器的迭代过程中保持统一的值。这与其他两种着色器输入形成对比。一个称为属性,它通常在顶点着色器的每次迭代期间从缓冲区中提取下一组值。另一种类型称为 variings,您可以在顶点着色器中设置它,并且是 interpolated for each iteration of your fragment shader .

关于javascript - 如何在 webgl 中定位对象以进行绘图?以及为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41083179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com