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

52 篇文章 36 订阅
  • 简介

本课是在第七课的基础上实现将立方体变透明的效果,其中用到了OpenGL中的混合(Blend)

  • 实现

在OpenGL中如何实现混合以及混合实现的原理和过程在NeHe教程中已经解释的很清楚了,在这里就不在赘述,本课主要探讨在OSG中实现混合的效果,混合同样是作为一种StateSet的方式来进行处理的,OSG中的混合主要涉及到一下几个类BlendFunc、BlendEquation和BlendColor,对应于OpenGL中的glBlendFunc 、glBlendEquation和glBlendColor三个函数,对混合的参数进行一些设置。本课中我们参考NeHe教程中设置混合的计算方式定义如下的BlendFunc

	osg::BlendFunc *blendFunc = new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE, 0.5, 0.5);
	quadGeometry->getOrCreateStateSet()->setAttribute(blendFunc,
		osg::StateAttribute::ON);

需要注意的是我们需要将初始的清除背景的颜色的alpha值设置为0.5

	camera->setClearColor( osg::Vec4(0.0, 0.0, 0.0, 0.5) );

在按下键盘上B键的时候开启和关闭混合模式

				if (ea.getKey()== osgGA::GUIEventAdapter::KEY_B)
				{
					static int i = 0;
					if (i % 2 == 0) {
						root->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
					} else {
						root->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::OFF);
					}
					++i;
				}

其他的代码与第七课相同,编译运行程序后点击B键时可以看到透明的效果。

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

#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/BlendFunc>

float textureVertices[][2] = {
	//Front Face
	{0.0f, 0.0f},
	{1.0f, 0.0f},
	{1.0f, 1.0f},
	{0.0f, 1.0f},
	// Back Face
	{1.0f, 0.0f},
	{1.0f, 1.0f},
	{0.0f, 1.0f},
	{0.0f, 0.0f},
	// Top Face
	{0.0f, 1.0f},
	{0.0f, 0.0f},
	{1.0f, 0.0f},
	{1.0f, 1.0f},
	// Bottom Face
	{1.0f, 1.0f},
	{0.0f, 1.0f},
	{0.0f, 0.0f},
	{1.0f, 0.0f},
	// Right face
	{1.0f, 0.0f},
	{1.0f, 1.0f},
	{0.0f, 1.0f},
	{0.0f, 0.0f},
	// Left Face
	{0.0f, 0.0f},
	{1.0f, 0.0f},
	{1.0f, 1.0f},
	{0.0f, 1.0f}
};

float QuadVertices[][3] = {

	{-1.0f, -1.0f,  1.0f},
	{ 1.0f, -1.0f,  1.0f},
	{ 1.0f,  1.0f,  1.0f},
	{-1.0f,  1.0f,  1.0f},

	{-1.0f, -1.0f, -1.0f},
	{-1.0f,  1.0f, -1.0f},
	{ 1.0f,  1.0f, -1.0f},
	{ 1.0f, -1.0f, -1.0f},

	{-1.0f,  1.0f, -1.0f},
	{-1.0f,  1.0f,  1.0f},
	{ 1.0f,  1.0f,  1.0f},
	{ 1.0f,  1.0f, -1.0f},

	{-1.0f, -1.0f, -1.0f},
	{ 1.0f, -1.0f, -1.0f},
	{ 1.0f, -1.0f,  1.0f},
	{-1.0f, -1.0f,  1.0f},

	{ 1.0f, -1.0f, -1.0f},
	{ 1.0f,  1.0f, -1.0f},
	{ 1.0f,  1.0f,  1.0f},
	{ 1.0f, -1.0f,  1.0f},

	{-1.0f, -1.0f, -1.0f},
	{-1.0f, -1.0f,  1.0f},
	{-1.0f,  1.0f,  1.0f},
	{-1.0f,  1.0f, -1.0f}

};

float normalVertics[][3] = {
	// Front Face
	{ 0.0f, 0.0f, 1.0f},
	// Back Face
	{ 0.0f, 0.0f,-1.0f},
	// Top Face
	{ 0.0f, 1.0f, 0.0f},
	// Bottom Face
	{ 0.0f,-1.0f, 0.0f},
	// Right face
	{ 1.0f, 0.0f, 0.0f},
	// Left Face
	{-1.0f, 0.0f, 0.0f}
};

