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

  • 简介

这节课我们将学习使用环境纹理映射。这种映射方式可以让物体表面看上去像镜子一样反射周围的环境。这节课的代码是在前面第十八节课程的基础上修改的。

  • 实现

本课的实现过程十分的简单,在几何体的生成中添加一个环境纹理osg::TexGen属性即可。

首先创建背景几何体

osg::Group*	createBackGroup()
{
	osg::Group *backGroup = new osg::Group;
	osg::Geode*	bgGeode = new osg::Geode;
	osg::Geometry *bgGeometry = new osg::Geometry;

	osg::Vec3Array *verticesArray = new osg::Vec3Array;
	verticesArray->push_back(osg::Vec3(-13.3f, -10.0f,  10.0f));
	verticesArray->push_back(osg::Vec3(13.3f, -10.0f,  10.0f));
	verticesArray->push_back(osg::Vec3(13.3f,  10.0f,  10.0f));
	verticesArray->push_back(osg::Vec3(-13.3f,  10.0f,  10.0f));
	osg::Vec3Array *verticesNormal = new osg::Vec3Array;
	verticesNormal->push_back(osg::Vec3(0.0f, 0.0f, 1.0f));
	osg::Vec2Array *texArray = new osg::Vec2Array;
	texArray->push_back(osg::Vec2(0.0f, 0.0f));
	texArray->push_back(osg::Vec2(1.0f, 0.0f));
	texArray->push_back(osg::Vec2(1.0f, 1.0f));
	texArray->push_back(osg::Vec2(0.0f, 1.0f));

	osg::Texture2D *texture = new osg::Texture2D;
	texture->setImage(osgDB::readImageFile("Data/BG.bmp"));
	texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
	texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);

	bgGeometry->setVertexArray(verticesArray);
	bgGeometry->setNormalArray(verticesNormal, osg::Array::BIND_OVERALL);
	bgGeometry->setTexCoordArray(0, texArray);
	bgGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4));
	bgGeometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture);

	bgGeode->addDrawable(bgGeometry);

	osg::MatrixTransform *zoomMT = new osg::MatrixTransform;
	zoomMT->setMatrix(osg::Matrix::translate(0, 0, -24));

	backGroup->addChild(zoomMT);
	zoomMT->addChild(bgGeode);

	return backGroup;
}
接着给几何体添加TexGen的属性,按照NeHe课程中的设置:

	osg::TexGen *texGen = new osg::TexGen;
	texGen->setMode(osg::TexGen::SPHERE_MAP);
	g_Switch->getOrCreateStateSet()->setTextureAttributeAndModes(0, texGen);

这里我们将节点的属性设置给它的父节点,默认情况下子节点会继承父节点的属性,我们也可以强制使用osg::StateAttribute::OVERRIDE设置。

接下来将两个节点添加到场景中:

	quadYRotMT->addChild(g_Switch);
	quadXRotMT->addChild(quadYRotMT);
	quadMT->addChild(quadXRotMT);

	root->addChild(quadMT);
	root->addChild(createBackGroup());
编译运行程序:

用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 <osg/NodeVisitor>
#include <osg/Texture2D>

#include <osgGA/GUIEventAdapter>

#include <osg/Light>
#include <osg/LightModel>
#include <osg/LightSource>

#include <osg/ShapeDrawable>
#include <osg/Switch>

#include <osg/TexGen>


//////////////////////////////////////////////////////////////////////////
//开关节点
osg::Switch		*g_Switch;

//////////////////////////////////////////////////////////////////////////
//FindFirstNamedNodeVisitor用来遍历寻找与指定名称相同的节点

class FindFirstNamedNodeVisitor : public osg::NodeVisitor
{
public:
	FindFirstNamedNodeVisitor(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 = &node;
			  return;
		  }
		  traverse(node);
	  }

	  std::string _name;
	  osg::Node *_foundNode;
};

//////////////////////////////////////////////////////////////////////////
//RotateCallback

class RotateCallback : public osg::NodeCallback
{

public:
	RotateCallback(osg::Vec3d rotateAxis, double rotateSpeed) : 
	  osg::NodeCallback(),
		  _rotateAxis(rotateAxis), 
		  _rotateSpeed(rotateSpeed),
		  _rotateAngle(0.0)
	  {
		  //Nop
	  }

	  void setRotateSpeed(double speed)
	  {
		  _rotateSpeed = speed;
	  }

	  double getRotateSpeed() const
	  {
		  return _rotateSpeed;
	  }

	  virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
	  {
		  osg::MatrixTransform *currentMT = dynamic_cast<osg::MatrixTransform*>(node);
		  if (currentMT)
		  {
			  //获取当前的平移位置
			  osg::Vec3d currentTranslate = currentMT->getMatrix().getTrans();
			  osg::Matrix newMatrix = osg::Matrix::rotate(_rotateAngle, _rotateAxis) * osg::Matrix::translate(currentTranslate);
			  currentMT->setMatrix(newMatrix);
			  _rotateAngle += _rotateSpeed;
		  }

		  traverse(node, nv);
	  }


private:
	osg::Vec3d _rotateAxis;			//旋转轴
	double        _rotateSpeed;		//旋转速度
	double        _rotateAngle;		//当前旋转的角度
};




