OpenSceneGraph中的osgGA.CameraViewSwitchManipulator为相机视角切换提供了一种交互方式。
osg::Object -> osgGA::CameraManipulator -> osgGA::CameraViewSwitchManipulator
通过调用setView()函数设置视角,在应用中实现视角切换。
例如,首先创建一个osgViewer::Viewer对象,并为其添加场景图和相机:
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
osg::ref_ptr<osg::Group> root = new osg::Group;
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::ref_ptr<osg::ShapeDrawable> drawable = new osg::ShapeDrawable(new osg::Box(osg::Vec3(), 1.0));
geode->addDrawable(drawable.get());
root->addChild(geode.get());
viewer->setSceneData(root.get());
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setClearColor(osg::Vec4(0.2f, 0.2f, 0.6f, 1.0f));
camera->setViewport(new osg::Viewport(0, 0, 800, 600));
camera->setProjectionMatrixAsPerspective(40.0, 800.0 / 600.0, 0.1, 1000.0);
root->addChild(camera.get());
然后创建一个osgGA::CameraViewSwitchManipulator对象:
osg::ref_ptr<osgGA::CameraViewSwitchManipulator> cvsmanipulator = new osgGA::CameraViewSwitchManipulator;
使用setView()函数设置四个不同的视角矩阵:
const osg::Vec3d center(0.0, 0.0, 0.0);
const osg::Vec3d eye1(0.0, 0.0, 5.0);
const osg::Vec3d eye2(0.0, 5.0, 0.0);
const osg::Vec3d eye3(5.0, 0.0, 0.0);
const osg::Vec3d up(0.0, 1.0, 0.0);
osg::Vec3d center1 = center, center2 = center, center3 = center;
osg::Matrix eye1matrix = osg::Matrix::lookAt(eye1, center1, up);
osg::Matrix eye2matrix = osg::Matrix::lookAt(eye2, center2, up);
osg::Matrix eye3matrix = osg::Matrix::lookAt(eye3, center3, up);
cvsmanipulator->setView(0, osg::Matrixd::identity());
cvsmanipulator->setView(1, eye1matrix);
cvsmanipulator->setView(2, eye2matrix);
cvsmanipulator->setView(3, eye3matrix);
最后通过调用setCameraManipulator()函数将CameraViewSwitchManipulator对象作为相机的交互器:
camera->setAllowEventFocus(false);
viewer->setCameraManipulator(cvsmanipulator.get());
效果如下: