通过键盘事件来控制拖拽器的隐藏和显示,来拾取三维模型
#ifdef _WIN32
#include <windows.h>
#endif
#include <osgViewer/Viewer>
#include <osgViewer/GraphicsWindow>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Camera>
#include <osg/Image>
#include <osg/BufferObject>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgUtil/Optimizer>
#include <osgGA/GUIEventHandler>
#include <osgGA/TrackballManipulator>
#include <osg/Geometry>
#include <osg/AutoTransform>
#include <osg/ProxyNode>
#include <osgText/Text>
#include <osgUtil/Optimizer>
#include <osgManipulator/Dragger>
#include <osgManipulator/Selection>
#include <osgManipulator/Constraint>
#include <osgManipulator/TranslateAxisDragger>
#include <osgManipulator/CommandManager>
#include<osgFX/Scribe>
#include <iostream>
#include <thread>
#include <future>
#include <string>
#include<osgManipulator/TabBoxDragger>
#include<osgManipulator/Selection>
#include<osg/MatrixTransform>
#include<osgGA/GUIEventAdapter>
#include<osgManipulator/TrackballDragger>
//键盘事件
class UseEventHandler :public::osgGA::GUIEventHandler
{
public:
UseEventHandler(osgManipulator::TabBoxDragger* tad)
{
this->_tad = tad;
}
virtual bool handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa)
{
//将aa强制转换为viewer对象
osgViewer::Viewer *viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
if (!viewer)//如果转换失败则直接退出
{
return false;
}
switch (ea.getEventType())//获取事件的类型,是键盘上的事件,还是鼠标上的事件
{
case osgGA::GUIEventAdapter::KEYDOWN://键盘响应事件
if (ea.getKey() == 0xFF51) //键盘左键
{
_tad->setNodeMask(0X1);
}
if (ea.getKey() == 0xFF53) //键盘右键
{
_tad->setNodeMask(0X0);
}
break;
default:
break;
}
return false;
}
private:
osgManipulator::TabBoxDragger* _tad;
};
int main()
{
float scale = 1.0;
osgViewer::Viewer viewer;
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("glider.osg");
osg::ref_ptr<osgManipulator::Selection> selection = new osgManipulator::Selection;
selection->addChild(loadedModel);
//盒式拖拽器
osgManipulator::TabBoxDragger* tad = new osgManipulator::TabBoxDragger();
tad->setupDefaultGeometry();//使用默认的图形,即一个立方体
tad->setMatrix(osg::Matrix::scale(scale, scale, scale)*osg::Matrix::translate(loadedModel->getBound().center()));
tad->addTransformUpdating(selection);//Dragger要改变的对象。
tad->setHandleEvents(true);
osg::ref_ptr<osg::Group> root = new osg::Group;
root->addChild(selection);
root->addChild(tad);
tad->setNodeMask(0X0);
/*root->addChild(rote);*/
viewer.setSceneData(root.get());
viewer.addEventHandler(new UseEventHandler(tad));
return viewer.run();
}