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

  • 简介

这节课NeHe课程教我们如何读取一张raw格式的图片,并且对两张raw格式图片进行处理生成了一张纹理图片。整个过程并不是十分复杂,文中大部分内容涉及到图片数据的操作。

  • 实现

首先我们创建需要显示的立方体:

osg::Geode*	createCubeGeode(osg::Image *image)
{
	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);
 ......
}
接着我们需要创建纹理所需要的image,这里的raw格式图片实际上并不是一种通用的格式,在osg中也并不支持。我们需要将raw格式中的字节数据读取出来并赋值给osg::Image用来作为我们的纹理图片。

首先我们使用NeHe中用到的函数读取图片:(函数代码并不完整,完整代码查看后面的附录中源码)

osg::Image*  ReadTextureData ( char *filename, unsigned int width, unsigned int height, unsigned int pixelPerBytes)
{
	//NeHe中使用256x256大小的图片,并且每个像素的字节数是4
	//因此这里在分配内存是使用RGBA都是8位的方式(1个字节)
	//正好是4个字节
	osg::Image *buffer = new osg::Image;
	buffer->allocateImage(width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
	int bytesPerPixel = buffer->getPixelSizeInBits() / 8;

	FILE *f;
	int i,j,k,done=0;
	int stride = buffer->s() * buffer->getPixelSizeInBits() / 8;				// Size Of A Row (Width * Bytes Per Pixel)
	unsigned char *p = NULL;
......
}
图片加载之后,我们使用Blit函数来对两张图片中的数据进行一些处理,具体代码参考Blit函数

最后生成我们的256x256的大小的纹理,图片的每个像素占用4个字节:

osg::Image*	createTextureImage()
{
	osg::Image *src = ReadTextureData("Data/GL.raw",  256, 256, 32);
	osg::Image *dst = ReadTextureData("Data/Monitor.raw", 256, 256, 32);
	
	Blit(src,dst,127,127,128,128,64,64,1,127);
	return dst;
}

将图片设置给立方体纹理,场景中为了简便用AnimationPathCallback来进行旋转:

	osg::AnimationPathCallback *quadAnimationCallbackX = 
		new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(1, 0, 0), 2.5);

	osg::AnimationPathCallback *quadAnimationCallbackY = 
		new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 1, 0), 1.5);

	osg::AnimationPathCallback *quadAnimationCallbackZ = 
		new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 0, 1), 0.5);

	osg::MatrixTransform *quadXRotMT = new osg::MatrixTransform;
	quadXRotMT->setUpdateCallback(quadAnimationCallbackX);

	osg::MatrixTransform *quadYRotMT = new osg::MatrixTransform;
	quadYRotMT->setUpdateCallback(quadAnimationCallbackY);

	osg::MatrixTransform *quadZRotMT = new osg::MatrixTransform;
	quadZRotMT->setUpdateCallback(quadAnimationCallbackZ);

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

	osg::Image *image = createTextureImage();
	quadZRotMT->addChild(createCubeGeode(image));
一般来说,纹理操作很少使用这种方式进行,大部分都是通过加载多重纹理的方式来实现贴多张纹理,并设置其中纹理的作用方式。这种方式相当于先将多张纹理处理成一张再贴到物体上。编译运行程序:

用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/Texture2D>

#include <osg/AnimationPath>



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 normalsArray[][3] = {
	{0.0f, 0.0f, 1.0f},
	{0.0f, 0.0f,-1.0f},
	{0.0f, 1.0f, 0.0f},
	{0.0f,-1.0f, 0.0f},
	{1.0f, 0.0f, 0.0f},
	{-1.0f, 0.0f, 0.0f}
};


//////////////////////////////////////////////////////////////////////////
osg::Geode*	createCubeGeode(osg::Image *image)
{
	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::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 *normals = new osg::Vec3Array;
	for (unsigned i = 0; i < sizeof(normals); ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			normals->push_back(osg::Vec3(normalsArray[i][0], normalsArray[i][1], normalsArray[i][2]));
		}
	}
	quadGeometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX);
	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::Texture2D *texture2D = new osg::Texture2D;
	texture2D->setImage(image);
	texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
	texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);

	quadGeometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);
	quadGeometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

	osg::Geode *quadGeode = new osg::Geode;
	quadGeode->addDrawable(quadGeometry);

	return quadGeode;
}

//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//操作Raw纹理

osg::Image*  ReadTextureData ( char *filename, unsigned int width, unsigned int height, unsigned int pixelPerBytes)
{
	//NeHe中使用256x256大小的图片,并且每个像素的字节数是4
	//因此这里在分配内存是使用RGBA都是8位的方式(1个字节)
	//正好是4个字节
	osg::Image *buffer = new osg::Image;
	buffer->allocateImage(width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
	int bytesPerPixel = buffer->getPixelSizeInBits() / 8;

	FILE *f;
	int i,j,k,done=0;
	int stride = buffer->s() * buffer->getPixelSizeInBits() / 8;				// Size Of A Row (Width * Bytes Per Pixel)
	unsigned char *p = NULL;

	f = fopen(filename, "rb");									// Open "filename" For Reading Bytes
	if( f != NULL )												// If File Exists
	{
		for( i = buffer->t()-1; i >= 0 ; i-- )				// Loop Through Height (Bottoms Up - Flip Image)
		{
			p = buffer->data() + (i * stride );					// 
			for ( j = 0; j < buffer->s() ; j++ )				// Loop Through Width
			{
				for ( k = 0 ; k < buffer->getPixelSizeInBits() / 8-1 ; k++, p++, done++ )
				{
					*p = fgetc(f);								// Read Value From File And Store In Memory
				}
				*p = 255; p++;									// Store 255 In Alpha Channel And Increase Pointer
			}
		}
		fclose(f);												// Close The File
	}
	return buffer;												// Returns Number Of Bytes Read In
}


void Blit( osg::Image *src, osg::Image *dst, 
		  int src_xstart, int src_ystart, int src_width, int src_height,
		  int dst_xstart, int dst_ystart, int blend, int alpha)
{
	int i,j,k;
	unsigned char *s, *d;

	// Clamp Alpha If Value Is Out Of Range
	if( alpha > 255 ) alpha = 255;
	if( alpha < 0 ) alpha = 0;

	// Check For Incorrect Blend Flag Values
	if( blend < 0 ) blend = 0;
	if( blend > 1 ) blend = 1;

	d = dst->data() + (dst_ystart * dst->s() * dst->getPixelSizeInBits() / 8);    // Start Row - dst (Row * Width In Pixels * Bytes Per Pixel)
	s = src->data() + (src_ystart * src->s() * src->getPixelSizeInBits() / 8);    // Start Row - src (Row * Width In Pixels * Bytes Per Pixel)

	for (i = 0 ; i < src_height ; i++ )							// Height Loop
	{
		s = s + (src_xstart * src->getPixelSizeInBits() / 8);						// Move Through Src Data By Bytes Per Pixel
		d = d + (dst_xstart * dst->getPixelSizeInBits() / 8);						// Move Through Dst Data By Bytes Per Pixel
		for (j = 0 ; j < src_width ; j++ )						// Width Loop
		{
			for( k = 0 ; k < src->getPixelSizeInBits()/8 ; k++, d++, s++)		// "n" Bytes At A Time
			{
				if (blend)										// If Blending Is On
					*d = ( (*s * alpha) + (*d * (255-alpha)) ) >> 8; // Multiply Src Data*alpha Add Dst Data*(255-alpha)
				else											// Keep in 0-255 Range With >> 8
					*d = *s;									// No Blending Just Do A Straight Copy
			}
		}
		d = d + (dst->s() - (src_width + dst_xstart))*dst->getPixelSizeInBits()/8;	// Add End Of Row */
		s = s + (src->s() - (src_width + src_xstart))*src->getPixelSizeInBits()/8;	// Add End Of Row */
	}
}


osg::Image*	createTextureImage()
{
	osg::Image *src = ReadTextureData("Data/GL.raw",  256, 256, 32);
	osg::Image *dst = ReadTextureData("Data/Monitor.raw", 256, 256, 32);
	
	Blit(src,dst,127,127,128,128,64,64,1,127);
	return dst;
}


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



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

		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::MatrixTransform *quadMT = new osg::MatrixTransform;
	quadMT->setMatrix(osg::Matrix::translate(0.0, 0.0, -5.0));

	osg::AnimationPathCallback *quadAnimationCallbackX = 
		new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(1, 0, 0), 2.5);

	osg::AnimationPathCallback *quadAnimationCallbackY = 
		new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 1, 0), 1.5);

	osg::AnimationPathCallback *quadAnimationCallbackZ = 
		new osg::AnimationPathCallback(osg::Vec3d(0, 0, 0), osg::Vec3(0, 0, 1), 0.5);

	osg::MatrixTransform *quadXRotMT = new osg::MatrixTransform;
	quadXRotMT->setUpdateCallback(quadAnimationCallbackX);

	osg::MatrixTransform *quadYRotMT = new osg::MatrixTransform;
	quadYRotMT->setUpdateCallback(quadAnimationCallbackY);

	osg::MatrixTransform *quadZRotMT = new osg::MatrixTransform;
	quadZRotMT->setUpdateCallback(quadAnimationCallbackZ);

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

	osg::Image *image = createTextureImage();
	quadZRotMT->addChild(createCubeGeode(image));

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

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