//////////////////////////////////////////////////////////////////////////

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):
			{
				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Left)
				{
					FindFirstNamedNodeVisitor fnv("yRotMT");
					root->accept(fnv);

					osg::Node *mtNode = fnv._foundNode;
					osg::MatrixTransform *yRotMT = dynamic_cast<osg::MatrixTransform*>(mtNode);
					if (!yRotMT)
						return false;

					RotateCallback *rotCallback = dynamic_cast<RotateCallback*>(yRotMT->getUpdateCallback());

					if (!rotCallback)
						return false;

					double speed = rotCallback->getRotateSpeed();
					speed += 0.02;
					rotCallback->setRotateSpeed(speed);

				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Right)
				{
					FindFirstNamedNodeVisitor fnv("yRotMT");
					root->accept(fnv);

					osg::Node *mtNode = fnv._foundNode;
					osg::MatrixTransform *yRotMT = dynamic_cast<osg::MatrixTransform*>(mtNode);
					if (!yRotMT)
						return false;

					RotateCallback *rotCallback = dynamic_cast<RotateCallback*>(yRotMT->getUpdateCallback());

					if (!rotCallback)
						return false;

					double speed = rotCallback->getRotateSpeed();
					speed -= 0.02;
					rotCallback->setRotateSpeed(speed);
				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Up)
				{
					FindFirstNamedNodeVisitor fnv("xRotMT");
					root->accept(fnv);

					osg::Node *mtNode = fnv._foundNode;
					osg::MatrixTransform *xRotMT = dynamic_cast<osg::MatrixTransform*>(mtNode);
					if (!xRotMT)
						return false;

					RotateCallback *rotCallback = dynamic_cast<RotateCallback*>(xRotMT->getUpdateCallback());

					if (!rotCallback)
						return false;

					double speed = rotCallback->getRotateSpeed();
					speed += 0.02;
					rotCallback->setRotateSpeed(speed);
				}

				if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Down)
				{
					FindFirstNamedNodeVisitor fnv("xRotMT");
					root->accept(fnv);

					osg::Node *mtNode = fnv._foundNode;
					osg::MatrixTransform *xRotMT = dynamic_cast<osg::MatrixTransform*>(mtNode);
					if (!xRotMT)
						return false;

					RotateCallback *rotCallback = dynamic_cast<RotateCallback*>(xRotMT->getUpdateCallback());

					if (!rotCallback)
						return false;

					double speed = rotCallback->getRotateSpeed();
					speed -= 0.02;
					rotCallback->setRotateSpeed(speed);
				}

				if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Page_Up)
				{	
					FindFirstNamedNodeVisitor fnv("zoomMT");
					root->accept(fnv);

					osg::Node *mtNode = fnv._foundNode;
					osg::MatrixTransform *zoomMT = dynamic_cast<osg::MatrixTransform*>(mtNode);
					if (!zoomMT)
						return false;

					osg::Vec3 trans = zoomMT->getMatrix().getTrans();
					trans.set(trans.x(), trans.y(), trans.z() + 0.2);
					zoomMT->setMatrix(osg::Matrix::translate(trans));
				}

				if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Page_Down)
				{
					FindFirstNamedNodeVisitor fnv("zoomMT");
					root->accept(fnv);

					osg::Node *mtNode = fnv._foundNode;
					osg::MatrixTransform *zoomMT = dynamic_cast<osg::MatrixTransform*>(mtNode);
					if (!zoomMT)
						return false;

					osg::Vec3 trans = zoomMT->getMatrix().getTrans();
					trans.set(trans.x(), trans.y(), trans.z() - 0.2);
					zoomMT->setMatrix(osg::Matrix::translate(trans));
				}

				if (ea.getKey()== osgGA::GUIEventAdapter::KEY_L)
				{
					static int i = 0;
					if (i % 2 == 0) {
						root->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
					} else {
						root->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::ON);
					}
					++i;
				}
				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Space)
				{
					static int index = 0;
					g_Switch->setSingleChildOn(++index % 4);
				}

			}
		default: break;
		}
		return false;
	}
};

