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

Revision 12529, 12.4 kB (checked in by robert, 3 years ago)

Replaced .osg with .osgt file usage

  • 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#include <osgViewer/CompositeViewer>
28
29#include <osgGA/TerrainManipulator>
30#include <osgGA/StateSetManipulator>
31#include <osgGA/AnimationPathManipulator>
32#include <osgGA/TrackballManipulator>
33#include <osgGA/FlightManipulator>
34#include <osgGA/DriveManipulator>
35#include <osgGA/KeySwitchMatrixManipulator>
36#include <osgGA/StateSetManipulator>
37#include <osgGA/AnimationPathManipulator>
38#include <osgGA/TerrainManipulator>
39
40#include <osg/Material>
41#include <osg/Geode>
42#include <osg/BlendFunc>
43#include <osg/Depth>
44#include <osg/Projection>
45#include <osg/MatrixTransform>
46#include <osg/Camera>
47#include <osg/io_utils>
48#include <osg/ShapeDrawable>
49
50#include <osgText/Text>
51
52#include <sstream>
53
54// class to handle events with a pick
55class PickHandler : public osgGA::GUIEventHandler {
56public:
57
58    PickHandler(osgText::Text* updateText):
59        _updateText(updateText) {}
60       
61    ~PickHandler() {}
62   
63    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);
64
65    virtual void pick(osgViewer::View* view, const osgGA::GUIEventAdapter& ea);
66
67    void setLabel(const std::string& name)
68    {
69        if (_updateText.get()) _updateText->setText(name);
70    }
71   
72protected:
73
74    osg::ref_ptr<osgText::Text>  _updateText;
75};
76
77bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
78{
79    switch(ea.getEventType())
80    {
81        case(osgGA::GUIEventAdapter::PUSH):
82        {
83            osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
84            if (view) pick(view,ea);
85            return false;
86        }   
87        case(osgGA::GUIEventAdapter::KEYDOWN):
88        {
89            if (ea.getKey()=='c')
90            {       
91                osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
92                osg::ref_ptr<osgGA::GUIEventAdapter> event = new osgGA::GUIEventAdapter(ea);
93                event->setX((ea.getXmin()+ea.getXmax())*0.5);
94                event->setY((ea.getYmin()+ea.getYmax())*0.5);
95                if (view) pick(view,*event);
96            }
97            return false;
98        }   
99        default:
100            return false;
101    }
102}
103
104void PickHandler::pick(osgViewer::View* view, const osgGA::GUIEventAdapter& ea)
105{
106    osgUtil::LineSegmentIntersector::Intersections intersections;
107
108    std::string gdlist="";
109    float x = ea.getX();
110    float y = ea.getY();
111#if 0
112    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::WINDOW, x, y);
113    osgUtil::IntersectionVisitor iv(picker.get());
114    view->getCamera()->accept(iv);
115    if (picker->containsIntersections())
116    {
117        intersections = picker->getIntersections();
118#else
119    if (view->computeIntersections(x,y,intersections))
120    {
121#endif
122        for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
123            hitr != intersections.end();
124            ++hitr)
125        {
126            std::ostringstream os;
127            if (!hitr->nodePath.empty() && !(hitr->nodePath.back()->getName().empty()))
128            {
129                // the geodes are identified by name.
130                os<<"Object \""<<hitr->nodePath.back()->getName()<<"\""<<std::endl;
131            }
132            else if (hitr->drawable.valid())
133            {
134                os<<"Object \""<<hitr->drawable->className()<<"\""<<std::endl;
135            }
136
137            os<<"        local coords vertex("<< hitr->getLocalIntersectPoint()<<")"<<"  normal("<<hitr->getLocalIntersectNormal()<<")"<<std::endl;
138            os<<"        world coords vertex("<< hitr->getWorldIntersectPoint()<<")"<<"  normal("<<hitr->getWorldIntersectNormal()<<")"<<std::endl;
139            const osgUtil::LineSegmentIntersector::Intersection::IndexList& vil = hitr->indexList;
140            for(unsigned int i=0;i<vil.size();++i)
141            {
142                os<<"        vertex indices ["<<i<<"] = "<<vil[i]<<std::endl;
143            }
144           
145            gdlist += os.str();
146        }
147    }
148    setLabel(gdlist);
149}
150
151osg::Node* createHUD(osgText::Text* updateText)
152{
153
154    // create the hud. derived from osgHud.cpp
155    // adds a set of quads, each in a separate Geode - which can be picked individually
156    // eg to be used as a menuing/help system!
157    // Can pick texts too!
158
159    osg::Camera* hudCamera = new osg::Camera;
160    hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
161    hudCamera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
162    hudCamera->setViewMatrix(osg::Matrix::identity());
163    hudCamera->setRenderOrder(osg::Camera::POST_RENDER);
164    hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
165   
166    std::string timesFont("fonts/times.ttf");
167   
168    // turn lighting off for the text and disable depth test to ensure its always ontop.
169    osg::Vec3 position(150.0f,800.0f,0.0f);
170    osg::Vec3 delta(0.0f,-60.0f,0.0f);
171   
172    {
173        osg::Geode* geode = new osg::Geode();
174        osg::StateSet* stateset = geode->getOrCreateStateSet();
175        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
176        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
177        geode->setName("simple");
178        hudCamera->addChild(geode);
179       
180        osgText::Text* text = new  osgText::Text;
181        geode->addDrawable( text );
182       
183        text->setFont(timesFont);
184        text->setText("Picking in Head Up Displays is simple!");
185        text->setPosition(position);
186       
187        position += delta;
188    }   
189   
190   
191    for (int i=0; i<5; i++) {
192        osg::Vec3 dy(0.0f,-30.0f,0.0f);
193        osg::Vec3 dx(120.0f,0.0f,0.0f);
194        osg::Geode* geode = new osg::Geode();
195        osg::StateSet* stateset = geode->getOrCreateStateSet();
196        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
197        osg::Geometry *quad=new osg::Geometry;
198        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
199        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
200        std::string name="subOption";
201        name += " ";
202        name += std::string(opts[i]);
203        geode->setName(name);
204        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
205        osg::Vec4Array* colors = new osg::Vec4Array;
206        colors = new osg::Vec4Array;
207        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
208        quad->setColorArray(colors);
209        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
210        (*vertices)[0]=position;
211        (*vertices)[1]=position+dx;
212        (*vertices)[2]=position+dx+dy;
213        (*vertices)[3]=position+dy;
214        quad->setVertexArray(vertices);
215        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
216        geode->addDrawable(quad);
217        hudCamera->addChild(geode);
218       
219        position += delta;
220    }   
221   
222   
223   
224    { // this displays what has been selected
225        osg::Geode* geode = new osg::Geode();
226        osg::StateSet* stateset = geode->getOrCreateStateSet();
227        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
228        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
229        geode->setName("The text label");
230        geode->addDrawable( updateText );
231        hudCamera->addChild(geode);
232       
233        updateText->setCharacterSize(20.0f);
234        updateText->setFont(timesFont);
235        updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
236        updateText->setText("");
237        updateText->setPosition(position);
238        updateText->setDataVariance(osg::Object::DYNAMIC);
239       
240        position += delta;
241    }   
242   
243    return hudCamera;
244
245}
246
247int main( int argc, char **argv )
248{
249    // use an ArgumentParser object to manage the program arguments.
250    osg::ArgumentParser arguments(&argc,argv);
251
252    // read the scene from the list of file specified commandline args.
253    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
254
255    if (!scene && arguments.read("--relative-camera-scene"))
256    {
257        // Create a test scene with a camera that has a relative reference frame.
258        osg::Group* group = new osg::Group();
259
260        osg::Geode* sphere = new osg::Geode();
261        sphere->setName("Sphere");
262        sphere->addDrawable(new osg::ShapeDrawable(new osg::Sphere()));
263
264        osg::Geode* cube = new osg::Geode();
265        cube->setName("Cube");
266        cube->addDrawable(new osg::ShapeDrawable(new osg::Box()));
267
268        osg::Camera* camera = new osg::Camera();
269        camera->setRenderOrder(osg::Camera::POST_RENDER);
270        camera->setClearMask(GL_DEPTH_BUFFER_BIT);
271        camera->setReferenceFrame(osg::Transform::RELATIVE_RF);
272        camera->setViewMatrix(osg::Matrix::translate(-2, 0, 0));
273
274        osg::MatrixTransform* xform = new osg::MatrixTransform(osg::Matrix::translate(1, 1, 1));
275        xform->addChild(camera);
276
277        group->addChild(sphere);
278        group->addChild(xform);
279        camera->addChild(cube);
280
281        scene = group;
282    }
283
284    // if not loaded assume no arguments passed in, try use default mode instead.
285    if (!scene) scene = osgDB::readNodeFile("fountain.osgt");
286
287    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
288    if (!group)
289    {
290        group = new osg::Group;
291        group->addChild(scene.get());
292    }
293
294    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
295
296    // add the HUD subgraph.   
297    group->addChild(createHUD(updateText.get()));
298
299    if (arguments.read("--CompositeViewer"))
300    {
301        osg::ref_ptr<osgViewer::View> view = new osgViewer::View;
302        // add the handler for doing the picking
303        view->addEventHandler(new PickHandler(updateText.get()));
304
305        // set the scene to render
306        view->setSceneData(group.get());
307
308        view->setUpViewAcrossAllScreens();
309
310        osgViewer::CompositeViewer viewer;
311        viewer.addView(view.get());
312
313        return viewer.run();
314
315    }
316    else
317    {
318        osgViewer::Viewer viewer;
319
320
321        // add all the camera manipulators
322        {
323            osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
324
325            keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
326            keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
327            keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
328
329            unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
330            keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
331
332            std::string pathfile;
333            char keyForAnimationPath = '5';
334            while (arguments.read("-p",pathfile))
335            {
336                osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
337                if (apm || !apm->valid())
338                {
339                    num = keyswitchManipulator->getNumMatrixManipulators();
340                    keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
341                    ++keyForAnimationPath;
342                }
343            }
344
345            keyswitchManipulator->selectMatrixManipulator(num);
346
347            viewer.setCameraManipulator( keyswitchManipulator.get() );
348        }
349
350        // add the handler for doing the picking
351        viewer.addEventHandler(new PickHandler(updateText.get()));
352
353        // set the scene to render
354        viewer.setSceneData(group.get());
355   
356        return viewer.run();
357    }
358
359}
Note: See TracBrowser for help on using the browser.