root/OpenSceneGraph/trunk/examples/osgQtWidgets/osgQtWidgets.cpp @ 13219

Revision 12292, 28.6 kB (checked in by robert, 4 years ago)

Ran svn propset -R svn:eol-style native . on the OpenSceneGraph

  • Property svn:eol-style set to native
Line 
1/* OpenSceneGraph example, osgcompositeviewer.
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 <iostream>
20
21#include <osg/Notify>
22#include <osg/io_utils>
23
24#include <osg/ArgumentParser>
25#include <osg/MatrixTransform>
26#include <osg/AutoTransform>
27#include <osg/Camera>
28#include <osg/TexMat>
29#include <osg/TextureRectangle>
30#include <osgDB/ReadFile>
31#include <osgDB/WriteFile>
32#include <osgGA/TrackballManipulator>
33#include <osgGA/StateSetManipulator>
34#include <osgViewer/Viewer>
35#include <osgViewer/ViewerEventHandlers>
36#include <osgWidget/Browser>
37
38
39//#include <QtWebKit/QWebSettings>
40//#include <QtWebKit/QtWebKit>
41#include <QtGui/QGraphicsScene>
42#include <QtGui/QGraphicsView>
43#include <QtGui/QApplication>
44#include <QtGui/QPainter>
45#include <QtGui/QtEvents>
46#include <QtGui/QDialog>
47#include <QtGui/QVBoxLayout>
48#include <QtGui/QMainWindow>
49#include <QtOpenGL/QtOpenGL>
50
51#include <osgQt/QGraphicsViewAdapter>
52#include <osgQt/QWebViewImage>
53#include <osgQt/QWidgetImage>
54
55
56// Thread that runs the viewer's frame loop as we can't run Qt in the background...
57class ViewerFrameThread : public OpenThreads::Thread
58{
59    public:
60
61        ViewerFrameThread(osgViewer::ViewerBase* viewerBase, bool doQApplicationExit):
62            _viewerBase(viewerBase),
63            _doQApplicationExit(doQApplicationExit) {}
64
65        ~ViewerFrameThread()
66        {
67            cancel();
68            while(isRunning())
69            {
70                OpenThreads::Thread::YieldCurrentThread();
71            }
72        }
73
74        int cancel()
75        {
76            _viewerBase->setDone(true);
77            return 0;
78        }
79
80        void run()
81        {
82            int result = _viewerBase->run();
83
84            if (_doQApplicationExit) QApplication::exit(result);
85        }
86
87        osg::ref_ptr<osgViewer::ViewerBase> _viewerBase;
88        bool _doQApplicationExit;
89};
90
91
92class MyPushButton : public QPushButton
93{
94public:
95    MyPushButton(const QString& text) : QPushButton(text) {}
96
97protected:
98    virtual void mousePressEvent(QMouseEvent* e)
99    {
100        bool ok = false;
101        int val = QInputDialog::getInteger(this, "Get integer", "Please enter an integer between 0 and pi", 0, 0, 3, 1, &ok);
102        std::cout << "Ok was " << (ok ? "" : "not") << " pressed, val is " << val << std::endl;
103    }
104};
105
106
107//We would need to document the following somewhere in order to guide people on
108//what they need to use...
109//
110//----------------------------------------------
111//There are two angles to consider.
112//
113//1. If someone wants a widget in their Qt app to be an OSG-rendered scene, they
114//need GraphicsWindowQt (in the osgViewerQtContext example) or QOSGWidget (in the
115//osgViewerQt example). These two allow both OSG and Qt to manage their threads
116//in a way which is optimal to them. We've used QOSGWidget in the past and had
117//trouble when Qt tried to overlay other widgets over the QOSGWidget (since OSG
118//did its rendering independently of Qt, it would overwrite what Qt had drawn). I
119//haven't tried GraphicsWindowQt yet, but I expect since it uses QGLWidget, it
120//will result in Qt knowing when OSG has drawn and be able to do overlays at the
121//right time. Eventually GraphicsWindowQt can be brought into osgViewer I imagine...
122//
123//2. If someone wants to bring Qt widgets inside their OSG scene (to do HUDs or
124//an interface on a computer screen which is inside the 3D scene, or even
125//floating Qt widgets, for example). That's where QGraphicsViewAdapter +
126//QWidgetImage will be useful.
127//----------------------------------------------
128
129
130int main(int argc, char **argv)
131{
132    // Qt requires that we construct the global QApplication before creating any widgets.
133    QApplication app(argc, argv);
134
135    // use an ArgumentParser object to manage the program arguments.
136    osg::ArgumentParser arguments(&argc,argv);
137
138    // true = run osgViewer in a separate thread than Qt
139    // false = interleave osgViewer and Qt in the main thread
140    bool useFrameLoopThread = false;
141    if (arguments.read("--no-frame-thread")) useFrameLoopThread = false;
142    if (arguments.read("--frame-thread")) useFrameLoopThread = true;
143
144    // true = use QWidgetImage
145    // false = use QWebViewImage
146    bool useWidgetImage = false;
147    if (arguments.read("--useWidgetImage")) useWidgetImage = true;
148
149    // true = use QWebView in a QWidgetImage to compare to QWebViewImage
150    // false = make an interesting widget
151    bool useBrowser = false;
152    if (arguments.read("--useBrowser")) useBrowser = true;
153
154    // true = use a QLabel for text
155    // false = use a QTextEdit for text
156    // (only applies if useWidgetImage == true and useBrowser == false)
157    bool useLabel = false;
158    if (arguments.read("--useLabel")) useLabel = true;
159
160    // true = make a Qt window with the same content to compare to
161    // QWebViewImage/QWidgetImage
162    // false = use QWebViewImage/QWidgetImage (depending on useWidgetImage)
163    bool sanityCheck = false;
164    if (arguments.read("--sanityCheck")) sanityCheck = true;
165
166    // Add n floating windows inside the QGraphicsScene.
167    int numFloatingWindows = 0;
168    while (arguments.read("--numFloatingWindows", numFloatingWindows));
169
170    // true = Qt widgets will be displayed on a quad inside the 3D scene
171    // false = Qt widgets will be an overlay over the scene (like a HUD)
172    bool inScene = true;
173    if (arguments.read("--fullscreen")) { inScene = false; }
174
175
176    osg::ref_ptr<osg::Group> root = new osg::Group;
177
178    if (!useWidgetImage)
179    {
180        //-------------------------------------------------------------------
181        // QWebViewImage test
182        //-------------------------------------------------------------------
183        // Note: When the last few issues with QWidgetImage are fixed,
184        // QWebViewImage and this if() {} section can be removed since
185        // QWidgetImage can display a QWebView just like QWebViewImage. Use
186        // --useWidgetImage --useBrowser to see that in action.
187
188        if (!sanityCheck)
189        {
190            osg::ref_ptr<osgQt::QWebViewImage> image = new osgQt::QWebViewImage;
191
192            if (arguments.argc()>1) image->navigateTo((arguments[1]));
193            else image->navigateTo("http://www.youtube.com/");
194
195            osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),
196                                           osg::Vec3(1.0f,0.0f,0.0f),
197                                           osg::Vec3(0.0f,0.0f,1.0f),
198                                           osg::Vec4(1.0f,1.0f,1.0f,1.0f),
199                                           osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);
200
201            osg::ref_ptr<osgWidget::Browser> browser = new osgWidget::Browser;
202            browser->assign(image.get(), hints);
203
204            root->addChild(browser.get());
205        }
206        else
207        {
208            // Sanity check, do the same thing as QGraphicsViewAdapter but in
209            // a separate Qt window.
210            QWebPage* webPage = new QWebPage;
211            webPage->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
212            webPage->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
213
214            QWebView* webView = new QWebView;
215            webView->setPage(webPage);
216
217            if (arguments.argc()>1) webView->load(QUrl(arguments[1]));
218            else webView->load(QUrl("http://www.youtube.com/"));
219
220            QGraphicsScene* graphicsScene = new QGraphicsScene;
221            graphicsScene->addWidget(webView);
222
223            QGraphicsView* graphicsView = new QGraphicsView;
224            graphicsView->setScene(graphicsScene);
225
226            QMainWindow* mainWindow = new QMainWindow;
227            //mainWindow->setLayout(new QVBoxLayout);
228            mainWindow->setCentralWidget(graphicsView);
229            mainWindow->setGeometry(50, 50, 1024, 768);
230            mainWindow->show();
231            mainWindow->raise();
232        }
233    }
234    else
235    {
236        //-------------------------------------------------------------------
237        // QWidgetImage test
238        //-------------------------------------------------------------------
239        // QWidgetImage still has some issues, some examples are:
240        //
241        // 1. Editing in the QTextEdit doesn't work. Also when started with
242        //    --useBrowser, editing in the search field on YouTube doesn't
243        //    work. But that same search field when using QWebViewImage
244        //    works... And editing in the text field in the pop-up getInteger
245        //    dialog works too. All these cases use QGraphicsViewAdapter
246        //    under the hood, so why do some work and others don't?
247        //
248        //    a) osgQtBrowser --useWidgetImage [--fullscreen] (optional)
249        //    b) Try to click in the QTextEdit and type, or to select text
250        //       and drag-and-drop it somewhere else in the QTextEdit. These
251        //       don't work.
252        //    c) osgQtBrowser --useWidgetImage --sanityCheck
253        //    d) Try the operations in b), they all work.
254        //    e) osgQtBrowser --useWidgetImage --useBrowser [--fullscreen]
255        //    f) Try to click in the search field and type, it doesn't work.
256        //    g) osgQtBrowser
257        //    h) Try the operation in f), it works.
258        //
259        // 2. Operations on floating windows (--numFloatingWindows 1 or more).
260        //    Moving by dragging the titlebar, clicking the close button,
261        //    resizing them, none of these work. I wonder if it's because the
262        //    OS manages those functions (they're functions of the window
263        //    decorations) so we need to do something special for that? But
264        //    in --sanityCheck mode they work.
265        //
266        //    a) osgQtBrowser --useWidgetImage --numFloatingWindows 1 [--fullscreen]
267        //    b) Try to drag the floating window, click the close button, or
268        //       drag its sides to resize it. None of these work.
269        //    c) osgQtBrowser --useWidgetImage --numFloatingWindows 1 --sanityCheck
270        //    d) Try the operations in b), all they work.
271        //    e) osgQtBrowser --useWidgetImage [--fullscreen]
272        //    f) Click the button so that the getInteger() dialog is
273        //       displayed, then try to move that dialog or close it with the
274        //       close button, these don't work.
275        //    g) osgQtBrowser --useWidgetImage --sanityCheck
276        //    h) Try the operation in f), it works.
277        //
278        // 3. (Minor) The QGraphicsView's scrollbars don't appear when
279        //    using QWidgetImage or QWebViewImage. QGraphicsView is a
280        //    QAbstractScrollArea and it should display scrollbars as soon as
281        //    the scene is too large to fit the view.
282        //
283        //    a) osgQtBrowser --useWidgetImage --fullscreen
284        //    b) Resize the OSG window so it's smaller than the QTextEdit.
285        //       Scrollbars should appear but don't.
286        //    c) osgQtBrowser --useWidgetImage --sanityCheck
287        //    d) Try the operation in b), scrollbars appear. Even if you have
288        //       floating windows (by clicking the button or by adding
289        //       --numFloatingWindows 1) and move them outside the view,
290        //       scrollbars appear too. You can't test that case in OSG for
291        //       now because of problem 2 above, but that's pretty cool.
292        //
293        // 4. (Minor) In sanity check mode, the widget added to the
294        //    QGraphicsView is centered. With QGraphicsViewAdapter, it is not.
295        //
296        //    a) osgQtBrowser --useWidgetImage [--fullscreen]
297        //    b) The QTextEdit and button are not in the center of the image
298        //       generated by the QGraphicsViewAdapter.
299        //    c) osgQtBrowser --useWidgetImage --sanityCheck
300        //    d) The QTextEdit and button are in the center of the
301        //       QGraphicsView.
302
303
304        QWidget* widget = 0;
305        if (useBrowser)
306        {
307            QWebPage* webPage = new QWebPage;
308            webPage->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
309            webPage->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
310
311            QWebView* webView = new QWebView;
312            webView->setPage(webPage);
313
314            if (arguments.argc()>1) webView->load(QUrl(arguments[1]));
315            else webView->load(QUrl("http://www.youtube.com/"));
316
317            widget = webView;
318        }
319        else
320        {
321            widget = new QWidget;
322            widget->setLayout(new QVBoxLayout);
323
324            QString text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque velit turpis, euismod ac ultrices et, molestie non nisi. Nullam egestas dignissim enim, quis placerat nulla suscipit sed. Donec molestie elementum risus sit amet sodales. Nunc consectetur congue neque, at viverra massa pharetra fringilla. Integer vitae mi sem. Donec dapibus semper elit nec sollicitudin. Vivamus egestas ultricies felis, in mollis mi facilisis quis. Nam suscipit bibendum eros sed cursus. Suspendisse mollis suscipit hendrerit. Etiam magna eros, convallis non congue vel, faucibus ac augue. Integer ante ante, porta in ornare ullamcorper, congue nec nibh. Etiam congue enim vitae enim sollicitudin fringilla. Mauris mattis, urna in fringilla dapibus, ipsum sem feugiat purus, ac hendrerit felis arcu sed sapien. Integer id velit quam, sit amet dignissim tortor. Sed mi tortor, placerat ac luctus id, tincidunt et urna. Nulla sed nunc ante.Sed ut sodales enim. Ut sollicitudin ultricies magna, vel ultricies ante venenatis id. Cras luctus mi in lectus rhoncus malesuada. Sed ac sollicitudin nisi. Nunc venenatis congue quam, et suscipit diam consectetur id. Donec vel enim ac enim elementum bibendum ut quis augue. Nulla posuere suscipit dolor, id convallis tortor congue eu. Vivamus sagittis consectetur dictum. Duis a ante quis dui varius fermentum. In hac habitasse platea dictumst. Nam dapibus dolor eu felis eleifend in scelerisque dolor ultrices. Donec arcu lectus, fringilla ut interdum non, tristique id dolor. Morbi sagittis sagittis volutpat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis venenatis ultrices euismod.Nam sit amet convallis libero. Integer lectus urna, eleifend et sollicitudin non, porttitor vel erat. Vestibulum pulvinar egestas leo, a porttitor turpis ullamcorper et. Vestibulum in ornare turpis. Ut nec libero a sem mattis iaculis quis id purus. Praesent ante neque, dictum vitae pretium vel, iaculis luctus dui. Etiam luctus tellus vel nunc suscipit a ullamcorper nisl semper. Nunc dapibus, eros in sodales dignissim, orci lectus egestas felis, sit amet vehicula tortor dolor eu quam. Vivamus pellentesque convallis quam aliquet pellentesque. Phasellus facilisis arcu ac orci fringilla aliquet. Donec sed euismod augue. Duis eget orci sit amet neque tempor fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse platea dictumst. Duis sollicitudin, lacus ac pellentesque lacinia, lacus magna pulvinar purus, pulvinar porttitor est nibh quis augue.Duis eleifend, massa sit amet mattis fringilla, elit turpis venenatis libero, sed convallis turpis diam sit amet ligula. Morbi non dictum turpis. Integer porttitor condimentum elit, sit amet sagittis nibh ultrices sit amet. Mauris ac arcu augue, id aliquet mauris. Donec ultricies urna id enim accumsan at pharetra dui adipiscing. Nunc luctus rutrum molestie. Curabitur libero ipsum, viverra at pulvinar ut, porttitor et neque. Aliquam sit amet dolor et purus sagittis adipiscing. Nam sit amet hendrerit sem. Etiam varius, ligula non ultricies dignissim, sapien dui commodo urna, eu vehicula enim nunc molestie augue. Fusce euismod, erat vitae pharetra tempor, quam eros tincidunt lorem, ut iaculis ligula erat vitae nibh. Aenean eu ultricies dolor. Curabitur suscipit viverra bibendum.Sed egestas adipiscing mi in egestas. Proin in neque in nibh blandit consequat nec quis tortor. Vestibulum sed interdum justo. Sed volutpat velit vitae elit pulvinar aliquam egestas elit rutrum. Proin lorem nibh, bibendum vitae sollicitudin condimentum, pulvinar ut turpis. Maecenas iaculis, mauris in consequat ultrices, ante erat blandit mi, vel fermentum lorem turpis eget sem. Integer ultrices tristique erat sit amet volutpat. In sit amet diam et nunc congue pellentesque at in dolor. Mauris eget orci orci. Integer posuere augue ornare tortor tempus elementum. Quisque iaculis, nunc ac cursus fringilla, magna elit cursus eros, id feugiat diam eros et tellus. Etiam consectetur ultrices erat quis rhoncus. Mauris eu lacinia neque. Curabitur suscipit feugiat tellus in dictum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed aliquam tempus ante a tempor. Praesent viverra erat quis sapien pretium rutrum. Praesent dictum scelerisque venenatis.Proin bibendum lectus eget nisl lacinia porta. Morbi eu erat in sapien malesuada vulputate. Cras non elit quam. Ut dictum urna quis nisl feugiat ac sollicitudin libero luctus. Donec leo mauris, varius at luctus eget, placerat quis arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam tristique, mauris ut lacinia elementum, mauris erat consequat massa, ac gravida nisi tellus vitae purus. Curabitur consectetur ultricies commodo. Cras pulvinar orci nec enim adipiscing tristique. Ut ornare orci id est fringilla sit amet blandit libero pellentesque. Vestibulum tincidunt sapien ut enim venenatis vestibulum ultricies ipsum tristique. Mauris tempus eleifend varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vitae dui ac quam gravida semper. In ac enim ac ligula rutrum porttitor.Integer dictum sagittis leo, at convallis sapien facilisis eget. Etiam cursus bibendum tortor, faucibus aliquam lectus ullamcorper sed. Nulla pulvinar posuere quam, ut sagittis ligula tincidunt ut. Nulla convallis velit ut enim condimentum pulvinar. Quisque gravida accumsan scelerisque. Proin pellentesque nisi cursus tortor aliquet dapibus. Duis vel eros orci. Sed eget purus ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ullamcorper porta congue. Nunc id velit ut neque malesuada consequat in eu nisi. Nulla facilisi. Quisque pellentesque magna vitae nisl euismod ac accumsan tellus feugiat.Nulla facilisi. Integer quis orci lectus, non aliquam nisi. Vivamus varius porta est, ac porttitor orci blandit mattis. Sed dapibus facilisis dapibus. Duis tincidunt leo ac tortor faucibus hendrerit. Morbi sit amet sapien risus, vel luctus enim. Aliquam sagittis nunc id purus aliquam lobortis. Duis posuere viverra dui, sit amet convallis sem vulputate at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pellentesque, lectus id imperdiet commodo, diam diam faucibus lectus, sit amet vestibulum tortor lacus viverra eros.Maecenas nec augue lectus. Duis nec arcu eget lorem tempus sollicitudin suscipit vitae arcu. Nullam vitae mauris lectus. Vivamus id risus neque, dignissim vehicula diam. Cras rhoncus velit sed velit iaculis ac dignissim turpis luctus. Suspendisse potenti. Sed vitae ligula a ligula ornare rutrum sit amet ut quam. Duis tincidunt, nibh vitae iaculis adipiscing, dolor orci cursus arcu, vel congue tortor quam eget arcu. Suspendisse tellus felis, blandit ac accumsan vitae, fringilla id lorem. Duis tempor lorem mollis est congue ut imperdiet velit laoreet. Nullam interdum cursus mollis. Pellentesque non mauris accumsan elit laoreet viverra ut at risus. Proin rutrum sollicitudin sem, vitae ultricies augue sagittis vel. Cras quis vehicula neque. Aliquam erat volutpat. Aliquam erat volutpat. Praesent non est erat, accumsan rutrum lacus. Pellentesque tristique molestie aliquet. Cras ullamcorper facilisis faucibus. In non lorem quis velit lobortis pulvinar.Phasellus non sem ipsum. Praesent ut libero quis turpis viverra semper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In hac habitasse platea dictumst. Donec at velit tellus. Fusce commodo pharetra tincidunt. Proin lacus enim, fringilla a fermentum ut, vestibulum ut nibh. Duis commodo dolor vel felis vehicula at egestas neque bibendum. Phasellus malesuada dictum ante in aliquam. Curabitur interdum semper urna, nec placerat justo gravida in. Praesent quis mauris massa. Pellentesque porttitor lacinia tincidunt. Phasellus egestas viverra elit vel blandit. Sed dapibus nisi et lectus pharetra dignissim. Mauris hendrerit lectus nec purus dapibus condimentum. Sed ac eros nulla. Aenean semper sapien a nibh aliquam lobortis. Aliquam elementum euismod sapien, in dapibus leo dictum et. Pellentesque augue neque, ultricies non viverra eu, tincidunt ac arcu. Morbi ut porttitor lectus.");
325
326            if (useLabel)
327            {
328                QLabel* label = new QLabel(text);
329                label->setWordWrap(true);
330                label->setTextInteractionFlags(Qt::TextEditorInteraction);
331
332                QPalette palette = label->palette();
333                palette.setColor(QPalette::Highlight, Qt::darkBlue);
334                palette.setColor(QPalette::HighlightedText, Qt::white);
335                label->setPalette(palette);
336
337                QScrollArea* scrollArea = new QScrollArea;
338                scrollArea->setWidget(label);
339
340                widget->layout()->addWidget(scrollArea);
341            }
342            else
343            {
344                QTextEdit* textEdit = new QTextEdit(text);
345                textEdit->setReadOnly(false);
346                textEdit->setTextInteractionFlags(Qt::TextEditable);
347
348                QPalette palette = textEdit->palette();
349                palette.setColor(QPalette::Highlight, Qt::darkBlue);
350                palette.setColor(QPalette::HighlightedText, Qt::white);
351                textEdit->setPalette(palette);
352
353                widget->layout()->addWidget(textEdit);
354            }
355
356            QPushButton* button = new MyPushButton("Button");
357            widget->layout()->addWidget(button);
358
359            widget->setGeometry(0, 0, 800, 600);
360        }
361
362        QGraphicsScene* graphicsScene = 0;
363
364        if (!sanityCheck)
365        {
366            osg::ref_ptr<osgQt::QWidgetImage> widgetImage = new osgQt::QWidgetImage(widget);
367#if (QT_VERSION >= QT_VERSION_CHECK(4, 5, 0))
368            widgetImage->getQWidget()->setAttribute(Qt::WA_TranslucentBackground);
369#endif
370            widgetImage->getQGraphicsViewAdapter()->setBackgroundColor(QColor(0, 0, 0, 0));
371            //widgetImage->getQGraphicsViewAdapter()->resize(800, 600);
372            graphicsScene = widgetImage->getQGraphicsViewAdapter()->getQGraphicsScene();
373
374            osg::Camera* camera = 0;        // Will stay NULL in the inScene case.
375            osg::Geometry* quad = osg::createTexturedQuadGeometry(osg::Vec3(0,0,0), osg::Vec3(1,0,0), osg::Vec3(0,1,0), 1, 1);
376            osg::Geode* geode = new osg::Geode;
377            geode->addDrawable(quad);
378
379            osg::MatrixTransform* mt = new osg::MatrixTransform;
380
381            osg::Texture2D* texture = new osg::Texture2D(widgetImage.get());
382            texture->setResizeNonPowerOfTwoHint(false);
383            texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
384            texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
385            texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
386            mt->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
387
388            osgViewer::InteractiveImageHandler* handler;
389            if (inScene)
390            {
391                mt->setMatrix(osg::Matrix::rotate(osg::Vec3(0,1,0), osg::Vec3(0,0,1)));
392                mt->addChild(geode);
393
394                handler = new osgViewer::InteractiveImageHandler(widgetImage.get());
395            }
396            else    // fullscreen
397            {
398                // The HUD camera's viewport needs to follow the size of the
399                // window. MyInteractiveImageHandler will make sure of this.
400                // As for the quad and the camera's projection, setting the
401                // projection resize policy to FIXED takes care of them, so
402                // they can stay the same: (0,1,0,1) with a quad that fits.
403
404                // Set the HUD camera's projection and viewport to match the screen.
405                camera = new osg::Camera;
406                camera->setProjectionResizePolicy(osg::Camera::FIXED);
407                camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
408                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
409                camera->setViewMatrix(osg::Matrix::identity());
410                camera->setClearMask(GL_DEPTH_BUFFER_BIT);
411                camera->setRenderOrder(osg::Camera::POST_RENDER);
412                camera->addChild(geode);
413                camera->setViewport(0, 0, 1024, 768);
414
415                mt->addChild(camera);
416
417                handler = new osgViewer::InteractiveImageHandler(widgetImage.get(), texture, camera);
418            }
419
420            mt->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
421            mt->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
422            mt->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
423            mt->getOrCreateStateSet()->setAttribute(new osg::Program);
424
425            osg::Group* overlay = new osg::Group;
426            overlay->addChild(mt);
427
428            root->addChild(overlay);
429           
430            quad->setEventCallback(handler);
431            quad->setCullCallback(handler);
432        }
433        else
434        {
435            // Sanity check, do the same thing as QWidgetImage and
436            // QGraphicsViewAdapter but in a separate Qt window.
437
438            graphicsScene = new QGraphicsScene;
439            graphicsScene->addWidget(widget);
440
441            QGraphicsView* graphicsView = new QGraphicsView;
442            graphicsView->setScene(graphicsScene);
443
444            QMainWindow* mainWindow = new QMainWindow;
445            mainWindow->setCentralWidget(graphicsView);
446            mainWindow->setGeometry(50, 50, 1024, 768);
447            mainWindow->show();
448            mainWindow->raise();
449        }
450
451        // Add numFloatingWindows windows to the graphicsScene.
452        for (unsigned int i = 0; i < (unsigned int)numFloatingWindows; ++i)
453        {
454            QWidget* window = new QWidget(0, Qt::Window);
455            window->setWindowTitle(QString("Window %1").arg(i));
456            window->setLayout(new QVBoxLayout);
457            window->layout()->addWidget(new QLabel(QString("This window %1").arg(i)));
458            window->layout()->addWidget(new MyPushButton(QString("Button in window %1").arg(i)));
459            window->setGeometry(100, 100, 300, 300);
460
461            QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, Qt::Window);
462            proxy->setWidget(window);
463            proxy->setFlag(QGraphicsItem::ItemIsMovable, true);
464
465            graphicsScene->addItem(proxy);
466        }
467
468    }
469
470    root->addChild(osgDB::readNodeFile("cow.osg.(15,0,5).trans.(0.1,0.1,0.1).scale"));
471
472    osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer(arguments);
473    viewer->setSceneData(root.get());
474    viewer->setCameraManipulator(new osgGA::TrackballManipulator());
475    viewer->addEventHandler(new osgGA::StateSetManipulator(root->getOrCreateStateSet()));
476    viewer->addEventHandler(new osgViewer::StatsHandler);
477    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
478
479    viewer->setUpViewInWindow(50, 50, 1024, 768);
480    viewer->getEventQueue()->windowResize(0, 0, 1024, 768);
481
482    if (useFrameLoopThread)
483    {
484        // create a thread to run the viewer's frame loop
485        ViewerFrameThread viewerThread(viewer.get(), true);
486        viewerThread.startThread();
487
488        // now start the standard Qt event loop, then exists when the viewerThead sends the QApplication::exit() signal.
489        return QApplication::exec();
490
491    }
492    else
493    {
494        // run the frame loop, interleaving Qt and the main OSG frame loop
495        while(!viewer->done())
496        {
497            // process Qt events - this handles both events and paints the browser image
498            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
499
500            viewer->frame();
501        }
502
503        return 0;
504    }
505}
Note: See TracBrowser for help on using the browser.