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

Revision 6941, 8.2 kB (checked in by robert, 8 years ago)

From Martin Lavery and Robert Osfield, Updated examples to use a variation of the MIT License

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgpick.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19/* osgpick sample
20* demonstrate use of osgUtil/PickVisitor for picking in a HUD or
21* in a 3d scene,
22*/
23
24#include <osgUtil/Optimizer>
25#include <osgDB/ReadFile>
26#include <osgViewer/Viewer>
27
28#include <osg/Material>
29#include <osg/Geode>
30#include <osg/BlendFunc>
31#include <osg/Depth>
32#include <osg/Projection>
33#include <osg/MatrixTransform>
34#include <osg/Camera>
35#include <osg/io_utils>
36
37#include <osgText/Text>
38
39#include <sstream>
40
41// class to handle events with a pick
42class PickHandler : public osgGA::GUIEventHandler {
43public:
44
45    PickHandler(osgText::Text* updateText):
46        _updateText(updateText) {}
47       
48    ~PickHandler() {}
49   
50    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);
51
52    virtual void pick(osgViewer::Viewer* viewer, const osgGA::GUIEventAdapter& ea);
53
54    void setLabel(const std::string& name)
55    {
56        if (_updateText.get()) _updateText->setText(name);
57    }
58   
59protected:
60
61    osg::ref_ptr<osgText::Text>  _updateText;
62};
63
64bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
65{
66    switch(ea.getEventType())
67    {
68        case(osgGA::GUIEventAdapter::FRAME):
69        {
70            osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
71            if (viewer) pick(viewer,ea);
72            return false;
73        }   
74        default:
75            return false;
76    }
77}
78
79void PickHandler::pick(osgViewer::Viewer* viewer, const osgGA::GUIEventAdapter& ea)
80{
81    osgUtil::LineSegmentIntersector::Intersections intersections;
82
83    std::string gdlist="";
84    if (viewer->computeIntersections(ea.getX(),ea.getY(),intersections))
85    {
86        for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
87            hitr != intersections.end();
88            ++hitr)
89        {
90            std::ostringstream os;
91            if (!hitr->nodePath.empty() && !(hitr->nodePath.back()->getName().empty()))
92            {
93                // the geodes are identified by name.
94                os<<"Object \""<<hitr->nodePath.back()->getName()<<"\""<<std::endl;
95            }
96            else if (hitr->drawable.valid())
97            {
98                os<<"Object \""<<hitr->drawable->className()<<"\""<<std::endl;
99            }
100
101            os<<"        local coords vertex("<< hitr->getLocalIntersectPoint()<<")"<<"  normal("<<hitr->getLocalIntersectNormal()<<")"<<std::endl;
102            os<<"        world coords vertex("<< hitr->getWorldIntersectPoint()<<")"<<"  normal("<<hitr->getWorldIntersectNormal()<<")"<<std::endl;
103            const osgUtil::LineSegmentIntersector::Intersection::IndexList& vil = hitr->indexList;
104            for(unsigned int i=0;i<vil.size();++i)
105            {
106                os<<"        vertex indices ["<<i<<"] = "<<vil[i]<<std::endl;
107            }
108           
109            gdlist += os.str();
110        }
111    }
112    setLabel(gdlist);
113}
114
115osg::Node* createHUD(osgText::Text* updateText)
116{
117
118    // create the hud. derived from osgHud.cpp
119    // adds a set of quads, each in a separate Geode - which can be picked individually
120    // eg to be used as a menuing/help system!
121    // Can pick texts too!
122
123    osg::Camera* hudCamera = new osg::Camera;
124    hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
125    hudCamera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
126    hudCamera->setViewMatrix(osg::Matrix::identity());
127    hudCamera->setRenderOrder(osg::Camera::POST_RENDER);
128    hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
129   
130    std::string timesFont("fonts/times.ttf");
131   
132    // turn lighting off for the text and disable depth test to ensure its always ontop.
133    osg::Vec3 position(150.0f,800.0f,0.0f);
134    osg::Vec3 delta(0.0f,-60.0f,0.0f);
135   
136    {
137        osg::Geode* geode = new osg::Geode();
138        osg::StateSet* stateset = geode->getOrCreateStateSet();
139        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
140        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
141        geode->setName("simple");
142        hudCamera->addChild(geode);
143       
144        osgText::Text* text = new  osgText::Text;
145        geode->addDrawable( text );
146       
147        text->setFont(timesFont);
148        text->setText("Picking in Head Up Displays is simple!");
149        text->setPosition(position);
150       
151        position += delta;
152    }   
153   
154   
155    for (int i=0; i<5; i++) {
156        osg::Vec3 dy(0.0f,-30.0f,0.0f);
157        osg::Vec3 dx(120.0f,0.0f,0.0f);
158        osg::Geode* geode = new osg::Geode();
159        osg::StateSet* stateset = geode->getOrCreateStateSet();
160        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
161        osg::Geometry *quad=new osg::Geometry;
162        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
163        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
164        std::string name="subOption";
165        name += " ";
166        name += std::string(opts[i]);
167        geode->setName(name);
168        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
169        osg::Vec4Array* colors = new osg::Vec4Array;
170        colors = new osg::Vec4Array;
171        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
172        quad->setColorArray(colors);
173        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
174        (*vertices)[0]=position;
175        (*vertices)[1]=position+dx;
176        (*vertices)[2]=position+dx+dy;
177        (*vertices)[3]=position+dy;
178        quad->setVertexArray(vertices);
179        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
180        geode->addDrawable(quad);
181        hudCamera->addChild(geode);
182       
183        position += delta;
184    }   
185   
186   
187   
188    { // this displays what has been selected
189        osg::Geode* geode = new osg::Geode();
190        osg::StateSet* stateset = geode->getOrCreateStateSet();
191        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
192        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
193        geode->setName("The text label");
194        geode->addDrawable( updateText );
195        hudCamera->addChild(geode);
196       
197        updateText->setCharacterSize(20.0f);
198        updateText->setFont(timesFont);
199        updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
200        updateText->setText("");
201        updateText->setPosition(position);
202        updateText->setDataVariance(osg::Object::DYNAMIC);
203       
204        position += delta;
205    }   
206   
207    return hudCamera;
208
209}
210
211int main( int argc, char **argv )
212{
213
214    // use an ArgumentParser object to manage the program arguments.
215    osg::ArgumentParser arguments(&argc,argv);
216
217    // construct the viewer.
218    osgViewer::Viewer viewer;
219
220    // read the scene from the list of file specified commandline args.
221    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
222     
223    // if not loaded assume no arguments passed in, try use default mode instead.
224    if (!scene) scene = osgDB::readNodeFile("fountain.osg");
225
226    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
227    if (!group)
228    {
229        group = new osg::Group;
230        group->addChild(scene.get());
231    }
232
233    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
234
235    // add the HUD subgraph.   
236    group->addChild(createHUD(updateText.get()));
237
238    // add the handler for doing the picking
239    viewer.addEventHandler(new PickHandler(updateText.get()));
240
241    // set the scene to render
242    viewer.setSceneData(group.get());
243
244    return viewer.run();
245}
Note: See TracBrowser for help on using the browser.