简述
osg提供了一个遍历节点的类。osg::NodeVisitor,它提供一系列apply的重载函数,用于访问某类型结点。
virtual void apply (Node &node)
virtual void apply (Geode &node)
virtual void apply (Group &node)
virtual void apply (LightSource &node)
virtual void apply (Transform &node)
virtual void apply (Camera &node)
virtual void apply (Switch &node)
还有很多重载的类型,根据自己的需求写。
实现
节点组织结构图:
class VisitorNode : public osg::NodeVisitor
{
public:
VisitorNode() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) {};
void apply(osg::Node &node)
{
std::cout << "apply node: " << node.getName() << std::endl;
traverse(node);
}
void apply(osg::Group &node)
{
std::cout << "apply group: " << node.getName() << std::endl;
traverse(node);
}
void apply(osg::MatrixTransform &node)
{
std::cout << "apply MatrixTransform: " << node.getName() << std::endl;
traverse(node);
}
void apply(osg::Switch &node)
{
std::cout << "apply Switch: " << node.getName() << std::endl;
traverse(node);
}
void apply(osg::Geode &node)
{
std::cout << "apply geode: " << node.getName() << std::endl;
traverse(node);
}
};
int main()
{
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
VisitorNode vn;
osg::ref_ptr<osg::Group> root = new osg::Group;
root->setName("root");
osg::ref_ptr<osg::Group> group = new osg::Group;
root->setName("group");
osg::ref_ptr<osg::Group> group1 = new osg::Group;
root->setName("group1");
osg::ref_ptr<osg::Node> glider = osgDB::readNodeFile("glider.osg");
glider->setName("glider");
osg::ref_ptr<osg::Node> cow = osgDB::readNodeFile("cow.osg");
cow->setName("cow");
osg::ref_ptr<osg::MatrixTransform> mt = new osg::MatrixTransform;
mt->setMatrix(osg::Matrix::translate(osg::Vec3(30, 0, 0)) * osg::Matrix::scale(osg::Vec3(0.2, 0.2, 0.2)));
mt->setName("mt");
osg::ref_ptr<osg::Switch> switchs = new osg::Switch;
switchs->setName("switchs");
//组织节点结构
root->addChild(group);
root->addChild(switchs);
group->addChild(mt);
group->addChild(cow);
switchs->addChild(group1);
group1->addChild(glider);
mt->addChild(cow);
mt->addChild(glider);
//设置遍历器
root->accept(vn);
viewer->setSceneData(root);
viewer->addEventHandler(new osgViewer::WindowSizeHandler);
return viewer->run();
return 0;
}