怎么利用osg访问和操作obj格式文件的节点

之前看到一篇利用osg修改obj格式文件的颜色,写了一个颜色节点到obj文件中,但是应该如何访问obj文件的节点信息呢?

基于Monster 组和GPT的调写:
用 OSG 中的适当类。以下是一个简单的示例,说明如何读取 OBJ 文件并访问其中的节点信息:

#include <osgDB/ReadFile>
#include <osg/NodeVisitor>
#include <osg/Geometry>
#include <iostream>

class FindGeometryVisitor : public osg::NodeVisitor
{
public:
    FindGeometryVisitor() : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
    {}

    virtual void apply(osg::Node& node)
    {
        if (osg::Geometry* geometry = node.asGeometry())
        {
            std::cout << "Found a geometry!" << std::endl;
            // Do something with the geometry...
        }
        traverse(node);
    }
};

int main(int argc, char** argv)
{
    osg::ref_ptr<osg::Node> model = osgDB::readNodeFile("model.obj");

    if (model.valid())
    {
        std::cout << "Loaded model!" << std::endl;
        FindGeometryVisitor visitor;
        model->accept(visitor);
    }
    else
    {
        std::cout << "Failed to load model!" << std::endl;
    }

    return 0;
}


先使用 osgDB::readNodeFile 函数加载了 OBJ 文件,然后创建了一个 FindGeometryVisitor 类,该类继承自 osg::NodeVisitor,并重写了 apply 函数以访问场景图中的每个节点。在 apply 函数中,我们检查节点是否为几何节点,并对其进行相应的处理。最后,我们将 FindGeometryVisitor 实例传递给场景图根节点的 accept 函数,以开始遍历整个场景图。

你可以按照需要扩展 FindGeometryVisitor 类,以执行其他类型的操作,如访问节点的顶点数据、纹理坐标数据等等。