OSG has implemented the method of directly communicating with objects through screen coordinates. The pick object can also obtain coordinates. I want to click and draw a straight line based on the clicked points. The screen coordinates are converted to the world coordinates, and then this function is implemented. # Pragma once
# Include <osgga/guieventhandler>
# Include <osgutil/linesegmentintersector>
# Include <osgviewer/Viewer>
Class cpickhandler: Public osgga: guieventhandler
{
Public:
Cpickhandler (osgviewer: viewer * viewer );
~ Cpickhandler (void );
Osgviewer: viewer * m_pviewer;
Virtual bool handle (const osgga: guieventadapter & EA, osgga: guiactionadapter & aa );
Void pick (float FX, float FY );
}; # Include "stdafx. H"
# Include "pickhandler. H"
Cpickhandler: cpickhandler (osgviewer: viewer * viewer): m_pviewer (viewer)
{
}
Cpickhandler ::~ Cpickhandler (void)
{
}
Bool cpickhandler: handle (const osgga: guieventadapter & EA, osgga: guiactionadapter & aa)
{
Switch (EA. geteventtype ())
{
Case (osgga: guieventadapter: Push ):
{
If (EA. getbutton () = 1)
{
Pick (EA. getx (), EA. Gety ());
}
Return true;
}
}
Return false;
}
Void cpickhandler: Pick (float FX, float FY)
{
Osgutil: linesegmentintersector: Intersections intersections;
If (m_pviewer-> computeintersections (FX, fy, intersections ))
{
For (Auto itr = intersections. Begin (); itr! = Intersections. End (); ++ itr)
{
If (! Itr-> nodepath. Empty ())
{
Const OSG: nodepath & NP = itr-> nodepath;
For (INT I = NP. Size ()-1; I> = 0; -- I)
{
OSG: ref_ptr <OSG: node> node = dynamic_cast <OSG: node *> (NP [I]);
If (null! = Node & node-> getname (). Compare ("cow") = 0)
{
Node-> setnodemask (0 );
// Itr-> getworldintersectpoint (); // obtain the coordinates
}
}
}
}
}
}
Screen coordinate and world coordinate transformation OSG: vec3 drawcallback: getpoint ()
{
OSG: vec3 vec3;
OSG: ref_ptr <osgviewer: viewer> viewer = dynamic_cast <osgviewer: viewer *> (m_paa );
OSG: ref_ptr <OSG: Camera> camera = viewer-> getcamera ();
Osgviewer: Renderer * render = dynamic_cast <osgviewer: Renderer *> (camera-> getrenderer ());
Osgutil: sceneview * sceneview = render-> getsceneview (0 );
OSG: vec3 vscreen (m_pea-> getx (), m_pea-> Gety (), 0 );
OSG: vec3 window;
Sceneview-> projectwindowintoobject (vscreen, window );
OSG: matrix mvpw = camera-> getviewmatrix () * camera-> getprojectionmatrix () * camera-> getviewport ()-> computewindowmatrix ();
OSG: matrix invertvpw;
Invertvpw. Invert (mvpw );
Vec3 = Window * invertvpw;
Return vec3;
}
1. Configure MD
2. Configure x643. locate MFC example4. write callback5. create a node and mount it to the root node. Then, set a callback for this node. Respond to the event to change the node.
URL: http://greatverve.cnblogs.com/archive/2013/04/21/osg-pick.html