root/OpenSceneGraph/trunk/examples/osglauncher/osglauncher.cpp @ 9395

Revision 9395, 13.1 kB (checked in by robert, 5 years ago)

Fixed warnings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osglauncher.
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//#include <cstdio>
20//#include <cstdlib>
21#include <iostream>
22#include <list>
23#include <string>
24#include <sstream>
25
26#include <osg/Geode>
27#include <osg/ShapeDrawable>
28#include <osg/Material>
29#include <osg/Texture2D>
30#include <osg/Geometry>
31#include <osg/MatrixTransform>
32#include <osg/PositionAttitudeTransform>
33#include <osg/BlendFunc>
34#include <osg/ClearNode>
35#include <osg/Depth>
36#include <osg/Projection>
37#include <osg/io_utils>
38
39#include <osgUtil/CullVisitor>
40#include <osgUtil/Optimizer>
41
42#include <osgText/Text>
43
44#include <osgGA/TrackballManipulator>
45
46#include <osgViewer/Viewer>
47
48#include <osgDB/ReadFile>
49#include <osgDB/FileUtils>
50#include <osgDB/fstream>
51
52int runApp(std::string xapp);
53
54// class to handle events with a pick
55class PickHandler : public osgGA::GUIEventHandler {
56public:
57
58    PickHandler(osgViewer::Viewer* viewer,osgText::Text* updateText):
59        _viewer(viewer),
60        _updateText(updateText) {}
61       
62    ~PickHandler() {}
63   
64    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us);
65
66    std::string pick(float x, float y);
67   
68    void highlight(const std::string& name)
69    {
70        if (_updateText.get()) _updateText->setText(name);
71    }
72   
73protected:
74
75    osgViewer::Viewer* _viewer;
76    osg::ref_ptr<osgText::Text>  _updateText;
77};
78
79bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
80{
81    switch(ea.getEventType())
82    {
83    case(osgGA::GUIEventAdapter::FRAME):
84    case(osgGA::GUIEventAdapter::MOVE):
85    {
86        //osg::notify(osg::NOTICE)<<"MOVE "<<ea.getX()<<ea.getY()<<std::endl;
87        std::string picked_name = pick(ea.getX(),ea.getY());
88        highlight(picked_name);
89        return false;
90    }
91    case(osgGA::GUIEventAdapter::PUSH):
92    {
93        //osg::notify(osg::NOTICE)<<"PUSH "<<ea.getX()<<ea.getY()<<std::endl;
94        std::string picked_name = pick(ea.getX(),ea.getY());
95        if (!picked_name.empty())
96        {
97            runApp(picked_name);
98            return true;
99        }
100        else
101        {
102            return false;
103        }
104    }
105    default:
106        return false;
107    }
108}
109
110
111std::string PickHandler::pick(float x, float y)
112{
113    osgUtil::LineSegmentIntersector::Intersections intersections;
114    if (_viewer->computeIntersections(x, y, intersections))
115    {
116        for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
117            hitr != intersections.end();
118            ++hitr)
119        {
120            osg::Node* node = hitr->nodePath.empty() ? 0 : hitr->nodePath.back();
121            if (node && !node->getName().empty()) return node->getName();
122        }
123    }
124
125    return "";
126}
127
128osg::Node* createHUD(osgText::Text* updateText)
129{    // create the hud. derived from osgHud.cpp
130    // adds a set of quads, each in a separate Geode - which can be picked individually
131    // eg to be used as a menuing/help system!
132    // Can pick texts too!
133    osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
134    modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
135    modelview_abs->setMatrix(osg::Matrix::identity());
136   
137    osg::Projection* projection = new osg::Projection;
138    projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
139    projection->addChild(modelview_abs);
140   
141   
142    std::string timesFont("fonts/times.ttf");
143   
144    // turn lighting off for the text and disable depth test to ensure its always ontop.
145    osg::Vec3 position(50.0f,510.0f,0.0f);
146    osg::Vec3 delta(0.0f,-60.0f,0.0f);
147
148    { // this displays what has been selected
149        osg::Geode* geode = new osg::Geode();
150        osg::StateSet* stateset = geode->getOrCreateStateSet();
151        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
152        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
153        geode->setName("The text label");
154        geode->addDrawable( updateText );
155        modelview_abs->addChild(geode);
156       
157        updateText->setCharacterSize(20.0f);
158        updateText->setFont(timesFont);
159        updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
160        updateText->setText("");
161        updateText->setPosition(position);
162       
163        position += delta;
164    }   
165   
166    return projection;
167
168} // end create HUDf
169
170
171
172
173static osg::Vec3 defaultPos( 0.0f, 0.0f, 0.0f );
174static osg::Vec3 centerScope(0.0f, 0.0f, 0.0f);
175
176class Xample
177{
178    std::string texture;
179    std::string app;
180  public:
181      Xample(std::string image, std::string prog)
182    {
183        texture    = image;
184        app     = prog;
185        osg::notify(osg::INFO) << "New Xample!" << std::endl;
186    };
187    ~Xample() { };
188   
189    std::string getTexture()
190    {
191        return texture;
192    }
193    std::string getApp()
194    {
195        return app;
196    }
197}; // end class Xample
198
199
200typedef std::list<Xample>::iterator OP;
201static std::list<Xample> Xamplelist;
202
203
204void printList()
205{
206    osg::notify(osg::INFO) << "start printList()" << std::endl;
207    for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i)
208    {
209        Xample& x = *i;
210        osg::notify(osg::INFO) << "current x.texture = " << x.getTexture() << std::endl;
211        osg::notify(osg::INFO) << "current x.app = " << x.getApp() << std::endl;
212    }
213    osg::notify(osg::INFO) << "end printList()" << std::endl;
214} // end printList()
215
216
217int runApp(std::string xapp)
218{
219    osg::notify(osg::INFO) << "start runApp()" << std::endl;
220    for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i)
221    {
222        Xample& x = *i;
223        if(!xapp.compare(x.getApp()))
224        {
225            osg::notify(osg::INFO) << "app found!" << std::endl;
226           
227            const char* cxapp = xapp.c_str();
228           
229            osg::notify(osg::INFO) << "char* = " << cxapp <<std::endl;
230           
231            return system(cxapp);
232        }
233    }
234    osg::notify(osg::INFO) << "app not found!" << std::endl;
235    return 1;
236} // end printList()
237
238
239void readConfFile(const char* confFile)                                                                // read confFile            1
240{
241    osg::notify(osg::INFO) << "Start reading confFile" << std::endl;
242   
243    std::string fileName = osgDB::findDataFile(confFile);
244    if (fileName.empty())
245    {
246        osg::notify(osg::INFO) << "Config file not found"<<confFile << std::endl;
247        return;
248    }
249   
250
251    osgDB::ifstream in(fileName.c_str());
252    if (!in)
253    {
254        osg::notify(osg::INFO) << "File " << fileName << " can not be opened!" << std::endl;
255        exit(1);
256    }
257    std::string imageBuffer;
258    std::string appBuffer;
259   
260    while (!in.eof())
261    {
262        std::getline(in, imageBuffer);
263        std::getline(in, appBuffer);
264        if(imageBuffer == "" || appBuffer == "");
265        else
266        {
267            osg::notify(osg::INFO) << "imageBuffer: " << imageBuffer << std::endl;
268            osg::notify(osg::INFO) << "appBuffer: " << appBuffer << std::endl;
269//            jeweils checken ob image vorhanden ist.
270           
271            Xample tmp(imageBuffer, appBuffer);                                                    // create Xample objects    2
272           
273            Xamplelist.push_back(tmp);                                                            // store objects in list    2
274           
275        }
276    }
277   
278    in.close();
279   
280    osg::notify(osg::INFO) << "End reading confFile" << std::endl;
281   
282    printList();
283} // end readConfFile
284
285
286void SetObjectTextureState(osg::Geode *geodeCurrent, std::string texture)
287{
288    // retrieve or create a StateSet
289    osg::StateSet* stateTexture = geodeCurrent->getOrCreateStateSet();
290
291    // load texture.jpg as an image
292    osg::Image* imgTexture = osgDB::readImageFile( texture );
293   
294    // if the image is successfully loaded
295    if (imgTexture)
296    {
297        // create a new two-dimensional texture object
298        osg::Texture2D* texCube = new osg::Texture2D;
299
300        // set the texture to the loaded image
301        texCube->setImage(imgTexture);
302
303        // set the texture to the state
304        stateTexture->setTextureAttributeAndModes(0,texCube,osg::StateAttribute::ON);
305
306        // set the state of the current geode
307        geodeCurrent->setStateSet(stateTexture);
308    }
309} // end SetObjectTextureState
310
311
312osg::Geode* createTexturedCube(float fRadius,osg::Vec3 vPosition, std::string texture, std::string geodeName)
313{
314    // create a cube shape
315    osg::Box *bCube = new osg::Box(vPosition,fRadius);
316    // osg::Box *bCube = new osg::Box(vPosition,fRadius);
317
318    // create a container that makes the cube drawable
319    osg::ShapeDrawable *sdCube = new osg::ShapeDrawable(bCube);
320
321    // create a geode object to as a container for our drawable cube object
322    osg::Geode* geodeCube = new osg::Geode();
323    geodeCube->setName( geodeName );
324
325    // set the object texture state
326    SetObjectTextureState(geodeCube, texture);
327
328    // add our drawable cube to the geode container
329    geodeCube->addDrawable(sdCube);
330
331    return(geodeCube);
332} // end CreateCube
333
334
335osg::PositionAttitudeTransform* getPATransformation(osg::Node* object, osg::Vec3 position, osg::Vec3 scale, osg::Vec3 pivot)
336{
337    osg::PositionAttitudeTransform* tmpTrans = new osg::PositionAttitudeTransform();
338    tmpTrans->addChild( object );
339   
340    tmpTrans->setPosition( position );
341    tmpTrans->setScale( scale );
342    tmpTrans->setPivotPoint( pivot );
343   
344    return tmpTrans;
345}
346
347void printBoundings(osg::Node* current, std::string name)
348{
349    const osg::BoundingSphere& currentBound = current->getBound();
350    osg::notify(osg::INFO) << name << std::endl;
351    osg::notify(osg::INFO) << "center = " << currentBound.center() << std::endl;
352    osg::notify(osg::INFO) << "radius = " << currentBound.radius() << std::endl;
353   
354//    return currentBound.radius();
355}
356
357
358osg::Group* setupGraph()                                                                        // create Geodes/Nodes from Xamplelist    3
359{
360    osg::Group* xGroup = new osg::Group();
361
362   
363//    positioning and sizes
364    float defaultRadius = 0.8f;
365
366    int itemsInLine    = 4;                                    // name says everything
367    float offset    = 0.05f;
368    float bs        = (defaultRadius / 4) + offset;
369    float xstart    = (3*bs) * (-1);
370    float zstart    = xstart * (-1);
371    float xnext        = xstart;
372    float znext        = zstart;
373    float xjump        = (2*bs);
374    float zjump        = xjump;
375    osg::Vec3 vScale( 0.5f, 0.5f, 0.5f );
376    osg::Vec3 vPivot( 0.0f, 0.0f, 0.0f );   
377
378//  run through Xampleliste
379    int z = 1;
380    for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i, ++z)
381    {
382        Xample& x = *i;
383       
384        osg::Node* tmpCube = createTexturedCube(defaultRadius, defaultPos, x.getTexture(), x.getApp());
385        printBoundings(tmpCube, x.getApp());
386        osg::Vec3 vPosition( xnext, 0.0f, znext );
387        osg::PositionAttitudeTransform*    transX = getPATransformation(tmpCube, vPosition, vScale, vPivot);
388        xGroup->addChild( transX );
389       
390        // line feed
391        if(z < itemsInLine)
392            xnext += xjump;
393        else
394        {
395            xnext = xstart;
396            znext -= zjump;
397            z = 0;
398        }
399    } // end run through list   
400   
401    return xGroup;
402} // end setupGraph
403
404
405int main( int argc, char **argv )
406{
407    if (argc<=1)
408    {
409        readConfFile("osg.conf");                                                                          // read ConfigFile        1
410    }
411    else
412    {
413        readConfFile(argv[1]);                                                                          // read ConfigFile        1
414    }
415   
416    // construct the viewer.
417    osgViewer::Viewer viewer;
418
419    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
420    updateText->setDataVariance(osg::Object::DYNAMIC);
421
422    // add the handler for doing the picking
423    viewer.addEventHandler(new PickHandler(&viewer,updateText.get()));
424
425    osg::Group* root = new osg::Group();
426
427    root->addChild( setupGraph() );
428
429    // add the HUD subgraph.   
430    root->addChild(createHUD(updateText.get()));
431   
432    // add model to viewer.
433    viewer.setSceneData( root );
434
435    osg::Matrix lookAt;
436    lookAt.makeLookAt(osg::Vec3(0.0f, -4.0f, 0.0f), centerScope, osg::Vec3(0.0f, 0.0f, 1.0f));
437
438    viewer.getCamera()->setViewMatrix(lookAt);
439       
440    viewer.realize();
441
442    while( !viewer.done() )
443    {
444        // fire off the cull and draw traversals of the scene.
445        viewer.frame();       
446    }
447
448    return 0;
449} // end main
Note: See TracBrowser for help on using the browser.