天天看點

Ogre中顯示Kinect的彩色圖像

首先建立材質檔案以顯示所需的圖檔

//-------------------------------------------------------------------------------------
void SetupImageMaterial()
{
	// Create the texture
	TexturePtr texture = TextureManager::getSingleton().createManual(
			"MyImageTexture", // name
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			TEX_TYPE_2D,      // type
			m_Width, m_Height,         // width & height
			0,                // number of mipmaps
			PF_B8G8R8A8,     // pixel format PF_BYTE_BGRA
			TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);// TU_WRITE_ONLY

	// Create a material using the texture
	MaterialPtr material = MaterialManager::getSingleton().create(
			"ImageTextureMaterial", // name
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

	material->getTechnique(0)->getPass(0)->createTextureUnitState("MyImageTexture");
}
           

作為前期測試,我們可以設定某一個顔色以在Ogre中生成動态紋理,方式如下:

void UpdateImageTexture()
{
	TexturePtr texture = TextureManager::getSingleton().getByName("MyImageTexture");
	// Get the pixel buffer
	Ogre::HardwarePixelBufferSharedPtr pixelBuffer = texture->getBuffer(); 

	// Lock the pixel buffer and get a pixel box
	pixelBuffer->lock(0, 480*640*4, Ogre::HardwareBuffer::HBL_DISCARD);
	const Ogre::PixelBox &pixelBox = pixelBuffer->getCurrentLock();  

	unsigned char* pDest = static_cast<unsigned char*>(pixelBox.data);  

	for(size_t j = 0; j<640; j++)
	{
		for(size_t i = 0; i<480; i++) // width
		{
			pDest[ ((j*480)+i)*4 + 0 ] = 255;
			pDest[ ((j*480)+i)*4 + 1 ] = 255;
			pDest[ ((j*480)+i)*4 + 2 ] = 0;
			pDest[ ((j*480)+i)*4 + 3 ] = 255;
		}
	}
	
	pixelBuffer->unlock(); 
}
           

最後,換成利用Kinect更新資料,如下所示

void UpdateImageTexture()
{
	TexturePtr texture = TextureManager::getSingleton().getByName("MyImageTexture");

	Ogre::HardwarePixelBufferSharedPtr buffer=texture->getBuffer(0,0);  
	buffer->lock(Ogre::HardwareBuffer::HBL_NORMAL);//HBL_DISCARD);  
	const Ogre::PixelBox &pb = buffer->getCurrentLock();  
	Ogre::uint32 *data = static_cast<Ogre::uint32*>(pb.data);  
	size_t height = pb.getHeight();  
	size_t width = pb.getWidth();   
	size_t pitch = pb.rowPitch; // Skip between rows of image  
	xn::ImageMetaData  imageMD;
	m_ImageGenerator.GetMetaData(imageMD);
	XnUInt16 g_nXRes = imageMD.XRes();
	XnUInt16 g_nYRes = imageMD.YRes();
	const XnUInt8* pImage = imageMD.Data(); 

	for(size_t j = 0; j<height; j++)
	{
		for(size_t i = 0; i< width; i++)
		{
			if(imageMD.PixelFormat()==XN_PIXEL_FORMAT_RGB24)
			{
				unsigned char R=pImage[0];  
				unsigned char G=pImage[1];  
				unsigned char B=pImage[2];  
				pImage+=3;
				Ogre::uint32 pixel=(R<<16)+(G<<8)+(B);  
				data[pitch*j + width-1-i] =pixel ;
			}
			else
			{
				unsigned char R=12;  
				unsigned char G=120;  
				unsigned char B=12;  
				Ogre::uint32 pixel=(R<<16)+(G<<8)+(B);  
				data[pitch*j + width-1-i] =pixel ;
			}
		}
	}

	buffer->unlock(); 
}