我们看到的场景是有四个部分组成,分别为场景唯一点(S),相机观察矩阵(V),投影矩阵(P),视口矩阵(W),由SVP*W=二维窗口的坐标,再根据argb进行上色渲染。
如下代码为相机的实现。
步骤分别为:获取设备属性—>创建图形上下文—>相机绑定图形上下文,其中用slave设置从相机,根据第二个参数设置从相机的状态。有注释
#include "OsgCommon.h"
void creatCamera(osgViewer::Viewer* view)
{
if (!view)
{
return;
}
osg::GraphicsContext::WindowingSystemInterface *wsi = osg::GraphicsContext::getWindowingSystemInterface();//获取设备信息
if (!wsi)
{
return;
}
unsigned int width, height;
wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0),width,height);//获取设备中的宽高
osg::ref_ptr<osg::GraphicsContext::Traits> tranis = new osg::GraphicsContext::Traits;//创建上下文需要的参数结构体
tranis->x = 0;
tranis->y = 0;
tranis->width = width;
tranis->height = height;
tranis->windowDecoration = false;
tranis->doubleBuffer = true;//双缓冲
tranis->sharedContext = false;//共享上下文
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(tranis);//创建图形上下文
if (!gc.valid())
{
return;
}
osg::ref_ptr<osg::Camera> master = new osg::Camera;
master->setGraphicsContext(gc);
master->setViewport(0, 0, 1200, 800);
view->addSlave(master.get());//如默认参数,即bool useMastersSceneData=true,则视口使用主相机的渲染数据
osg::ref_ptr<osg::Camera> slace_camera = new osg::Camera;
slace_camera->setGraphicsContext(gc);
slace_camera->setViewport(0, 0, 200, 200);
view->addSlave(slace_camera.get(),osg::Matrix::scale(osg::Vec3d(2, 2, 2)),osg::Matrix::identity());//第二个参数可设置从相机的姿态,位置矩阵会和主相机同步移动
}
int main()
{
osg::ref_ptr<osgViewer::Viewer>view = new osgViewer::Viewer;
creatCamera(view);
osg::Group*gp = new osg::Group;
gp->addChild(osgDB::readNodeFile("cow.osg"));
view->setSceneData(gp);
return view->run();
}