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

Revision 5954, 7.7 kB (checked in by robert, 7 years ago)

Ported following examples to osgViewer:

osgparticleeffects
osgphotoalbum
osgpick
osgpoints
osgpointsprite
osgprecipitation
osgprerender
osgprerendercubemap
osgreflect
osgscalarbar
osgscribe
osgsequence
osgplanets

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 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 <osgViewer/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#include <osg/Camera>
29#include <osg/io_utils>
30
31#include <osgText/Text>
32
33#include <sstream>
34
35// class to handle events with a pick
36class PickHandler : public osgGA::GUIEventHandler {
37public:
38
39    PickHandler(osgText::Text* updateText):
40        _updateText(updateText) {}
41       
42    ~PickHandler() {}
43   
44    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);
45
46    virtual void pick(osgViewer::Viewer* viewer, const osgGA::GUIEventAdapter& ea);
47
48    void setLabel(const std::string& name)
49    {
50        if (_updateText.get()) _updateText->setText(name);
51    }
52   
53protected:
54
55    osg::ref_ptr<osgText::Text>  _updateText;
56};
57
58bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
59{
60    switch(ea.getEventType())
61    {
62        case(osgGA::GUIEventAdapter::FRAME):
63        {
64            osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
65            if (viewer) pick(viewer,ea);
66            return false;
67        }   
68        default:
69            return false;
70    }
71}
72
73void PickHandler::pick(osgViewer::Viewer* viewer, const osgGA::GUIEventAdapter& ea)
74{
75    osgUtil::LineSegmentIntersector::Intersections intersections;
76
77    std::string gdlist="";
78    if (viewer->computeIntersections(ea.getX(),ea.getY(),intersections))
79    {
80        for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
81            hitr != intersections.end();
82            ++hitr)
83        {
84            std::ostringstream os;
85            if (!hitr->nodePath.empty() && !(hitr->nodePath.back()->getName().empty()))
86            {
87                // the geodes are identified by name.
88                os<<"Object \""<<hitr->nodePath.back()->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            const osgUtil::LineSegmentIntersector::Intersection::IndexList& vil = hitr->indexList;
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{
111
112    // create the hud. derived from osgHud.cpp
113    // adds a set of quads, each in a separate Geode - which can be picked individually
114    // eg to be used as a menuing/help system!
115    // Can pick texts too!
116
117    osg::Camera* hudCamera = new osg::Camera;
118    hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
119    hudCamera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
120    hudCamera->setViewMatrix(osg::Matrix::identity());
121    hudCamera->setRenderOrder(osg::Camera::POST_RENDER);
122    hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
123   
124    std::string timesFont("fonts/times.ttf");
125   
126    // turn lighting off for the text and disable depth test to ensure its always ontop.
127    osg::Vec3 position(150.0f,800.0f,0.0f);
128    osg::Vec3 delta(0.0f,-60.0f,0.0f);
129   
130    {
131        osg::Geode* geode = new osg::Geode();
132        osg::StateSet* stateset = geode->getOrCreateStateSet();
133        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
134        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
135        geode->setName("simple");
136        hudCamera->addChild(geode);
137       
138        osgText::Text* text = new  osgText::Text;
139        geode->addDrawable( text );
140       
141        text->setFont(timesFont);
142        text->setText("Picking in Head Up Displays is simple!");
143        text->setPosition(position);
144       
145        position += delta;
146    }   
147   
148   
149    for (int i=0; i<5; i++) {
150        osg::Vec3 dy(0.0f,-30.0f,0.0f);
151        osg::Vec3 dx(120.0f,0.0f,0.0f);
152        osg::Geode* geode = new osg::Geode();
153        osg::StateSet* stateset = geode->getOrCreateStateSet();
154        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
155        osg::Geometry *quad=new osg::Geometry;
156        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
157        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
158        std::string name="subOption";
159        name += " ";
160        name += std::string(opts[i]);
161        geode->setName(name);
162        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
163        osg::Vec4Array* colors = new osg::Vec4Array;
164        colors = new osg::Vec4Array;
165        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
166        quad->setColorArray(colors);
167        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
168        (*vertices)[0]=position;
169        (*vertices)[1]=position+dx;
170        (*vertices)[2]=position+dx+dy;
171        (*vertices)[3]=position+dy;
172        quad->setVertexArray(vertices);
173        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
174        geode->addDrawable(quad);
175        hudCamera->addChild(geode);
176       
177        position += delta;
178    }   
179   
180   
181   
182    { // this displays what has been selected
183        osg::Geode* geode = new osg::Geode();
184        osg::StateSet* stateset = geode->getOrCreateStateSet();
185        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
186        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
187        geode->setName("The text label");
188        geode->addDrawable( updateText );
189        hudCamera->addChild(geode);
190       
191        updateText->setCharacterSize(20.0f);
192        updateText->setFont(timesFont);
193        updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
194        updateText->setText("");
195        updateText->setPosition(position);
196       
197        position += delta;
198    }   
199   
200    return hudCamera;
201
202}
203
204int main( int argc, char **argv )
205{
206
207    // use an ArgumentParser object to manage the program arguments.
208    osg::ArgumentParser arguments(&argc,argv);
209
210    // construct the viewer.
211    osgViewer::Viewer viewer;
212
213    // read the scene from the list of file specified commandline args.
214    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
215
216    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
217    if (!group)
218    {
219        group = new osg::Group;
220        group->addChild(scene.get());
221    }
222
223    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
224
225    // add the HUD subgraph.   
226    group->addChild(createHUD(updateText.get()));
227
228    // add the handler for doing the picking
229    viewer.addEventHandler(new PickHandler(updateText.get()));
230
231    // set the scene to render
232    viewer.setSceneData(group.get());
233
234    return viewer.run();
235}
Note: See TracBrowser for help on using the browser.