Friday, March 24, 2017

Using OSG Node to Load 3D Object Model



It is very easy to load 3D object model in OpenSceneGraph. Let starts to write  some code and build it. What we need, just included headers, <osgDB/ReadFile> and <osgViewer/Viewer> then add root variable that provides the runtime access to the 3D model and assign to it to the setSceneData() method.

This code was implemented in OpenSuse 42.2, Netbean C++, OpenSceneGraph-3.0.1
If you don't have a 3D object model, you can download here

Please copy paste the code to your main.cpp file

#include <cstdlib>
#include <iostream>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osg/ShapeDrawable>

using namespace std;

int main(int argc, char** argv) {
    osg::ref_ptr<osg::Node> model1 = osgDB::readNodeFile("/home/addies/osg/data/cessna.osg" );
    osg::ref_ptr<osg::Group> root = new osg::Group;
    root->addChild( model1.get() );

    osgViewer::Viewer viewer;
    viewer.setSceneData( root.get() );

    return viewer.run();
}


If you are successfully, then you will get result as below.




In this example, I just introduce two new OSG classes osg::ref_ptr<> and osg::Node. The osg::Node class represents the basic element of a scene graph. The variable root stands for the root node of the 3D model, which is used as the scene data to be visualized.

Meanwhile, an instance of the osg::ref_ptr<> class template is created to manage the node object. It is a smart pointer that provide efficient memory management.

Thank you

Hope you enjoy it




Other Topics:


2 comments: