Exemplo n.º 1
0
bool QueryCoordinatesHandler::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
{
  if ( ea.getEventType() == osgGA::GUIEventAdapter::MOVE )
  {
    osgViewer::View* view = static_cast<osgViewer::View*>( aa.asView() );
    osg::Vec3d coords = getCoords( ea.getX(), ea.getY(), view, false );
    mGlobe->showCurrentCoordinates( coords.x(), coords.y() );
  }
  if ( ea.getEventType() == osgGA::GUIEventAdapter::PUSH
       && ea.getButtonMask() == osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON )
  {
    osgViewer::View* view = static_cast<osgViewer::View*>( aa.asView() );
    osg::Vec3d coords = getCoords( ea.getX(), ea.getY(), view, false );

    OE_NOTICE << "SelectedCoordinates set to:\nLon: " << coords.x() << " Lat: " << coords.y()
    << " Ele: " << coords.z() << std::endl;

    mGlobe->setSelectedCoordinates( coords );

    if ( ea.getModKeyMask() == osgGA::GUIEventAdapter::MODKEY_CTRL )
      //ctrl + rightclick pops up a QMessageBox
    {
      mGlobe->showSelectedCoordinates();
    }
  }

  return false;
}
Exemplo n.º 2
0
 virtual bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
 {
     if ( ea.getEventType()!=osgGA::GUIEventAdapter::RELEASE ||
          ea.getButton()!=osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON ||
          !(ea.getModKeyMask()&osgGA::GUIEventAdapter::MODKEY_CTRL) )
         return false;
     
     osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
     if ( viewer )
     {
         osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector =
             new osgUtil::LineSegmentIntersector(osgUtil::Intersector::WINDOW, ea.getX(), ea.getY());
         osgUtil::IntersectionVisitor iv( intersector.get() );
         iv.setTraversalMask( ~DO_NOT_PICK_NODE_MASK );
         viewer->getCamera()->accept( iv );
         
         if ( intersector->containsIntersections() )
         {
             const osgUtil::LineSegmentIntersector::Intersection& result =
                 *(intersector->getIntersections().begin());
             
             osg::BoundingBox bb = result.drawable->getBound();
             osg::Vec3 worldCenter = bb.center() * osg::computeLocalToWorld(result.nodePath);
             _selectionBox->setMatrix(
                 osg::Matrix::scale(bb.xMax()-bb.xMin(), bb.yMax()-bb.yMin(), bb.zMax()-bb.zMin()) *
                 osg::Matrix::translate(worldCenter) );
         }
     }
     return false;
 }
Exemplo n.º 3
0
 virtual bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
 {
     osgViewer::View* view = dynamic_cast<osgViewer::View*>( &aa );
     if ( ea.getEventType()==osgGA::GUIEventAdapter::FRAME )
     {
         double time = ea.getTime();
         _recast->update( time - _lastSimulationTime );
         _lastSimulationTime = time;
     }
     else if ( ea.getEventType()==osgGA::GUIEventAdapter::RELEASE ||
               ea.getEventType()==osgGA::GUIEventAdapter::DOUBLECLICK )
     {
         osgUtil::LineSegmentIntersector::Intersections intersections;
         if ( view->computeIntersections(ea.getX(), ea.getY(), intersections) )
         {
             const osgUtil::LineSegmentIntersector::Intersection& result = *(intersections.begin());
             osg::Vec3 pt = result.getWorldIntersectPoint();
             
             if ( ea.getModKeyMask()&osgGA::GUIEventAdapter::MODKEY_CTRL )
             {
                 osg::ref_ptr<osg::MatrixTransform> agent = new osg::MatrixTransform;
                 agent->setMatrix( osg::Matrix::translate(pt) );
                 agent->addChild( _agentShape.get() );
                 _scene->addChild( agent.get() );
                 _recast->addAgent( pt, agent.get() );
             }
             else if ( ea.getEventType()==osgGA::GUIEventAdapter::DOUBLECLICK )
                 _recast->moveTo( pt );
         }
     }
     return false;
 }
Exemplo n.º 4
0
    virtual bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
    {
        if( ( ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL ) == 0 )
        {
            return( false );
        }
        else if( ea.getEventType() == osgGA::GUIEventAdapter::PUSH )
        {
            _lastX = ea.getXnormalized();
            _lastY = ea.getYnormalized();
            return( true );
        }
        else if( ea.getEventType() == osgGA::GUIEventAdapter::DRAG )
        {
            double deltaX = ea.getXnormalized() - _lastX;
            double deltaY = ea.getYnormalized() - _lastY;
            _lastX = ea.getXnormalized();
            _lastY = ea.getYnormalized();

            deltaX *= 6.;
            deltaY *= 6.;
            osg::Matrix trans = osgbCollision::asOsgMatrix( _co->getWorldTransform() );
            trans = trans * osg::Matrix::translate( deltaX, 0., deltaY );
            _mt->setMatrix( trans );
            _co->setWorldTransform( osgbCollision::asBtTransform( trans ) );
            return( true );
        }
        return( false );
    }
Exemplo n.º 5
0
bool Handler::handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osg::Object *object, osg::NodeVisitor *visitor) {

	osg::Vec2 pos(ea.getX(), ea.getY());

	switch (ea.getModKeyMask()) {
	case osgGA::GUIEventAdapter::ModKeyMask::MODKEY_SHIFT:
		this->m_indicator->setFillColor(osg::Vec4(0.0f, 0.0f, 1.0f, 0.2f));
		this->m_indicator->setBorderColor(osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f));
		break;
	case osgGA::GUIEventAdapter::ModKeyMask::MODKEY_ALT:
		this->m_indicator->setFillColor(osg::Vec4(1.0f, 0.0f, 0.0f, 0.2f));
		this->m_indicator->setBorderColor(osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f));
		break;
	default:
		return (false);
	}

	switch (ea.getEventType()) {
	case osgGA::GUIEventAdapter::EventType::PUSH:
		this->m_beginPos = pos;
		this->m_lastPos = pos;
		this->m_start = pos;
		this->m_stop = pos;
		this->m_indicator->setGeometry(this->m_start, this->m_stop - this->m_start);
		break;
	case osgGA::GUIEventAdapter::EventType::RELEASE:
		this->m_lastPos = pos;
		this->m_selector->operator ()(this->m_start, this->m_stop, ea.getModKeyMask() == osgGA::GUIEventAdapter::ModKeyMask::MODKEY_SHIFT);
		this->m_indicator->setGeometry(osg::Vec2(0.0f, 0.0f), osg::Vec2(0.0f, 0.0f));
		break;
	case osgGA::GUIEventAdapter::EventType::DRAG:
		this->m_lastPos = pos;
		this->m_start = osg::Vec2(
				std::min<float>(this->m_beginPos.x(), this->m_lastPos.x()),
				std::min<float>(this->m_beginPos.y(), this->m_lastPos.y()));
		this->m_stop = osg::Vec2(
				std::max<float>(this->m_beginPos.x(), this->m_lastPos.x()),
				std::max<float>(this->m_beginPos.y(), this->m_lastPos.y()));
		this->m_indicator->setGeometry(this->m_start, this->m_stop - this->m_start);
		break;
	default:
		return (false);
	}

	return (true);
}
Exemplo n.º 6
0
    bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
    { 
        if ( ea.getHandled() ) return false;
        if ( ea.getEventType() == osgGA::GUIEventAdapter::PUSH &&
             ea.getButtonMask() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON &&
             (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL) != 0 &&
             terrain_srs.valid() &&
             layer.valid() )
        {
            osgViewer::View* view = dynamic_cast<osgViewer::View*>( &aa );
            if ( !view ) return false;
            osgUtil::LineSegmentIntersector::Intersections hits;
            if ( view->computeIntersections( ea.getX(), ea.getY(), hits ) )
            {
                osgUtil::LineSegmentIntersector::Intersection first = *hits.begin();
                osg::Vec3d hit = first.getWorldIntersectPoint() - first.getWorldIntersectNormal()*0.2;
                osgGIS::GeoPoint world( hit, terrain_srs.get() );
                osgGIS::GeoPoint result = terrain_srs->getGeographicSRS()->transform( world );

                osgGIS::FeatureCursor cursor = layer->getCursor( result );
                highlight( cursor );

                std::stringstream buf;

                buf << "World: " << world.toString() << std::endl
                    << "Geo: " << result.toString() << std::endl
                    << "SRS: " << terrain_srs->getName() << std::endl;
                int line_count = 2;

                for( cursor.reset(); cursor.hasNext(); )
                {
                    osgGIS::Feature* f = cursor.next();
                    osgGIS::AttributeList attrs = f->getAttributes();
                    for( osgGIS::AttributeList::const_iterator i = attrs.begin(); i != attrs.end(); i++ )
                    {
                        std::string key = i->getKey();
                        if ( key.length() > 0 )
                        {
                            buf << key << " : " << i->asString() << std::endl;
                            line_count++;
                        }
                    }
                    break;
                }

                if ( buf.str().length() == 0 )
                {
                    buf << "Control-Left-Click to query";
                    line_count++;
                }
                hud_text->setText( buf.str() );
                hud_text->setPosition( osg::Vec3( 10, line_count*TEXT_SIZE*1.1f, 0 ) );
                hud_text->dirtyDisplayList();
            }
        }

        return false; // never "handled"
    }
Exemplo n.º 7
0
bool QOsgEventHandler::handle(
    const osgGA::GUIEventAdapter &ea
,   osgGA::GUIActionAdapter &)
{
    if(ea.getEventType() == osgGA::GUIEventAdapter::FRAME
    || ea.getEventType() == osgGA::GUIEventAdapter::MOVE)
        return false;

    switch(ea.getEventType())
    {

  case(osgGA::GUIEventAdapter::KEYDOWN):
            {
                if(ea.getKey() == '-'
                || ea.getKey() == '+')
                {
                    const float f = 1.00f
                        + (ea.getKey() == '+' ? +0.004f : -0.004f);

                    if(m_fov * f >= 1.f && m_fov * f <= 179.f)
                        m_fov *= f;

                    emit fovChanged(m_fov);
                }
            }
            break;

    case(osgGA::GUIEventAdapter::SCROLL):
        {
            const float f = 1.00f
                + (ea.getScrollingMotion() == osgGA::GUIEventAdapter::SCROLL_DOWN ? -0.08f : +0.08f);

            if(m_fov * f >= 1.f && m_fov * f <= 179.f)
                m_fov *= f;

            emit fovChanged(m_fov);

            return true;
        }
        break;

    case(osgGA::GUIEventAdapter::RELEASE):

        if(ea.getButton() == osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON
        && (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL) != 0)
        {
            m_fov = m_fovBackup;
            emit fovChanged(m_fov);

            return true;
        }
        break;

    default:
        break;
    };
    return false;
}
Exemplo n.º 8
0
bool ManipulatorControl::ProcessMouseInput(const osgGA::GUIEventAdapter &ea) {

	if (ea.getEventType() == osgGA::GUIEventAdapter::PUSH) {
		lastX = ea.getX();
		lastY = ea.getY();
	}
	else if (ea.getEventType() == osgGA::GUIEventAdapter::DRAG) {
		const bool ctrl( ( ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL ) != 0 );
		if (!ctrl) return false;
		// drag the active manipulator in the plane of view
		// get our current view

		float dx = ea.getX() - lastX;
		lastX = ea.getX();
		float dy = ea.getY() - lastY;
		lastY = ea.getY();




		Vec3d from, to, up;
		m_viewer->m_handler->getTransformation(from, to, up);
		up.normalize();
		Vec3d depthdir = (to - from); depthdir.normalize();
		osg::Vec3 ydir = up;
		osg::Vec3 xdir = depthdir ^ ydir;


		OpenRAVE::Transform T = m_manip->GetEndEffectorTransform();
		float depth = (toOsgVec3(T.trans)-from) * depthdir;
		osg::Vec3 dragvec = xdir*(depth*dx/ea.getWindowWidth()) + ydir*(depth*dy/ea.getWindowHeight());
		cout << toRave(dragvec) << endl;

		T.trans += toRave(dragvec);
		vector<double> iksoln;
		m_manip->FindIKSolution(OR::IkParameterization(T), iksoln, 18);
		if (iksoln.empty()) {
			cerr << "no ik solution found" << endl;
		}
		else {
			cout << "ik succeeded!" << endl;
			m_manip->GetRobot()->SetDOFValues(iksoln, false, m_manip->GetArmIndices());
			m_viewer->UpdateSceneData();
		}
		return true;
	}
	return false;

}
Exemplo n.º 9
0
bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
{
    switch(ea.getEventType())
    {
    case(osgGA::GUIEventAdapter::PUSH):
        {
            if (ea.getModKeyMask() == 0)
                return false;

            osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
            if (view == NULL)
                return false;

            osgUtil::LineSegmentIntersector::Intersection intersection;
            osg::NodePath node_path;
            Renderable* renderable = NULL;
            if (ea.getButtonMask() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
                renderable = computeIntersection<Renderable>(view, ea, intersection, node_path);
            else if (ea.getButtonMask() == osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
                renderable = computePointIntersection<Renderable>(view, ea, intersection, node_path);
            else 
                return false;

            if (renderable == NULL)
                return false;

            renderable->pickEvent(ea.getModKeyMask(), intersection.getWorldIntersectPoint());
            return true;
        }
        break;
    default:
        return false;
    }

    return false;
}
Exemplo n.º 10
0
bool
GeometrySelector::handle( const osgGA::GUIEventAdapter& ea
                        , osgGA::GUIActionAdapter& aa
                        )
{
    // RECORD_INFO("reaching here");
    osgViewer::View* viewer = dynamic_cast<osgViewer::View*>(&aa);

    if ( !viewer )
    {
        return false;

    }

    bool drag_event_occurred = ea.getEventType() & osgGA::GUIEventAdapter::DRAG;
    bool push_event_occurred = ea.getEventType() & osgGA::GUIEventAdapter::PUSH;
    bool release_event_occurred = ea.getEventType() & osgGA::GUIEventAdapter::RELEASE;
    bool left_mouse_button_pressed = ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON;
    bool ctrl_key_pressed = ea.getModKeyMask() &  osgGA::GUIEventAdapter::MODKEY_CTRL;

    if(left_mouse_button_pressed && push_event_occurred)
    {
        Geometry * geometry = _get_intersection(ea,viewer);
        bool blank_click    = geometry == nullptr;
        if(blank_click)
        {
            id = "";
            selected = false;
            RECORD_INFO("not selected");
        }
        else
        {
            id = geometry -> getName();
            selected = true;
            RECORD_INFO(std::string("Selected") + geometry -> getName() );
        }
    }
    else
    {
        selected = false;
    }
    return false;
}
Exemplo n.º 11
0
 void write(const osgGA::GUIEventAdapter& event)
 {
     writeUInt(event.getEventType());
     writeUInt(event.getKey());
     writeUInt(event.getButton());
     writeInt(event.getWindowX());
     writeInt(event.getWindowY());
     writeUInt(event.getWindowWidth());
     writeUInt(event.getWindowHeight());
     writeFloat(event.getXmin());
     writeFloat(event.getYmin());
     writeFloat(event.getXmax());
     writeFloat(event.getYmax());
     writeFloat(event.getX());
     writeFloat(event.getY());
     writeUInt(event.getButtonMask());
     writeUInt(event.getModKeyMask());
     writeDouble(event.getTime());
 }
Exemplo n.º 12
0
bool SaveRestoreHandler::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
{
    if( ea.getEventType() != osgGA::GUIEventAdapter::KEYDOWN )
        return( false );
    const bool ctrl( ( ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL ) != 0 );

    if( ea.getKey() == osgGA::GUIEventAdapter::KEY_Insert )
    {
        if( _pt != NULL )
            _pt->pause( true );
        capture();
        if( _pt != NULL )
            _pt->pause( false );
        return( true );
    }
    else if( ea.getKey() == osgGA::GUIEventAdapter::KEY_Delete )
    {
        if( _pt != NULL )
            _pt->pause( true );
        reset();
        if( _pt != NULL )
            _pt->pause( false );
        return( true );
    }
    else if( ea.getKey() == osgGA::GUIEventAdapter::KEY_F1 )
    {
        save();
        return( true );
    }
    else if( ea.getKey() == osgGA::GUIEventAdapter::KEY_F2 )
    {
        if( _pt != NULL )
            _pt->pause( true );
        capture();
        if( _pt != NULL )
            _pt->pause( false );
        save();
        return( true );
    }
    return( false );
}
Exemplo n.º 13
0
bool OsgKeyboardHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&)
{
	bool result = false;

	switch (ea.getEventType())
	{
		case (osgGA::GUIEventAdapter::KEYDOWN) :
			{
				// Note that we are setting the modifier mask here instead of the modifier itself
				m_keyboardScaffold.lock()->updateDevice(ea.getUnmodifiedKey(), ea.getModKeyMask());
				result = true;
				break;
			}
		case (osgGA::GUIEventAdapter::KEYUP) :
			{
				m_keyboardScaffold.lock()->updateDevice(KeyCode::NONE, ModKeyMask::MODKEY_NONE);
				result = true;
				break;
			}
		default:
			result = false;
			break;
	}

	// We wan to to support some of the osg viewer keys, pass these through, we will still receive the event, but osg
	// will also react here
	int key = ea.getUnmodifiedKey();
	if (key == 's' || key == 't' || key == 'v' || key == 'w')
	{
		// s: Stats Display
		// t: texturing
		// v: vsync
		// w: wireframe
		result = false;
	}

	return result;
}
Exemplo n.º 14
0
	bool MouseEventHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) {
		if (ea.getEventType()!=osgGA::GUIEventAdapter::RELEASE ||
			ea.getButton()!=osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON ||
			!(ea.getModKeyMask()&osgGA::GUIEventAdapter::MODKEY_CTRL))
				return false;
	
		osgViewer::Viewer* viewer= dynamic_cast<osgViewer::Viewer*>(&aa);
		if (viewer) {
			osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector=
			new osgUtil::LineSegmentIntersector(osgUtil::Intersector::WINDOW, ea.getX(), ea.getY());
			osgUtil::IntersectionVisitor iv(intersector.get());
			// Sólo recorrer aquellos nodos con nodeMask=0x1
			iv.setTraversalMask(~0x1);
			viewer->getCamera()->accept(iv);
			if (intersector->containsIntersections()) {
				//osgUtil::LineSegmentIntersector::Intersection& elegido= *(intersector->getIntersections().begin());
				//orbita= elegido.;
				//std::cout<<"ola k ase\n";
			// Hagamos lo que tengamos que hacer...
			}
		}
		return false;
	}
Exemplo n.º 15
0
bool Dragger::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
    if (ea.getHandled()) return false;

    osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
    if (!view) return false;
    if (!_mapNode.valid()) return false;

    if (ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
    {
        Picker picker( view, this );
        Picker::Hits hits;

        if ( picker.pick( ea.getX(), ea.getY(), hits ) )
        {
            _dragging = true;

            //Check for and handle vertical dragging if necessary
            bool pressedAlt = _modKeyMask && (ea.getModKeyMask() & _modKeyMask) > 0;
            _elevationDragging = (_defaultMode == Dragger::DRAGMODE_VERTICAL && !pressedAlt) || (_defaultMode == Dragger::DRAGMODE_HORIZONTAL && pressedAlt);

            if (_elevationDragging)
            {
              _pointer.reset();

              // set movement range
              // TODO: values 0.0 and 300000.0 are rather experimental
              GeoPoint posStart(_position.getSRS(), _position.x(), _position.y(), 0.0, ALTMODE_ABSOLUTE);
              osg::Vec3d posStartXYZ;
              posStart.toWorld(posStartXYZ);

              GeoPoint posEnd(_position.getSRS(), _position.x(), _position.y(), 300000.0, ALTMODE_ABSOLUTE);
              osg::Vec3d posEndXYZ;
              posEnd.toWorld(posEndXYZ);

              _projector->setLine(posStartXYZ, posEndXYZ);

              // set camera
              osgUtil::LineSegmentIntersector::Intersections intersections;
              osg::Node::NodeMask intersectionMask = 0xffffffff;
              osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
              if (view->computeIntersections(ea.getX(),ea.getY(),intersections, intersectionMask))
              {
                  for (osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin(); hitr != intersections.end(); ++hitr)
                  {
                      _pointer.addIntersection(hitr->nodePath, hitr->getLocalIntersectPoint());
                  }

                  bool draggerFound = false;
                  for (osgManipulator::PointerInfo::IntersectionList::iterator piit = _pointer._hitList.begin(); piit != _pointer._hitList.end(); ++piit)
                  {
                      for (osg::NodePath::iterator itr = piit->first.begin(); itr != piit->first.end(); ++itr)
                      {
                          Dragger* dragger = dynamic_cast<Dragger*>(*itr);
                          if (dragger==this)
                          {
                            draggerFound = true;
                              osg::Camera *rootCamera = view->getCamera();
                              osg::NodePath nodePath = _pointer._hitList.front().first;
                              osg::NodePath::reverse_iterator ritr;
                              for (ritr = nodePath.rbegin(); ritr != nodePath.rend(); ++ritr)
                              {
                                  osg::Camera* camera = dynamic_cast<osg::Camera*>(*ritr);
                                  if (camera && (camera->getReferenceFrame()!=osg::Transform::RELATIVE_RF || camera->getParents().empty()))
                                  {
                                       rootCamera = camera;
                                       break;
                                  }
                              }
                              _pointer.setCamera(rootCamera);
                              _pointer.setMousePosition(ea.getX(), ea.getY());

                              break;
                          }
                      }

                      if (draggerFound)
                        break;
                  }
              }
            }

            aa.requestRedraw();
            return true;
        }
    }
    else if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
    {
        _elevationDragging = false;

        if ( _dragging )
        {
            _dragging = false;
            firePositionChanged();
        }

        aa.requestRedraw();
    }
    else if (ea.getEventType() == osgGA::GUIEventAdapter::DRAG)
    {
        if (_elevationDragging) 
        {
            _pointer._hitIter = _pointer._hitList.begin();
            _pointer.setMousePosition(ea.getX(), ea.getY());

            if (_projector->project(_pointer, _startProjectedPoint)) 
            {
                //Get the absolute mapPoint that they've drug it to.
                GeoPoint projectedPos;
                projectedPos.fromWorld(_position.getSRS(), _startProjectedPoint);

                // make sure point is not dragged down below
                // TODO: think of a better solution / HeightAboveTerrain performance issues?
                if (projectedPos.z() >= _verticalMinimum)
                {
                    //If the current position is relative, we need to convert the absolute world point to relative.
                    //If the point is absolute then just emit the absolute point.
                    if (_position.altitudeMode() == ALTMODE_RELATIVE)
                    {
                        projectedPos.transformZ(ALTMODE_RELATIVE, getMapNode()->getTerrain());
                    }

                    setPosition( projectedPos );
                    aa.requestRedraw();
                }
            }

            return true;
        }
        
        if (_dragging)
        {
            osg::Vec3d world;
            if ( getMapNode() && getMapNode()->getTerrain()->getWorldCoordsUnderMouse(view, ea.getX(), ea.getY(), world) )
            {
                //Get the absolute mapPoint that they've drug it to.
                GeoPoint mapPoint;
                mapPoint.fromWorld( getMapNode()->getMapSRS(), world );
                //_mapNode->getMap()->worldPointToMapPoint(world, mapPoint);

                //If the current position is relative, we need to convert the absolute world point to relative.
                //If the point is absolute then just emit the absolute point.
                if (_position.altitudeMode() == ALTMODE_RELATIVE)
                {
                    mapPoint.alt() = _position.alt();
                    mapPoint.altitudeMode() = ALTMODE_RELATIVE;
                }

                setPosition( mapPoint );
                aa.requestRedraw();
                return true;
            }
        }
    }   
    else if (ea.getEventType() == osgGA::GUIEventAdapter::MOVE)
    {
        Picker picker( view, this );
        Picker::Hits hits;

        if ( picker.pick( ea.getX(), ea.getY(), hits ) )
        {
            setHover( true );
        }
        else
        {
            setHover( false );
        }        
        aa.requestRedraw();
    }
    return false;
}
Exemplo n.º 16
0
bool LaunchHandler::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& )
{
    // We want a shift-leftmouse event. Return false if we don't have it.
    if( ( ea.getEventType() != osgGA::GUIEventAdapter::PUSH ) ||
        ( ea.getButton() != osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON ) ||
        ( ( ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT ) == 0 ) )
        return( false );

    osg::Matrix view = _camera->getViewMatrix();
    osg::Vec3 look, at, up;
    view.getLookAt( look, at, up );

    osg::Matrix proj = _camera->getProjectionMatrix();
    double fovy, aspect, zNear, zFar;
    proj.getPerspective( fovy, aspect, zNear, zFar );

    view.invert( view );
    proj.invert( proj );
    osg::Vec4 clip( ea.getXnormalized() * zFar, ea.getYnormalized() * zFar, zFar, zFar );
    osg::Vec4 wc = clip * proj * view;

    const osg::Vec3 launchPos = look + ( up * ( _launchModel->getBound()._radius * 2. ) );

    osg::Matrix parentTrans = osg::Matrix::translate( launchPos );
    osg::Vec3 launchDir = osg::Vec3( wc[0], wc[1], wc[2] ) - launchPos;
    launchDir.normalize();

    osg::ref_ptr< osgwTools::AbsoluteModelTransform > amt = new osgwTools::AbsoluteModelTransform;
    amt->setDataVariance( osg::Object::DYNAMIC );
    amt->addChild( _launchModel.get() );

    _attachPoint->addChild( amt.get() );
    _nodeList.push_back( amt.get() );

    osg::ref_ptr< osgbDynamics::CreationRecord > cr = new osgbDynamics::CreationRecord;
    cr->_sceneGraph = amt.get();
    cr->_mass = 1.;
    cr->_parentTransform = parentTrans;
    btRigidBody* rb = osgbDynamics::createRigidBody( cr.get(), _launchCollisionShape );
    rb->setLinearVelocity( osgbCollision::asBtVector3( launchDir * _initialVelocity ) );
    rb->setAngularVelocity( btVector3( .2, .3, 1.5 ) );

    osgbDynamics::MotionState* motion = static_cast< osgbDynamics::MotionState* >( rb->getMotionState() );
    if( _tb != NULL )
        motion->registerTripleBuffer( _tb );
    if( _msl != NULL )
        _msl->insert( motion );

    if( _pt != NULL )
        _pt->pause( true );

    bool added( false );
    amt->setUserData( new osgbCollision::RefRigidBody( rb ) );
    if( (_group != 0) || (_mask != 0) )
    {
        // Collision filters were specified. Get the discrete dynamics world.
        btDiscreteDynamicsWorld* ddw = dynamic_cast< btDiscreteDynamicsWorld* >( _dw );
        if( ddw != NULL )
        {
            ddw->addRigidBody( rb, _group, _mask );
            added = true;
        }
    }
    if( !added )
    {
        // This is both the main path for not using collision filters, and
        // also the fallback if the btDiscreteDynamicsWorld* dynamic cast fails.
        _dw->addRigidBody( rb );
    }

    if( _pt != NULL )
        _pt->pause( false );

    return( true );
}
Exemplo n.º 17
0
bool ElevationDragger::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
    bool ret = true;
    if (ea.getHandled()) {
        ret = false;
    }
    else
    {
        bool handled = false;
        if (_elevationMode)
        {
            if (ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
            {
                ret = osgEarth::Dragger::handle(ea, aa);
                if (ret) 
                {
                    bool pressedAlt = ((ea.getModKeyMask() & _modKeyMask) > 0);
                    if (pressedAlt)
                    {
                        _pointer.reset();

                        // set movement range
                        // TODO: values 0.0 and 300000.0 are rather experimental
                        GeoPoint posStart(_position.getSRS(), _position.x(), _position.y(), 0.0, ALTMODE_ABSOLUTE);
                        osg::Vec3d posStartXYZ;
                        posStart.toWorld(posStartXYZ);

                        GeoPoint posEnd(_position.getSRS(), _position.x(), _position.y(), 300000.0, ALTMODE_ABSOLUTE);
                        osg::Vec3d posEndXYZ;
                        posEnd.toWorld(posEndXYZ);

                        _projector->setLine(posStartXYZ, posEndXYZ);

                        // set camera
                        osgUtil::LineSegmentIntersector::Intersections intersections;
                        osg::Node::NodeMask intersectionMask = 0xffffffff;
                        osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
                        if (view->computeIntersections(ea.getX(),ea.getY(),intersections, intersectionMask))
                        {
                            for (osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin(); hitr != intersections.end(); ++hitr)
                            {
                                _pointer.addIntersection(hitr->nodePath, hitr->getLocalIntersectPoint());
                            }
                            for (osg::NodePath::iterator itr = _pointer._hitList.front().first.begin(); itr != _pointer._hitList.front().first.end(); ++itr)
                            {
                                ElevationDragger* dragger = dynamic_cast<ElevationDragger*>(*itr);
                                if (dragger==this)
                                {
                                    osg::Camera *rootCamera = view->getCamera();
                                    osg::NodePath nodePath = _pointer._hitList.front().first;
                                    osg::NodePath::reverse_iterator ritr;
                                    for (ritr = nodePath.rbegin(); ritr != nodePath.rend(); ++ritr)
                                    {
                                        osg::Camera* camera = dynamic_cast<osg::Camera*>(*ritr);
                                        if (camera && (camera->getReferenceFrame()!=osg::Transform::RELATIVE_RF || camera->getParents().empty()))
                                        {
                                             rootCamera = camera;
                                             break;
                                        }
                                    }
                                    _pointer.setCamera(rootCamera);
                                    _pointer.setMousePosition(ea.getX(), ea.getY());
                                }
                            }
                        }

                        _elevationDragging = true;
                    }
                }
                handled = true;
            }
            else if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
            {
                _elevationDragging = false;
            }
            else if (ea.getEventType() == osgGA::GUIEventAdapter::DRAG) 
            {
                if (_elevationDragging) 
                {
                    _pointer._hitIter = _pointer._hitList.begin();
                    _pointer.setMousePosition(ea.getX(), ea.getY());

                    if (_projector->project(_pointer, _startProjectedPoint)) 
                    {
                        //Get the absolute mapPoint that they've drug it to.
                        GeoPoint projectedPos;
                        projectedPos.fromWorld(_position.getSRS(), _startProjectedPoint);

                        // make sure point is not dragged down below
                        // TODO: think of a better solution / HeightAboveTerrain performance issues?
                        if (projectedPos.z() > 0)
                        {
                            //If the current position is relative, we need to convert the absolute world point to relative.
                            //If the point is absolute then just emit the absolute point.
                            if (_position.altitudeMode() == ALTMODE_RELATIVE)
                            {
                                projectedPos.alt() = _position.alt();
                                projectedPos.altitudeMode() = ALTMODE_RELATIVE;
                            }

                            setPosition( projectedPos );
                            aa.requestRedraw();
                        }
                    }

                    handled = true;
                }
            }
        }
        
        if (!handled) {
            ret = osgEarth::Dragger::handle(ea, aa);
        }
    }
    return ret;
}
Exemplo n.º 18
0
bool
Selector::handle( const osgGA::GUIEventAdapter& ea
                , osgGA::GUIActionAdapter& aa
                )
{
    osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);

    if ( !viewer )
    {
        return false;
    }

    // Geometry * geometry   = _get_intersection(ea,viewer);
    // cout << geometry;
    // bool blank_click      = geometry == nullptr;
    // if(!blank_click)
    // {
    //     RECORD_INFO("Compartment clicked " + geometry -> getName());
    // }
    // else
    // {
    //     // return true;
    //     // RECORD_INFO("Problem");
    // }

    if(select_info -> get_event_type() == 2)
    {
        // RECORD_INFO("Event Type => 2");
        return true;
    }

    // select_info -> set_event_type(0);
    // select_info -> set_id("");

    // if(ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
    // {
    //     RECORD_INFO(to_string(mode));
    //     if(mode == -1)
    //     {
    //         return false;
    //     }
    //     if(mode == 2)
    //     {
    //         menu -> exec(QCursor::pos());
    //     }
    //     if(mode == 3)
    //     {
    //         menu -> exec(QCursor::pos());
    //     }
    //     mode = -1;
    //     return true;
    // }

    // if(ea.getEventType() == osgGA::GUIEventAdapter::DRAG)
    // {
    //     QDrag *drag = new QDrag(this);
    //     // The data to be transferred by the drag and drop operation is contained in a QMimeData object
    //     QMimeData *data = new QMimeData;
    //     data->setText("This is a test");
    //     // Assign ownership of the QMimeData object to the QDrag object.
    //     drag->setMimeData(data);
    //     // Start the drag and drop operation
    //     drag->start();
    // }

    bool drag_event_occurred = ea.getEventType() & osgGA::GUIEventAdapter::DRAG;
    bool push_event_occurred = ea.getEventType() & osgGA::GUIEventAdapter::PUSH;
    bool release_event_occurred = ea.getEventType() & osgGA::GUIEventAdapter::RELEASE;
    bool left_mouse_button_pressed = ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON;
    bool ctrl_key_pressed = ea.getModKeyMask() &  osgGA::GUIEventAdapter::MODKEY_CTRL;

    if(left_mouse_button_pressed && push_event_occurred && ctrl_key_pressed)
    {
        Geometry * geometry = _get_intersection(ea,viewer);
        bool blank_click    = geometry == nullptr;
        if(blank_click)
        {
            _deselect_everything();
            return false;
        }
        else
        {
            _select_compartment(geometry);
            RECORD_INFO("Compartment clicked " + geometry -> getName());
            // viewer -> emit_signal(geometry -> getName());
            select_info -> set_event_type(2);
            select_info -> set_id(geometry -> getName().c_str());
            return true;
        }
        return false;
    }

    if(release_event_occurred && left_mouse_button_pressed)
    {
        Geometry * geometry   = _get_intersection(ea,viewer);
        bool blank_click      = geometry == nullptr;
        bool selection_exists = false; //blank_click ? false : selections.find(geometry -> getName()) == selection.end()
        if(!ctrl_key_pressed)
        {
            if(blank_click)
            {
                _deselect_everything();
            }
            else
            {
                // RECORD_INFO("Select Compartment"); // do nothing
                _select_compartment(geometry);
                select_info -> set_event_type(1);
                select_info -> set_id(geometry -> getName().c_str());
                return true;
            }
        }
        return false;
        // else
        // {
        //     if(blank_click)
        //     {
        //         RECORD_INFO("Deselect Everything."); // do nothing
        //         // _deselect_everything();
        //     }
        //     else if(selection_exists)
        //     {
        //         RECORD_INFO("Select Neuron.");
        //         _select_neuron(geometry);
        //     }
        //     else
        //     {
        //         RECORD_INFO("Select Compartment"); // do nothing
        //         // _deselect_everything();
        //         _select_compartment(geometry);
        //     }
        // }
    }

    // if(ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
    // {
    //     if(ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
    //     {
    //         Geometry * geometry = _get_intersection(ea,viewer);
    //         if(geometry)
    //         {
    //             if
    //             {
    //                 _select_compartment(geometry);
    //                 mode = 0;
    //             }
    //             else
    //             {
    //                 _select_neuron(geometry);
    //                 mode = 1;
    //             }
    //             return true;
    //         }
    //         mode = -1;
    //         return false;
    //     }

    //     if(ea.getButton() == osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
    //     {
    //         Geometry * geometry = _get_intersection(ea,viewer);
    //         if(geometry)
    //         {
    //             if(ea.getModKeyMask() &  osgGA::GUIEventAdapter::MODKEY_CTRL)
    //             {
    //                 _select_compartment(geometry);
    //                 mode = 2;
    //             }
    //             else
    //             {
    //                 _select_neuron(geometry);
    //                 mode = 3;
    //             }
    //             return true;
    //         }
    //         mode = -1;
    //         return false;
    //     }
    // }
    return false;
}
Exemplo n.º 19
0
bool MultiCamViewer::handle(const osgGA::GUIEventAdapter& ea,
		osgGA::GUIActionAdapter& aa) {
	//Show the visualizations from the last rendered frame:
	//display_raw_image_overlay();//TEMP - disable the overlay display for speed

	switch (ea.getEventType()) {
	case osgGA::GUIEventAdapter::KEYDOWN:
		switch (ea.getKey()) {

//		//Extract the whole core scene to a single OBJ file:
//		case osgGA::GUIEventAdapter::KEY_E:
//			//DEBUG:
//			//std::cout << "[e] pressed" << std::endl;
//			extract_core_scene_to_ply();
//			break;
//

		//Toggle aplha of colour rendering:
		case osgGA::GUIEventAdapter::KEY_A:
			if (alpha == 0.f)
				alpha = 0.7f;
			else {
				alpha = 0.f;
			}
			update_dynamics();
			break;

			//Toggle colour rendering:
		case osgGA::GUIEventAdapter::KEY_C:
			with_colour = !with_colour;
			update_dynamics();
			break;

			//Toggle cam 1 visibility:
		case osgGA::GUIEventAdapter::KEY_1:
			cam_vis_switch->setValue(0, !cam_vis_switch->getValue(0));
			last_cam_index = 0;
			update_dynamics();
			break;

			//Toggle cam 2 visibility:
		case osgGA::GUIEventAdapter::KEY_2:
			cam_vis_switch->setValue(1, !cam_vis_switch->getValue(1));
			last_cam_index = 1;
			update_dynamics();
			break;

			//Toggle cam 3 visibility:
		case osgGA::GUIEventAdapter::KEY_3:
			cam_vis_switch->setValue(2, !cam_vis_switch->getValue(2));
			last_cam_index = 3;
			update_dynamics();
			break;

			//Toggle all cameras visibility
		case osgGA::GUIEventAdapter::KEY_4:
			cam_vis_switch->setValue(0, !cam_vis_switch->getValue(0));
			cam_vis_switch->setValue(1, !cam_vis_switch->getValue(1));
			cam_vis_switch->setValue(2, !cam_vis_switch->getValue(2));
			update_dynamics();
			break;
			//Write out the entire rendered sequence:
		case osgGA::GUIEventAdapter::KEY_Y:
			//DEBUG:
			//std::cout << "[y] pressed" << std::endl;

			//Pause:
			paused = true;
			//Cycle through frames and save them:
			for (int i = begin_frame_no; i <= end_frame_no; i++) {
				disp_frame_no = i;
				update_dynamics();
				viewer.frame();
				viewer.frame(); // necessary to avoid incomplete rendering in buffers
				save_image_freeview();
			}
			break;

			//Exit the app, this avoids the clean up errors.
		case osgGA::GUIEventAdapter::KEY_Escape:
			exit(EXIT_SUCCESS);
			break;

			//Toggle playing/pausing
		case osgGA::GUIEventAdapter::KEY_P:
			//DEBUG:
			//std::cout << "[p] pressed" << std::endl;
			paused = (!paused);
			break;

			//Increment frame number
		case osgGA::GUIEventAdapter::KEY_Right:
			//DEBUG:
			//std::cout << "[Right] pressed" << std::endl;
			if (disp_frame_no < end_frame_no) {
				disp_frame_no++;
				update_dynamics();
			} else {
				update_dynamics();
			}
			break;

			//Decrement frame number:
		case osgGA::GUIEventAdapter::KEY_Left:
			//DEBUG:
			//std::cout << "[Left] pressed" << std::endl;
			if (disp_frame_no > begin_frame_no) {
				disp_frame_no--;
				update_dynamics();
			} else {
				update_dynamics();
			}
			break;

		case osgGA::GUIEventAdapter::KEY_V:
			if (manual_origin_set && manual_axis_rot) {
				cam_calibrator.manual_axis_rotation(0.001, current_axis_manual);
				update_dynamics();
			}
			break;
		case osgGA::GUIEventAdapter::KEY_B:
			if (manual_origin_set && manual_axis_rot) {
				cam_calibrator.manual_axis_rotation(-0.001,
						current_axis_manual);
				update_dynamics();
			}
			break;
		case osgGA::GUIEventAdapter::KEY_N:
			if (manual_origin_set && manual_axis_rot) {
				current_axis_manual++;
				if (current_axis_manual == 3) {
					current_axis_manual = 0;
				}
			}
			break;
		case osgGA::GUIEventAdapter::KEY_M:
			if (manual_origin_set && manual_axis_rot) {
				cam_calibrator.save_all_cameras(_dataset_path);
				update_dynamics();
			}
			break;
		default:
			break;
		}
		break;
	default:
		break;
	}

	if (manual_origin_set
			&& ea.getEventType() == osgGA::GUIEventAdapter::RELEASE
			&& ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON
			&& (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL)) {
		set_calibration_point(ea, aa);
	}

	if (set_ground_truth && ea.getEventType() == osgGA::GUIEventAdapter::RELEASE
			&& ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON
			&& (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL)) {
		set_ground_truth_point(ea, aa);
	}

	//Play the sequence:
	if (!paused) {
		if (disp_frame_no < end_frame_no) {

			double current_ticks = (double) cv::getTickCount();
			float elapsed_time = (current_ticks - last_frame_tick_count)
					/ ((double) cv::getTickFrequency());
			if (elapsed_time > frame_period_s) {

				//Set last ticks:
				last_frame_tick_count = current_ticks;

				//Increment the frame:
				disp_frame_no++;
				update_dynamics();
			}
		}
		//Reset to beginning:
		else {
			disp_frame_no = begin_frame_no;
			//Don't automatically replay:
			paused = true;
		}
	}

	return skel_controller.handle(ea, aa);
}
Exemplo n.º 20
0
bool KeyPadEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*)
{
    switch (ea.getEventType())
    {
    case(osgGA::GUIEventAdapter::FRAME) :
        update(0.0);
        break;
    case(osgGA::GUIEventAdapter::KEYDOWN) :
        if (ea.getModKeyMask() && osgGA::GUIEventAdapter::KEY_Alt_L)
            switch (ea.getKey())
            {
            case osgGA::GUIEventAdapter::KEY_KP_Add:
            case osgGA::GUIEventAdapter::KEY_Plus:
                _posStep.z() -= _delta;
                break;
            case osgGA::GUIEventAdapter::KEY_KP_Subtract:
            case osgGA::GUIEventAdapter::KEY_Minus:
                _posStep.z() += _delta;
                break;
            case osgGA::GUIEventAdapter::KEY_KP_Enter:
            case osgGA::GUIEventAdapter::KEY_Return:
                _posStep.y() += _delta;
                break;
            case osgGA::GUIEventAdapter::KEY_KP_Delete:
            case osgGA::GUIEventAdapter::KEY_Delete:
            case '.':
                _posStep.y() -= _delta;
                break;
            case osgGA::GUIEventAdapter::KEY_KP_1:
            case osgGA::GUIEventAdapter::KEY_KP_End:
            case osgGA::GUIEventAdapter::KEY_1:
            case osgGA::GUIEventAdapter::KEY_End:
                _posStep.x() -= _delta;
                break;
            case osgGA::GUIEventAdapter::KEY_KP_3:
            case osgGA::GUIEventAdapter::KEY_KP_Page_Down:
            case osgGA::GUIEventAdapter::KEY_3:
            case osgGA::GUIEventAdapter::KEY_Page_Down:
                _posStep.x() += _delta;
                break;
            case osgGA::GUIEventAdapter::KEY_KP_0:
            case osgGA::GUIEventAdapter::KEY_0:
            case osgGA::GUIEventAdapter::KEY_KP_Insert:
            case osgGA::GUIEventAdapter::KEY_Insert:
                _posStep = osg::Vec3d(0.0, 0.0, 0.0);
                _oriStep = osg::Vec3d(0.0, 0.0, 0.0);
                break;
                break;
            case osgGA::GUIEventAdapter::KEY_KP_4:
            case osgGA::GUIEventAdapter::KEY_KP_Left:
            case osgGA::GUIEventAdapter::KEY_4:
            case osgGA::GUIEventAdapter::KEY_Left:
                _oriStep.x() += osg::DegreesToRadians(_delta);
                break;
            case osgGA::GUIEventAdapter::KEY_KP_6:
            case osgGA::GUIEventAdapter::KEY_KP_Right:
            case osgGA::GUIEventAdapter::KEY_6:
            case osgGA::GUIEventAdapter::KEY_Right:
                _oriStep.x() -= osg::DegreesToRadians(_delta);
                break;
            case osgGA::GUIEventAdapter::KEY_KP_5:
            case osgGA::GUIEventAdapter::KEY_5:
                _oriStep = osg::Vec3d(0.0, 0.0, 0.0);
                break;
            case osgGA::GUIEventAdapter::KEY_KP_7:
            case osgGA::GUIEventAdapter::KEY_KP_Home:
            case osgGA::GUIEventAdapter::KEY_7:
            case osgGA::GUIEventAdapter::KEY_Home:
                _oriStep.z() -= osg::DegreesToRadians(_delta);
                break;
            case osgGA::GUIEventAdapter::KEY_KP_9:
            case osgGA::GUIEventAdapter::KEY_KP_Page_Up:
            case osgGA::GUIEventAdapter::KEY_9:
            case osgGA::GUIEventAdapter::KEY_Page_Up:
                _oriStep.z() += osg::DegreesToRadians(_delta);
                break;
            case osgGA::GUIEventAdapter::KEY_KP_8:
            case osgGA::GUIEventAdapter::KEY_KP_Up:
            case osgGA::GUIEventAdapter::KEY_8:
            case osgGA::GUIEventAdapter::KEY_Up:
                _oriStep.y() += osg::DegreesToRadians(_delta);
                break;
            case osgGA::GUIEventAdapter::KEY_KP_2:
            case osgGA::GUIEventAdapter::KEY_KP_Down:
            case osgGA::GUIEventAdapter::KEY_2:
            case osgGA::GUIEventAdapter::KEY_Down:
                _oriStep.y() -= osg::DegreesToRadians(_delta);
                break;
            default:
                break;
            }
        break;
    default:
        break;
    }
    return false;
}
Exemplo n.º 21
0
bool CSulGuiEventHandler::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object* pObject, osg::NodeVisitor* pNodeVisitor )
{
    if ( ea.getEventType() & osgGA::GUIEventAdapter::RESIZE )
    {
		float windowWidth = ea.getWindowWidth();
		float windowHeight = ea.getWindowHeight();

		if ( m_fixedDimensions.x()>0 && m_fixedDimensions.y()>0 )
		{
			windowWidth = m_fixedDimensions.x();
			windowHeight = m_fixedDimensions.y();
		}

		signalViewResize( windowWidth, windowHeight );
	}

	if ( m_bPause )
		return false;

    if ( ea.getEventType() & osgGA::GUIEventAdapter::KEYDOWN )
    {
/*
		float w = pViewer->getCamera()->getViewport()->width();
		float h = pViewer->getCamera()->getViewport()->height();
		osg::notify(osg::NOTICE) << "w = " << w << "   h = " << h << std::endl;
*/

		int key = ea.getKey();
		int mod = ea.getModKeyMask();

		if ( key!=-1 )				// -1 if inappropriate for this GUIEventAdapter
		{
			signalKeyDown( key, mod );
			return true;
		}
    }

    if ( ea.getEventType() & osgGA::GUIEventAdapter::MOVE )
    {
		if ( CSulInit::profiler.valid() )
			CSulInit::profiler->start( "CSulGuiEventHandler event MOVE" );
		
		float mouse_x = ea.getX();
		float mouse_y = ea.getYmax()-ea.getY();
		signalMouseMove( mouse_x, mouse_y );
		
		if ( CSulInit::profiler.valid() )
			CSulInit::profiler->end( "CSulGuiEventHandler event MOVE" );
    }

    if ( ea.getEventType() & osgGA::GUIEventAdapter::DRAG )
    {
		if ( CSulInit::profiler.valid() )
			CSulInit::profiler->start( "CSulGuiEventHandler event DRAG" );

		float mouse_x = ea.getX();
		float mouse_y = ea.getYmax()-ea.getY();
		signalMouseDrag( mouse_x, mouse_y );

		if ( CSulInit::profiler.valid() )
			CSulInit::profiler->end( "CSulGuiEventHandler event DRAG" );
    }

    if ( ea.getEventType() & osgGA::GUIEventAdapter::PUSH )
    {
		float mouse_x = ea.getX();
		float mouse_y = ea.getYmax()-ea.getY();

		// deprecated, not well suited for gui
		signalMousePush( mouse_x, mouse_y );

		// send new event
		VEC_EVENT::iterator i = m_vecMousePush.begin();
		VEC_EVENT::iterator ie = m_vecMousePush.end();
		while ( i!=ie )
		{
			CSulGuiEvent* e = *i;
			CSulGuiCanvas* pCanvas = e->m_rGuiCanvas;	// test event against this canvas

			// calc local mouse coords
			osg::NodePath path;
			sulNodePath( *pCanvas, path, 0, true );
			osg::Matrix m = osg::computeLocalToWorld( path );
			float mouse_local_x = mouse_x-m.getTrans().x();
			float mouse_local_y = mouse_y-m.getTrans().y();
			
			// are we inside
			if ( pCanvas->isInside( mouse_local_x, mouse_local_y ) )
			{
				e->m_rGuiCompReceiver->eventMousePush( pCanvas, mouse_local_x, mouse_local_y, mouse_x, mouse_y );
			}
			
			++i;
		}
    }

    if ( ea.getEventType() & osgGA::GUIEventAdapter::RELEASE )
    {
		float mouse_x = ea.getX();
		float mouse_y = ea.getYmax()-ea.getY();

		signalMouseRelease( mouse_x, mouse_y );

		VEC_EVENTDATA vecEventData;

		// send new event
		VEC_EVENT::iterator i = m_vecMouseRelease.begin();
		VEC_EVENT::iterator ie = m_vecMouseRelease.end();
		while ( i!=ie )
		{
			CSulGuiEvent* e = *i;
			CSulGuiCanvas* pCanvas = e->m_rGuiCanvas;	// test event against this canvas

			// calc local mouse coords
			osg::Vec2 mouse_local = pCanvas->getLocal( mouse_x, mouse_y );
			
			// HACK: this checks that the mouse position is also inside the parents canvas (need a better way to handle this)
			bool bCheck = true;			

			// Need to check if there is a parent or we will get a zero index crash 
			if ( !pCanvas->getParents().empty() )
			{
				CSulGuiCanvas* pParent = dynamic_cast<CSulGuiCanvas*>(pCanvas->getParent(0));
				if ( pParent )
				{
					bCheck = pParent->isInsideWorld( mouse_x, mouse_y );
				}
			}
			else
			{
				//TKG Unsure if bCheck should be set to false in this case
				//std::cout << "CSulGuiEventHandler::handle -> line 155 \"Hello\"" << std::endl;
			}
			

			// are we inside
			if ( bCheck && pCanvas->isInside( mouse_local ) )
			{
				// save event data
				eventDataTest ed;
				ed.pReceiver = e->m_rGuiCompReceiver;
				ed.pCanvas = pCanvas;
				ed.mouse_local_x = mouse_local.x();
				ed.mouse_local_y = mouse_local.y();
				vecEventData.push_back( ed );
			}
			
			++i;
		}

		// sort eventData after layer
		std::sort( vecEventData.begin(), vecEventData.end(), sortByLayer );

		// send events and check if handled
		VEC_EVENTDATA::iterator iEDs, iEDe;
		iEDs = vecEventData.begin();
		iEDe = vecEventData.end();
		while ( iEDs!=iEDe )
		{
			bool bHandled = iEDs->pReceiver->eventMouseRelease( 
				iEDs->pCanvas,
				iEDs->mouse_local_x,
				iEDs->mouse_local_y,
				mouse_x,
				mouse_y
			);
			
			if ( bHandled )
			{
				// echo who handled it
			//	osg::notify(osg::NOTICE) << "EVENT MOUSE RELEASE: " << iEDs->pCanvas->getCompName() << " (" << iEDs->pCanvas->getLayer() << ")" << std::endl;
				break;
			}
			

			++iEDs;
		}
    }

	return false;
}
Exemplo n.º 22
0
bool KeystoneHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& /*aa*/, osg::Object* obj, osg::NodeVisitor* /*nv*/)
{
    osg::Camera* camera = obj ? obj->asCamera() : 0;
    osg::Viewport* viewport = camera ? camera->getViewport() : 0;

    if (!viewport) return false;

    if (ea.getEventType()==osgGA::GUIEventAdapter::KEYDOWN && ((ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_LEFT_CTRL || ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_RIGHT_CTRL)))
    {
        if (ea.getUnmodifiedKey()=='g')
        {
            setKeystoneEditingEnabled(!getKeystoneEditingEnabled());
            return true;
        }
        if (ea.getUnmodifiedKey()=='r')
        {
            _selectedRegion = NONE_SELECTED;
            _startControlPoints->reset();
            _currentControlPoints->reset();
            return true;
        }
        else if (ea.getUnmodifiedKey()=='s')
        {
            _keystone->writeToFile();
            return true;
        }
    }

    bool haveCameraMatch = false;
    float x = ea.getXnormalized();
    float y = ea.getYnormalized();
    for(unsigned int i=0; i<ea.getNumPointerData(); ++i)
    {
        const osgGA::PointerData* pd = ea.getPointerData(i);
        if (pd->object==obj)
        {
            haveCameraMatch = true;
            x = pd->getXnormalized();
            y = pd->getYnormalized();
            break;
        }
    }

    if (!haveCameraMatch || !getKeystoneEditingEnabled()) return false;

    switch(ea.getEventType())
    {
    case(osgGA::GUIEventAdapter::PUSH):
    {
        osg::Vec2d scale = incrementScale(ea);
        if (scale.length2()!=0.0)
        {
            _selectedRegion = computeRegion(ea);
            (*_startControlPoints) = (*_currentControlPoints);
            _startPosition.set(x,y);
        }
        else
        {
            _selectedRegion = NONE_SELECTED;
        }
        return false;
    }
    case(osgGA::GUIEventAdapter::DRAG):
    {
        if (_selectedRegion!=NONE_SELECTED)
        {
            (*_currentControlPoints) = (*_startControlPoints);
            osg::Vec2d currentPosition(x, y);
            osg::Vec2d delta(currentPosition-_startPosition);
            osg::Vec2d scale = incrementScale(ea);
            move(_selectedRegion, osg::Vec2d(delta.x()*scale.x(), delta.y()*scale.y()) );
            return true;
        }
        return false;
    }
    case(osgGA::GUIEventAdapter::RELEASE):
    {
        _selectedRegion = NONE_SELECTED;
        return false;
    }
    case(osgGA::GUIEventAdapter::KEYDOWN):
    {
        if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Up)
        {
            move(computeRegion(ea), osg::Vec2d(0.0, _keyIncrement.y()*incrementScale(ea).y()) );
        }
        else if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Down)
        {
            move(computeRegion(ea), osg::Vec2d(0.0, -_keyIncrement.y()*incrementScale(ea).y()) );
        }
        else if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Left)
        {
            move(computeRegion(ea), osg::Vec2d(-_keyIncrement.x()*incrementScale(ea).x(), 0.0) );
        }
        else if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Right)
        {
            move(computeRegion(ea), osg::Vec2d(_keyIncrement.x()*incrementScale(ea).x(), 0.0) );
        }
        else if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_7 || ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Home)
        {
            _currentControlPoints->setTopLeft(osg::Vec2d(x, y));
        }
        else if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_9 || ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Page_Up)
        {
            _currentControlPoints->setTopRight(osg::Vec2d(x, y));
        }
        else if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_3 || ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Page_Down)
        {
            _currentControlPoints->setBottomRight(osg::Vec2d(x, y));
        }
        else if (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_1 || ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_End)
        {
            _currentControlPoints->setBottomLeft(osg::Vec2d(x, y));
        }
        return false;
    }
    default:
        return false;
    }
}
Exemplo n.º 23
0
  /** Automatically fires when an event is detected.
   * @param ea : osgGA::GUIEventAdapter
   * @param aa : osgGA::GUIActionAdapter
   * @return false : the return value tells if the event is treated.
   * If true is returned, OSG consider that the event is no longer needed to other handlers, and they will ignore it. The camera manipulator is on of these other handlers.
   */
