//method that will be called when entering
            //a new node
			osg::Action::ResultE enter(osg::NodePtr& node)
			{
                if (node->getCore()->getType().isDerivedFrom(OSG::CharacterBase::getClassType()))
				{
					osg::CharacterPtr charac = osg::CharacterPtr::dcast(node->getCore());
					std::string name;
					if (getName(node))
					{
						name = getName(node);
					}
					else 
					{
						osg::CharacterModelPtr model = charac->getModel();
						name = model->getConfigFile();
						std::cout << "character model file " << name << std::endl;
						std::string::size_type slashpos = name.size()-1;
						slashpos = name.find_last_of("/");
						if(slashpos != name.npos)
							name = name.substr(slashpos+1);
						slashpos = name.size()-1;
						slashpos = name.find_last_of("\\");
						if(slashpos != name.npos)
							name = name.substr(slashpos+1);
						std::string::size_type dotpos = 0;
						dotpos = name.find_last_of(".");
						if(dotpos != name.npos)
							name = name.substr(0, dotpos);
					}
					std::cout << name << " is a character" << std::endl;
					return process(node, charac, name);
				}
                return osg::Action::Continue;
            }
Exemple #2
0
int main(int argc, char **argv)
{
    OSG::NodePtr pRoot;

    int i = 0;

    OSG::osgInit(i, NULL);

    OSG::Node::create();

    if((argc > 2) && (OSG::stringcmp(argv[2], "pushNames") == 0))
    {    
        OSG::SceneFileHandler::the().setOptions("wrl", "pushNames=true");
    }
    
    pRoot = OSG::SceneFileHandler::the().read(argv[1]);

    std::cerr << "Tree : " << std::endl;

    if(pRoot == OSG::NullFC)
    {
        std::cerr << "\t Empty" << std::endl;
    }
    else
    {
        pRoot->dump();
    }

//    char *szFilename = "stirnwand.wrl";

    OSG::osgExit();

    return 0;
}
OSG::NodePtr makePolygon(double pntData[][3], int numPoints) {

  OSG::GeometryPtr geoPtr  = OSG::Geometry::create();
  OSG::NodePtr     nodePtr = OSG::Node::create();

  GeoPositions3fPtr    pnts    = GeoPositions3f::create();
  GeoNormals3fPtr      norms   = GeoNormals3f::create();
  GeoTexCoords2fPtr    tex     = GeoTexCoords2f::create();
  GeoIndicesUI32Ptr    indices = GeoIndicesUI32::create();   
  GeoPLengthsUI32Ptr   lens    = GeoPLengthsUI32::create();  
  GeoPTypesUI8Ptr      types   = GeoPTypesUI8::create();     

  //Set up the properties according to the geometry defined above
  beginEditCP(pnts);
  beginEditCP(norms);
  
  for(int i = 0; i < numPoints; i++) 
    {
      pnts->push_back(Pnt3f(pntData[i][0],
                            pntData[i][1], 
                            pntData[i][2]));

      indices->push_back(2*i);

      norms->push_back(Vec3f(0.0, 0.0, pntData[i][2]));
      indices->push_back(2*i + 1);
    }

  endEditCP(pnts);
  endEditCP(norms);

  beginEditCP(types);
  beginEditCP(lens);
  types->push_back(GL_POLYGON);
  lens->push_back(numPoints);
  endEditCP(types);
  endEditCP(lens);

  beginEditCP(geoPtr);
  
  geoPtr->setMaterial(getDefaultMaterial());
  geoPtr->setPositions(pnts);
  geoPtr->setNormals(norms);
  geoPtr->setIndices(indices);
  
  geoPtr->editMFIndexMapping()->push_back(Geometry::MapPosition | 
                                          Geometry::MapNormal);
  
  geoPtr->setTypes(types);
  geoPtr->setLengths(lens);
  
  endEditCP(geoPtr);

  nodePtr->setCore(geoPtr);
  return nodePtr;
}
Exemple #4
0
void testObj::setActive( osg::NodePtr parent, bool active )
{
	if ( _isActive && ! active )
	{
		osg::addRefCP( node );
		parent->subChild( node );
	}
	else if ( ! _isActive && active )
 		parent->addChild( node );
	_isActive = active;
}
void testNode(void)
{
#if 0
    OSG::SFNodePtr sfNode;
    OSG::MFNodePtr mfNode;

    OSG::NodePtr pNode = OSG::Node::create();

    sfNode.setValue(pNode);
    mfNode.push_back(pNode);

/*
    fprintf(stderr, "%p %p %p | %d %d\n", 
            pNode, 
            sfNode.getValue(), 
            mfNode[0],
            OSG::Node::VolumeFieldId,
            OSG::Node::TravMaskFieldId);
 */

    OSG::NodePtr pNode1 = OSG::Node::create();

    sfNode.setValue(pNode1);
    mfNode.resize(2);
    mfNode.replace(1, pNode1);

    const OSG::Field *pF1 = pNode->getSFVolume();
          OSG::Field *pF2 = pNode->editSFVolume();

    OSG::GetFieldHandlePtr  pRF1 = pNode->getField("volume");
    OSG::EditFieldHandlePtr pRF2 = pNode->editField("volume");

    fprintf(stderr, "#### Field %p %p | %p %p\n", 
            pF1, 
            pF2, 
            pRF1.get(), 
            pRF2.get());

//    fprintf(stderr, "%p %p %p\n", pNode1, sfNode.getValue(), mfNode[1]);

    const OSG::SFNodePtr constSFNode;

//    fprintf(stderr, "%p %p\n", pNode1, constSFNode.getValue());

    OSG::FieldContainerPtr pNodeClone = deepClone(pNode);

    OSG::FieldContainerPtr pFC = 
        OSG::FieldContainerFactory::the()->createContainer("Billboard");

    fprintf(stderr, "### FOO %p\n", getCPtr(pFC));

#endif
}
Exemple #6
0
void addWithHull( osg::NodePtr	testObj )
{
	testGeom = osg::GeometryPtr::dcast( testObj->getCore() );
	testHull = testGeom;
	testHullObj = testHull.getGeomNode();

	testHull.print();

	// set material
	osg::SimpleMaterialPtr mat = osg::SimpleMaterial::create();
    	mat->setDiffuse( osg::Color3f( 1.0,0.7,1.0 ) );
    	mat->setAmbient( osg::Color3f( 0.2,0.2,0.2 ) );
    	mat->setSpecular( osg::Color3f( 1,1,1 ) );
    	mat->setShininess( 20 );

	testGeom->setMaterial( mat );
	osg::GeometryPtr::dcast(testHullObj->getCore())->setMaterial( mat );

	// add to scene graph
	beginEditCP(root);

	root->addChild( testObj );
	root->addChild( testHullObj );

	endEditCP(root);
}
Transform::Transform(OSG::NodePtr node) : Group(node)
{
    _transform = OSG::cast_dynamic<OSG::TransformPtr>(node->getCore());
   
    // OSG::beginEditCP(_node);
    _node->setCore(_transform);
    // OSG::endEditCP(_node);
}
Group::Group(OSG::NodePtr node) : NodeBase(node)
{
    _group = OSG::cast_dynamic<OSG::GroupPtr>(node->getCore());
   
    // OSG::beginEditCP(_node);
    _node->setCore(_group);
    // OSG::endEditCP(_node);
}
Geometry::Geometry(OSG::NodePtr node) : NodeBase(node)
{
    _geometry = OSG::cast_dynamic<OSG::GeometryPtr>(node->getCore());
   
    // OSG::beginEditCP(_node);
    _node->setCore(_geometry);
    // OSG::endEditCP(_node);
}
NodeBase NodeIterator::next(void)
{
    while(!_stack.empty())
    {
        OSG::NodePtr act = _stack.back();

        _stack.pop_back();

        for(OSG::UInt32 i = 0; i < act->getNChildren(); ++i)
            _stack.push_back(act->getChild(i));

        if(act->getCore()->getType().isDerivedFrom(*_type))
        {
            return NodeBase(act);
        }    
    }
   
    PyErr_SetString(PyExc_StopIteration, "Out of Nodes");   
    boost::python::throw_error_already_set();
}
osg::Action::ResultE enter(osg::NodePtr& node)
{   
    //if (osg::getName(node))
	if (node->getCore()->getType().isDerivedFrom(OSG::CharacterBase::getClassType()))
    {
		std::cout << osg::getName(node) << "is a character" << std::endl;
    }
    //else
	//{
    //     std::cout << osg::getName(node) << "is not a character" << std::endl;
	//}

    return osg::Action::Continue; 
}
void InventorLoader::checkForRedundancy( osg::NodePtr OSGGroup )
{
  return;
  
    // TODO: Check the type of the node and return, if it's not a node
    // that should be discarded (discardable: group, not discardable: geometry)

    // If the group node has no children, then let's kick it !
    if( OSGGroup->getNChildren() == 0 )
    {
        if(OSGGroup->getParent() != NullFC)
        {
            OSGGroup->getParent()->subChild(OSGGroup);
        }
        else
        {
            subRefCP(OSGGroup);
        }
    }
    // If there's only one child, then add it to the parent of the group,
    // copy the name and remove the group
    else if ( OSGGroup->getNChildren() == 1 )
    {
        // Get parent and child
        osg::NodePtr _Child = OSGGroup->getChild(0);
        osg::NodePtr _Parent = OSGGroup->getParent();

        // Copy the name
        const char* _Name = getName(OSGGroup);
        if( _Name )
            setName( _Child, _Name );

        // Add the child to the parent
        _Parent->addChild( _Child );

        // Remove the group node
        _Parent->subChild( OSGGroup );
    }
}
Exemple #13
0
NodePtr createScoreBoards()
{
	GeometryPtr geo;
	NodePtr bg;
	SimpleMaterialPtr m;
	ScoreBoard1 = new TextStuff() ;
	ScoreBoard2 = new TextStuff() ;

	// First get the global group node
    OSG::NodePtr scoreBoardsNodePtr = OSG::Node::create();
    scoreBoardsNodePtr->setCore(OSG::Group::create());

    // Setup text 1
    ScoreBoard1->initialize();
    ScoreBoard1->updateFace();
    ScoreBoard1->updateScore(0,0);
    // Setup text 2
    ScoreBoard2->initialize();
    ScoreBoard2->updateFace();
    ScoreBoard2->updateScore(0,0);

	////////// 1 /////////
	// make its transform
	TransformPtr trans1;
    NodePtr trans_node1 = makeCoredNode<Transform>(&trans1);
    beginEditCP(trans1);
		trans1->getMatrix().setTransform(Vec3f(0,4,-10.5),Quaternion( Vec3f(0,1,0),deg2rad(0)));
    endEditCP(trans1);

	// make geometry
	bg = makePlane(9.3, 1, 8,2);
	 m= SimpleMaterial::create();
    beginEditCP(m);
    {		
        m->setAmbient      (Color3f(0,0,0));
        m->setDiffuse      (Color3f(0.0,0.0,0.0));
    }
    endEditCP  (m);  
	geo = GeometryPtr::dcast(bg->getCore());  
    beginEditCP(geo);
		geo->setMaterial(m);
    beginEditCP(geo);

	beginEditCP(bg);
	bg->addChild(ScoreBoard1->mRootNode);
	endEditCP(bg);

	beginEditCP(trans_node1);
		trans_node1->addChild(bg);
	endEditCP(trans_node1);

	////////// 2 /////////
	// make its transform
	TransformPtr trans2;
    NodePtr trans_node2 = makeCoredNode<Transform>(&trans2);
    beginEditCP(trans2);
		trans2->getMatrix().setTransform(Vec3f(0,4,10.5),Quaternion( Vec3f(0,1,0),deg2rad(180)));
    endEditCP(trans2);

	// make geometry
	bg = makePlane(9.3, 1, 8,2);
	m = SimpleMaterial::create();
    beginEditCP(m);
    {		
        m->setAmbient      (Color3f(0,0,0));
        m->setDiffuse      (Color3f(0.0,0.0,0.0));
    }
    endEditCP  (m);  
	geo = GeometryPtr::dcast(bg->getCore());  
    beginEditCP(geo);
		geo->setMaterial(m);
    beginEditCP(geo);

	beginEditCP(bg);
	bg->addChild(ScoreBoard2->mRootNode);
	endEditCP(bg);

	beginEditCP(trans_node2);
		trans_node2->addChild(bg);
	endEditCP(trans_node2);


	beginEditCP(scoreBoardsNodePtr);
		scoreBoardsNodePtr->addChild(trans_node1);
		scoreBoardsNodePtr->addChild(trans_node2);
	endEditCP(scoreBoardsNodePtr);
  

    return scoreBoardsNodePtr;
}
Exemple #14
0
int main(int argc, char *argv[])
{/*
    int j = 0;

    // Allocate Sotrage
    std::vector<std::vector<cv::Point3f> > object_points;
    std::vector<std::vector<cv::Point2f> > image_points;

    int numBoards = 20;
    int numCornersHor = 9;
    int numCornersVer = 6;

    int numSquares = numCornersHor * numCornersVer;
    cv::Size board_sz = cv::Size(numCornersVer, numCornersHor);

    vector<cv::Point2f> corners;
    int successes=0;


    cv::Mat init_Image;

	vector<cv::Point3f> obj;
	for(int y(0); y < numCornersHor; ++y) {
	    double tmp (y * 60.0);
	    for(int x(0); x < numCornersVer; ++x){
		obj.push_back(cv::Point3f(x * 60.0, tmp, 0));
		cout << "::" <<   x * 60.0 << " - " << tmp << endl;
	    }
	}

	//cv::VideoCapture capture = cv::VideoCapture(0);

	//while(successes < numBoards){
	for(int i = 1 ; i< 518 ; i++){
	    // every 10 pictures
	    if(j != 1){
		j++;
		continue;
	    } else {
		j=0;
	    }
	    stringstream stream;
	    stream << "pics/init/";
	    stream << i;
	    stream << ".bmp";
	    cout << "#### PICTURE NO. "<<i<<"####" << stream.str().c_str() <<endl;
	    init_Image = cvLoadImage(stream.str().c_str());
	    cv::Mat grayImage;
	    //capture >> init_Image;

	    cv::cvtColor(init_Image, grayImage, CV_BGR2GRAY);
	    bool found = cv::findChessboardCorners(grayImage, board_sz, corners, cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_NORMALIZE_IMAGE);

	    if(found)
	    {
		cv::cornerSubPix(grayImage, corners, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
		cv::drawChessboardCorners(grayImage, board_sz, corners, found);

		image_points.push_back(corners);
		object_points.push_back(obj);

		cout << "Snap stored!" << endl;
		successes++;

		if(successes>=numBoards)
		    break;
	    }

	   cv::imshow("Calib1",init_Image);
	   cv::imshow("Calib2",grayImage);

	   int key = cv::waitKey(1);


	}
	cout << "image point size : " << image_points.size() << endl;
	cout << "object point size : " << object_points.size() << endl;

	cv::Mat distCoeffs;
	vector<cv::Mat> rvecs;
	vector<cv::Mat> tvecs;

	cv::Mat intrinsic;

	cv::calibrateCamera(object_points, image_points, init_Image.size(), intrinsic, distCoeffs, rvecs, tvecs);

	cout << "##INTRINSIC##" <<endl;
	cout << intrinsic.ptr<double>(0)[0] << " " <<intrinsic.ptr<double>(0)[1]<<" " <<intrinsic.ptr<double>(0)[2]<< endl;
	cout << intrinsic.ptr<double>(1)[0] << " " <<intrinsic.ptr<double>(1)[1]<< " " <<intrinsic.ptr<double>(1)[2] << endl;
	cout << intrinsic.ptr<double>(2)[0] << " " <<intrinsic.ptr<double>(2)[1]<< " " <<intrinsic.ptr<double>(2)[2] << endl;

	cout << "##DISTORTION##" <<endl;
	cout << distCoeffs.ptr<double>(0)[0] << " " << distCoeffs.ptr<double>(0)[1] << " " << distCoeffs.ptr<double>(0)[2] << " "
		<< distCoeffs.ptr<double>(0)[3] << " " << distCoeffs.ptr<double>(0)[4] << " " << distCoeffs.ptr<double>(0)[5] << " "  <<endl;


	for(int i = 1 ; i< 300 ; i++){

	    stringstream stream,s2;
	    stream << "pics/";
	    stream << i;
	    stream << ".bmp";
	    cout << "#### PICTURE NO. "<<i<<"####" << stream.str().c_str() <<endl;
	    cv:: Mat image = cvLoadImage(stream.str().c_str());
	cv::Mat newI;
		cv::undistort(image,newI,intrinsic,distCoeffs);
		s2 << "pics/undist/";
		s2 << i;
		s2 << ".bmp";
		cv::imwrite(s2.str().c_str(),newI);
	}
	exit(0);*/
    // AR _BEGIN_
/*


    const char    *cparam_name    = "pics/camera_para.dat";
    ARParam cparam;
    ARParam wparam;

    // opencv-test
    char	*patt_name      = "davit.patt";

    std::cout << QDir::currentPath().toStdString() << endl;
    cv::Mat m,n;
    cv::namedWindow("looky looky");

    ARUint8  *dataPtr;
    int patt_id;
    if( (patt_id=arLoadPatt(patt_name)) < 0 ) {
	cout << "Pattern load error" <<endl;
    } else {
	cout << "Pattern loaded... "<<endl;
    }

    // set the initial camera parameters
    if( arParamLoad(cparam_name, 1, &wparam) < 0 ) {
	cout << "Camera parameter load error !!"<<endl;
	exit(0);
    } else {
	cout << "Loaded Camera Parameter !! "<<endl;
    }

    //wparam.xsize = 1280;
    //wparam.ysize = 1024;
    //wparam.mat[0][0] = 1598.0;
    //wparam.mat[1][1] = 1596.15;
    //wparam.mat[0][2] = 555.006;
    //wparam.mat[1][2] = 525.028;

    //wparam.dist_factor[0] = -0.477959;
    //wparam.dist_factor[1] = 1.83017;
    //wparam.dist_factor[2] = -0.0036001;
    //wparam.dist_factor[3] = -0.0001997;
    //cout <<"RESET..."<<endl;

    arParamChangeSize( &wparam, 1280, 1024, &cparam );
    arInitCparam( &cparam );
    cout << "*** Camera Parameter ***"<<endl;
    arParamDisp( &cparam );

    //open file
    fstream file;
    file.open("1280x1024Data.dat",ios::out);

    cv::Mat RGB;
    int v = 0;
    for(int u=1;u<=200;++u){
	file<<"#FRAME_"<<u<<endl;
	//cout << "in loop..."<<endl;
	stringstream stream;
	stream << "pics/undist/";
	stream << u;
	stream << ".bmp";

	RGB = cv::imread(stream.str().c_str());
	cv::flip(RGB,RGB,0);

	cv::Mat matAR(RGB.rows,RGB.cols,CV_8UC4);
	cv::cvtColor(RGB,matAR,CV_BGR2BGRA);

	cv::Mat newAR(RGB.rows,RGB.cols,CV_8UC4);

	cv::Mat in[] = {matAR};
	cv::Mat out[] = {newAR};
	int from[] = {3,0,0,3,1,2,2,1};
	cv::mixChannels(in,1,out,1,from,4);

	dataPtr = (ARUint8*)newAR.data;

	ARMarkerInfo    *marker_info;
	int             marker_num;

	if( dataPtr == NULL ) {
		arUtilSleep(2);
		cout << "No Image data found...";
		return 2;
	}

	cout << "try detecting... " << u <<endl;
	if( arDetectMarker(dataPtr, 45, &marker_info, &marker_num) < 0 ) {
	    cout << "No Markers found... :(";
		//cleanup();
		//exit(0);
		return 4;
	}

	int j,k;
	k = -1;
	    for( j = 0; j < marker_num; j++ ) {
		if( patt_id == marker_info[j].id ) {
		    if( k == -1 ) k = j;
		    else if( marker_info[k].cf < marker_info[j].cf ) k = j;
		}
	    }
	    //cout << "k: " << k << endl;
	    double patt_width = 225.0;
	    double patt_center[2] = {0.0,0.0};
	    double patt_trans[3][4];

	    double quat[4];
	    double pos[3];

	    if(marker_num > 0 && k == 0){
		//cout << "Marker found : " << marker_num << "  " << v++ << " - k: " << k <<endl;
		arGetTransMat(&marker_info[k],patt_center,patt_width,patt_trans);
		if(arUtilMat2QuatPos(patt_trans,quat,pos) == 0){
			cout << "quat worked" <<endl;
			cout << "quat: " << quat[0] << " " << quat[1] << " " << quat[2] << " " << quat[3] << endl;
			cout << "pos: " << pos[0] << " " << pos[1] << " " << pos[2] << endl;
			cout <<endl;
		}

		file << patt_trans[0][0] << " " << patt_trans[0][1] << " " << patt_trans[0][2] << " " << patt_trans[0][3] << " "<<endl;
		file << patt_trans[1][0] << " " << patt_trans[1][1] << " " << patt_trans[1][2] << " " << patt_trans[1][3] << " "<<endl;
		file << patt_trans[2][0] << " " << patt_trans[2][1] << " " << patt_trans[2][2] << " " << patt_trans[2][3] << " "<<endl;

		//file << patt_center[0] << " " << patt_center[1] <<endl;
		//cout << "patt width: " << patt_width <<endl;


		file << marker_info[k].pos[0] << " " << marker_info[k].pos[1] <<endl;

		cout << "p1: " << marker_info[k].vertex[0][0] << " " << marker_info[k].vertex[0][1]<< endl;
		cout << "p2: " << marker_info[k].vertex[1][0] << " " << marker_info[k].vertex[1][1]<< endl;
		cout << "p3: " << marker_info[k].vertex[2][0] << " " << marker_info[k].vertex[2][1]<< endl;
		cout << "p4: " << marker_info[k].vertex[3][0] << " " << marker_info[k].vertex[3][1]<< endl;

		cv::line(newAR,cv::Point(marker_info[k].vertex[0][0],marker_info[k].vertex[0][1]),cv::Point(marker_info[k].vertex[1][0],marker_info[k].vertex[1][1]),CV_RGB(255,0,0));
		cv::line(newAR,cv::Point(marker_info[k].vertex[1][0],marker_info[k].vertex[1][1]),cv::Point(marker_info[k].vertex[2][0],marker_info[k].vertex[2][1]),CV_RGB(255,0,0));
		cv::line(newAR,cv::Point(marker_info[k].vertex[2][0],marker_info[k].vertex[2][1]),cv::Point(marker_info[k].vertex[3][0],marker_info[k].vertex[3][1]),CV_RGB(255,0,0));
		cv::line(newAR,cv::Point(marker_info[k].vertex[3][0],marker_info[k].vertex[3][1]),cv::Point(marker_info[k].vertex[0][0],marker_info[k].vertex[0][1]),CV_RGB(255,0,0));

		cv::line(newAR,cv::Point(marker_info[k].vertex[0][0],marker_info[k].vertex[0][1]),cv::Point(marker_info[k].vertex[2][0],marker_info[k].vertex[2][1]),CV_RGB(255,0,0));
		cv::line(newAR,cv::Point(marker_info[k].vertex[1][0],marker_info[k].vertex[1][1]),cv::Point(marker_info[k].vertex[3][0],marker_info[k].vertex[3][1]),CV_RGB(255,0,0));

		cv::line(RGB,cv::Point(marker_info[k].vertex[0][0],marker_info[k].vertex[0][1]),cv::Point(marker_info[k].vertex[1][0],marker_info[k].vertex[1][1]),CV_RGB(255,0,0));
		cv::line(RGB,cv::Point(marker_info[k].vertex[1][0],marker_info[k].vertex[1][1]),cv::Point(marker_info[k].vertex[2][0],marker_info[k].vertex[2][1]),CV_RGB(255,0,0));
		cv::line(RGB,cv::Point(marker_info[k].vertex[2][0],marker_info[k].vertex[2][1]),cv::Point(marker_info[k].vertex[3][0],marker_info[k].vertex[3][1]),CV_RGB(255,0,0));
		cv::line(RGB,cv::Point(marker_info[k].vertex[3][0],marker_info[k].vertex[3][1]),cv::Point(marker_info[k].vertex[0][0],marker_info[k].vertex[0][1]),CV_RGB(255,0,0));

		cv::line(RGB,cv::Point(marker_info[k].vertex[0][0],marker_info[k].vertex[0][1]),cv::Point(marker_info[k].vertex[2][0],marker_info[k].vertex[2][1]),CV_RGB(255,0,0));
		cv::line(RGB,cv::Point(marker_info[k].vertex[1][0],marker_info[k].vertex[1][1]),cv::Point(marker_info[k].vertex[3][0],marker_info[k].vertex[3][1]),CV_RGB(255,0,0));

		cv::waitKey(1);
	    }
	stringstream stream2;
	stream2 << "pics/new/";
	stream2 << u;
	stream2 << ".bmp";
	//cv::imwrite(stream2.str().c_str(),RGB);

	file<< "##"<<endl;
	cv::imshow("looky looky",RGB);
	cv::waitKey(1);
    }
    file.close();

*/
    // AR _ENDE_ !!
    //}


  //  QCoreApplication a(argc, argv);

	OSG::osgInit(argc,argv);
	cout << "argc " << argc <<endl;
	for(int ar(0);ar<argc;++ar)
		cout << argv[ar] << " ";
	cout << endl;
	int winid = setupGLUT(&argc,argv);
	//GLUTWindowPtr gwin = GLUTWindow::create();
	//gwin->setGlutId(winid);
	//gwin->init();


	OSG::NodePtr scene = SceneFileHandler::the().read("data/test__1.obj");
	//OSG::NodePtr scene = SceneFileHandler::the().read("data/test3_4.obj");
	//GroupPtr scene = GroupPtr::dcast(scene);


	cout << "type: " << scene.getCore()->getTypeName()<< endl;

	cout << "children in scene: " << scene->getNChildren()<<endl;

		GeometryPtr geo = GeometryPtr::dcast(scene->getCore());

		GeoPTypesPtr type = GeoPTypesUI8::create();
		type->addValue(GL_LINE);

		LineIterator lit;
		int lines(0);
		TEST = geo;
		for(lit = geo->beginLines();lit != geo->endLines();++lit){
			lines++;
		}

		cout << "lines: " << lines <<endl;
		SimpleMaterialPtr mat = SimpleMaterial::create();
		geo->setMaterial(mat);

	// Create and setup our little friend - the SSM
	mgr = new SimpleSceneManager;
	//mgr->setWindow(gwin);
	//mgr->setRoot(scene);
	//mgr->showAll();
	//glutCreateWindow("test");

    glutMainLoop();

    return 0;
}
osg::NodePtr InventorLoader::traverseGraph( SoNode* OIVNode,
                                            osg::NodePtr OSGNode )
{
    ////////////////////////////////////////////////////////////////////////////
  FDEBUG(("   InventorLoader::traverseGraph( %x )\n",
                          OIVNode));
    ////////////////////////////////////////////////////////////////////////////


    /////////////////
    // Material node
    /////////////////

    if( OIVNode->isOfType( SoMaterial::getClassTypeId() ) )
    {
        // Convert current material
        osg::SimpleMaterialPtr _Material;
        _Material = convertMaterial( ( SoMaterial* ) OIVNode );

        if( mMergeMaterial )
        {
            // Check if that material was already encountered
            TMaterialSet::iterator _Iter;
            for(_Iter = mMaterialSet.begin();
                _Iter != mMaterialSet.end();
                ++_Iter )
            {
                if( compareMaterial( *_Iter, _Material, mMergeTolerance ) )
                    break;
            }

            if( _Iter != mMaterialSet.end() )
            {
                mCurrentState.Material = *_Iter;

                // Delete the converted material from above as it isn't used.
                subRefCP( _Material );
            }
            else
            {
                mMaterialSet.insert( _Material );
                mCurrentState.Material = _Material;
            }
        }
        else
        {
            mCurrentState.Material = _Material;
        }

        // Return the old OSG node as the current OSG node
        return OSGNode;
    }


    ///////////////////
    // Coordinate node
    ///////////////////

    if( OIVNode->isOfType( SoCoordinate3::getClassTypeId() ) )
    {
        // Save current coordinates
        mCurrentState.Positions = convertCoordinates((SoCoordinate3*)OIVNode);

        // Return the old OSG node as the current OSG node
        return OSGNode;
    }


    //////////////////////
    // Normalbinding node
    //////////////////////

    if( OIVNode->isOfType( SoNormalBinding::getClassTypeId() ) )
    {
        // Save current normalbinding
        SoNormalBinding* _Binding = ( SoNormalBinding* ) OIVNode;
        mCurrentState.NormalBinding = _Binding->value.getValue();

        // Return the old OSG node as the current OSG node
        return OSGNode;
    }


    ///////////////
    // Normal node
    ///////////////

    if( OIVNode->isOfType( SoNormal::getClassTypeId() ) )
    {
        // Save current normals
        mCurrentState.Normals = convertNormals( ( SoNormal* ) OIVNode );

        // Return the old OSG node as the current OSG node
        return OSGNode;
    }


    ///////////////////////
    // Transformation node
    ///////////////////////

    if( OIVNode->isOfType( SoTransform::getClassTypeId() ) )
    {
        osg::NodePtr _OSGTransform = convertTransformation( OIVNode );

        // Add the transformation to the current OSG node
        beginEditCP ( OSGNode, Node::ChildrenFieldMask );
        {
            OSGNode->addChild( _OSGTransform );
        }
        endEditCP   ( OSGNode, Node::ChildrenFieldMask );

        // Return the new transform node as the current OSG node
        return _OSGTransform;
    }

    ///////////////////////
    // MatrixTransformation node
    ///////////////////////

    if( OIVNode->isOfType( SoMatrixTransform::getClassTypeId() ) )
    {
        osg::NodePtr _OSGTransform = convertMatrixTransformation( OIVNode );

        // Add the transformation to the current OSG node
        beginEditCP ( OSGNode, Node::ChildrenFieldMask );
        {
            OSGNode->addChild( _OSGTransform );
        }
        endEditCP   ( OSGNode, Node::ChildrenFieldMask );

        // Return the new transform node as the current OSG node
        return _OSGTransform;
    }


    ////////////////////
    // Indexed face set
    ////////////////////

    if( OIVNode->isOfType( SoIndexedFaceSet::getClassTypeId() ) )
    {
        osg::NodePtr _OSGGeometry = convertIFSGeometry( OIVNode );

        // Add the geometry to the current OSG node
        beginEditCP ( OSGNode, Node::ChildrenFieldMask );
        {
            OSGNode->addChild( _OSGGeometry );
        }
        endEditCP   ( OSGNode, Node::ChildrenFieldMask );

        // Return the old OSG node as the current OSG node
        return OSGNode;
    }

    ////////////////////
    // Face set
    ////////////////////

    if( OIVNode->isOfType( SoFaceSet::getClassTypeId() ) )
    {
        osg::NodePtr _OSGGeometry = convertFSGeometry( OIVNode );

        // Add the geometry to the current OSG node
        beginEditCP ( OSGNode, Node::ChildrenFieldMask );
        {
            OSGNode->addChild( _OSGGeometry );
        }
        endEditCP   ( OSGNode, Node::ChildrenFieldMask );

        // Return the old OSG node as the current OSG node
        return OSGNode;
    }


    //////////////////
    // Separator node
    //////////////////

    if( OIVNode->isOfType( SoSeparator::getClassTypeId() ) )
    {
        SoGroup* _OIVGroup = ( SoGroup* ) OIVNode;
        osg::NodePtr _OSGGroup = getGroupNode( OIVNode );
        osg::NodePtr _CurrentNode = _OSGGroup;

        // Add the group to the current OSG node
        beginEditCP ( OSGNode, Node::ChildrenFieldMask );
        {
            OSGNode->addChild( _OSGGroup );
        }
        endEditCP   ( OSGNode, Node::ChildrenFieldMask );

        // Save the current state
        TState _TmpState = mCurrentState;

        // Traverse children
        for( int i=0; i < _OIVGroup->getNumChildren(); ++i )
        {
            SoNode* _OIVChild = _OIVGroup->getChild( i );
            _CurrentNode = traverseGraph( _OIVChild, _CurrentNode );
        }

        // Restore the state
        mCurrentState = _TmpState;

        // Check if the new group node has only one child
        // --> then it's redundant and can be discarded
        checkForRedundancy( _OSGGroup );

        // Return the old OSG node as the current OSG node
        return OSGNode;
    }


    //////////////
    // Group node
    //////////////

    else if( OIVNode->isOfType( SoGroup::getClassTypeId() ) )
    {
        osg::NodePtr _CurrentNode = OSGNode;
        SoGroup* _OIVGroup = ( SoGroup* ) OIVNode;

        // Traverse children
        for( int i=0; i < _OIVGroup->getNumChildren(); ++i )
        {
            SoNode* _OIVChild = _OIVGroup->getChild( i );
            _CurrentNode = traverseGraph( _OIVChild, _CurrentNode );
        }

        // Return the end of the group as current OSG node
        return _CurrentNode;
    }

    FWARNING (( "Unhandled Inventor node: %s\n",
                OIVNode->getTypeId().getName().getString() ));

    return OSGNode;
}
void parsecommandline( int argc, char *argv[] )
{
	/* valid option characters; last char MUST be 0 ! */
	char optionchar[] =   { 'h', 'g', 'x', 'v', 'n', 'a', 'w', 'd', 'A',
							'T', 'f', 'W', 'c',  'r', 'p', 0 };
	int musthaveparam[] = {  0 ,  1,   1,   1,   2,   1,   0,   2,   1,
							 0,   1,   0,   0,   1, 0, 0 };
	int nopts;
	int mhp[256];
	int isopt[256];
	int optchar;


	nopts = strlen(optionchar);
	if ( nopts > 50 )
	{
		fprintf(stderr, "\n\nparsecommandline: the option-chars string "
				"seems to be\nVERY long (%d bytes) !\n\n", nopts );
		exit(-1);
	}

	fill_n( isopt, 256, 0 );
	fill_n( mhp, 256, 0 );
	for ( int i = 0; i < nopts; i ++ )
	{
		if ( isopt[static_cast<int>(optionchar[i])] )
		{
			fprintf(stderr, "\n\nparsecommandline: Bug: option character '%c'"
					" is specified twice in the\n"
				   "option character array !\n\n", optionchar[i] );
			exit(-1);
		}
		isopt[ static_cast<int>(optionchar[i]) ] = 1;
		mhp[ static_cast<int>(optionchar[i])] = musthaveparam[i];
	}

	++argv; --argc;
	while ( argc > 0 )
	{
		if ( argv[0][0] == '-' )
		{
			optchar = argv[0][1];

			if ( ! isopt[optchar] )
			{
				fprintf(stderr, "\nIs not a valid command line option\n");
				commandlineerror( argv[0], NULL );
			}
			for ( int i = 0; i < mhp[optchar]; i ++ )
				if ( ! argv[1+i] || argv[1+i][0] == '-' )
				{
					fprintf(stderr, "\nCommand line option -%c must "
							"have %d parameter(s)\n",
							argv[0][1], mhp[optchar] );
					commandlineerror( argv[0], NULL );
					argv += 1 + i;
					argc -= 1 + i;
					continue;
				}

			switch ( optchar )
			{
				case 'h': commandlineerror( NULL, NULL);  break;

				case 'w': With_window = true; break;
				case 'T': No_timing = true; break;
				case 'W': White_background = true; break;
				case 'c': All_collisions = true; break;

				case 'x': Complexity = atoi( argv[1] ); break;
				case 'a': Rot_vel = atof( argv[1] ); break;

				case 'n': Ndistances = atoi( argv[1] );
						  Nrotations = atoi( argv[2] );
						  break;

				case 'd': Dist_1 = atof( argv[1] );
						  Dist_2 = atof( argv[2] );
						  break;


				case 'v': for ( unsigned int i = 0; i < strlen(argv[1]); i ++ )
							  switch ( argv[1][i] )
							  {
								  case 'v': col_verbose = true;
											break;
								  case 'b': verbose |= VERBOSE_PRINT;
											break;
								  case 'h': col_verboseShowHulls = true;
											break;
								  default : commandlineerror(argv[0],argv[1]);
							  }
						  break;

				case 'g': if ( ! strcmp(argv[1],"pl") )
							  geom_type = OBJ_PLANES;
						  else
						  if ( ! strcmp(argv[1],"sh") )
							  geom_type = OBJ_SPHERES;
						  else
						  if ( ! strcmp(argv[1],"to") )
							  geom_type = OBJ_TORUS;
						  else
						  if ( ! strcmp(argv[1],"file") )
							  geom_type = OBJ_FILE;			// just a dummy
						  else
						  {
							  fputs("unrecognized obj type\n",stderr);
							  commandlineerror(argv[0],argv[1]);
						  }
						  break;

				case 'A': if ( ! strcmp(argv[1],"do") )
							  Algorithm = col::ALGO_DOPTREE;
						  else
						  if ( ! strcmp(argv[1],"bx") )
							  Algorithm = col::ALGO_BOXTREE;

						   else
						   {
							  fputs("unrecognized algorithm\n",stderr);
							  commandlineerror(argv[0],argv[1]);
						   }
						   break;

				case 'f': loadGeom( argv[1], &fixed_node );
						  moving_node = fixed_node->clone();
						  fixed_geom = col::getGeom( fixed_node );
						  moving_geom = col::getGeom( moving_node );
						  geom_type = OBJ_FILE;
						  // post: moving_geom == fixed_geom
						  break;
				case 'r':
						configFile = argv[1];
						break;
				case 'p':
						print_pairs = true;
						break;
				default: fprintf(stderr, "\nBug in parsecommandline !\n");
						 commandlineerror( argv[0], NULL );
			}

			argv += 1 + mhp[optchar];
			argc -= 1 + mhp[optchar];
		}
		else
		{
			/* command line arg doesn't start with '-' */
			fprintf(stderr, "\nThis is not a valid command line option\n");
			commandlineerror( argv[0], NULL );
			/* or, load file instead .. */
		}
	}

	// check sanity of options
	if ( Complexity < 1 ||
		 (geom_type != OBJ_PLANES && Complexity < 3) ||
		 Complexity > 1000 )
	{
		fprintf(stderr,"complexity (%u) out of range!\n", Complexity );
		exit(-1);
	}

	if ( Ndistances > MaxNumDistances )
	{
		fprintf(stderr,"too many (%u) distances!\n", Ndistances );
		Ndistances = MaxNumDistances;
	}
	if ( Ndistances < 1 )
		Ndistances = 1;

	if ( Rot_vel < col::NearZero )
		Rot_vel = 360.0f / Nrotations;
	Rot_vel *= 2.0 * 3.1415926535 / 360.0;

	if ( Ndistances > 1 )
		// Dist_vel will be used like this:
		// d = Dist_1 + dist_step * Dist_vel
		Dist_vel = (Dist_2 - Dist_1) / (Ndistances - 1);
	else
		Dist_vel = 0.0;

	if ( geom_type == OBJ_FILE &&
		 (moving_node == osg::NullFC || fixed_node == osg::NullFC) )
	{
		fputs("bench: '-g file' or '-f' option given,\n"
			  "       but moving node or fixed node is still NULL!", stderr );
		exit(-1);
	}
}
void testRefCount(void)
{
#if 0
    OSG::NodePtr pNode = OSG::Node::create();

    OSG::NodePtr pNode1 = OSG::Node::create();

    fprintf(stderr, "1\n");

//XX
#if 0
    pNode.dump();
    pNode1.dump();
#endif

    pNode->addChild(pNode1);

    fprintf(stderr, "2\n");

//XX
#if 0
    pNode.dump();
    pNode1.dump();
#endif

    fprintf(stderr, "3\n");

//XX
#if 0
    pNode.dump();
    pNode1.dump();
#endif

    applyToAspect(1, false);
    applyToAspect(2);

    fprintf(stderr, "4\n");

//XX
#if 0
    pNode.dump();
    pNode1.dump();
#endif
    
    fprintf(stderr, "5\n");

//XX
#if 0
    pNode.dump();
    pNode1.dump();
#endif

    applyToAspect(1, false);

    fprintf(stderr, "6\n");

//XX
#if 0
    pNode.dump();
    pNode1.dump();
#endif

    applyToAspect(2);

    fprintf(stderr, "7\n");
#endif
}
int main( int argc, char *argv[] )
{

	// OSG init
	osg::osgLog().setLogLevel(osg::LOG_WARNING);
	osg::osgInit(argc, argv);

	// parse command line options
	parsecommandline( argc, argv );

	// disable display lists
	osg::FieldContainerPtr pProto= osg::Geometry::getClassType().getPrototype();
	osg::GeometryPtr pGeoProto = osg::GeometryPtr::dcast(pProto);
    if ( pGeoProto != osg::NullFC )
        pGeoProto->setDlistCache(false);

	// create the graph
	osg::NodePtr node;

	// root
	root = osg::Node::create();
	beginEditCP(root);
	root->setCore( osg::Group::create() );

	// beacon for camera and light
	osg::NodePtr beacon;
	beacon = osg::Node::create();
	beginEditCP(beacon);
	beacon->setCore( osg::Group::create() );
	endEditCP(beacon);

	// light
	light_node = osg::Node::create();
	osg::DirectionalLightPtr light = osg::DirectionalLight::create();
	beginEditCP( light_node );
	light_node->setCore( light );
	root->addChild( light_node );
	beginEditCP(light);
	light->setAmbient( .3, .3, .3, 1 );
	light->setDiffuse( 1, 1, 1, 1 );
	light->setDirection(0,0,1);
	light->setBeacon( beacon );
	endEditCP(light);

	// transformation, parent of beacon
	node = osg::Node::create();
	cam_trans = osg::Transform::create();
	beginEditCP(node);
	node->setCore( cam_trans );
	node->addChild( beacon );
	endEditCP(node);
	root->addChild( node );

	// Camera
	osg::PerspectiveCameraPtr cam = osg::PerspectiveCamera::create();
	cam->setBeacon( beacon );
	cam->setFov( 50 );
	cam->setNear( 0.1 );
	cam->setFar( 10000 );

	// Background
	osg::SolidBackgroundPtr background = osg::SolidBackground::create();
	if ( White_background )
	{
		beginEditCP( background );
		background->setColor(osg::Color3f(1,1,1));
		endEditCP( background );
	}

	// Viewport
	osg::ViewportPtr vp = osg::Viewport::create();
	vp->setCamera( cam );
	vp->setBackground( background );
	vp->setRoot( root );
	vp->setSize( 0,0, 1,1 );

	if ( With_window )
	{
		// GLUT init
		glutInitWindowSize( 400, 400 );		// before glutInit so user can
		glutInitWindowPosition( 100, 100 );	// override with comannd line args
		glutInit(&argc, argv);
		glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
		int winid = glutCreateWindow("Collision Benchmark");
		glutKeyboardFunc(key);
		glutVisibilityFunc(vis);
		glutReshapeFunc(reshape);
		glutDisplayFunc(display);
		glutMouseFunc(mouse);
		glutMotionFunc(motion);

		glutIdleFunc(display);

		glEnable( GL_DEPTH_TEST );
		glEnable( GL_LIGHTING );
		glEnable( GL_LIGHT0 );
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);

		// Window
		osg::GLUTWindowPtr gwin;
		GLint glvp[4];
		glGetIntegerv( GL_VIEWPORT, glvp );
		gwin = osg::GLUTWindow::create();
		gwin->setId(winid);
		gwin->setSize( glvp[2], glvp[3] );
		win = gwin;
		win->addPort( vp );

		// Action
		render_action = osg::DrawAction::create();

		// trackball
			Vec3f min(-2.5,-2.5,-2.5), max(2.5,2.5,2.5);
		trackball.setMode( osg::Trackball::OSGObject );
			float d = max[2] + (max[2]-min[2]);
		trackball.setStartPosition( 0, 0, d, true );
		trackball.setSum( true );
		trackball.setTranslationMode( osg::Trackball::OSGFree );
	}

	// create moving objects
	if ( geom_type != OBJ_FILE )
		createGeom( geom_type, Complexity, &fixed_node, &fixed_geom );
	// else: has been loaded from file
	light_node->addChild( fixed_node );

	if ( geom_type != OBJ_FILE )
		createGeom( geom_type, Complexity, &moving_node, &moving_geom );


	//#define DOPTREE_NUM_ORI 16

	double pi = 3.141592653589793f;
	vector<Vec3f> translates;
	vector<Vec3f> rotation_xyzs;
	vector<float> rotates;
	//string config("");
	if(configFile.length() == 0)
	{
		printf("config file is null, use -r configFileName\n");
		return 0;
	}

	ifstream fin(configFile.data());
    string line;
    int i = 0;
    int angle;
    float x,y,z;
    while(std::getline(fin, line))
    {
        stringstream ss;
        ss << line;
        if(i & 0x1) // tranls
        {
            ss >> x >> y >> z;
            translates.push_back(Vec3f(x,y,z));
            
        }else //angle rot
        {
Exemple #19
0
int main( int argc, char *argv[] )
{
	// parse command line options
	parsecommandline( argc, argv );


	// OSG init
	osg::osgLog().setLogLevel(osg::LOG_WARNING);
	osg::osgInit(argc, argv);

	// disable display lists
	osg::FieldContainerPtr pProto= osg::Geometry::getClassType().getPrototype();
	osg::GeometryPtr pGeoProto = osg::GeometryPtr::dcast(pProto);
    if ( pGeoProto != osg::NullFC )
        pGeoProto->setDlistCache(false);

	// create the graph
	osg::NodePtr node;

	// root
	root = osg::Node::create();
	beginEditCP(root);
	root->setCore( osg::Group::create() );

	// beacon for camera and light
	osg::NodePtr beacon;
	beacon = osg::Node::create();
	beginEditCP(beacon);
	beacon->setCore( osg::Group::create() );
	endEditCP(beacon);

	// light
	light_node = osg::Node::create();
	osg::DirectionalLightPtr light = osg::DirectionalLight::create();
	beginEditCP( light_node );
	light_node->setCore( light );
	endEditCP( light_node );
	root->addChild( light_node );
	beginEditCP(light);
	light->setAmbient( .3, .3, .3, 1 );
	light->setDiffuse( 1, 1, 1, 1 );
	light->setDirection(0,0,1);
	light->setBeacon( beacon );
	endEditCP(light);

	// transformation, parent of beacon
	node = osg::Node::create();
	cam_trans = osg::Transform::create();
	beginEditCP(node);
	node->setCore( cam_trans );
	node->addChild( beacon );
	endEditCP(node);
	root->addChild( node );

	// finish scene graph
	endEditCP(root);

	// Camera
	osg::PerspectiveCameraPtr cam = osg::PerspectiveCamera::create();
	cam->setBeacon( beacon );
	cam->setFov( 50 );
	cam->setNear( 0.1 );
	cam->setFar( 10000 );

	// Background
	osg::SolidBackgroundPtr background = osg::SolidBackground::create();

	// Viewport
	osg::ViewportPtr vp = osg::Viewport::create();
	vp->setCamera( cam );
	vp->setBackground( background );
	vp->setRoot( root );
	vp->setSize( 0,0, 1,1 );

	if ( with_window )
	{
		// GLUT init
		glutInitWindowSize( 400, 400 );		// before glutInit so user can
		glutInitWindowPosition( 100, 100 );	// override with comannd line args
		glutInit(&argc, argv);
		glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
		int winid = glutCreateWindow("Polygon Intersection Check Test");
		glutKeyboardFunc(key);
		glutVisibilityFunc(vis);
		glutReshapeFunc(reshape);
		glutDisplayFunc(display);
		glutMouseFunc(mouse);
		glutMotionFunc(motion);

		glutIdleFunc(display);

		glEnable( GL_DEPTH_TEST );
		glEnable( GL_LIGHTING );
		glEnable( GL_LIGHT0 );

		// Window
		osg::GLUTWindowPtr gwin;
		GLint glvp[4];
		glGetIntegerv( GL_VIEWPORT, glvp );
		gwin = osg::GLUTWindow::create();
		gwin->setId(winid);
		gwin->setSize( glvp[2], glvp[3] );
		win = gwin;
		win->addPort( vp );

		// Action
		render_action = osg::DrawAction::create();
		// trackball
		Vec3f min(-1,-1,-1), max(1,1,1);
		// root->updateVolume();
		// const osg::BoxVolume &vol = dynamic_cast<const osg::BoxVolume &>(root->getVolume());
		// // in the long term, the abstract volume will be able to provide min/max
		// vol.getBounds( min, max );
		trackball.setMode( osg::Trackball::OSGObject );
		float d = max[2] + (max[2]-min[2])*1.5;
		trackball.setStartPosition( 0, 0, d, true );
		trackball.setSum( true );
		trackball.setTranslationMode( osg::Trackball::OSGFree );

		// run...
		glutMainLoop();
	}
	else
	{
		// run in batch mode
		int phase = 0;
		do
			testcase( &phase );
		while ( phase > 0 );
	}

	return 0;
}
Exemple #20
0
	void SimulationEngine::createChildVisualEntity(osg::NodePtr parentNode, 
		/*osg::TransformPtr trans,*/ const opal::ShapeData* data, const std::string& name, 
		const std::string& materialName)
	{
		// Create an Ogre SceneNode for the Entity.		
		osg::Matrix m;
		
		opal::Point3r offsetPos = data->offset.getPosition();
		//Ogre::Vector3 translationOffset(offsetPos[0], offsetPos[1], 
			//offsetPos[2]);
		opal::Quaternion offsetQuat = data->offset.getQuaternion();
		//Ogre::Quaternion rotationOffset;
		//rotationOffset.x = offsetQuat.x;
		//rotationOffset.y = offsetQuat.y;
		//rotationOffset.z = offsetQuat.z;
		//rotationOffset.w = offsetQuat.w;
		
		//Ogre::SceneNode* newChildNode = NULL;
		//Ogre::Entity* e = NULL;
		
		// OSG covention: we need one new node and transformation
		osg::NodePtr newChildNode; //= osg::Node::create();
		osg::TransformPtr newTransCore = osg::Transform::create();	
		
		osg::beginEditCP(newTransCore);
			m.setIdentity();
				
   			m.setTranslate(
   						(osg::Real32)offsetPos[0], 
   						(osg::Real32)offsetPos[1], 
						(osg::Real32)offsetPos[2]);
			
  			m.setRotate(
  						osg::Quaternion(
  							osg::Vec3f(
  								(osg::Real32)offsetQuat[1],
  								(osg::Real32)offsetQuat[2],
  								(osg::Real32)offsetQuat[3]), 
  							(osg::Real32)offsetQuat[0]));
  				
            newTransCore->setMatrix(m);
       	osg::endEditCP(newTransCore);
		
		switch(data->getType())
		{
			case opal::BOX_SHAPE:
			{				
				//newChildNode = parentNode->createChildSceneNode(name, 
					//translationOffset, rotationOffset);	

				// Scale the object according to the given dimensions.
				opal::Vec3r boxDim = static_cast<const opal::BoxShapeData*>
					(data)->dimensions;
					
				//Ogre::Vector3 dimensions(boxDim[0], boxDim[1], boxDim[2]);
				//newChildNode->scale(dimensions[0], dimensions[1], 
					//dimensions[2]);
					
				//create the geometry which we will assign a texture to
				newChildNode = osg::makeBox((osg::Real32)boxDim[0],
											(osg::Real32)boxDim[1],
											(osg::Real32)boxDim[2],1,1,1);

				// Create an Ogre Entity using a cube mesh.  This mesh must be 
				// stored as a box with dimensions 1x1x1.
				//e = mOgreSceneMgr->createEntity(name, "cube.mesh");
				//e->setMaterialName(materialName);

				// Keep the normals normalized even after scaling.
				//e->setNormaliseNormals(true);

				// Attach the Entity to the SceneNode.
				//newChildNode->attachObject(e);
				
				//osg::beginEditCP(parentNode, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);
				osg::beginEditCP(parentNode);
    				parentNode->setCore(newTransCore);
    				parentNode->addChild(newChildNode);
    			osg::endEditCP(parentNode);
				//osg::endEditCP(parentNode, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);				
				  				
				break;
			}

			case opal::SPHERE_SHAPE:
			{
				//newChildNode = parentNode->createChildSceneNode(name, 
					//translationOffset, rotationOffset);

				// Scale the object according to the given dimensions.
				//Ogre::Real radius = static_cast<const opal::SphereShapeData*>
					//(data)->radius;
				//newChildNode->scale(radius, radius, radius);
				
				opal::real radius = static_cast<const opal::SphereShapeData*>
					(data)->radius;
					
				newChildNode = osg::makeSphere(3, (osg::Real32)radius);

				// Create an Ogre Entity using a sphere mesh.  This mesh must be 
				// stored as a sphere with radius 1.
				//e = mOgreSceneMgr->createEntity(name, "sphere.mesh");
				//e->setMaterialName(materialName);

				// Keep the normals normalized even after scaling.
				//e->setNormaliseNormals(true);

				// Attach the Entity to the SceneNode.
				//newChildNode->attachObject(e);
				
				//osg::beginEditCP(parentNode, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);
				osg::beginEditCP(parentNode);
    				parentNode->setCore(newTransCore);
    				parentNode->addChild(newChildNode);
    			osg::endEditCP(parentNode);
				//osg::endEditCP(parentNode, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);				
								
				break;
			}
		
			case opal::CAPSULE_SHAPE:
			{
				osg::NodePtr capsule =  osg::Node::create();
        		osg::NodePtr topcap  =  osg::Node::create();
       			osg::NodePtr botcap  =  osg::Node::create();  
        		     
				// Create an Ogre SceneNode for the cylinder Entity.
				std::string subObjectName = "cylinder" + name;
				//newChildNode = parentNode->createChildSceneNode(
					//subObjectName, translationOffset, rotationOffset);

				// Scale the object according to the given dimensions.  This 
				// will also scale the transforms for the child nodes, but 
				// we disable the "inherit scale" option for child nodes 
				// here so the shapes themselves don't get scaled.
				//Ogre::Real radius = static_cast<const opal::CapsuleShapeData*>
					//(data)->radius;
				opal::real radius = static_cast<const opal::CapsuleShapeData*>
					(data)->radius;
				//Ogre::Real length = static_cast<const opal::CapsuleShapeData*>
					//(data)->length;
				opal::real length = static_cast<const opal::CapsuleShapeData*>
					(data)->length;
				//newChildNode->scale(radius, radius, length);

				osg::NodePtr cyl = osg::makeCylinder((osg::Real32)length,
													 (osg::Real32)radius,
													 40,true,false,false); 
				
				// This mesh must be stored as a cylinder with length 1 and 
				// radius 1.
				//e = mOgreSceneMgr->createEntity(subObjectName, "cylinder.mesh");
				//e->setMaterialName(materialName);
				//e->setNormaliseNormals(true);
				//newChildNode->attachObject(e);

				// The spheres must use separate scene nodes that are offset 
				// from the cylinder's scene node.

				// This mesh must be stored as a sphere with radius 1.
				subObjectName = "sphere0" + name;
				//Ogre::SceneNode* sphereNode = newChildNode->createChildSceneNode(
					//subObjectName);
				//sphereNode->setInheritScale(false);
				//sphereNode->translate(0, 0, -0.5);
				//sphereNode->scale(radius, radius, radius);
				//e = mOgreSceneMgr->createEntity(subObjectName, "sphere.mesh");
				//e->setMaterialName(materialName);
				//e->setNormaliseNormals(true);
				//sphereNode->attachObject(e);
				
				osg::NodePtr topGeo = osg::makeSphere(3,(osg::Real32)radius);     
				//one geometry and one transform node        
        		osg::TransformPtr topTr = osg::Transform::create();
        		osg::Matrix _m;
  				//osg::beginEditCP(tChimney, osg::Transform::MatrixFieldMask);
  				osg::beginEditCP(topTr);
      				_m.setIdentity();
      				_m.setTranslate(0,(osg::Real32)length/2.0,0);
      				topTr->setMatrix(_m);
      			osg::endEditCP(topTr);
  				//osg::endEditCP(tChimney, osg::Transform::MatrixFieldMask);

  				//osg::beginEditCP(chimneyTrans, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);
  				osg::beginEditCP(topcap);
      				topcap->setCore(topTr);
      				topcap->addChild(topGeo);
      			osg::endEditCP(topcap);
  				//osg::endEditCP(chimneyTrans, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);
  		   		
				subObjectName = "sphere1" + name;
				//sphereNode = newChildNode->createChildSceneNode(subObjectName);
				//sphereNode->setInheritScale(false);
				//sphereNode->translate(0, 0, 0.5);
				//sphereNode->scale(radius, radius, radius);
				//e = mOgreSceneMgr->createEntity(subObjectName, "sphere.mesh");
				//e->setMaterialName(materialName);
				//e->setNormaliseNormals(true);
				//sphereNode->attachObject(e);
				
				osg::NodePtr botGeo = osg::makeSphere(3,(osg::Real32)radius);
				osg::TransformPtr botTr = osg::Transform::create();
  				osg::Matrix _n;
  				//osg::beginEditCP(tChimney, osg::Transform::MatrixFieldMask);
  				osg::beginEditCP(botTr);
      				_n.setIdentity();
      				_n.setTranslate(0,-(osg::Real32)length/2.0,0);
      				botTr->setMatrix(_n);
      			osg::endEditCP(botTr);
  				//osg::endEditCP(tChimney, osg::Transform::MatrixFieldMask);

  				//osg::beginEditCP(chimneyTrans, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);
  				osg::beginEditCP(botcap);
      				botcap->setCore(botTr);
      				botcap->addChild(botGeo);
      			osg::endEditCP(botcap);
  				//osg::endEditCP(chimneyTrans, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);
  		
  				// Finally Compose everything to a Capsule!!
        		osg::beginEditCP(capsule);
        			capsule->setCore(osg::Group::create());
    				capsule->addChild(cyl);
    				capsule->addChild(topcap);
    				capsule->addChild(botcap);
    			osg::endEditCP(capsule);
    			
    			// OK send to new scene noe
    			newChildNode = capsule;
    			
    			//osg::beginEditCP(parentNode, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);
				osg::beginEditCP(parentNode);
    				parentNode->setCore(newTransCore);
    				parentNode->addChild(newChildNode);
    			osg::endEditCP(parentNode);
				//osg::endEditCP(parentNode, osg::Node::CoreFieldMask | osg::Node::ChildrenFieldMask);				
			
				break;
			}
		
			default:
				assert(false);
				break;
		}
	}
// No arguments: batch convert all vt* files
// switch argument: batch convert all vt* files into one osb file with a switch
// file argument: convert only the specified file
int main (int argc, char const* argv[])
{
	vector<string> filenames;
	bool useSwitch = false;
	if (argc == 2)
	{
		if (string(argv[1]).find("switch") != string::npos)
			useSwitch = true;
		else
			filenames.push_back(string(argv[1]));
	}

	if (useSwitch || filenames.empty())
	{
		const boost::regex e(".+\\.vt[a-z]");
		directory_iterator end;
		for (directory_iterator it("./"); it != end; ++it)
		{
			string curFile = it->path().filename().string();
			if (regex_match(curFile, e))
				filenames.push_back(curFile);
		}
	}

	OSG::osgInit(0, NULL);

	vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();
	OSG::NodePtr switchNode = OSG::Node::create();
	OSG::SwitchPtr switchCore = OSG::Switch::create();
	beginEditCP(switchCore);
	switchCore->setChoice(0);
	endEditCP(switchCore);
	beginEditCP(switchNode);
	switchNode->setCore(switchCore);
	endEditCP(switchNode);

	for (vector<string>::const_iterator it = filenames.begin(); it != filenames.end(); ++it)
	{
		string filename(*it);
		cout << "Opening file " << filename << " ... " << endl << flush;
		string fileExt = getFileExt(filename);

		vtkXMLDataReader* reader = NULL;
		vtkGenericDataObjectReader* oldStyleReader = NULL;
		if (fileExt.find("vti") != string::npos)
		{
			reader = vtkXMLImageDataReader::New();
			vtkSmartPointer<vtkImageDataGeometryFilter> geoFilter =
			        vtkSmartPointer<vtkImageDataGeometryFilter>::New();
			geoFilter->SetInputConnection(reader->GetOutputPort());
			mapper->SetInputConnection(geoFilter->GetOutputPort());
		}
		if (fileExt.find("vtr") != string::npos)
		{
			reader = vtkXMLRectilinearGridReader::New();
			vtkSmartPointer<vtkGeometryFilter> geoFilter =
			        vtkSmartPointer<vtkGeometryFilter>::New();
			geoFilter->SetInputConnection(reader->GetOutputPort());
			mapper->SetInputConnection(geoFilter->GetOutputPort());
		}
		else if (fileExt.find("vts") != string::npos)
		{
			reader = vtkXMLStructuredGridReader::New();
			vtkSmartPointer<vtkGeometryFilter> geoFilter =
			        vtkSmartPointer<vtkGeometryFilter>::New();
			geoFilter->SetInputConnection(reader->GetOutputPort());
			mapper->SetInputConnection(geoFilter->GetOutputPort());
		}
		else if (fileExt.find("vtp") != string::npos)
		{
			reader = vtkXMLPolyDataReader::New();
			mapper->SetInputConnection(reader->GetOutputPort());
		}
		else if (fileExt.find("vtu") != string::npos)
		{
			reader = vtkXMLUnstructuredGridReader::New();
			vtkSmartPointer<vtkGeometryFilter> geoFilter =
			        vtkSmartPointer<vtkGeometryFilter>::New();
			geoFilter->SetInputConnection(reader->GetOutputPort());
			mapper->SetInputConnection(geoFilter->GetOutputPort());
		}
		else if (fileExt.find("vtk") != string::npos)
		{
			oldStyleReader = vtkGenericDataObjectReader::New();
			oldStyleReader->SetFileName(filename.c_str());
			oldStyleReader->Update();
			if(oldStyleReader->IsFilePolyData())
				mapper->SetInputConnection(oldStyleReader->GetOutputPort());
			else
			{
				vtkSmartPointer<vtkGeometryFilter> geoFilter =
				        vtkSmartPointer<vtkGeometryFilter>::New();
				geoFilter->SetInputConnection(oldStyleReader->GetOutputPort());
				mapper->SetInputConnection(geoFilter->GetOutputPort());
			}
		}
		else
		{
			cout << "Not a valid vtk file ending (vti, vtr, vts, vtp, vtu, vtk)" <<
			endl;
			return 1;
		}

		if (fileExt.find("vtk") == string::npos)
		{
			reader->SetFileName(filename.c_str());
			reader->Update();
		}

		vtkActor* actor = vtkActor::New();
		actor->SetMapper(mapper);

		vtkOsgConverter converter(actor);
		converter.SetVerbose(true);
		//converter->SetMapper(mapper);
		converter.WriteAnActor();
		OSG::NodePtr node = converter.GetOsgNode();
		replaceExt(filename, "osb");
		if (useSwitch)
		{
			beginEditCP(switchNode);
			switchNode->addChild(node);
			endEditCP(switchNode);
		}
		else
			OSG::SceneFileHandler::the().write(node, filename.c_str());

		if (reader)
			reader->Delete();
		if (oldStyleReader)
			oldStyleReader->Delete();
	}
	if (useSwitch)
	{
		string filename(filenames[0]);
		replaceExt(filename, "osb");
		OSG::SceneFileHandler::the().write(switchNode, filename.c_str());
	}
	//mapper->Delete(); // TODO crashes

	OSG::osgExit();

	cout << "File conversion finished" << endl;

	return 0;
}
Exemple #22
0
CameraPtr Camera::init()
{
   // Create a transform to contain the location and orientation of the camera.
   mTransform = OSG::Transform::create();

   OSG::NodePtr beacon = OSG::Node::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor be(beacon, OSG::Node::CoreFieldMask);
#endif
   beacon->setCore(mTransform);

   mLeftTexture = tex_chunk_t::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor lte(mLeftTexture);
   mLeftTexture->setEnvMode(GL_MODULATE);
#else
   mLeftTexEnv = OSG::TextureEnvChunk::create();
   mLeftTexEnv->setEnvMode(GL_MODULATE);
#endif

   mRightTexture = tex_chunk_t::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor rte(mRightTexture);
   mRightTexture->setEnvMode(GL_MODULATE);
#else
   mRightTexEnv = OSG::TextureEnvChunk::create();
   mRightTexEnv->setEnvMode(GL_MODULATE);
#endif

   mCurrentTexture = mLeftTexture;
#if OSG_MAJOR_VERSION >= 2
   mCurrentTexEnv = mLeftTexEnv;
#endif

   // setup camera
   mCamera = OSG::PerspectiveCamera::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor ce(mCamera);
#endif
   mCamera->setFov(
#if OSG_MAJOR_VERSION < 2
      OSG::osgdegree2rad(60.0)
#else
      OSG::osgDegree2Rad(60.0)
#endif
   );
   mCamera->setNear(0.01);
   mCamera->setFar(10000);
   mCamera->setBeacon(beacon);

   mLeftImage = OSG::Image::create();
   mRightImage = OSG::Image::create();

   OSG::ImagePtr img;

   // Set up FBO textures.
   img = mLeftImage;
   mLeftTexture->setMinFilter(GL_LINEAR);
   mLeftTexture->setMagFilter(GL_LINEAR);
   mLeftTexture->setTarget(GL_TEXTURE_2D);
   mLeftTexture->setInternalFormat(GL_RGBA8);
   mLeftTexture->setImage(img);

   img = mRightImage;
   mRightTexture->setMinFilter(GL_LINEAR);
   mRightTexture->setMagFilter(GL_LINEAR);
   mRightTexture->setTarget(GL_TEXTURE_2D);
   mRightTexture->setInternalFormat(GL_RGBA8);
   mRightTexture->setImage(img);

   mCurrentImage = mLeftImage;

   return shared_from_this();
}