//////////////////////////////////////////////////////////////////////////

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));

		osg::StateSet* globalStateset = camera->getStateSet();
		if (globalStateset)
		{
			osg::LightModel* lightModel = new osg::LightModel;
			lightModel->setAmbientIntensity(osg::Vec4(0,0,0,0));
			globalStateset->setAttributeAndModes(lightModel, osg::StateAttribute::ON);
		}

		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::Group*	createBackGroup()
{
	osg::Group *backGroup = new osg::Group;
	osg::Geode*	bgGeode = new osg::Geode;
	osg::Geometry *bgGeometry = new osg::Geometry;

	osg::Vec3Array *verticesArray = new osg::Vec3Array;
	verticesArray->push_back(osg::Vec3(-13.3f, -10.0f,  10.0f));
	verticesArray->push_back(osg::Vec3(13.3f, -10.0f,  10.0f));
	verticesArray->push_back(osg::Vec3(13.3f,  10.0f,  10.0f));
	verticesArray->push_back(osg::Vec3(-13.3f,  10.0f,  10.0f));
	osg::Vec3Array *verticesNormal = new osg::Vec3Array;
	verticesNormal->push_back(osg::Vec3(0.0f, 0.0f, 1.0f));
	osg::Vec2Array *texArray = new osg::Vec2Array;
	texArray->push_back(osg::Vec2(0.0f, 0.0f));
	texArray->push_back(osg::Vec2(1.0f, 0.0f));
	texArray->push_back(osg::Vec2(1.0f, 1.0f));
	texArray->push_back(osg::Vec2(0.0f, 1.0f));

	osg::Texture2D *texture = new osg::Texture2D;
	texture->setImage(osgDB::readImageFile("Data/BG.bmp"));
	texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
	texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);

	bgGeometry->setVertexArray(verticesArray);
	bgGeometry->setNormalArray(verticesNormal, osg::Array::BIND_OVERALL);
	bgGeometry->setTexCoordArray(0, texArray);
	bgGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4));
	bgGeometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture);

	bgGeode->addDrawable(bgGeometry);

	osg::MatrixTransform *zoomMT = new osg::MatrixTransform;
	zoomMT->setMatrix(osg::Matrix::translate(0, 0, -24));

	backGroup->addChild(zoomMT);
	zoomMT->addChild(bgGeode);

	return backGroup;
}

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

	osg::Light* light = new osg::Light();
	light->setLightNum(0);
	light->setAmbient(osg::Vec4(0.5f, 0.5f, 0.5f, 1.0f));
	light->setDiffuse(osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
	light->setPosition(osg::Vec4(0.0f, 0.0f, 2.0f, 1.0f));
	osg::LightSource* lightsource = new osg::LightSource();
	lightsource->setLight (light);
	root->addChild (lightsource); 

	osg::MatrixTransform *quadMT = new osg::MatrixTransform;
	quadMT->setName("zoomMT");
	quadMT->setMatrix(osg::Matrix::translate(0.0, 0.0, -5.0));

	osg::MatrixTransform *quadXRotMT = new osg::MatrixTransform;
	quadXRotMT->setName("xRotMT");
	RotateCallback *xRotCallback = new RotateCallback(osg::X_AXIS, 0.0);
	quadXRotMT->setUpdateCallback(xRotCallback);


	osg::MatrixTransform *quadYRotMT = new osg::MatrixTransform;
	quadYRotMT->setName("yRotMT");
	RotateCallback *yRotCallback = new RotateCallback(osg::Y_AXIS, 0.0);
	quadYRotMT->setUpdateCallback(yRotCallback);

	//////////////////////////////////////////////////////////////////////////
	//新增代码,使用开关节点管理
	g_Switch = new osg::Switch;

	//添加立方体
	osg::Geode *box = new osg::Geode;
	osg::ShapeDrawable *boxDrawable = new osg::ShapeDrawable;
	osg::Box *boxShape = new osg::Box(osg::Vec3(0, 0,0), 2);
	boxDrawable->setShape(boxShape);
	box->addDrawable(boxDrawable);
	g_Switch->addChild(box);

	//添加圆柱体
	osg::Geode *cylinder = new osg::Geode;
	osg::ShapeDrawable *cylinderDrawable = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0,0,0), 0.5, 2.0));
	cylinder->addDrawable(cylinderDrawable);
	g_Switch->addChild(cylinder);

	//添加圆球
	osg::Geode *sphere = new osg::Geode;
	osg::ShapeDrawable *sphereDrawable = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0,0,0), 1.3));
	sphere->addDrawable(sphereDrawable);
	g_Switch->addChild(sphere);

	//添加圆锥
	osg::Geode *cone = new osg::Geode;
	osg::ShapeDrawable *coneDrawable = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0,0,0), 0.5, 2));
	cone->addDrawable(coneDrawable);
	g_Switch->addChild(cone);

	g_Switch->setSingleChildOn(0);
	//////////////////////////////////////////////////////////////////////////

	osg::Image *textureImage = osgDB::readImageFile("Data/Reflect.bmp");
	osg::Texture2D *texture2D = new osg::Texture2D;
	texture2D->setImage(textureImage);
	texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
	texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
	g_Switch->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);

	osg::TexGen *texGen = new osg::TexGen;
	texGen->setMode(osg::TexGen::SPHERE_MAP);
	g_Switch->getOrCreateStateSet()->setTextureAttributeAndModes(0, texGen);

	quadYRotMT->addChild(g_Switch);
	quadXRotMT->addChild(quadYRotMT);
	quadMT->addChild(quadXRotMT);

	root->addChild(quadMT);
	root->addChild(createBackGroup());

	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)