bool lgInteraction::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
{
    // Ctrl + left click : label picking
    if (ea.getEventType()==osgGA::GUIEventAdapter::RELEASE && ea.getButton()==osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON && ea.getModKeyMask()&osgGA::GUIEventAdapter::MODKEY_CTRL )
    {
        //viewer
        ref_ptr<osgViewer::Viewer> viewer = dynamic_cast<osgViewer::Viewer*>(&aa);

        if ( viewer )
        {
            // To know what the user clicked on:
            ref_ptr<osgUtil::LineSegmentIntersector> intersector = new osgUtil::LineSegmentIntersector( osgUtil::Intersector::WINDOW, ea.getX(), ea.getY());
            osgUtil::IntersectionVisitor iv( intersector.get() );
            iv.setTraversalMask( ~0x1 );

            viewer->getCamera()->accept( iv );
            //If there is an object
            if ( intersector->containsIntersections() )
            {
                osgUtil::LineSegmentIntersector::Intersection result = *(intersector->getIntersections().begin());

                // If it is a label :
                if (result.drawable->isSameKindAs(new lgLabel()))
                {
                    //Add the label to the list of selected labels
                    selectedLabels.push_back(dynamic_cast<lgLabel*>(result.drawable.get()));

                    // Disable depth testing so geometry is draw regardless of depth values of geometry.
                    ref_ptr<StateSet> stateSet = selectedLabels.at(selectedLabels.size()-1)->getUpdatedMatrix()->getOrCreateStateSet();
                    stateSet->setMode(GL_DEPTH_TEST,StateAttribute::OFF);
                    stateSet->setRenderingHint( StateSet::TRANSPARENT_BIN );

                    // Make sure this geometry is draw last. RenderBins are handled in numerical order so set bin number to 11
                    stateSet->setRenderBinDetails(11, "DepthSortedBin");

                    //Bounding box
                    if (selectedLabels.at(selectedLabels.size()-1)->getDrawMode() < osgText::Text::BOUNDINGBOX )
                    {
                        selectedLabels.at(selectedLabels.size()-1)->setDrawMode(selectedLabels.at(selectedLabels.size()-1)->getDrawMode() | osgText::Text::BOUNDINGBOX);
                        selectedLabels.at(selectedLabels.size()-1)->setPreviousDrawMode(selectedLabels.at(selectedLabels.size()-1)->getDrawMode());
                    }
                }
                else
                {
                    //Reset the stateset of the previous selected objects
                    //Clear the list of selected labels
                    for (unsigned i(0); i<selectedLabels.size();i++)
                    {
                        selectedLabels.at(i)->getParent(0)->getParent(0)->setStateSet(new StateSet());
                         if (selectedLabels.at(i)->getPreviousDrawMode() <  osgText::Text::BOUNDINGBOX )
                        {
                            selectedLabels.at(i)->setPreviousDrawMode(selectedLabels.at(i)->getPreviousDrawMode() - osgText::Text::BOUNDINGBOX);
                            selectedLabels.at(i)->setDrawMode( selectedLabels.at(i)->getDefaultDrawMode());
                        }
                    }
                    selectedLabels.clear();
                }
            }
            else
            {
                //Reset the stateset of the previous selected objects
                //Clear the list of selected labels
                for (unsigned i(0); i<selectedLabels.size();i++)
                {
                        selectedLabels.at(i)->getParent(0)->getParent(0)->setStateSet(new StateSet());
                        if (selectedLabels.at(i)->getPreviousDrawMode() <  osgText::Text::BOUNDINGBOX )
                        {
                            selectedLabels.at(i)->setPreviousDrawMode(selectedLabels.at(i)->getPreviousDrawMode() - osgText::Text::BOUNDINGBOX);
                            selectedLabels.at(i)->setDrawMode( selectedLabels.at(i)->getDefaultDrawMode());
                        }
                }
                selectedLabels.clear();
            }
        }
    }
    // 'a' : select every label
    else if (ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN && (ea.getKey() =='a' || ea.getKey()=='A'))
    {
        selectedLabels.clear();
        for (unsigned i(0);i<listLabels.size();i++)
        {
            selectedLabels.push_back(listLabels.at(i));

            // Disable depth testing so geometry is draw regardless of depth values of geometry already draw.
            ref_ptr<StateSet> stateSet = selectedLabels.at(selectedLabels.size()-1)->getUpdatedMatrix()->getOrCreateStateSet();
            stateSet->setMode(GL_DEPTH_TEST,StateAttribute::OFF);
            stateSet->setRenderingHint( StateSet::TRANSPARENT_BIN );

            // Make sure this geometry is draw last. RenderBins are handled in numerical order so set bin number to 11
            stateSet->setRenderBinDetails(11, "DepthSortedBin");

            //Bounding box :
            if (selectedLabels.at(i)->getDrawMode() <  osgText::Text::BOUNDINGBOX )
            {
                selectedLabels.at(i)->setDrawMode(selectedLabels.at(i)->getPreviousDrawMode() | osgText::Text::BOUNDINGBOX);
                selectedLabels.at(i)->setPreviousDrawMode(selectedLabels.at(i)->getDrawMode());
            }
        }
    }
    else
    {
         switch ( ea.getEventType() )
        {
        case osgGA::GUIEventAdapter::KEYDOWN:
            switch ( ea.getKey() )
            {
            // 'q' or 'Q' or Left : decrease the X value of the labels
            case 'q': case 'Q': case osgGA::GUIEventAdapter::KEY_Left :
                for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    selectedLabels.at(i)->getUpdatedMatrix()->setMatrix(selectedLabels.at(i)->getUpdatedMatrix()->getMatrix()*Matrix::translate(-5,0,0));
                }
                break;
            // 'd' or 'D' or Right : increase the X value of the labels
            case 'd': case 'D':  case osgGA::GUIEventAdapter::KEY_Right :
               for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    selectedLabels.at(i)->getUpdatedMatrix()->setMatrix(selectedLabels.at(i)->getUpdatedMatrix()->getMatrix()*Matrix::translate(5,0,0));
                }
                break;
            // 'z' or 'Z' or Up : increase the Y value of the labels
            case 'z': case 'Z': case osgGA::GUIEventAdapter::KEY_Up :
               for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    selectedLabels.at(i)->getUpdatedMatrix()->setMatrix(selectedLabels.at(i)->getUpdatedMatrix()->getMatrix()*Matrix::translate(0,5,0));
                }
                break;
            // 's' or 'S' or Down : decrease the Y value of the labels
            case 's': case 'S': case osgGA::GUIEventAdapter::KEY_Down :
               for (unsigned i(0);i<selectedLabels.size();i++)
                {
                   selectedLabels.at(i)->getUpdatedMatrix()->setMatrix(selectedLabels.at(i)->getUpdatedMatrix()->getMatrix()*Matrix::translate(5,-5,0));
                }
                break;
            // '+' : increase the size of the labels
            case osgGA::GUIEventAdapter::KEY_Plus : case osgGA::GUIEventAdapter::KEY_KP_Add :
                for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    selectedLabels.at(i)->setCharacterSize(selectedLabels.at(i)->getCharacterHeight()+1);
                }
                break;
            // '-' : decrease  the size of the lables
            case osgGA::GUIEventAdapter::KEY_Minus : case osgGA::GUIEventAdapter::KEY_KP_Subtract :
                for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    selectedLabels.at(i)->setCharacterSize(selectedLabels.at(i)->getCharacterHeight()-1);
                }
                break;
            // 'h' or 'H' : hide the labels
            case 'h' : case 'H' :
                for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    if (selectedLabels.at(i)->getDrawMode() != 0)
                    {
                        selectedLabels.at(i)->setDrawMode(0);
                        selectedLabels.at(i)->setPreviousDrawMode(0);
                        if (selectedLabels.at(i)->getInfoLabel() !=NULL) selectedLabels.at(i)->getInfoLabel()->setDrawMode(0);
                    }
                    else
                    {
                        selectedLabels.at(i)->setDrawMode(selectedLabels.at(i)->getDefaultDrawMode() | osgText::Text::BOUNDINGBOX);
                        selectedLabels.at(i)->setPreviousDrawMode(selectedLabels.at(i)->getDrawMode());
                        if (selectedLabels.at(i)->getInfoLabel() !=NULL) selectedLabels.at(i)->getInfoLabel()->setDrawMode(osgText::Text::TEXT);
                    }
                }
                break;
            // 'l' or 'L' : see in dark the objects linked to the selected labels
            case 'l' : case 'L' :
                for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    StateSet * stateset = selectedLabels.at(i)->getUpdatedMatrix()->getParent(0)->getOrCreateStateSet();
                    stateset->setMode(GL_FOG, StateAttribute::ON);

                }
                break;
            // 'm' or 'M' : set the objects linked to the selected labels back to normal
            case 'm' : case 'M' :
                for (unsigned i(0);i<selectedLabels.size();i++)
                {
                    StateSet * stateset = selectedLabels.at(i)->getUpdatedMatrix()->getParent(0)->getOrCreateStateSet();
                    stateset->setMode(GL_FOG, StateAttribute::OFF);
                }
                break;
            // 'i'  or 'I' : show the information label if it exists
            case 'i' : case 'I' :
                for (unsigned i(0);i<selectedLabels.size();i++)
                {
                  if (selectedLabels.at(i)->getInfoLabel() != NULL)
                  {
                      ref_ptr<osgText::Text> infoLabel = selectedLabels.at(i)->getInfoLabel();
                      if (infoLabel->getDrawMode()==0)
                      {
                          infoLabel->setDrawMode(osgText::Text::TEXT);
                          selectedLabels.at(i)->setPositionInit(selectedLabels.at(i)->getPositionInit()+Vec3(0,0,(infoLabel->getBound().zMax()-infoLabel->getBound().zMin())));
                      }
                      else
                      {
                           infoLabel->setDrawMode(0);
                           selectedLabels.at(i)->setPositionInit(selectedLabels.at(i)->getPositionInit()-Vec3(0,0,(infoLabel->getBound().zMax()-infoLabel->getBound().zMin())));
                      }
                  }
                }
                break;
            default:
                break;
            }
            break;
        case osgGA::GUIEventAdapter::MOVE:
            {
                ref_ptr<osgViewer::Viewer> viewer = dynamic_cast<osgViewer::Viewer*>(&aa);

                if ( viewer)
                {
                    // To know where the mouse is:
                    ref_ptr<osgUtil::LineSegmentIntersector> intersector = new osgUtil::LineSegmentIntersector( osgUtil::Intersector::WINDOW, ea.getX(), ea.getY());
                    osgUtil::IntersectionVisitor iv( intersector.get() );
                    iv.setTraversalMask( ~0x1 );

                    viewer->getCamera()->accept( iv );
                    //If there is an object
                    if ( intersector->containsIntersections() )
                    {
                        osgUtil::LineSegmentIntersector::Intersection result = *(intersector->getIntersections().begin());

                        // If it is a label :
                        if (result.drawable->isSameKindAs(new lgLabel()))
                        {
                            if (dynamic_cast<lgLabel*>(result.drawable.get())->isChangingWhenMouse())
                            {
                                //See if it was already mouseLabel
                                if (mouseLabel != result.drawable)
                                {
                                    if (mouseLabel != NULL)
                                    {
                                        int characterSize = mouseLabel->getCharacterHeight();
                                        if (characterSize >2)
                                        {
                                           //Decrease size of the previous label
                                           mouseLabel->setCharacterSize(characterSize-2);
                                        }
                                    }
                                    //Increase size of the label
                                    mouseLabel = dynamic_cast<lgLabel*>(result.drawable.get());
                                    int characterSize = static_cast<lgLabel*>(mouseLabel)->getCharacterHeight();
                                    mouseLabel->setCharacterSize(characterSize+2);
                                }
                            }
                        }
                        //If it is not a label : decrease size of previous label and set to NULL the current label under the mouse
                        else
                        {
                            if (mouseLabel != NULL)
                            {
                                int characterSize = mouseLabel->getCharacterHeight();
                                if (characterSize >2)
                                {
                                    mouseLabel->setCharacterSize(characterSize-2);
                                }
                                mouseLabel = NULL;
                            }
                        }
                    }
                    //If there is no object : decrease size of previous label and set to NULL the current label under the mouse
                    else
                    {
                          if (mouseLabel != NULL)
                            {
                                 int characterSize = mouseLabel->getCharacterHeight();
                                if (characterSize >2)
                                {
                                    mouseLabel->setCharacterSize(characterSize-2);
                                }
                            }
                            mouseLabel = NULL;
                    }
                }
                break;
            }
        default:
            break;
        }
    }
    return false;
}
Exemplo n.º 24
0
//==============================================================================
bool DefaultEventHandler::handle(const osgGA::GUIEventAdapter& ea,
                                 osgGA::GUIActionAdapter&)
{
    mLastModKeyMask = ea.getModKeyMask();

    switch(ea.getEventType())
    {
    case osgGA::GUIEventAdapter::PUSH:
    case osgGA::GUIEventAdapter::DRAG:
    case osgGA::GUIEventAdapter::RELEASE:
    case osgGA::GUIEventAdapter::MOVE:
        mLastCursorPosition[0] = ea.getX();
        mLastCursorPosition[1] = ea.getY();

        break;

    default:
        break;
    }

    switch(ea.getEventType())
    {
    case osgGA::GUIEventAdapter::KEYDOWN:
    {
        switch(ea.getKey())
        {
        case 8: // ctrl+h
        {
            mViewer->switchHeadlights(!mViewer->checkHeadlights());
            return true;
            break;
        }

        case ' ':
        {
            if(mViewer->isAllowingSimulation())
            {
                mViewer->simulate(!mViewer->isSimulating());
                return true;
            }
            break;
        }
        }
    }

    case osgGA::GUIEventAdapter::MOVE:
    {
        if(!mSuppressMovePicks)
            pick(mMovePicks, ea);

        triggerMouseEventHandlers();
        break;
    }

    case osgGA::GUIEventAdapter::PUSH:
    case osgGA::GUIEventAdapter::DRAG:
    case osgGA::GUIEventAdapter::RELEASE:

        assignEventToButtons(mLastButtonEvent, ea);
        eventPick(ea);

        mViewer->updateDragAndDrops();

        triggerMouseEventHandlers();
        break;

    default:
        break;
    }

    return false;
}
Exemplo n.º 25
0
/* virtual */ bool 
av::osg::viewer::InputEventHandler::handle(const ::osgGA::GUIEventAdapter& event, ::osgGA::GUIActionAdapter& action)
{
  logger.trace() << "handle()";

  if (mEventFields->MouseButtonLeftDoubleClick.getValue())
    mEventFields->MouseButtonLeftDoubleClick.setValue(false);
  if (mEventFields->MouseButtonMiddleDoubleClick.getValue())
    mEventFields->MouseButtonMiddleDoubleClick.setValue(false);
  if (mEventFields->MouseButtonRightDoubleClick.getValue())
    mEventFields->MouseButtonRightDoubleClick.setValue(false);
  if (mEventFields->MouseScrollUp.getValue())
    mEventFields->MouseScrollUp.setValue(false);
  if (mEventFields->MouseScrollDown.getValue())
    mEventFields->MouseScrollDown.setValue(false);

  switch(event.getEventType())
  {
    case(::osgGA::GUIEventAdapter::DRAG):
    {
      const ::osg::Vec2 mousePos(event.getX(), event.getY());
      mEventFields->DragEvent.setValue(mousePos);

      break;
    }

    case(::osgGA::GUIEventAdapter::MOVE):
    {
      const ::osg::Vec2 mousePos(event.getX(), event.getY());
      mEventFields->MoveEvent.setValue(mousePos);

      break;
    }

    case(::osgGA::GUIEventAdapter::PUSH):
    case(::osgGA::GUIEventAdapter::RELEASE):
    {
      const unsigned int buttonmask = event.getButtonMask();
      const bool left   = (buttonmask & ::osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) != 0u;
      const bool middle = (buttonmask & ::osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON) != 0u;
      const bool right  = (buttonmask & ::osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON) != 0u;

      if (mEventFields->MouseButtonLeft.getValue() != left)
        mEventFields->MouseButtonLeft.setValue(left);
      if (mEventFields->MouseButtonMiddle.getValue() != middle)
        mEventFields->MouseButtonMiddle.setValue(middle);
      if (mEventFields->MouseButtonRight.getValue() != right)
        mEventFields->MouseButtonRight.setValue(right);

      if (mEventFields->MouseButtons_OnlyLeft.getValue() != (left && !middle && !right))
        mEventFields->MouseButtons_OnlyLeft.setValue(left && !middle && !right);
      if (mEventFields->MouseButtons_OnlyMiddle.getValue() != (!left && middle && !right))
        mEventFields->MouseButtons_OnlyMiddle.setValue(!left && middle && !right);
      if (mEventFields->MouseButtons_OnlyRight.getValue() != (!left && !middle && right))
        mEventFields->MouseButtons_OnlyRight.setValue(!left && !middle && right);
      if (mEventFields->MouseButtons_LeftAndMiddle.getValue() != (left && middle && !right))
        mEventFields->MouseButtons_LeftAndMiddle.setValue(left && middle && !right);
      if (mEventFields->MouseButtons_LeftAndRight.getValue() != (left && !middle && right))
        mEventFields->MouseButtons_LeftAndRight.setValue(left && !middle && right);
      if (mEventFields->MouseButtons_MiddleAndRight.getValue() != (!left && middle && right))
        mEventFields->MouseButtons_MiddleAndRight.setValue(!left && middle && right);
      if (mEventFields->MouseButtons_LeftAndMiddleAndRight.getValue() != (left && middle && right))
        mEventFields->MouseButtons_LeftAndMiddleAndRight.setValue(left && middle && right);

      break;
    }

    case(::osgGA::GUIEventAdapter::DOUBLECLICK):
    {
      switch (event.getButton())
      {
        case ::osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON:
        {
          mEventFields->MouseButtonLeftDoubleClick.setValue(true);
          break;
        }

        case ::osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON:
        {
          mEventFields->MouseButtonMiddleDoubleClick.setValue(true);
          break;
        }

        case ::osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON:
        {
          mEventFields->MouseButtonRightDoubleClick.setValue(true);
          break;
        }

        default:
          break;
      }

      break;
    }

    case(::osgGA::GUIEventAdapter::SCROLL):
    {
      switch (event.getScrollingMotion())
      {
        case ::osgGA::GUIEventAdapter::SCROLL_UP:
        {
          mEventFields->MouseScrollUp.setValue(true);
          break;
        }

        case ::osgGA::GUIEventAdapter::SCROLL_DOWN:
        {
          mEventFields->MouseScrollDown.setValue(true);
          break;
        }

        default:
          break;
      }

      break;
    }

    case(::osgGA::GUIEventAdapter::KEYDOWN):
    case(::osgGA::GUIEventAdapter::KEYUP):
    {
      const bool pressed = (event.getEventType() == ::osgGA::GUIEventAdapter::KEYDOWN);
      const int key = event.getKey();

      const bool shiftPressed =
        (event.getModKeyMask() & (::osgGA::GUIEventAdapter::MODKEY_LEFT_SHIFT |
                                  ::osgGA::GUIEventAdapter::MODKEY_RIGHT_SHIFT)) != 0u;
      const bool ctrlPressed =
        (event.getModKeyMask() & (::osgGA::GUIEventAdapter::MODKEY_LEFT_CTRL |
                                  ::osgGA::GUIEventAdapter::MODKEY_RIGHT_CTRL)) != 0u;
      const bool altPressed =
        (event.getModKeyMask() & (::osgGA::GUIEventAdapter::MODKEY_LEFT_ALT |
                                  ::osgGA::GUIEventAdapter::MODKEY_RIGHT_ALT)) != 0u;

      if (mEventFields->KeyShift.getValue() != shiftPressed)
        mEventFields->KeyShift.setValue(shiftPressed);
      if (mEventFields->KeyCtrl.getValue() != ctrlPressed)
        mEventFields->KeyCtrl.setValue(ctrlPressed);
      if (mEventFields->KeyAlt.getValue() != altPressed)
        mEventFields->KeyAlt.setValue(altPressed);

      if (pressed)
        mKeys.insert(key);
      else
        mKeys.erase(key);

      std::vector<int> keys(mKeys.size());
      std::copy(mKeys.begin(), mKeys.end(), keys.begin());
      mEventFields->KeysPressed.setValue(keys);

      switch (key)
      {
        case ::osgGA::GUIEventAdapter::KEY_Insert:    mEventFields->KeyInsert.setValue(pressed);   break;
        case ::osgGA::GUIEventAdapter::KEY_Delete:    mEventFields->KeyDelete.setValue(pressed);   break;
        case ::osgGA::GUIEventAdapter::KEY_Home:      mEventFields->KeyHome.setValue(pressed);     break;
        case ::osgGA::GUIEventAdapter::KEY_End:       mEventFields->KeyEnd.setValue(pressed);      break;
        case ::osgGA::GUIEventAdapter::KEY_Page_Up:   mEventFields->KeyPageUp.setValue(pressed);   break;
        case ::osgGA::GUIEventAdapter::KEY_Page_Down: mEventFields->KeyPageDown.setValue(pressed); break;
        case ::osgGA::GUIEventAdapter::KEY_Left:      mEventFields->KeyLeft.setValue(pressed);     break;
        case ::osgGA::GUIEventAdapter::KEY_Right:     mEventFields->KeyRight.setValue(pressed);    break;
        case ::osgGA::GUIEventAdapter::KEY_Up:        mEventFields->KeyUp.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_Down:      mEventFields->KeyDown.setValue(pressed);     break;
        case ::osgGA::GUIEventAdapter::KEY_Escape:    mEventFields->KeyEsc.setValue(pressed);      break;
        case ::osgGA::GUIEventAdapter::KEY_Space:     mEventFields->KeySpace.setValue(pressed);    break;
        case ::osgGA::GUIEventAdapter::KEY_Return:    mEventFields->KeyEnter.setValue(pressed);    break;
        case ::osgGA::GUIEventAdapter::KEY_F1:        mEventFields->KeyF1.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F2:        mEventFields->KeyF2.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F3:        mEventFields->KeyF3.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F4:        mEventFields->KeyF4.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F5:        mEventFields->KeyF5.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F6:        mEventFields->KeyF6.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F7:        mEventFields->KeyF7.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F8:        mEventFields->KeyF8.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F9:        mEventFields->KeyF9.setValue(pressed);       break;
        case ::osgGA::GUIEventAdapter::KEY_F10:       mEventFields->KeyF10.setValue(pressed);      break;
        case ::osgGA::GUIEventAdapter::KEY_F11:       mEventFields->KeyF11.setValue(pressed);      break;
        case ::osgGA::GUIEventAdapter::KEY_F12:       mEventFields->KeyF12.setValue(pressed);      break;

      }

      if (altPressed && key == ::osgGA::GUIEventAdapter::KEY_Return && pressed)
      {
        mEventFields->KeyAltReturn.setValue(true);
      }

      break;
    }

    default:
      break;
  }

  return false;
}
Exemplo n.º 26
0
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* /*nv*/)
{
    switch(ea.getEventType())
    {
        case(osgGA::GUIEventAdapter::MOVE):
        {
            if(_currentImageStream.valid() && (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT))
            {
                float scalar = (ea.getXnormalized()+1) / 2.0;
                _currentImageStream->seek(scalar * _currentImageStream->getLength());
            }
        }
        break;

        case(osgGA::GUIEventAdapter::RELEASE):
        {

            osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
            osgUtil::LineSegmentIntersector::Intersections intersections;
            bool foundIntersection = view==0 ? false : view->computeIntersections(ea, intersections);

            if (foundIntersection)
            {
                // use the nearest intersection
                const osgUtil::LineSegmentIntersector::Intersection& intersection = *(intersections.begin());
                osg::Drawable* drawable = intersection.drawable.get();
                osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;

                if (geometry) {
                    osg::Texture* tex = geometry->getStateSet() ? dynamic_cast<osg::Texture*>(geometry->getStateSet()->getTextureAttribute(0, osg::StateAttribute::TEXTURE)) : NULL;
                    if (tex) {
                        osg::ImageStream* is = dynamic_cast<osg::ImageStream*>(tex->getImage(0));
                        if (is)
                        {
                            setColor(_currentGeometry.get(), osg::Vec4(0.7, 0.7, 0.7, 1.0));
                            _currentGeometry = geometry;
                            setColor(_currentGeometry.get(), osg::Vec4(1,1,1,1));
                            _currentImageStream = is;

                            if (is->getStatus() == osg::ImageStream::PLAYING)
                            {
                                is->pause();
                            }
                            else
                            {
                                is->play();
                            }

                        }
                    }
                }
            }

            break;
        }
        case(osgGA::GUIEventAdapter::KEYDOWN):
        {
            if (!_currentImageStream.valid())
                return false;

            if (ea.getKey()=='p')
            {
                osg::ImageStream::StreamStatus playToggle = _currentImageStream->getStatus();
                if (playToggle != osg::ImageStream::PLAYING)
                {
                    std::cout<< _currentImageStream.get() << " Play"<<std::endl;
                    _currentImageStream->play();
                }
                else
                {
                    // playing, so pause
                    std::cout<< _currentImageStream.get() << " Pause"<<std::endl;
                    _currentImageStream->pause();
                }
                return true;
            }
            else if (ea.getKey()=='r')
            {
                std::cout<< _currentImageStream.get() << " Restart"<<std::endl;
                _currentImageStream->rewind();
                _currentImageStream->play();
                return true;
            }
            else if (ea.getKey()=='>')
            {
                std::cout << _currentImageStream.get() << " Seeking"<<std::endl;
                _currentImageStream->seek(_currentImageStream->getCurrentTime() + 1.0);

                return true;
            }
            else if (ea.getKey()=='L')
            {
                if ( _currentImageStream->getLoopingMode() == osg::ImageStream::LOOPING)
                {
                    std::cout<< _currentImageStream.get() << " Toggle Looping Off"<<std::endl;
                    _currentImageStream->setLoopingMode( osg::ImageStream::NO_LOOPING );
                }
                else
                {
                    std::cout<< _currentImageStream.get() << " Toggle Looping On"<<std::endl;
                    _currentImageStream->setLoopingMode( osg::ImageStream::LOOPING );
                }
                return true;
            }
            else if (ea.getKey()=='+')
            {
                double tm = _currentImageStream->getTimeMultiplier();
                tm += 0.1;
                _currentImageStream->setTimeMultiplier(tm);
                std::cout << _currentImageStream.get() << " Increase speed rate "<< _currentImageStream->getTimeMultiplier() << std::endl;

                return true;
            }
            else if (ea.getKey()=='-')
            {
                double tm = _currentImageStream->getTimeMultiplier();
                tm -= 0.1;
                _currentImageStream->setTimeMultiplier(tm);
                std::cout << _currentImageStream.get() << " Decrease speed rate "<< _currentImageStream->getTimeMultiplier() << std::endl;

                return true;
            }
            else if (ea.getKey()=='o')
            {
                std::cout<< _currentImageStream.get() << " Frame rate  "<< _currentImageStream->getFrameRate() <<std::endl;

                return true;
            }
            return false;
        }

        default:
            return false;
    }
    return false;
}
Exemplo n.º 27
0
void ViewerManipulator::handleMouse(osgViewer::View* view, const osgGA::GUIEventAdapter& ea)
{
    using namespace osgGA;

	osg::ref_ptr<GroupNode> hitNode, drawNode;
	
	float dX = lastX - ea.getXnormalized();
	float dY = lastY - ea.getYnormalized();

	float dXclick = clickX - ea.getXnormalized();
	float dYclick = clickY - ea.getYnormalized();

	unsigned int buttonMask = ea.getButtonMask();
	unsigned int modkeyMask = ea.getModKeyMask();

	// adjust modkeyMask to ignore numlock and capslock:
	if (modkeyMask>=GUIEventAdapter::MODKEY_CAPS_LOCK) modkeyMask -= GUIEventAdapter::MODKEY_CAPS_LOCK;
	if (modkeyMask>=GUIEventAdapter::MODKEY_NUM_LOCK) modkeyMask -= GUIEventAdapter::MODKEY_NUM_LOCK;
	
	
	// correct dX for aspect ratio:		
	//std::cout << "aspect= " << (float)ea.getWindowWidth()/ea.getWindowHeight() << std::endl;
	dX *= (float)ea.getWindowWidth()/ea.getWindowHeight();
	dXclick *= (float)ea.getWindowWidth()/ea.getWindowHeight();

#if 0
	if (0) // (ea.getEventType() != osgGA::GUIEventAdapter::MOVE)
	{
		switch(ea.getEventType())
		{
			case(osgGA::GUIEventAdapter::PUSH):
				std::cout << "PUSH ("<<ea.getEventType()<<")"; break;
			case(osgGA::GUIEventAdapter::RELEASE):
				std::cout << "RELEASE ("<<ea.getEventType()<<")"; break;
			case(osgGA::GUIEventAdapter::DOUBLECLICK):
				std::cout << "DOUBLECLICK ("<<ea.getEventType()<<")"; break;
			case(osgGA::GUIEventAdapter::DRAG):
				std::cout << "DRAG ("<<ea.getEventType()<<")"; break;
			case(osgGA::GUIEventAdapter::MOVE):
				std::cout << "MOVE ("<<ea.getEventType()<<")"; break;
			case(osgGA::GUIEventAdapter::SCROLL):
				std::cout << "SCROLL ("<<ea.getEventType()<<")"; break;
			default:
				std::cout << "some other message?" << std::endl; break;
		}
		std::cout << " buttonMask=" << buttonMask << ", modkeyMask=" << modkeyMask << ", dXYclick: " << dXclick<<","<<dYclick << std::endl;
		std::cout << " currently selected nodes:";
		for (unsigned j = 0; j < selectedNodes.size(); ++j)
		{
			std::cout << " " << selectedNodes[j]->s_name;
		}
		std::cout << std::endl;
	}
#endif


	float scrollX = 0.0;
    float scrollY = 0.0;
	if (ea.getEventType()==osgGA::GUIEventAdapter::SCROLL)
	{
		scrollX = ea.getScrollingDeltaX();
		scrollY = ea.getScrollingDeltaY();

		// some devices can't report the delta, so we check if both deltas are
		// zero and in that case, we set the delta to a unit value (1.0) in the 
		// appropriate direction
		if (scrollX == 0 && scrollY == 0)
		{
			switch (ea.getScrollingMotion())
			{
				case osgGA::GUIEventAdapter::SCROLL_LEFT:
					scrollX = 1.0;
					break;
				case osgGA::GUIEventAdapter::SCROLL_RIGHT:
					scrollX = -1.0;
					break;
				case osgGA::GUIEventAdapter::SCROLL_UP:
					scrollY = -1.0;
					break;
				case osgGA::GUIEventAdapter::SCROLL_DOWN:
					scrollY = 1.0;
					break;
				default:
					// nothing
					break;
			}
		}
	}
	
	if (this->picker)
	{
		// This is how the Picker works:
		//
		// A node is "selected" when the user does a PUSH on an GroupNode that
		// has an appropriate interactionMode property (eg, DRAG, THROW)
		//
		// We store the id of the selectedNodes, so that we can disable camera
		// motion if anything is selected.
		//
		// Morover, it is possible for the user to move the cursor so quickly
		// that a selected node is not intersecting anymore and we won't find
		// the node in the intersections list. However, SPIN expects us to send
		// a RELEASE event for that node, so the id must be stored.

		osgUtil::LineSegmentIntersector::Intersections intersections;
		view->computeIntersections(ea.getX(),ea.getY(),intersections);
		//bool haveIntersections = view->computeIntersections(ea.getX(),ea.getY(),intersections, INTERACTIVE_NODE_MASK);

		// first, we fill 2 vectors with data (the pointer to the node, and the
		// local intersect point)
        std::vector<GroupNode*> hitNodes;
        std::vector<osg::Vec3> hitPoints;

		// intersections are ordered from nearest to furthest, so we iterate and
		// a return list of all nodes that can be cast as interactive SPIN nodes
		osgUtil::LineSegmentIntersector::Intersections::const_iterator itr;
		for (itr = intersections.begin(); itr != intersections.end(); ++itr)
		{
			// look down the nodePath for the first SPIN node:
			for (int i = (*itr).nodePath.size() - 1; i >= 0; i--)
			{
				osg::ref_ptr<GroupNode> testNode = dynamic_cast<GroupNode*>((*itr).nodePath[i]);
				if (testNode.valid())
				{
					// we check if this node is interactive, or if it has an
					// owner (since sometimes interactive mode can be unset
					// before the RELEASE event gets sent)
					//if ((testNode->getInteractionMode()>0) || (testNode->owner.valid()))
					if (testNode->getInteractionMode()>0)
					{
						// Yes. This is an interactive SPIN node, so add it to 
						// the list, but only once! ... we must check if it has
						// already been added since the intersector can
						// intersect with the same node several times:
						if (std::find( hitNodes.begin(), hitNodes.end(), testNode.get() ) == hitNodes.end())
						{
							osg::Vec3 v = (*itr).getLocalIntersectPoint();
							hitPoints.push_back((*itr).getLocalIntersectPoint());
							hitNodes.push_back(testNode.get());
						}
					}

					// Once we've found the first SPIN node, we break and move
					// to the next intersection. We don't look up the nodePath
					// to see if parentNodes are interactive, otherwise we'll
					// get bad intersect points.
					break;
				}
			}
		}

		// ******
	
		// If any nodes are currently "selected" (ie, the user did a PUSH but
		// hasn't done a RELEASE yet), we are ONLY interested in subsequent
		// events to those node(s). ie, we do not select additional nodes until
		// a RELEASE has been performed.
		//
		// We do however try to use the intersect list to update the hitPoint.
		
		if (selectedNodes.size())
		{
			//for (j=0; j<selectedNodes.size(); j++)
			for (std::vector<t_symbol*>::iterator it=selectedNodes.begin(); it!=selectedNodes.end();)
			{	
				bool found = false;
				GroupNode *n = dynamic_cast<GroupNode*>((*it)->s_thing);
				for (unsigned i = 0; i < hitNodes.size(); i++)
				{
					if (hitNodes[i] == n)
					{
						sendPick(n, ea.getEventType(), modkeyMask, buttonMask,
								scrollX, scrollY, dX, dY, hitPoints[i]);
						found = true;
						break;
					}
				}
				
				// if it wasn't found in the intersections list, we still want to
				// send the event (eg, a RELEASE), but we set the hitpoint to 0,0,0
				if (!found)
				{
					sendPick(n, ea.getEventType(), modkeyMask, buttonMask,
							scrollX, scrollY, dX, dY, osg::Vec3(0.0,0.0,0.0));
				}

				// if the event is a RELEASE, then remove it from selectedNodes
				if (ea.getEventType()==GUIEventAdapter::RELEASE)
					selectedNodes.erase(it);
				else
					++it;
			}
		}
		
		// if no nodes are selected, then we go through the intersect list and
		// send events to the first selectable (ie, type SELECT, DRAG, or THROW)
		// in the list, and the first DRAW node. We NEVER send to more than one
		// selectable, or we will end up selecting several nodes at once.
		//
		// Also, the rule with DRAW nodes is that once we find one, we no longer
		// look for selectables. ie, a selectable node can be selected in front
		// of a drawable (eg, for a brush), but we cannot select nodes behind
		// a drawable.
		else
		{	
			bool foundSelectable = false;
			bool foundDrawable = false;
			
			for (unsigned i = 0; i < hitNodes.size(); i++)
			{
				if ( hitNodes[i]->getInteractionMode()==GroupNode::DRAW )
				{
					if (!foundDrawable)
					{
						sendPick(hitNodes[i], ea.getEventType(), modkeyMask, buttonMask,
								scrollX, scrollY, dX, dY, hitPoints[i]);
						
						// add it to the selectedNodes in the case of a PUSH
						if (ea.getEventType()==GUIEventAdapter::PUSH)
							selectedNodes.push_back(hitNodes[i]->id);
						
						foundDrawable = true;
					}
				}

				// If we've found a drawable, thus we stop right away so that
				// nodes behind cannot be selected
				if (foundDrawable) break;
				
				else if ((int) hitNodes[i]->getInteractionMode()>0)
				{
					if (!foundSelectable)
					{
						sendPick(hitNodes[i], ea.getEventType(), modkeyMask, buttonMask,
								scrollX, scrollY, dX, dY, hitPoints[i]);
						
						// add it to the selectedNodes in the case of a PUSH
						if (ea.getEventType()==GUIEventAdapter::PUSH)
							selectedNodes.push_back(hitNodes[i]->id);
						
						foundSelectable = true;
					}
				}
				
				// if we've found one of each, we can stop:
				if (foundSelectable && foundDrawable) break;

				// otherwise we keep looking, allowing one selectable in front
				// of one drawable
			}
		}

		
	} // end picker
	
	
	
    // scene event processing (eg, camera motion):
	if ( this->mover && selectedNodes.empty() )
	{
		float movScalar = 10.0;
		float rotScalar = 30.0;
		
		switch(ea.getEventType())
		{
			case(GUIEventAdapter::PUSH):
				// in the case of a mouse click, we store the current coords
				clickX = ea.getXnormalized();
				clickY = ea.getYnormalized();
				
				
				sendEvent(user->s_name, "sfff", "setVelocity", 0.0, 0.0, 0.0, LO_ARGS_END);
				if (buttonMask == (GUIEventAdapter::LEFT_MOUSE_BUTTON+GUIEventAdapter::RIGHT_MOUSE_BUTTON))
					sendEvent(user->s_name, "sfff", "setSpin", 0.0, 0.0, 0.0, LO_ARGS_END);

				
				break;
				
			case(GUIEventAdapter::DRAG):
				
				// here we can move the user relative to the current camera
				// view, so we get the view's world coords:
				/*
			    osg::Vec3d camCenter;
			    osg::Quat camRotation;
			    computeNodeCenterAndRotation(camCenter, camRotation);
			    osg::Vec3 camEulers = QuatToEuler( camRotation );
			    float camDistance = ((*itr).getWorldIntersectPoint() - camCenter).length();
			    
			    std::cout << "cam center=("<<camCenter.x()<<","<<camCenter.y()<<","<<camCenter.z()<<")";
			    std::cout << ", distance="<<camDistance;
			    std::cout << ", pitch="<<osg::RadiansToDegrees(camEulers.x());
			    std::cout << ", yaw="<<osg::RadiansToDegrees(camEulers.z());
			    std::cout << std::endl;
			    */
				
				if (!modkeyMask)
				{
				    if (buttonMask == GUIEventAdapter::LEFT_MOUSE_BUTTON)
				    {
				    	// pan forward/back & left/right:
				    	sendEvent(user->s_name, "sfff", "move", dX*movScalar, dY*movScalar, 0.0, LO_ARGS_END);
				    }
				    else if (buttonMask == GUIEventAdapter::RIGHT_MOUSE_BUTTON)
				    {
				    	// pan up/down & left/right:
				    	sendEvent(user->s_name, "sfff", "move", dX*movScalar, 0.0, dY*movScalar, LO_ARGS_END);
				    }
				    else if (buttonMask == (GUIEventAdapter::LEFT_MOUSE_BUTTON+GUIEventAdapter::RIGHT_MOUSE_BUTTON))
				    {
				    	// rotate mode:
				    	sendEvent(user->s_name, "sfff", "rotate", dY*rotScalar, 0.0, dX*rotScalar, LO_ARGS_END);
				    }
				}
			
			    else if ( (modkeyMask==GUIEventAdapter::MODKEY_LEFT_CTRL) || (modkeyMask==GUIEventAdapter::MODKEY_RIGHT_CTRL) )
			    	
			    {
			    	int dXsign, dYsign;
			    	(dXclick<0) ? dXsign=-1 : dXsign=1;
			    	(dYclick<0) ? dYsign=-1 : dYsign=1;
			    	
			    	// drive mode:
				    if (buttonMask == GUIEventAdapter::LEFT_MOUSE_BUTTON)
				    {
				    	// drive forward/back & left/right:
			    		sendEvent(user->s_name, "sfff", "setVelocity", dXsign*pow(dXclick*movScalar,2), dYsign*pow(dYclick*movScalar,2), 0.0f, LO_ARGS_END);
			    		
				    }
				    else if (buttonMask == GUIEventAdapter::RIGHT_MOUSE_BUTTON)
				    {
				    	// drive up/down & left/right:
			    		sendEvent(user->s_name, "sfff", "setVelocity", dXsign*pow(dXclick*movScalar,2), 0.0f, dYsign*pow(dYclick*movScalar,2), LO_ARGS_END);
			    	}
				    else if (buttonMask == (GUIEventAdapter::LEFT_MOUSE_BUTTON+GUIEventAdapter::RIGHT_MOUSE_BUTTON))
				    {
				    	// rotate mode:
			    		sendEvent(user->s_name, "sfff", "setSpin", dYsign*pow(dYclick*rotScalar,2), 0.0, dXsign*pow(dXclick*rotScalar,2), LO_ARGS_END);
				    }
			    }

				break;
				
			case(GUIEventAdapter::RELEASE):
				sendEvent(user->s_name, "sfff", "setVelocity", 0.0, 0.0, 0.0, LO_ARGS_END);
				sendEvent(user->s_name, "sfff", "setSpin", 0.0, 0.0, 0.0, LO_ARGS_END);
				break;
				
			case(GUIEventAdapter::SCROLL):
				// zoom?
				break;
			default:
				// here we could pop up an HUD menu if someone double-clicks or right-clicks
				break;
		}
	}

	// send raw events if user requests them
	if (this->raw)
	{
		sendEvent(user->s_name,
		    "siiiff",
		    "mouseEvent",
			(int)ea.getEventType(),
			(int) ea.getModKeyMask(),
			(int) ea.getButtonMask(),
		    (float) ea.getXnormalized(),
		    (float) ea.getYnormalized(),
		    LO_ARGS_END);
	}

	lastX = ea.getXnormalized();
	lastY = ea.getYnormalized();
}
Exemplo n.º 28
0
Arquivo: Dragger.cpp Projeto: 4ker/osg
bool Dragger::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
    if (ea.getHandled()) return false;

    osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
    if (!view) return false;

    bool handled = false;

    bool activationPermitted = true;
    if (_activationModKeyMask!=0 || _activationMouseButtonMask!=0 || _activationKeyEvent!=0)
    {
        _activationPermittedByModKeyMask = (_activationModKeyMask!=0) ?
            ((ea.getModKeyMask() & _activationModKeyMask)!=0) :
            false;

        _activationPermittedByMouseButtonMask = (_activationMouseButtonMask!=0) ?
            ((ea.getButtonMask() & _activationMouseButtonMask)!=0) :
            false;

        if (_activationKeyEvent!=0)
        {
            switch (ea.getEventType())
            {
                case osgGA::GUIEventAdapter::KEYDOWN:
                {
                    if (ea.getKey()==_activationKeyEvent) _activationPermittedByKeyEvent = true;
                    break;
                }
                case osgGA::GUIEventAdapter::KEYUP:
                {
                    if (ea.getKey()==_activationKeyEvent) _activationPermittedByKeyEvent = false;
                    break;
                }
                default:
                    break;
            }
        }

        activationPermitted =  _activationPermittedByModKeyMask || _activationPermittedByMouseButtonMask || _activationPermittedByKeyEvent;

    }

    if (activationPermitted || _draggerActive)
    {
        switch (ea.getEventType())
        {
            case osgGA::GUIEventAdapter::PUSH:
            {
                osgUtil::LineSegmentIntersector::Intersections intersections;

                _pointer.reset();

                if (view->computeIntersections(ea ,intersections, _intersectionMask))
                {
                    for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
                        hitr != intersections.end();
                        ++hitr)
                    {
                        _pointer.addIntersection(hitr->nodePath, hitr->getLocalIntersectPoint());
                    }
                    for (osg::NodePath::iterator itr = _pointer._hitList.front().first.begin();
                            itr != _pointer._hitList.front().first.end();
                            ++itr)
                    {
                        osgManipulator::Dragger* dragger = dynamic_cast<osgManipulator::Dragger*>(*itr);
                        if (dragger)
                        {
                            if (dragger==this)
                            {
                                osg::Camera *rootCamera = view->getCamera();
                                osg::NodePath nodePath = _pointer._hitList.front().first;
                                osg::NodePath::reverse_iterator ritr;
                                for(ritr = nodePath.rbegin();
                                    ritr != nodePath.rend();
                                    ++ritr)
                                {
                                    osg::Camera* camera = dynamic_cast<osg::Camera*>(*ritr);
                                    if (camera && (camera->getReferenceFrame()!=osg::Transform::RELATIVE_RF || camera->getParents().empty()))
                                    {
                                         rootCamera = camera;
                                         break;
                                    }
                                }

                                _pointer.setCamera(rootCamera);
                                _pointer.setMousePosition(ea.getX(), ea.getY());

                                if(dragger->handle(_pointer, ea, aa))
                                {
                                    dragger->setDraggerActive(true);
                                    handled = true;
                                }
                            }
                        }
                    }
                }
                break;
            }
            case osgGA::GUIEventAdapter::DRAG:
            case osgGA::GUIEventAdapter::RELEASE:
            {
                if (_draggerActive)
                {
                    _pointer._hitIter = _pointer._hitList.begin();
//                    _pointer.setCamera(view->getCamera());
                    _pointer.setMousePosition(ea.getX(), ea.getY());

                    if(handle(_pointer, ea, aa))
                    {
                        handled = true;
                    }
                }
                break;
            }
            default:
                break;
        }

        if (_draggerActive && ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
        {
            setDraggerActive(false);
            _pointer.reset();
        }
    }

    return handled;
}
Exemplo n.º 29
0
osg::Vec2d KeystoneHandler::incrementScale(const osgGA::GUIEventAdapter& ea) const
{
    if (_ctrlIncrement!=osg::Vec2d(0.0,0.0) && (ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_LEFT_CTRL || ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_RIGHT_CTRL )) return _ctrlIncrement;
    if (_shiftIncrement!=osg::Vec2d(0.0,0.0) && (ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_LEFT_SHIFT || ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_RIGHT_SHIFT )) return _shiftIncrement;
    return _defaultIncrement;
}
Exemplo n.º 30
0
	virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
	{
		if (ea.getHandled() == true)
		{
			return true;
		}

		osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
		if (!viewer)
		{
			return false;
		}

		float x = ea.getX ();
		float y = ea.getY ();

		switch (ea.getEventType())
		{
		case osgGA::GUIEventAdapter::KEYDOWN:
			{
				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_1)
				{
					CustomDraggerManager::Instence()->setActiveDragger("move");

				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_2)
				{
					CustomDraggerManager::Instence()->setActiveDragger("rotate");

				}
			}
			break;

		case osgGA::GUIEventAdapter::PUSH:
			{
				//更改与模型相关联的Selection
				if(osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON & ea.getButtonMask())
				{

					osg::MatrixTransform* mt= pick(viewer, x, y);

					if (mt)
					{
						if ( (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL) == 0)
						{
							_pickSelections.clear();
						}
						
						_pickSelections.push_back(mt);

						OSG_WARN<<mt->getName()<<std::endl;
						OSG_WARN<<"in"<<std::endl;
						CustomDraggerManager::Instence()->setSelections(_pickSelections);
						osgDragger::ShowBound::Instence()->setSelections(_pickSelections);
						
					}

				   //std::cout<<_pickSelections.size()<<std::endl;

				}
			}
			break;
		}

		return false;
	}