osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
viewer.setCameraManipulator( keyswitchManipulator.get() );
申請一個使用按鍵來切換操作器的類,即:osgGA::KeySwitchMatrixManipulator,意思是這樣的,往這個類中添操作器,添的時候帶個標識和快捷鍵,然後再把這個類添加到viewer當中,這樣viewer運行的時候就可以通過按鍵來換操作器了,真方便。
源代碼分析:osgGA\KeySwitchMatrixManipulator頭文件
public:
typedef std::pair<std::string, osg::ref_ptr<CameraManipulator> > NamedManipulator;
typedef std::map<int, NamedManipulator> KeyManipMap;
virtual const char* className() const { return "KeySwitchMatrixManipulator"; }
/**
Add a camera manipulator with an associated name, and a key to
trigger the switch,
*/
void addMatrixManipulator(int key, std::string name, CameraManipulator *cm);
private:
KeyManipMap _manips;
osg::ref_ptr<CameraManipulator> _current;
用了一個map映射(C#中有Dictionary詞典),map對象是模板類,需要關鍵字key和存儲對象value兩個模板參數,map中的key和value是一個pair結構中的兩個分量:
源文件
bool KeySwitchMatrixManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& aa)
{
if (!_current) return false;
bool handled = false;
if (!ea.getHandled() && ea.getEventType()==GUIEventAdapter::KEYDOWN)
{
KeyManipMap::iterator it=_manips.find(ea.getKey());//找到按鍵如'E'
if(it != _manips.end())//不爲空
{
CameraManipulator* selectedManipulator = it->second.second.get();//it爲一個pair,key爲pair.first value爲pair.second
if (selectedManipulator!=_current)
{
OSG_INFO<<"Switching to manipulator: "<<it->second.first<<std::endl;
if ( !selectedManipulator->getNode() )
{
selectedManipulator->setNode(_current->getNode());
}
selectedManipulator->setByMatrix(_current->getMatrix());//設置當前矩陣
selectedManipulator->init(ea,aa);
_current = selectedManipulator;
}
handled = true;
}
}
return _current->handle(ea,aa) || handled;
}
添加數字切換
void KeySwitchMatrixManipulator::addNumberedMatrixManipulator(CameraManipulator *cm)
{
if(!cm) return;
addMatrixManipulator('1'+_manips.size(),cm->className(),cm);
}