用OpenSceneGraph实现的NeHe OpenGL教程 - 第十二课

  • 简介

本课NeHe教程主要是使用了OpenGL中的显示列表。OpenGL的显示列表是加速OpenGL性能的一种重要的手段。OpenGl的几何体绘制方法主要包括立即模式、顶点数组、显示列表和VBO。在OSG中显示列表是大部分OSG程序所使用的默认绘制优化行为,因此不需要我们去像OpenGL那样进行设置。

  • 实现

首先创建整个场景,本课中我使用了OSG中预定义的几种基本形体,(osg::Box)来绘制立方体

osg::Node*	buildScene()
{
	osg::Group *root = new osg::Group;

	for (int yloop=1;yloop<6;yloop++)
	{
		osg::Group *cubeGroup = new osg::Group;

		for (int xloop=0;xloop<yloop;xloop++)
		{
			osg::MatrixTransform *posMT = new osg::MatrixTransform;
			posMT->setMatrix(osg::Matrix::translate(1.4f+(float(xloop)*2.8f)-(float(yloop)*1.4f),((6.0f-float(yloop))*2.4f)-7.0f,-20.0f));
			cubeGroup->addChild(posMT);
			
			osg::MatrixTransform *rotXMT = new osg::MatrixTransform;
			rotXMT->setName("XRotMT");
			posMT->addChild(rotXMT);
			XRotCallback* xrot = new XRotCallback(osg::DegreesToRadians(45.0f-(2.0f*yloop)));
			rotXMT->setUpdateCallback(xrot);

			osg::MatrixTransform *rotYMT = new osg::MatrixTransform;
			rotXMT->addChild(rotYMT);
			rotYMT->setName("YRotMT");
			YRotCallback* yrot = new YRotCallback(osg::DegreesToRadians(45.0f));
			rotYMT->setUpdateCallback(yrot);

			osg::Geode *cube = createCube(yloop-1);
			rotYMT->addChild(cube);
		}
		root->addChild(cubeGroup);
	}

	return root;
}
参照NeHe教程中平移量进行(glTranslate对应一个osg::MatrixTransform),对于每一个几何体叶节点,通过不同的颜色索引值创建它

osg::Geode* createCube(int colorIndex)
{
	osg::Image *textureImage = osgDB::readImageFile("Data/Cube.bmp");
	osg::Texture2D *texture2D = new osg::Texture2D;
	texture2D->setImage(textureImage);
	texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
	texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);

	osg::ShapeDrawable *sd = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, 0), 2));
	sd->setColor(osg::Vec4d(boxcol[colorIndex][0], boxcol[colorIndex][1], boxcol[colorIndex][2], 1));

	osg::Geode *cubeGeode = new osg::Geode;
	cubeGeode->addDrawable(sd);
	cubeGeode->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);

	return cubeGeode;
}

可以看到场景中对每一个MatrixTransform均设置了UpdateCallback,为的是通过键盘对它们进行操作。首先先通过名字找到所有这些节点

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
	FindNamedNodeVisitor(const std::string& name):
	  osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
		  _name(name), _foundNode(NULL) {}

	  virtual void apply(osg::Node& node)
	  {
		  if (node.getName()==_name)
		  {
			  _foundNode.push_back(&node);
		  }
		  traverse(node);
	  }

	  std::string _name;
	  std::vector<osg::Node*> _foundNode;
};

在EventHandler交互类中进行设置如下:

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Left)
				{
					FindNamedNodeVisitor fnnv("YRotMT");
					root->accept(fnnv);

					for (unsigned i = 0; i < fnnv._foundNode.size(); ++i)
					{
						yrot = dynamic_cast<YRotCallback*>(fnnv._foundNode.at(i)->getUpdateCallback());
						if (yrot)
						{
							yrot->setAngle(yrot->getAngle() - osg::DegreesToRadians(2.0));
						}
					}
				}
编译运行程序

用OpenSceneGraph实现的NeHe OpenGL教程 - 第十二课_第1张图片

附:本课源码(源码中可能存在错误和不足,仅供参考)

#include "../osgNeHe.h"

#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QVBoxLayout>

#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osgQt/GraphicsWindowQt>

#include <osg/MatrixTransform>

#include <osgDB/ReadFile>
#include <osg/Texture2D>

#include <osg/ShapeDrawable>
#include <osg/NodeVisitor>

