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

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

From Michael Platings, Converted std::fstream/ifstream/ofstream to osgDB::fstream/ifstream/ofstream and
fopen to osgDB::fopen to facilitate support for wide character filenames using UT8 encoding.

  • 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            system(cxapp);
232            return 1;
233        }
234    }
235    osg::notify(osg::INFO) << "app not found!" << std::endl;
236    return 0;
237} // end printList()
238
239
240void readConfFile(const char* confFile)                                                                // read confFile            1
241{
242    osg::notify(osg::INFO) << "Start reading confFile" << std::endl;
243   
244    std::string fileName = osgDB::findDataFile(confFile);
245    if (fileName.empty())
246    {
247        osg::notify(osg::INFO) << "Config file not found"<<confFile << std::endl;
248        return;
249    }
250   
251
252    osgDB::ifstream in(fileName.c_str());
253    if (!in)
254    {
255        osg::notify(osg::INFO) << "File " << fileName << " can not be opened!" << std::endl;
256        exit(1);
257    }
258    std::string imageBuffer;
259    std::string appBuffer;
260   
261    while (!in.eof())
262    {
263        std::getline(in, imageBuffer);
264        std::getline(in, appBuffer);
265        if(imageBuffer == "" || appBuffer == "");
266        else
267        {
268            osg::notify(osg::INFO) << "imageBuffer: " << imageBuffer << std::endl;
269            osg::notify(osg::INFO) << "appBuffer: " << appBuffer << std::endl;
270//            jeweils checken ob image vorhanden ist.
271           
272            Xample tmp(imageBuffer, appBuffer);                                                    // create Xample objects    2
273           
274            Xamplelist.push_back(tmp);                                                            // store objects in list    2
275           
276        }
277    }
278   
279    in.close();
280   
281    osg::notify(osg::INFO) << "End reading confFile" << std::endl;
282   
283    printList();
284} // end readConfFile
285
286
287void SetObjectTextureState(osg::Geode *geodeCurrent, std::string texture)
288{
289    // retrieve or create a StateSet
290    osg::StateSet* stateTexture = geodeCurrent->getOrCreateStateSet();
291
292    // load texture.jpg as an image
293    osg::Image* imgTexture = osgDB::readImageFile( texture );
294   
295    // if the image is successfully loaded
296    if (imgTexture)
297    {
298        // create a new two-dimensional texture object
299        osg::Texture2D* texCube = new osg::Texture2D;
300
301        // set the texture to the loaded image
302        texCube->setImage(imgTexture);
303
304        // set the texture to the state
305        stateTexture->setTextureAttributeAndModes(0,texCube,osg::StateAttribute::ON);
306
307        // set the state of the current geode
308        geodeCurrent->setStateSet(stateTexture);
309    }
310} // end SetObjectTextureState
311
312
313osg::Geode* createTexturedCube(float fRadius,osg::Vec3 vPosition, std::string texture, std::string geodeName)
314{
315    // create a cube shape
316    osg::Box *bCube = new osg::Box(vPosition,fRadius);
317    // osg::Box *bCube = new osg::Box(vPosition,fRadius);
318
319    // create a container that makes the cube drawable
320    osg::ShapeDrawable *sdCube = new osg::ShapeDrawable(bCube);
321
322    // create a geode object to as a container for our drawable cube object
323    osg::Geode* geodeCube = new osg::Geode();
324    geodeCube->setName( geodeName );
325
326    // set the object texture state
327    SetObjectTextureState(geodeCube, texture);
328
329    // add our drawable cube to the geode container
330    geodeCube->addDrawable(sdCube);
331
332    return(geodeCube);
333} // end CreateCube
334
335
336osg::PositionAttitudeTransform* getPATransformation(osg::Node* object, osg::Vec3 position, osg::Vec3 scale, osg::Vec3 pivot)
337{
338    osg::PositionAttitudeTransform* tmpTrans = new osg::PositionAttitudeTransform();
339    tmpTrans->addChild( object );
340   
341    tmpTrans->setPosition( position );
342    tmpTrans->setScale( scale );
343    tmpTrans->setPivotPoint( pivot );
344   
345    return tmpTrans;
346}
347
348void printBoundings(osg::Node* current, std::string name)
349{
350    const osg::BoundingSphere& currentBound = current->getBound();
351    osg::notify(osg::INFO) << name << std::endl;
352    osg::notify(osg::INFO) << "center = " << currentBound.center() << std::endl;
353    osg::notify(osg::INFO) << "radius = " << currentBound.radius() << std::endl;
354   
355//    return currentBound.radius();
356}
357
358
359osg::Group* setupGraph()                                                                        // create Geodes/Nodes from Xamplelist    3
360{
361    osg::Group* xGroup = new osg::Group();
362
363   
364//    positioning and sizes
365    float defaultRadius = 0.8f;
366
367    int itemsInLine    = 4;                                    // name says everything
368    float offset    = 0.05f;
369    float bs        = (defaultRadius / 4) + offset;
370    float xstart    = (3*bs) * (-1);
371    float zstart    = xstart * (-1);
372    float xnext        = xstart;
373    float znext        = zstart;
374    float xjump        = (2*bs);
375    float zjump        = xjump;
376    osg::Vec3 vScale( 0.5f, 0.5f, 0.5f );
377    osg::Vec3 vPivot( 0.0f, 0.0f, 0.0f );   
378
379//  run through Xampleliste
380    int z = 1;
381    for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i, ++z)
382    {
383        Xample& x = *i;
384       
385        osg::Node* tmpCube = createTexturedCube(defaultRadius, defaultPos, x.getTexture(), x.getApp());
386        printBoundings(tmpCube, x.getApp());
387        osg::Vec3 vPosition( xnext, 0.0f, znext );
388        osg::PositionAttitudeTransform*    transX = getPATransformation(tmpCube, vPosition, vScale, vPivot);
389        xGroup->addChild( transX );
390       
391        // line feed
392        if(z < itemsInLine)
393            xnext += xjump;
394        else
395        {
396            xnext = xstart;
397            znext -= zjump;
398            z = 0;
399        }
400    } // end run through list   
401   
402    return xGroup;
403} // end setupGraph
404
405
406int main( int argc, char **argv )
407{
408    if (argc<=1)
409    {
410        readConfFile("osg.conf");                                                                          // read ConfigFile        1
411    }
412    else
413    {
414        readConfFile(argv[1]);                                                                          // read ConfigFile        1
415    }
416   
417    // construct the viewer.
418    osgViewer::Viewer viewer;
419
420    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
421    updateText->setDataVariance(osg::Object::DYNAMIC);
422
423    // add the handler for doing the picking
424    viewer.addEventHandler(new PickHandler(&viewer,updateText.get()));
425
426    osg::Group* root = new osg::Group();
427
428    root->addChild( setupGraph() );
429
430    // add the HUD subgraph.   
431    root->addChild(createHUD(updateText.get()));
432   
433    // add model to viewer.
434    viewer.setSceneData( root );
435
436    osg::Matrix lookAt;
437    lookAt.makeLookAt(osg::Vec3(0.0f, -4.0f, 0.0f), centerScope, osg::Vec3(0.0f, 0.0f, 1.0f));
438
439    viewer.getCamera()->setViewMatrix(lookAt);
440       
441    viewer.realize();
442
443    while( !viewer.done() )
444    {
445        // fire off the cull and draw traversals of the scene.
446        viewer.frame();       
447    }
448
449    return 0;
450} // end main
Note: See TracBrowser for help on using the browser.