选中节点高亮显示
#include <Windows.h>
#include <osg/Node>
#include <osg/Group>
#include <osg/Geode>
#include <osg/Switch>
#include <osgFX/Scribe>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osgViewer/ViewerEventHandlers>
class PickHander : public osgGA::GUIEventHandler
{
public:
virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) override
{
osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
if (!viewer)
return false;
if (ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
{
osgUtil::LineSegmentIntersector::Intersections intersections;
if (viewer->computeIntersections(ea.getX(), ea.getY(), intersections))
{
osgUtil::LineSegmentIntersector::Intersection intersection = *intersections.begin();
doUserOperations(intersection);
}
}
return false;
}
void doUserOperations(const osgUtil::LineSegmentIntersector::Intersection& intersection)
{
osg::NodePath node_path = intersection.nodePath;
for (auto itr = node_path.begin(); itr != node_path.end(); ++itr)
{
osg::Group* group = dynamic_cast<osg::Group*>(*itr);
if (!group)
continue;
if (group->getName() != std::string("pick_node"))
continue;
osgFX::Scribe* scribe = dynamic_cast<osgFX::Scribe*>(group->getChild(1));
if (!scribe)
continue;
bool enabled = scribe->getEnabled();
scribe->setEnabled(!enabled);
}
}
};
void composeNodeFactory(osg::Node* node,osg::Group* parent)
{
osg::ref_ptr<osg::Switch> group = new osg::Switch();
group->setName("pick_node");
osg::ref_ptr<osgFX::Scribe> scribe = new osgFX::Scribe();
scribe->setWireframeColor(osg::Vec4(0.0, 0.0, 1.0, 1.0));
scribe->setWireframeLineWidth(2.0);
scribe->addChild(node);
scribe->setEnabled(false);
group->addChild(node);
group->addChild(scribe);
parent->addChild(group);
}
int main()
{
osgViewer::Viewer viewer;
osg::ref_ptr<osg::Group> group = new osg::Group();
composeNodeFactory(osgDB::readNodeFile("avatar.osg"), group);
composeNodeFactory(osgDB::readNodeFile("cessna.osgt"), group);
viewer.setSceneData(group);
viewer.addEventHandler(new PickHander());
viewer.addEventHandler(new osgViewer::StatsHandler());
viewer.setUpViewInWindow(100, 100, 500, 400);
return viewer.run();
}
自定义事件处理