C++ OpenGL中的层次建模

C++ OpenGL中的层次建模,c++,windows,opengl,modeling,C++,Windows,Opengl,Modeling,我目前正在学习OpenGL,并展示了我的第一批几何图形和纹理 现在我正试图在不同的图形角色之间建立一个父子层次模型。 我知道它通常是这样实现的: void Draw(){ glPushMatrix(); <apply all transformations> <draw this model> <for each child c of this actor:> c.Draw(); glPopMatrix(

我目前正在学习OpenGL,并展示了我的第一批几何图形和纹理

现在我正试图在不同的图形角色之间建立一个父子层次模型。 我知道它通常是这样实现的:

void Draw(){
    glPushMatrix();
    <apply all transformations>
    <draw this model>
    <for each child c of this actor:>
        c.Draw();
    glPopMatrix();
}
void Draw(){
glPushMatrix();
c、 Draw();
glPopMatrix();
}
这样子对象将继承父对象的所有变换(比例、位置、旋转)。 但有时我只希望应用某些变换(例如,特效演员应与其父角色一起移动,但不使用其父角色的旋转,而头盔演员希望继承所有变换)

我想到的想法是传递应应用于绘图函数的变换参数:

class Actor{
    Vec3 m_pos, m_rot, m_scale; //This object's own transformation data
    std::vector<Actor*> m_children;

    void Draw(Vec3 pos, Vec3 rot, Vec3 scale){
        (translate by pos) //transform by the given parent data
        (rotate around rot)
        (scale by scale)

        glPushMatrix(); //Apply own transformations
        (translate by m_pos)
        (rotate around m_rot)
        (scale by m_scale)
        (draw model)
        glPopMatrix(); //discard own transformations

        for( Actor a : m_children ){
            glPushMatrix();
            a.Draw( pass m_pos, m_rot and/or m_scale depending on what the current child wants to inherit );
            glPopMatrix();
        }
    }
}

void StartDrawing(){
    glLoadIdentity();
    //g_wold is the "world actor" which everything major is attached to.
    g_world.Draw( Vec3(0,0,0), Vec3(0,0,0), Vec3(0,0,0) );
}
类参与者{
Vec3 m_pos,m_rot,m_scale;//此对象自身的转换数据
性病::媒介m_儿童;
无效绘制(Vec3位置、Vec3旋转、Vec3比例){
(按位置转换)//按给定的父数据转换
(围绕旋转)
(按比例)
glPushMatrix();//应用自己的变换
(由m_pos翻译)
(围绕m_rot旋转)
(按m_比例缩放)
(绘制模型)
glPopMatrix();//放弃自己的转换
为(演员a:m_儿童){
glPushMatrix();
a、 绘制(根据当前子级希望继承的内容传递m_pos、m_rot和/或m_scale);
glPopMatrix();
}
}
}
void StartDrawing(){
glLoadIdentity();
//g_wold是一个“世界演员”,所有主要人物都依附于他。
g_world.Draw(Vec3(0,0,0),Vec3(0,0,0),Vec3(0,0,0));
}
(伪代码。可能是错误的,但应该传达这个想法。)

但这看起来相当不整洁,并且看起来程序的工作量要大得多(因为会有大量额外的向量数学)

我读过一些关于层次化建模的文章,但是所有关于层次化建模的文献似乎都假设每个子对象都希望继承所有父属性


有更好的方法吗?

首先需要注意的是:矩阵堆栈在最新的OpenGL版本中被弃用,用户应该自己控制转换

您面临的问题是在渲染图中使用的每种OpenGL状态。解决此问题的一种常见方法(例如在OpenSceneGraph中)是为每个状态定义一个附加属性,该属性定义子图是否覆盖其子图中的属性。反过来,子对象可以保护其状态不被父对象覆盖。这适用于各种OpenGL状态

你的情况似乎有点奇怪。通常,要将变换应用于整个子图。虽然这个计划在这里也可以奏效