static GLfloat boxcol[5][3]=
{
	{1.0f,0.0f,0.0f},{1.0f,0.5f,0.0f},{1.0f,1.0f,0.0f},{0.0f,1.0f,0.0f},{0.0f,1.0f,1.0f}
};

//////////////////////////////////////////////////////////////////////////
//RotCallback

class XRotCallback : public osg::NodeCallback
{
public:

	XRotCallback(double angle) : _angle(angle){}

	virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
	{

		if (dynamic_cast<osg::MatrixTransform*>(node))
		{
			osg::MatrixTransform *rot = dynamic_cast<osg::MatrixTransform*>(node);
			rot->setMatrix(osg::Matrix::rotate(_angle, osg::X_AXIS));
		}

		traverse(node, nv);
	}

	void setAngle(double angle)
	{
		_angle = angle;
	}

	double getAngle() const
	{
		return _angle;
	}

	double _angle;
};


class YRotCallback : public osg::NodeCallback
{
public:

	YRotCallback(double angle) : _angle(angle){}

	virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
	{

		if (dynamic_cast<osg::MatrixTransform*>(node))
		{
			osg::MatrixTransform *rot = dynamic_cast<osg::MatrixTransform*>(node);
			rot->setMatrix(osg::Matrix::rotate(_angle, osg::Y_AXIS));
		}

		traverse(node, nv);
	}

	void setAngle(double angle)
	{
		_angle = angle;
	}

	double getAngle() const
	{
		return _angle;
	}

	double _angle;
};

//End
//////////////////////////////////////////////////////////////////////////

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
	FindNamedNodeVisitor(const std::string& name):
	  osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
		  _name(name), _foundNode(NULL) {}

	  virtual void apply(osg::Node& node)
	  {
		  if (node.getName()==_name)
		  {
			  _foundNode.push_back(&node);
		  }
		  traverse(node);
	  }

	  std::string _name;
	  std::vector<osg::Node*> _foundNode;
};



//////////////////////////////////////////////////////////////////////////
//EventHandler
class ManipulatorSceneHandler : public osgGA::GUIEventHandler
{
public:
	ManipulatorSceneHandler()
	{
	}

	virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
	{
		osgViewer::Viewer *viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
		if (!viewer)
			return false;
		if (!viewer->getSceneData())
			return false;
		if (ea.getHandled()) 
			return false;

		osg::Group *root = viewer->getSceneData()->asGroup();

		switch(ea.getEventType())
		{
		case(osgGA::GUIEventAdapter::KEYDOWN):
			{
				XRotCallback *xrot;
				YRotCallback *yrot;

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Left)
				{
					FindNamedNodeVisitor fnnv("YRotMT");
					root->accept(fnnv);

					for (unsigned i = 0; i < fnnv._foundNode.size(); ++i)
					{
						yrot = dynamic_cast<YRotCallback*>(fnnv._foundNode.at(i)->getUpdateCallback());
						if (yrot)
						{
							yrot->setAngle(yrot->getAngle() - osg::DegreesToRadians(2.0));
						}
					}
				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Right)
				{
					FindNamedNodeVisitor fnnv("YRotMT");
					root->accept(fnnv);

					for (unsigned i = 0; i < fnnv._foundNode.size(); ++i)
					{
						yrot = dynamic_cast<YRotCallback*>(fnnv._foundNode.at(i)->getUpdateCallback());
						if (yrot)
						{
							yrot->setAngle(yrot->getAngle() + osg::DegreesToRadians(2.0));
						}
					}
				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Up)
				{
					FindNamedNodeVisitor fnnv("XRotMT");
					root->accept(fnnv);

					for (unsigned i = 0; i < fnnv._foundNode.size(); ++i)
					{
						xrot = dynamic_cast<XRotCallback*>(fnnv._foundNode.at(i)->getUpdateCallback());
						if (xrot)
						{
							xrot->setAngle(xrot->getAngle() - osg::DegreesToRadians(2.0));
						}
					}
				}

				if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Down)
				{
					FindNamedNodeVisitor fnnv("XRotMT");
					root->accept(fnnv);

					for (unsigned i = 0; i < fnnv._foundNode.size(); ++i)
					{
						xrot = dynamic_cast<XRotCallback*>(fnnv._foundNode.at(i)->getUpdateCallback());
						if (xrot)
						{
							xrot->setAngle(xrot->getAngle() + osg::DegreesToRadians(2.0));
						}
					}
				}
			}
		default: break;
		}
		return false;
	}
};


