用于opengl的投影和正交矩阵

时间:2015-08-05 17:29:57

标签: c++ c opengl matrix

我正在编写此代码来设置opengl投影矩阵,但我得到了奇怪的结果,并希望得到一些帮助。

void mat4Projection(mat4* out, double r, double l, double t, double b, double n, double f);
void mat4OrthoProjection(mat4* out, double r, double l, double t, double b, double n, double f);

void mat4Projection(mat4* out, double r, double l, double t, double b, double n, double f)
{
    double data[] = { (2*n)/(r-l),  0,           (r+l)/(r-l),        0,
                       0,          (2*n)/(t-b),  (t+b)/(t-b),        0,
                       0,           0,           (-(f+n))/(f-n),     (-2*(f*n))/(f-n),
                       0,           0,           -1,                 1                };
    copyMatrix(out, data);
}

void mat4OrthoProjection(mat4* out, double r, double l, double t, double b, double n, double f)
{
    double data[] = { (2)/(r-l),  0,          0,           -((r+l)/(r-l)),
                       0,         (2)/(t-b),  0,           -((t+b)/(t-b)),
                       0,         0,          (-2)/(f-n),  -((f+n)/(f-n)),
                       0,         0,          0,           1              };
    copyMatrix(out, data);
}

我从此链接http://www.songho.ca/opengl/gl_projectionmatrix.html

获取此代码

1 个答案:

答案 0 :(得分:1)

与我的比较。这是一个标准的代码并且运行良好,但您应该知道的一件事是基于行向量。

void Matrix_OrthoProjection( Matrix& out_M, const __VERTEX__TYPE__ width, const __VERTEX__TYPE__ height, const __VERTEX__TYPE__ nZ, const __VERTEX__TYPE__ fZ)
{
    // asumed r-l = width , t-b = height
    out_M.s[_0x0_] = 2./width; out_M.s[_0x1_] = 0;              out_M.s[_0x2_] = 0;                    out_M.s[_0x3_] = 0;
    out_M.s[_1x0_] = 0;        out_M.s[_1x1_] = 2./height;      out_M.s[_1x2_] = 0;                    out_M.s[_1x3_] = 0;
    out_M.s[_2x0_] = 0;        out_M.s[_2x1_] = 0;              out_M.s[_2x2_] = -2./(fZ-nZ);          out_M.s[_2x3_] = 0;
    out_M.s[_3x0_] = 0;        out_M.s[_3x1_] = 0;              out_M.s[_3x2_] = -(fZ+nZ)/(fZ-nZ);     out_M.s[_3x3_] = 1.;
}

void Matrix_PerspectiveProjection
(Matrix& out_M,
 const __VERTEX__TYPE__ FOV,
 const __VERTEX__TYPE__ ASPECT,
 const __VERTEX__TYPE__ NEAR,
 const __VERTEX__TYPE__ FAR)
{

    float fov = 1.0f / (float)tan(FOV * 0.5f); 
    float nf = 1.0f / (NEAR - FAR);

    out_M.s[_0x0_] = fov/ASPECT;
    out_M.s[_1x0_] = 0;
    out_M.s[_2x0_] = 0;
    out_M.s[_3x0_] = 0;

    out_M.s[_0x1_] = 0.0;
    out_M.s[_1x1_] = fov;
    out_M.s[_2x1_] = 0.0;
    out_M.s[_3x1_] = 0.0;

    out_M.s[_0x2_] = 0.0;
    out_M.s[_1x2_] = 0.0;
    out_M.s[_2x2_] = (NEAR+FAR) * nf;
    out_M.s[_3x2_] = (2.f*NEAR*FAR) * nf;

    out_M.s[_0x3_] = 0.0;
    out_M.s[_1x3_] = 0.0;
    out_M.s[_2x3_] = -1.0;
    out_M.s[_3x3_] = 0.0;

}

也请参阅此图片。

<强>正交 enter image description here

<强>视角 enter image description here