5.从文件中加载模型并放入到场景中
几何模型使用scene graph的节点表示。因此,为了加载并操作一个几何模型文件,我们需要声明一个句柄(或指针)指向osg::Node类型实例。(在一些要求的#include后)。
#include <osg/Node> #include <osgDB/ReadFile> ... osg::Node* cessnaNode = NULL; osg::Node* tankNode = NULL; ... cessnaNode = osgDB::readNodeFile("cessna.osg"); tankNode = osgDB::readNodeFile("Models/T72-tank/t72-tank_des.flt"); |
这就是加载数据库需要做的事。下一步我们把它作为scene graph的一部分加入。将模型加载到transform节点的子节点上,这样我们就可以重新定位它了。
// Declare a node which will serve as the root node // for the scene graph. Since we will be adding nodes // as 'children' of this node we need to make it a 'group' // instance.实例 // The 'node' class represents表现 the most generic version of nodes. // This includes nodes that do not have children (leaf nodes.) // The 'group' class is a specialized version of the node class. // It adds functions associated with adding and manipulating 操作 // children. osg::Group* root = new osg::Group(); root->addChild(cessnaNode); // Declare transform, initialize with defaults.声明位置函数并以默认方式初始化 osg::PositionAttitudeTransform* tankXform = new osg::PositionAttitudeTransform(); // Use the 'addChild' method of the osg::Group class to // add the transform as a child of the root node and the // tank node as a child of the transform. root->addChild(tankXform); tankXform->addChild(tankNode); // Declare and initialize a Vec3 instance to change the // position of the tank model in the scene osg::Vec3 tankPosit(5,0,0); tankXform->setPosition( tankPosit ); |
现在,我们的scene graph由一个根节点和两个子节点组成。一个是cessna的几何模型,另一个是一个右子树,由一个仅有一个tank的几何模型的transform节点组成。为了观察场景,需要建立一个viewer和一个仿真循环。就像这样做的:
#include <osgProducer/Viewer> // Declare a 'viewer' osgProducer::Viewer viewer; // For now, we can initialize with 'standard settings' // Standard settings include a standard keyboard mouse // interface as well as default drive, fly and trackball // motion models for updating the scene. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // Next we will need to assign the scene graph we created // above to this viewer: viewer.setSceneData( root ); // create the windows and start the required threads. viewer.realize(); // Enter the simulation loop. viewer.done() returns false // until the user presses the 'esc' key. // (This can be changed by adding your own keyboard/mouse // event handler or by changing the settings of the default // keyboard/mouse event handler) while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // Initiate scene graph traversal to update nodes. // Animation nodes will require update. Additionally, // any node for which an 'update' callback has been // set up will also be updated. More information on // settting up callbacks to follow. viewer.update(); // initiate the cull and draw traversals of the scene. viewer.frame(); } |
你应当能编译并执行上面的代码(保证调用的顺序是正确的,已经添加了main等等)。执行代码的时候,按h键会弹出一个菜单选项(似乎没有这个功能——译者)。按‘esc’退出。
评论