//End
//////////////////////////////////////////////////////////////////////////


class ViewerWidget : public QWidget, public osgViewer::Viewer
{
public:
	ViewerWidget(osg::Node *scene = NULL)
	{
		QWidget* renderWidget = getRenderWidget( createGraphicsWindow(0,0,100,100), scene);

		QVBoxLayout* layout = new QVBoxLayout;
		layout->addWidget(renderWidget);
		layout->setContentsMargins(0, 0, 0, 1);
		setLayout( layout );

		connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
		_timer.start( 10 );
	}

	QWidget* getRenderWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene )
	{
		osg::Camera* camera = this->getCamera();
		camera->setGraphicsContext( gw );

		const osg::GraphicsContext::Traits* traits = gw->getTraits();

		camera->setClearColor( osg::Vec4(0.0, 0.0, 0.0, 1.0) );
		camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
		camera->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 0.1f, 100.0f );
		camera->setViewMatrixAsLookAt(osg::Vec3d(0, 0, 1), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0));

		this->setSceneData( scene );
		this->addEventHandler(new ManipulatorSceneHandler);

		return gw->getGLWidget();
	}

	osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false )
	{
		osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
		osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
		traits->windowName = name;
		traits->windowDecoration = windowDecoration;
		traits->x = x;
		traits->y = y;
		traits->width = w;
		traits->height = h;
		traits->doubleBuffer = true;
		traits->alpha = ds->getMinimumNumAlphaBits();
		traits->stencil = ds->getMinimumNumStencilBits();
		traits->sampleBuffers = ds->getMultiSamples();
		traits->samples = ds->getNumMultiSamples();

		return new osgQt::GraphicsWindowQt(traits.get());
	}

	virtual void paintEvent( QPaintEvent* event )
	{ 
		frame(); 
	}

protected:

	QTimer _timer;
};


osg::Geode* createCube(int colorIndex)
{
	osg::Image *textureImage = osgDB::readImageFile("Data/Cube.bmp");
	osg::Texture2D *texture2D = new osg::Texture2D;
	texture2D->setImage(textureImage);
	texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
	texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);

	osg::ShapeDrawable *sd = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0, 0, 0), 2));
	sd->setColor(osg::Vec4d(boxcol[colorIndex][0], boxcol[colorIndex][1], boxcol[colorIndex][2], 1));

	osg::Geode *cubeGeode = new osg::Geode;
	cubeGeode->addDrawable(sd);
	cubeGeode->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);

	return cubeGeode;
}


osg::Node*	buildScene()
{
	osg::Group *root = new osg::Group;

	for (int yloop=1;yloop<6;yloop++)
	{
		osg::Group *cubeGroup = new osg::Group;

		for (int xloop=0;xloop<yloop;xloop++)
		{
			osg::MatrixTransform *posMT = new osg::MatrixTransform;
			posMT->setMatrix(osg::Matrix::translate(1.4f+(float(xloop)*2.8f)-(float(yloop)*1.4f),((6.0f-float(yloop))*2.4f)-7.0f,-20.0f));
			cubeGroup->addChild(posMT);
			
			osg::MatrixTransform *rotXMT = new osg::MatrixTransform;
			rotXMT->setName("XRotMT");
			posMT->addChild(rotXMT);
			XRotCallback* xrot = new XRotCallback(osg::DegreesToRadians(45.0f-(2.0f*yloop)));
			rotXMT->setUpdateCallback(xrot);

			osg::MatrixTransform *rotYMT = new osg::MatrixTransform;
			rotXMT->addChild(rotYMT);
			rotYMT->setName("YRotMT");
			YRotCallback* yrot = new YRotCallback(osg::DegreesToRadians(45.0f));
			rotYMT->setUpdateCallback(yrot);

			osg::Geode *cube = createCube(yloop-1);
			rotYMT->addChild(cube);
		}
		root->addChild(cubeGroup);
	}

	return root;
}



int main( int argc, char** argv )
{
	QApplication app(argc, argv);
	ViewerWidget* viewWidget = new ViewerWidget(buildScene());
	viewWidget->setGeometry( 100, 100, 640, 480 );
	viewWidget->show();
	return app.exec();
}




你可能感兴趣的:(C++,qt,OpenGL,nehe,OSG)