这是顶点着色器:
uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
void main(void)
{
gl_Position = projection * view * model * gl_Vertex;
gl_TexCoord[0] = gl_MultiTexCoord0;
}
我的理解是,通过各种变换,模型空间最终变成了裁剪空间,也就是一个由每个轴上的每个单元直接绘制到视口的框,即(-1, 1,0)处的东西在顶部视口的左侧。当我从着色器中删除所有矩阵变换时,
gl_Position = gl_Vertex;
并作为模型传入一个简单的四边形
public Vector3[] verts = new Vector3[] {
new Vector3(-1f, -1f, 0),
new Vector3(1f, -1f, 0),
new Vector3(1f, 1f, 0),
new Vector3(-1f, 1f, 0),
};
public Vector2[] coords = new Vector2[] {
new Vector2(0, 1f),
new Vector2(1f, 1f),
new Vector2(1f, 0f),
new Vector2(0f, 0f),
};
public uint[] indices = new uint[] {
0,1,2,
0,2,3,
};
我得到了预期的全屏图像。当我应用转换时,图像在屏幕中央显示为一个小方块,正如您所期望的那样。当我尝试在 CPU 上的剪辑坐标中计算模型顶点的位置时,就会出现问题:
public Vector4 testMult(Vector4 v, Matrix4 m)
{
return new Vector4(
m.M11 * v.X + m.M12 * v.Y + m.M13 * v.Z + m.M14 * v.W,
m.M21 * v.X + m.M22 * v.Y + m.M23 * v.Z + m.M24 * v.W,
m.M31 * v.X + m.M32 * v.Y + m.M33 * v.Z + m.M34 * v.W,
m.M41 * v.X + m.M42 * v.Y + m.M43 * v.Z + m.M44 * v.W);
}
Matrix4 test = (GlobalDrawer.projectionMatrix * GlobalDrawer.viewMatrix) * modelMatrix;
Vector4 testv = (new Vector4(1f, 1f, 0, 1));
Console.WriteLine("Test Input: " + testv);
Console.WriteLine("Test Output: " + Vector4.Transform(testv, test));
Vector4 testv2 = testMult(testv, test);
Console.WriteLine("Test Output: " + testv2);
Console.WriteLine("Test Output division: " + testv2 / testv2.W);
(传入的矩阵与传递给着色器的矩阵相同)
然后程序继续在剪辑空间之外提供输出,除以 W 导致除以 0:
Test Input: (1, 1, 0, 1)
Test Output: (0.9053301, 1.207107, -2.031746, 0)
Test Output: (0.9053301, 1.207107, -1, 0)
Test Output division: (Infinity, Infinity, -Infinity, NaN)
创建矩阵如下:
projectionMatrix = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, window.Width / (float)window.Height, 1.0f, 64.0f);
projectionMatrix =
(1.81066, 0, 0, 0)
(0, 2.414213, 0, 0)
(0, 0, -1.031746, -1)
(0, 0, -2.031746, 0)
viewMatrix = Matrix4.LookAt(new Vector3(0,0,4), -Vector3.UnitZ, Vector3.UnitY);
viewMatrix =
(1, 0, 0, 0)
(0, 1, 0, 0)
(0, 0, 1, 0)
(0, 0, -4, 1)
modelMatrix =
(0.5, 0 , 0 , 0)
(0 , 0.5, 0 , 0)
(0 , 0 , 1 , 0)
(0 , 0 , 0 , 1)
所以,问题是为什么;我究竟做错了什么?