在學習OSG提供的例子osgCamera中,由于例子很長,涉及很多細節,考慮将其分解為幾個小例子。本文介紹實作在一個視窗中添加多個相機的功能。
此函數接受一個Viewer引用類型參數,設定圖形上下文的特征變量traits,并由它建立圖形上下文。根據需要差建立的相機數量,循環建立相機變量,并将其添加到觀察器變量中,作為從相機。每次建立相機,都需要擷取目前圖形上下文,并設定相機的起點(左下角)坐标和相機的寬度與高度。相機間的差別僅在于相機起點的不同。完整的程式代碼如下。
void singleWindowMultipleCameras(osgViewer::Viewer& viewer)
{
osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
if (!wsi)
{
osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
return;
}
unsigned int width, height;
osg::GraphicsContext::ScreenIdentifier main_screen_id;
main_screen_id.readDISPLAY();
main_screen_id.setUndefinedScreenDetailsToDefaultScreen();
wsi->getScreenResolution(main_screen_id, width, height);
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->x = 0;
traits->y = 0;
traits->width = width;
traits->height = height;
traits->windowDecoration = true;
traits->doubleBuffer = true;
traits->sharedContext = 0;
traits->readDISPLAY();
traits->setUndefinedScreenDetailsToDefaultScreen();
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
if (gc.valid())
{
osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl;
// need to ensure that the window is cleared make sure that the complete window is set the correct colour
// rather than just the parts of the window that are under the camera's viewports
gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f));
gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
else
{
osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl;
}
unsigned int numCameras = 3;
double aspectRatioScale = 1.0;///(double)numCameras;
for(unsigned int i=0; i<numCameras;++i)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setGraphicsContext(gc.get());
camera->setViewport(new osg::Viewport((i*width)/numCameras,(i*height)/numCameras, width/numCameras, height/numCameras));
GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
camera->setDrawBuffer(buffer);
camera->setReadBuffer(buffer);
viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::scale(aspectRatioScale,1.0,1.0));
}
}
之後在主函數中調用建立多相機函數,為觀察器添加從相機,并向觀察器中加入模型,進行顯示。主函數代碼如下:
int main(){
osgViewer::Viewer viewer;
singleWindowMultipleCameras(viewer);
viewer.setSceneData(osgDB::readRefNodeFile("cow.osg"));
return viewer.run();
}
運作程式,可顯示多相機效果,如下所示:

可以更改singleWindowMultipleCameras函數中的numCameras變量,建立更多的從相機。
建立多相機的關鍵是相機視點的設定和向觀察器中添加從相機。而程式最開始的建立視窗系統接口,圖形上下文,圖形上下文特征以及相機的緩沖設定,則是一些輔助性工作。
轉載于:https://www.cnblogs.com/SupremeGIS-Developer/p/10685269.html