//
//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::ON);
					} else {
						root->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
					}
					++i;
				}

				if (ea.getKey()== osgGA::GUIEventAdapter::KEY_B)
				{
					static int i = 0;
					if (i % 2 == 0) {
						root->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
					} else {
						root->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::OFF);
					}
					++i;
				}

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

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

					osg::Texture2D *texture2D = dynamic_cast<osg::Texture2D*>(quadGeode->getOrCreateStateSet()->getTextureAttribute(0, osg::StateAttribute::TEXTURE));

					static int i = 0;
					if (i % 3 == 0) {
						texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
						texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
					} else if (i % 3 == 1) {
						texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
						texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR_MIPMAP_NEAREST);
					} else {
						texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
						texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
					}
					++i;
				}
			}
		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, 0.5) );
		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::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);

	osg::Geometry *quadGeometry = new osg::Geometry;
	osg::Vec3Array *quadVertexArray = new osg::Vec3Array;
	for (unsigned i = 0; i < sizeof(QuadVertices); ++i)
	{
		quadVertexArray->push_back(osg::Vec3(QuadVertices[i][0], QuadVertices[i][1], QuadVertices[i][2]));
	}
	quadGeometry->setVertexArray(quadVertexArray);

	osg::Vec4Array *colorArray = new osg::Vec4Array;
	colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, 0.5));
	quadGeometry->setColorArray(colorArray, osg::Array::BIND_OVERALL);

	osg::BlendFunc *blendFunc = new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE, 0.5, 0.5);
	quadGeometry->getOrCreateStateSet()->setRenderingHint(
		osg::StateSet::TRANSPARENT_BIN );
	quadGeometry->getOrCreateStateSet()->setAttribute(blendFunc,
		osg::StateAttribute::ON);

	osg::Vec2Array* texcoords = new osg::Vec2Array;
	for (unsigned i = 0; i < sizeof(textureVertices); ++i)
	{
		texcoords->push_back(osg::Vec2(textureVertices[i][0], textureVertices[i][1]));
	}
	quadGeometry->setTexCoordArray(0,texcoords);

	osg::Vec3Array *quadNormalArray = new osg::Vec3Array;
	for (unsigned i = 0; i < sizeof(normalVertics); ++i)
	{
		quadNormalArray->push_back(osg::Vec3(normalVertics[i][0], normalVertics[i][1], normalVertics[i][2]));
	}
	quadGeometry->setNormalArray(quadNormalArray, osg::Array::BIND_PER_PRIMITIVE_SET);

	int first = 0;
	for (unsigned i = 0; i < 6; ++i)
	{
		osg::DrawArrays *vertexIndices = new osg::DrawArrays(osg::PrimitiveSet::QUADS, first, 4);
		first += 4;
		quadGeometry->addPrimitiveSet(vertexIndices);
	}

	osg::Image *textureImage = osgDB::readImageFile("Data/Glass.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);

	osg::Geode *quadGeode = new osg::Geode;
	quadGeode->setName("quadGeode");
	quadGeode->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);

	quadGeode->addDrawable(quadGeometry);
	quadYRotMT->addChild(quadGeode);
	quadXRotMT->addChild(quadYRotMT);
	quadMT->addChild(quadXRotMT);

	root->addChild(quadMT);

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编译运行 OpenSceneGraph-OpenSceneGraph-3.6.4 需要按照以下步骤进行操作: 1. 首先,确保你的计算机上已经安装了 CMake,C++ 编译器和 OpenGL 兼容的图形驱动程序。这些是编译和运行 OpenSceneGraph 所必需的工具和库。 2. 下载 OpenSceneGraph-OpenSceneGraph-3.6.4 的源代码,可以在官方网站或开源项目托管网站上找到。确保下载的版本正确,避免出错。 3. 解压源代码文件并进入解压后的目录。 4. 创建一个用于构建的构建目录,并进入该目录。例如:mkdir build && cd build。 5. 运行 CMake 命令来生成构建系统所需的文件和配置。命令可能类似于:cmake path/to/OpenSceneGraph-OpenSceneGraph-3.6.4。你可以使用其他参数和选项来自定义构建过程。 6. 确保 CMake 执行成功并生成了构建系统所需的文件。 7. 使用你的 C++ 编译器来构建 OpenSceneGraph。可以使用 make 命令,或者其他编译工具,根据你的操作系统和编译环境来选择。例如:make。 8. 等待编译完成,这可能需要一段时间,具体取决于你的计算机性能。 9. 构建完成后,检查是否有错误或警告信息。如果有,需要解决它们,并重新运行编译步骤。 10. 运行编译好的 OpenSceneGraph 可执行文件,这将启动 OpenSceneGraph 程序并运行示例或其他自定义的应用程序。 总之,编译和运行 OpenSceneGraph-OpenSceneGraph-3.6.4 需要先安装必需的工具和库,然后使用 CMake 生成构建系统所需的文件,再使用 C++ 编译器进行编译,最后运行生成的可执行文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值