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

Revision 1882, 12.4 kB (checked in by robert, 11 years ago)

Added support for multiple cameras into osgpick.

  • 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 <osgUtil/PickVisitor>
32
33
34
35static Producer::CameraConfig *BuildConfig(void)
36{
37    Producer::RenderSurface *rs1 = new Producer::RenderSurface;
38    rs1->setScreenNum(0);
39    //rs1->useBorder(false);
40    rs1->setWindowRect(0,0,640,480);
41    Producer::Camera *camera1 = new Producer::Camera;
42    camera1->setRenderSurface(rs1);
43    camera1->setOffset( 1.0, 0.0 );
44
45    Producer::RenderSurface *rs2 = new Producer::RenderSurface;
46    rs2->setScreenNum(0);
47    //rs2->useBorder(false);
48    rs2->setWindowRect(640,0,640,480);
49    Producer::Camera *camera2 = new Producer::Camera;
50    camera2->setRenderSurface(rs2);
51    camera2->setOffset( -1.0, 0.0 );
52
53    Producer::InputArea *ia = new Producer::InputArea;
54    ia->addInputRectangle( rs1, Producer::InputRectangle(0.0,0.5,0.0,1.0));
55    ia->addInputRectangle( rs2, Producer::InputRectangle(0.5,1.0,0.0,1.0));
56//    ia->addInputRectangle( rs1, Producer::InputRectangle(-1.0,0.0,-1.0,1.0));
57//    ia->addInputRectangle( rs2, Producer::InputRectangle(0.0,1.0,-1.0,1.0));
58
59
60    Producer::CameraConfig *cfg = new Producer::CameraConfig;
61    cfg->addCamera("Camera 1",camera1);
62    cfg->addCamera("Camera 2", camera2);
63    cfg->setInputArea(ia);
64    return cfg;
65}
66
67// class to handle events with a pick
68class PickHandler : public osgGA::GUIEventHandler {
69public:
70
71    PickHandler(osgProducer::Viewer* viewer,osgText::Text* updateText):
72        _viewer(viewer),
73        _updateText(updateText) {}
74       
75    ~PickHandler() {}
76   
77    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us);
78
79    virtual void pick(const osgGA::GUIEventAdapter& ea);
80
81    void setLabel(const std::string& name)
82    {
83        if (_updateText.get()) _updateText->setText(name);
84    }
85   
86protected:
87
88    osgProducer::Viewer* _viewer;
89    osg::ref_ptr<osgText::Text>  _updateText;
90};
91
92bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
93{
94    switch(ea.getEventType())
95    {
96    case(osgGA::GUIEventAdapter::FRAME):
97        {
98            pick(ea);
99        }
100        return false;
101       
102    default:
103        return false;
104    }
105}
106
107void PickHandler::pick(const osgGA::GUIEventAdapter& ea)
108{
109    // OK here is the interesting bit - How To Pick a Geode
110    // including geodes in a HUD under a Projection Matrix
111    osg::Node *scene=_viewer->getSceneData();//main node of the scene.
112    if (scene)
113    {
114        float x=ea.getX();
115        float y=ea.getY();
116
117
118        Producer::KeyboardMouse* km = _viewer->getKeyboardMouse();
119
120
121        std::string gdlist="";
122
123        for(unsigned int i=0;i<_viewer->getNumberOfCameras();++i)
124        {
125            Producer::Camera* cmm=_viewer->getCamera(i);
126            Producer::RenderSurface* rs = cmm->getRenderSurface();
127
128            std::cout << "checking camara "<<i<<std::endl;
129
130            float pixel_x,pixel_y;
131            if (km->computePixelCoords(x,y,rs,pixel_x,pixel_y))
132            {
133                std::cout << "    compute pixel coords "<<pixel_x<<"  "<<pixel_y<<std::endl;
134
135                int pr_wx, pr_wy;
136                unsigned int pr_width, pr_height;
137                cmm->getProjectionRect( pr_wx, pr_wy, pr_width, pr_height );
138
139                int rs_wx, rs_wy;
140                unsigned int rs_width, rs_height;
141                rs->getWindowRect( rs_wx, rs_wy, rs_width, rs_height );
142               
143                pr_wx += rs_wx;
144                pr_wy += rs_wy;
145
146                std::cout << "    wx = "<<pr_wx<<"  wy = "<<pr_wy<<" width="<<pr_width<<" height="<<pr_height<<std::endl;
147
148
149
150                if (pixel_x<(float)pr_wx) break;
151                if (pixel_x>(float)(pr_wx+pr_width)) break;
152
153                if (pixel_y<(float)pr_wy) break;
154                if (pixel_y>(float)(pr_wy+pr_height)) break;
155
156
157                float rx = 2.0f*(pixel_x - (float)pr_wx)/(float)pr_width-1.0f;
158                float ry = 2.0f*(pixel_y - (float)pr_wy)/(float)pr_height-1.0f;
159
160                std::cout << "    rx "<<rx<<"  "<<ry<<std::endl;
161
162                osg::Matrix vum(osg::Matrix(cmm->getViewMatrix()) *
163                                osg::Matrix(cmm->getProjectionMatrix())/* *
164                                osg::Matrix::translate(1.0f,1.0f,1.0f) *
165                                osg::Matrix::scale(0.5f,0.5f,0.5f)*/);
166
167                osgUtil::PickVisitor iv;
168                osgUtil::IntersectVisitor::HitList& hlist=iv.getHits(scene, vum, rx,ry);
169                if (iv.hits())
170                {
171                    for(osgUtil::IntersectVisitor::HitList::iterator hitr=hlist.begin();
172                    hitr!=hlist.end();
173                    ++hitr)
174                    {
175                        //osg::Vec3 ip = hitr->getLocalIntersectPoint();
176                        //osg::Vec3 in = hitr->getLocalIntersectNormal();
177                        osg::Geode* geode = hitr->_geode.get();
178                        // the geodes are identified by name.
179                        if (geode)
180                        {
181                            if (!geode->getName().empty())
182                            {
183                                gdlist=gdlist+" "+geode->getName();
184                            }
185                            else
186                            {
187                                gdlist=gdlist+" geode";
188                            }
189                        }
190                    }
191                }
192            }
193        }
194
195        setLabel(gdlist);
196    }
197}
198
199osg::Node* createHUD(osgText::Text* updateText)
200{    // create the hud. derived from osgHud.cpp
201    // adds a set of quads, each in a separate Geode - which can be picked individually
202    // eg to be used as a menuing/help system!
203    // Can pick texts too!
204    osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
205    modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE);
206    modelview_abs->setMatrix(osg::Matrix::identity());
207   
208    osg::Projection* projection = new osg::Projection;
209    projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
210    projection->addChild(modelview_abs);
211   
212   
213    std::string timesFont("fonts/times.ttf");
214   
215    // turn lighting off for the text and disable depth test to ensure its always ontop.
216    osg::Vec3 position(150.0f,800.0f,0.0f);
217    osg::Vec3 delta(0.0f,-60.0f,0.0f);
218   
219    {
220        osg::Geode* geode = new osg::Geode();
221        osg::StateSet* stateset = geode->getOrCreateStateSet();
222        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
223        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
224        geode->setName("simple");
225        modelview_abs->addChild(geode);
226       
227        osgText::Text* text = new  osgText::Text;
228        geode->addDrawable( text );
229       
230        text->setFont(timesFont);
231        text->setText("Picking in Head Up Displays is simple !=]");
232        text->setPosition(position);
233       
234        position += delta;
235    }   
236   
237   
238    for (int i=0; i<5; i++) {
239        osg::Vec3 dy(0.0f,-30.0f,0.0f);
240        osg::Vec3 dx(120.0f,0.0f,0.0f);
241        osg::Geode* geode = new osg::Geode();
242        osg::StateSet* stateset = geode->getOrCreateStateSet();
243        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
244        osg::Geometry *quad=new osg::Geometry;
245        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
246        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
247        std::string name="subOption";
248        name += " ";
249        name += std::string(opts[i]);
250        geode->setName(name);
251        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
252        osg::Vec4Array* colors = new osg::Vec4Array;
253        colors = new osg::Vec4Array;
254        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
255        quad->setColorArray(colors);
256        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
257        (*vertices)[0]=position;
258        (*vertices)[1]=position+dx;
259        (*vertices)[2]=position+dx+dy;
260        (*vertices)[3]=position+dy;
261        quad->setVertexArray(vertices);
262        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
263        geode->addDrawable(quad);
264        modelview_abs->addChild(geode);
265       
266        position += delta;
267    }   
268   
269   
270   
271    { // this displays what has been selected
272        osg::Geode* geode = new osg::Geode();
273        osg::StateSet* stateset = geode->getOrCreateStateSet();
274        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
275        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
276        geode->setName("whatis");
277        geode->addDrawable( updateText );
278        modelview_abs->addChild(geode);
279       
280        updateText->setFont(timesFont);
281        updateText->setText("whatis will tell you what is under the mouse");
282        updateText->setPosition(position);
283       
284        position += delta;
285    }   
286   
287    return projection;
288
289}
290
291int main( int argc, char **argv )
292{
293
294    // use an ArgumentParser object to manage the program arguments.
295    osg::ArgumentParser arguments(&argc,argv);
296   
297    // set up the usage document, in case we need to print out how to use this program.
298    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to do Head Up Displays.");
299    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] [filename] ...");
300    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
301   
302
303    // construct the viewer.
304    //osgProducer::Viewer viewer(arguments);
305    osgProducer::Viewer viewer(BuildConfig());
306
307    // set up the value with sensible default event handlers.
308    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
309
310    // get details on keyboard and mouse bindings used by the viewer.
311    viewer.getUsage(*arguments.getApplicationUsage());
312
313    // if user request help write it out to cout.
314    if (arguments.read("-h") || arguments.read("--help"))
315    {
316        arguments.getApplicationUsage()->write(std::cout);
317        return 1;
318    }
319
320    // any option left unread are converted into errors to write out later.
321    arguments.reportRemainingOptionsAsUnrecognized();
322
323    // report any errors if they have occured when parsing the program aguments.
324    if (arguments.errors())
325    {
326        arguments.writeErrorMessages(std::cout);
327        return 1;
328    }
329   
330    // read the scene from the list of file specified commandline args.
331    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
332
333    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
334    if (!group)
335    {
336        group = new osg::Group;
337        group->addChild(scene.get());
338    }
339
340    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
341
342    // add the HUD subgraph.   
343    group->addChild(createHUD(updateText.get()));
344
345    // add the handler for doing the picking
346    viewer.getEventHandlerList().push_front(new PickHandler(&viewer,updateText.get()));
347
348    // set the scene to render
349    viewer.setSceneData(group.get());
350
351    // create the windows and run the threads.
352    viewer.realize();
353
354    while( !viewer.done() )
355    {
356        // wait for all cull and draw threads to complete.
357        viewer.sync();
358
359        // update the scene by traversing it with the the update visitor which will
360        // call all node update callbacks and animations.
361        viewer.update();
362         
363        // fire off the cull and draw traversals of the scene.
364        viewer.frame();
365       
366    }
367   
368    // wait for all cull and draw threads to complete before exit.
369    viewer.sync();
370   
371    return 0;
372}
Note: See TracBrowser for help on using the browser.