root/OpenSceneGraph/trunk/examples/osgpick/osgpick.cpp @ 1917

Revision 1917, 9.3 kB (checked in by robert, 11 years ago)

Added support for gather information on which vertices have been intersected with.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under 
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13/* osgpick sample
14* demonstrate use of osgUtil/PickVisitor for picking in a HUD or
15* in a 3d scene,
16*/
17
18#include <osgUtil/Optimizer>
19#include <osgDB/ReadFile>
20#include <osgProducer/Viewer>
21
22#include <osg/Material>
23#include <osg/Geode>
24#include <osg/BlendFunc>
25#include <osg/Depth>
26#include <osg/Projection>
27#include <osg/MatrixTransform>
28
29#include <osgText/Text>
30
31#include <sstream>
32
33// class to handle events with a pick
34class PickHandler : public osgGA::GUIEventHandler {
35public:
36
37    PickHandler(osgProducer::Viewer* viewer,osgText::Text* updateText):
38        _viewer(viewer),
39        _updateText(updateText) {}
40       
41    ~PickHandler() {}
42   
43    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us);
44
45    virtual void pick(const osgGA::GUIEventAdapter& ea);
46
47    void setLabel(const std::string& name)
48    {
49        if (_updateText.get()) _updateText->setText(name);
50    }
51   
52protected:
53
54    osgProducer::Viewer* _viewer;
55    osg::ref_ptr<osgText::Text>  _updateText;
56};
57
58bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
59{
60    switch(ea.getEventType())
61    {
62    case(osgGA::GUIEventAdapter::FRAME):
63        {
64            pick(ea);
65        }
66        return false;
67       
68    default:
69        return false;
70    }
71}
72
73void PickHandler::pick(const osgGA::GUIEventAdapter& ea)
74{
75    osgUtil::IntersectVisitor::HitList hlist;
76   
77    std::string gdlist="";
78    if (_viewer->computeIntersections(ea.getX(),ea.getY(),hlist))
79    {
80        for(osgUtil::IntersectVisitor::HitList::iterator hitr=hlist.begin();
81            hitr!=hlist.end();
82            ++hitr)
83        {
84            std::ostringstream os;
85            if (hitr->_geode.valid() && !hitr->_geode->getName().empty())
86            {
87                // the geodes are identified by name.
88                os<<"Object \""<<hitr->_geode->getName()<<"\""<<std::endl;
89            }
90            else if (hitr->_drawable.valid())
91            {
92                os<<"Object \""<<hitr->_drawable->className()<<"\""<<std::endl;
93            }
94
95            os<<"        local coords vertex("<< hitr->getLocalIntersectPoint()<<")"<<"  normal("<<hitr->getLocalIntersectNormal()<<")"<<std::endl;
96            os<<"        world coords vertex("<< hitr->getWorldIntersectPoint()<<")"<<"  normal("<<hitr->getWorldIntersectNormal()<<")"<<std::endl;
97            osgUtil::Hit::VecIndexList& vil = hitr->_vecIndexList;
98            for(unsigned int i=0;i<vil.size();++i)
99            {
100                os<<"        vertex indices ["<<i<<"] = "<<vil[i]<<std::endl;
101            }
102           
103            gdlist += os.str();
104        }
105    }
106    setLabel(gdlist);
107}
108
109osg::Node* createHUD(osgText::Text* updateText)
110{    // create the hud. derived from osgHud.cpp
111    // adds a set of quads, each in a separate Geode - which can be picked individually
112    // eg to be used as a menuing/help system!
113    // Can pick texts too!
114    osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
115    modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE);
116    modelview_abs->setMatrix(osg::Matrix::identity());
117   
118    osg::Projection* projection = new osg::Projection;
119    projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
120    projection->addChild(modelview_abs);
121   
122   
123    std::string timesFont("fonts/times.ttf");
124   
125    // turn lighting off for the text and disable depth test to ensure its always ontop.
126    osg::Vec3 position(150.0f,800.0f,0.0f);
127    osg::Vec3 delta(0.0f,-60.0f,0.0f);
128   
129    {
130        osg::Geode* geode = new osg::Geode();
131        osg::StateSet* stateset = geode->getOrCreateStateSet();
132        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
133        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
134        geode->setName("simple");
135        modelview_abs->addChild(geode);
136       
137        osgText::Text* text = new  osgText::Text;
138        geode->addDrawable( text );
139       
140        text->setFont(timesFont);
141        text->setText("Picking in Head Up Displays is simple !=]");
142        text->setPosition(position);
143       
144        position += delta;
145    }   
146   
147   
148    for (int i=0; i<5; i++) {
149        osg::Vec3 dy(0.0f,-30.0f,0.0f);
150        osg::Vec3 dx(120.0f,0.0f,0.0f);
151        osg::Geode* geode = new osg::Geode();
152        osg::StateSet* stateset = geode->getOrCreateStateSet();
153        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
154        osg::Geometry *quad=new osg::Geometry;
155        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
156        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
157        std::string name="subOption";
158        name += " ";
159        name += std::string(opts[i]);
160        geode->setName(name);
161        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
162        osg::Vec4Array* colors = new osg::Vec4Array;
163        colors = new osg::Vec4Array;
164        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
165        quad->setColorArray(colors);
166        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
167        (*vertices)[0]=position;
168        (*vertices)[1]=position+dx;
169        (*vertices)[2]=position+dx+dy;
170        (*vertices)[3]=position+dy;
171        quad->setVertexArray(vertices);
172        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
173        geode->addDrawable(quad);
174        modelview_abs->addChild(geode);
175       
176        position += delta;
177    }   
178   
179   
180   
181    { // this displays what has been selected
182        osg::Geode* geode = new osg::Geode();
183        osg::StateSet* stateset = geode->getOrCreateStateSet();
184        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
185        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
186        geode->setName("The text label");
187        geode->addDrawable( updateText );
188        modelview_abs->addChild(geode);
189       
190        updateText->setCharacterSize(20.0f);
191        updateText->setFont(timesFont);
192        updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
193        updateText->setText("");
194        updateText->setPosition(position);
195       
196        position += delta;
197    }   
198   
199    return projection;
200
201}
202
203int main( int argc, char **argv )
204{
205
206    // use an ArgumentParser object to manage the program arguments.
207    osg::ArgumentParser arguments(&argc,argv);
208   
209    // set up the usage document, in case we need to print out how to use this program.
210    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to do Head Up Displays.");
211    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] [filename] ...");
212    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
213   
214
215    // construct the viewer.
216    osgProducer::Viewer viewer(arguments);
217
218    // set up the value with sensible default event handlers.
219    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
220
221    // get details on keyboard and mouse bindings used by the viewer.
222    viewer.getUsage(*arguments.getApplicationUsage());
223
224    // if user request help write it out to cout.
225    if (arguments.read("-h") || arguments.read("--help"))
226    {
227        arguments.getApplicationUsage()->write(std::cout);
228        return 1;
229    }
230
231    // any option left unread are converted into errors to write out later.
232    arguments.reportRemainingOptionsAsUnrecognized();
233
234    // report any errors if they have occured when parsing the program aguments.
235    if (arguments.errors())
236    {
237        arguments.writeErrorMessages(std::cout);
238        return 1;
239    }
240   
241    // read the scene from the list of file specified commandline args.
242    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
243
244    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
245    if (!group)
246    {
247        group = new osg::Group;
248        group->addChild(scene.get());
249    }
250
251    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
252
253    // add the HUD subgraph.   
254    group->addChild(createHUD(updateText.get()));
255
256    // add the handler for doing the picking
257    viewer.getEventHandlerList().push_front(new PickHandler(&viewer,updateText.get()));
258
259    // set the scene to render
260    viewer.setSceneData(group.get());
261
262    // create the windows and run the threads.
263    viewer.realize();
264
265    while( !viewer.done() )
266    {
267        // wait for all cull and draw threads to complete.
268        viewer.sync();
269
270        // update the scene by traversing it with the the update visitor which will
271        // call all node update callbacks and animations.
272        viewer.update();
273         
274        // fire off the cull and draw traversals of the scene.
275        viewer.frame();
276       
277    }
278   
279    // wait for all cull and draw threads to complete before exit.
280    viewer.sync();
281   
282    return 0;
283}
Note: See TracBrowser for help on using the browser.