2011-03-20 72 views

回答

16

OpenGL使用几个矩阵来转换几何和相关数据。这些矩阵是:

  • 模型变换 - 地点在全局对象的几何形状,未投影空间
  • 投影 - 项目整体坐标到剪辑空间;你可以把它看成是一种镜头
  • 纹理 - 调整之前的纹理坐标;主要用于实现纹理投影(即投影纹理,就好像它是投影机中的幻灯片一样)
  • 颜色 - 调整顶点颜色。很少触及所有这些矩阵

所有这些矩阵一直在使用。由于他们都遵循相同的规则的OpenGL只有一组矩阵操作函数:glPushMatrixglPopMatrixglLoadIdentityglLoadMatrixglMultMatrixglTranslateglRotateglScaleglOrthoglFrustum

glMatrixMode选择这些操作对哪个矩阵起作用。假设你想写一些C++命名空间的包装,它看起来是这样的:

namespace OpenGL { 
    // A single template class for easy OpenGL matrix mode association 
    template<GLenum mat> class Matrix 
    { 
    public: 
    void LoadIdentity() const 
     { glMatrixMode(mat); glLoadIdentity(); } 

    void Translate(GLfloat x, GLfloat y, GLfloat z) const 
     { glMatrixMode(mat); glTranslatef(x,y,z); } 
    void Translate(GLdouble x, GLdouble y, GLdouble z) const 
     { glMatrixMode(mat); glTranslated(x,y,z); } 

    void Rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) const 
     { glMatrixMode(mat); glRotatef(angle, x, y, z); } 
    void Rotate(GLdouble angle, GLdouble x, GLdouble y, GLdouble z) const 
     { glMatrixMode(mat); glRotated(angle, x, y, z); } 

    // And all the other matrix manipulation functions 
    // using overloading to select proper OpenGL variant depending on 
    // function parameters, and all the other C++ whiz. 
    // ... 
    }; 

    // 
    const Matrix<GL_MODELVIEW> Modelview; 
    const Matrix<GL_PROJECTION> Projection; 
    const Matrix<GL_TEXTURE> Texture; 
    const Matrix<GL_COLOR>  Color; 
} 

后来在一个C++程序,你可以写,然后

void draw_something() 
{ 
    OpenGL::Projection::LoadIdentity(); 
    OpenGL::Projection::Frustum(...); 

    OpenGL::Modelview::LoadIdentity(); 
    OpenGL::Modelview::Translate(...); 

    // drawing commands 
} 

不幸的是C++无法模板命名空间,或应用using(或with)的情况下,(其它语言有这个),否则我写了类似的信息(无效C++)

void draw_something_else() 
{ 
    using namespace OpenGL; 

    with(Projection) { // glMatrixMode(GL_PROJECTION); 
     LoadIdentity(); // glLoadIdentity(); 
     Frustum(...);  // glFrustum(...); 
    } 

    with(Modelview) {  // glMatrixMode(GL_MODELVIEW); 
     LoadIdentity(); // glLoadIdentity(); 
     Translate(...); // glTranslatef(...); 
    } 

} 

我认为日是最后剪去的(伪)代码清楚地表明:glMatrixMode是OpenGL的一个with语句。

1

所有的都由OpenGL内部使用,但是否需要更改它们取决于您的应用程序。

您将始终需要设置投影矩阵来确定您的视野和您正在查看的空间范围。通常你会设置模型视图矩阵来选择你的“相机”方向,并在场景中定位对象。

纹理和颜色矩阵不太常用。在我当前的项目中,我使用Texture矩阵来翻转位图中的Y.我从未使用过Color矩阵。

3

作为旁注,矩阵模式(以及矩阵堆栈功能的其余部分)在OpenGL 3.3及更高版本中不推荐使用。

相关问题