root/OpenSceneGraph/trunk/applications/present3D/present3D.cpp @ 10519

Revision 10519, 24.6 kB (checked in by robert, 5 years ago)

Updated the Present3D version number

Line 
1/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield
2 *
3 * This software is open source and may be redistributed and/or modified under 
4 * the terms of the GNU General Public License (GPL) version 2.0.
5 * The full license is in LICENSE.txt file included with this distribution,.
6 *
7 * This software is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 * include LICENSE.txt for more details.
11*/
12
13#include <osg/Geometry>
14#include <osg/CameraNode>
15#include <osg/Texture2D>
16#include <osg/Notify>
17
18
19#include <osgDB/ReadFile>
20#include <osgDB/WriteFile>
21#include <osgDB/FileNameUtils>
22#include <osgUtil/Optimizer>
23#include <osgUtil/SceneView>
24
25#include <osgViewer/Viewer>
26#include <osgViewer/ViewerEventHandlers>
27
28#include <OpenThreads/Thread>
29
30#include <osgGA/TrackballManipulator>
31#include <osgGA/FlightManipulator>
32#include <osgGA/DriveManipulator>
33#include <osgGA/KeySwitchMatrixManipulator>
34#include <osgGA/AnimationPathManipulator>
35#include <osgGA/TerrainManipulator>
36#include <osgGA/AnimationPathManipulator>
37#include <osgGA/StateSetManipulator>
38
39#include <osgPresentation/SlideEventHandler>
40#include <osgPresentation/SlideShowConstructor>
41
42#include "ReadShowFile.h"
43#include "PointsEventHandler.h"
44#include "Cluster.h"
45#include "ExportHTML.h"
46
47
48#include <sstream>
49#include <fstream>
50#include <iostream>
51
52#include <string.h>
53
54#ifdef USE_SDL
55    #include "SDLIntegration.h"
56#endif
57
58#if OSG_LIBRARY_STATIC
59
60    // include the plugins we need
61    USE_OSGPLUGIN(ive)
62    USE_OSGPLUGIN(osg)
63    USE_OSGPLUGIN(p3d)
64    USE_OSGPLUGIN(paths)
65
66    USE_OSGPLUGIN(freetype)
67    USE_OSGPLUGIN(rgb)
68    USE_OSGPLUGIN(png)
69    USE_OSGPLUGIN(jpeg)
70
71    USE_OSGPLUGIN(ffmpeg)
72    USE_OSGPLUGIN(pdf)
73
74    USE_OSGPLUGIN(OpenFlight)
75    USE_OSGPLUGIN(obj)
76
77    USE_OSGPLUGIN(curl)
78
79
80    // include the platform specific GraphicsWindow implementation.
81    USE_GRAPHICSWINDOW()
82
83#endif
84
85static const char* s_version = "1.4 beta";
86
87void setViewer(osgViewer::Viewer& viewer, float width, float height, float distance)
88{
89    double vfov = osg::RadiansToDegrees(atan2(height/2.0f,distance)*2.0);
90    // double hfov = osg::RadiansToDegrees(atan2(width/2.0f,distance)*2.0);
91
92    viewer.getCamera()->setProjectionMatrixAsPerspective( vfov, width/height, 0.1, 1000.0);
93}
94
95class FollowMouseCallback: public osgGA::GUIEventHandler
96{
97    public:
98   
99        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&, osg::Object* object, osg::NodeVisitor*)
100        {
101            switch(ea.getEventType())
102            {
103                case(osgGA::GUIEventAdapter::MOVE):
104                case(osgGA::GUIEventAdapter::DRAG):
105                {
106                    osg::CameraNode* camera = dynamic_cast<osg::CameraNode*>(object);
107                    if (camera)
108                    {
109                        camera->setViewMatrix(osg::Matrixd::translate(ea.getX(),ea.getY(),0.0));
110                    }
111                    break;
112                }
113                case(osgGA::GUIEventAdapter::KEYDOWN):
114                {
115                    if (ea.getKey()=='c')
116                    {
117                        osg::CameraNode* camera = dynamic_cast<osg::CameraNode*>(object);
118                        if (camera)
119                        {
120                            for(unsigned int i=0; i< camera->getNumChildren(); ++i)
121                            {
122                                osg::Node* node = camera->getChild(i);
123                                node->setNodeMask(
124                                    node->getNodeMask()!=0 ?
125                                    0 :
126                                    0xffffff);
127                               
128                            }
129                        }
130                    }
131                    break;
132                }
133                default:
134                    break;
135            }
136            return false;
137        }
138               
139        virtual void accept(osgGA::GUIEventHandlerVisitor& v)
140        {
141            v.visit(*this);
142        }
143
144};
145 
146osg::Node* createCursorSubgraph(const std::string& filename, float size)
147{
148    osg::Geode* geode = new osg::Geode;
149
150    osg::Geometry* geom = osg::createTexturedQuadGeometry(osg::Vec3(-size*0.5f,-size*0.5f,0.0f),osg::Vec3(size,0.0f,0.0f),osg::Vec3(0.0f,size,0.0f));
151
152    osg::Image* image = osgDB::readImageFile(osgDB::findDataFile(filename));
153    if (image)
154    {
155        osg::StateSet* stateset = geom->getOrCreateStateSet();
156        stateset->setTextureAttributeAndModes(0, new osg::Texture2D(image),osg::StateAttribute::ON);
157        stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
158        stateset->setRenderBinDetails(1000, "DepthSortedBin");
159    }
160   
161    geode->addDrawable(geom);
162   
163    osg::CameraNode* camera = new osg::CameraNode;
164
165    // set the projection matrix
166    camera->setProjectionMatrix(osg::Matrix::ortho2D(-1,1,-1,1));
167
168    // set the view matrix   
169    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
170    camera->setViewMatrix(osg::Matrix::identity());
171
172    // only clear the depth buffer
173    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
174
175    // draw subgraph after main camera view.
176    camera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
177
178    camera->addChild(geode);
179   
180    camera->setEventCallback(new FollowMouseCallback());
181   
182    return camera;
183
184}
185
186
187enum P3DApplicationType
188{
189    VIEWER,
190    MASTER,
191    SLAVE
192};
193
194
195
196int main( int argc, char **argv )
197{
198    // use an ArgumentParser object to manage the program arguments.
199    osg::ArgumentParser arguments(&argc,argv);
200   
201    // set up the usage document, in case we need to print out how to use this program.
202    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
203    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the application for presenting 3D interactive slide shows.");
204    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
205    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
206    arguments.getApplicationUsage()->addCommandLineOption("-a","Turn auto stepping on by default");
207    arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time duration in seconds between layers/slides");
208    arguments.getApplicationUsage()->addCommandLineOption("-s <float> <float> <float>","width, height, distance and of the screen away from the viewer");
209    arguments.getApplicationUsage()->addCommandLineOption("--viewer","Start Present3D as the viewer version.");
210    arguments.getApplicationUsage()->addCommandLineOption("--authoring","Start Presen3D as the authoring version, license required.");
211    arguments.getApplicationUsage()->addCommandLineOption("--master","Start Present3D as the master version, license required.");
212    arguments.getApplicationUsage()->addCommandLineOption("--slave","Start Present3D as the slave version, license required.");
213    arguments.getApplicationUsage()->addCommandLineOption("--publishing","Start Present3D as the publishing version, license required.");
214    arguments.getApplicationUsage()->addCommandLineOption("--timeDelayOnNewSlideWithMovies","Set the time delay on new slide with movies, done to allow movie threads to get in sync with rendering thread.");
215    arguments.getApplicationUsage()->addCommandLineOption("--targetFrameRate","Set the target frame rate, defaults to 80Hz.");
216    arguments.getApplicationUsage()->addCommandLineOption("--version","Report the Present3D version.");
217    arguments.getApplicationUsage()->addCommandLineOption("--print <filename>","Print out slides to a series of image files.");
218    arguments.getApplicationUsage()->addCommandLineOption("--html <filename>","Print out slides to a series of html & image files.");
219    arguments.getApplicationUsage()->addCommandLineOption("--loop","Switch on looping of presentation.");
220    arguments.getApplicationUsage()->addCommandLineOption("--devices","Print the Video input capability via QuickTime and exit.");
221
222    // add alias from xml to p3d to provide backwards compatibility for old p3d files.
223    osgDB::Registry::instance()->addFileExtensionAlias("xml","p3d");
224
225    // if user requests devices video capability.
226    if (arguments.read("-devices") || arguments.read("--devices"))
227    {
228        // Force load QuickTime plugin, probe video capability, exit
229        osgDB::readImageFile("devices.live");
230        return 1;
231    }
232
233
234    // read any env vars from presentations before we create viewer to make sure the viewer
235    // utilises these env vars
236    if (p3d::readEnvVars(arguments))
237    {
238        osg::DisplaySettings::instance()->readEnvironmentalVariables();
239    }
240
241
242#ifdef USE_SDL
243    SDLIntegration sdlIntegration;
244   
245    osg::notify(osg::INFO)<<"USE_SDL"<<std::endl;
246#endif   
247   
248    bool doSetViewer = true;
249    std::string configurationFile;
250
251    // check env vars for configuration file
252    const char* str = getenv("PRESENT3D_CONFIG_FILE");
253    if (!str) str = getenv("OSG_CONFIG_FILE");
254    if (str) configurationFile = str;
255
256    // check command line parameters for configuration file.
257    while (arguments.read("-c",configurationFile)) {}
258
259    osg::Vec4 clearColor(0.0f,0.0f,0.0f,0.0f);
260   
261    while (arguments.read("--clear-color",clearColor[0],clearColor[1],clearColor[2],clearColor[3])) {}
262
263    // construct the viewer.
264    osgViewer::Viewer viewer(arguments);
265   
266    // set clear colour to black by default.
267    viewer.getCamera()->setClearColor(clearColor);
268
269    if (!configurationFile.empty())
270    {
271        viewer.readConfiguration(configurationFile);
272        doSetViewer = false;
273    }
274   
275    // set up stereo masks
276    viewer.getCamera()->setCullMask(0xffffffff);
277    viewer.getCamera()->setCullMaskLeft(0x00000001);
278    viewer.getCamera()->setCullMaskRight(0x00000002);   
279
280    // set up the camera manipulators.
281    {
282        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
283
284        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
285        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
286        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
287        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
288
289        std::string pathfile;
290        char keyForAnimationPath = '5';
291        while (arguments.read("-p",pathfile))
292        {
293            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
294            if (apm || !apm->valid())
295            {
296                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
297                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
298                keyswitchManipulator->selectMatrixManipulator(num);
299                ++keyForAnimationPath;
300            }
301        }
302
303        viewer.setCameraManipulator( keyswitchManipulator.get() );
304    }
305
306    // add the state manipulator
307    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
308
309    // add the state manipulator
310    viewer.addEventHandler( new osgViewer::StatsHandler() );
311
312    viewer.addEventHandler( new osgViewer::WindowSizeHandler() );
313
314    // neeed to address.
315    // viewer.getScene()->getUpdateVisitor()->setTraversalMode(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN);
316
317
318    const char* p3dCursor = getenv("P3D_CURSOR");
319    std::string cursorFileName( p3dCursor ? p3dCursor : "");
320    while (arguments.read("--cursor",cursorFileName)) {}
321
322
323    while (arguments.read("--set-viewer")) { doSetViewer = true; }
324   
325    while (arguments.read("--no-set-viewer")) { doSetViewer = false; }
326   
327
328    // cluster related entries.
329    int socketNumber=8100;
330    while (arguments.read("-n",socketNumber)) {}
331
332    float camera_fov=-1.0f;
333    while (arguments.read("-f",camera_fov)) {}
334
335    float camera_offset=45.0f;
336    while (arguments.read("-o",camera_offset)) {}
337
338
339    std::string exportName;
340    while (arguments.read("--print",exportName)) {}
341
342    while (arguments.read("--html",exportName)) {}
343
344    // read any time delay argument.
345    float timeDelayBetweenSlides = 1.0f;
346    while (arguments.read("-d",timeDelayBetweenSlides)) {}
347
348    bool autoSteppingActive = false;
349    while (arguments.read("-a")) autoSteppingActive = true;
350
351    bool loopPresentation = false;
352    while (arguments.read("--loop")) loopPresentation = true;
353
354
355    // register the slide event handler - which moves the presentation from slide to slide, layer to layer.
356    osgPresentation::SlideEventHandler* seh = new osgPresentation::SlideEventHandler(&viewer);
357    viewer.addEventHandler(seh);
358
359    seh->setAutoSteppingActive(autoSteppingActive);
360    seh->setTimeDelayBetweenSlides(timeDelayBetweenSlides);
361    seh->setLoopPresentation(loopPresentation);
362
363    double targetFrameRate = 80.0;
364    while (arguments.read("--targetFrameRate",targetFrameRate)) {}
365
366
367    // set the time delay
368    float timeDelayOnNewSlideWithMovies = 0.4f;
369    while (arguments.read("--timeDelayOnNewSlideWithMovies",timeDelayOnNewSlideWithMovies)) {}
370    seh->setTimeDelayOnNewSlideWithMovies(timeDelayOnNewSlideWithMovies);
371
372    // set up optimizer options
373    unsigned int optimizer_options = osgUtil::Optimizer::DEFAULT_OPTIMIZATIONS;
374    bool relase_and_compile = false;
375    while (arguments.read("--release-and-compile"))
376    {
377        relase_and_compile = true;
378    }
379    seh->setReleaseAndCompileOnEachNewSlide(relase_and_compile);
380    if (relase_and_compile)
381    {
382        // make sure that imagery stays around after being applied to textures.
383        viewer.getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
384        // optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
385        // viewer.setRealizeSceneViewOptions(viewer.getRealizeSceneViewOptions() & ~osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
386    }
387//
388//     osgDB::Registry::instance()->getOrCreateDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
389//     optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
390//     osg::Texture::getTextureObjectManager()->setExpiryDelay(0.0f);
391//     osgDB::Registry::instance()->getOrCreateDatabasePager()->setExpiryDelay(1.0f);
392
393    // register the handler for modifying the point size
394    PointsEventHandler* peh = new PointsEventHandler;
395    viewer.addEventHandler(peh);
396   
397    // osg::DisplaySettings::instance()->setSplitStereoAutoAjustAspectRatio(false);
398
399    float width = osg::DisplaySettings::instance()->getScreenWidth();
400    float height = osg::DisplaySettings::instance()->getScreenHeight();
401    float distance = osg::DisplaySettings::instance()->getScreenDistance();
402    bool sizesSpecified = false;
403    while (arguments.read("-s", width, height, distance))
404    {
405        sizesSpecified = true;
406       
407        osg::DisplaySettings::instance()->setScreenDistance(distance);
408        osg::DisplaySettings::instance()->setScreenHeight(height);
409        osg::DisplaySettings::instance()->setScreenWidth(width);
410    }
411
412    // get details on keyboard and mouse bindings used by the viewer.
413    viewer.getUsage(*arguments.getApplicationUsage());
414
415    // if user request help write it out to cout.
416    if (arguments.read("-h") || arguments.read("--help"))
417    {
418        arguments.getApplicationUsage()->write(osg::notify(osg::NOTICE));
419        return 1;
420    }
421
422    P3DApplicationType P3DApplicationType = VIEWER;
423
424    str = getenv("PRESENT3D_TYPE");
425    if (str)
426    {
427        if (strcmp(str,"viewer")==0) P3DApplicationType = VIEWER;
428        else if (strcmp(str,"master")==0) P3DApplicationType = MASTER;
429        else if (strcmp(str,"slave")==0) P3DApplicationType = SLAVE;
430    }
431       
432    while (arguments.read("--viewer")) { P3DApplicationType = VIEWER; }
433    while (arguments.read("--master")) { P3DApplicationType = MASTER; }
434    while (arguments.read("--slave")) { P3DApplicationType = SLAVE; }
435   
436    while (arguments.read("--version"))
437    {
438        std::string appTypeName = "invalid";
439        switch(P3DApplicationType)
440        {
441            case(VIEWER): appTypeName = "viewer"; break;
442            case(MASTER): appTypeName = "master"; break;
443            case(SLAVE): appTypeName = "slave"; break;
444        }
445
446        osg::notify(osg::NOTICE)<<std::endl;
447        osg::notify(osg::NOTICE)<<"Present3D "<<appTypeName<<" version : "<<s_version<<std::endl;
448        osg::notify(osg::NOTICE)<<std::endl;
449
450        return 0;
451    }
452
453    // any option left unread are converted into errors to write out later.
454    //arguments.reportRemainingOptionsAsUnrecognized();
455
456    // report any errors if they have occured when parsing the program aguments.
457    if (arguments.errors())
458    {
459        arguments.writeErrorMessages(osg::notify(osg::INFO));
460        return 1;
461    }
462
463
464    // read files name from arguments.
465    p3d::FileNameList xmlFiles, normalFiles;
466    if (!p3d::getFileNames(arguments, xmlFiles, normalFiles))
467    {
468        osg::notify(osg::NOTICE)<<std::endl;
469        osg::notify(osg::NOTICE)<<"No file specified, please specify and file to load."<<std::endl;
470        osg::notify(osg::NOTICE)<<std::endl;
471        return 1;
472    }
473
474
475
476    bool viewerInitialized = false;
477    if (!xmlFiles.empty())
478    {
479        osg::ref_ptr<osg::Node> holdingModel = p3d::readHoldingSlide(xmlFiles.front());
480
481        if (holdingModel.valid())
482        {
483            viewer.setSceneData(holdingModel.get());
484
485            seh->selectSlide(0);
486
487            if (!viewerInitialized)
488            {
489                // pass the global stateset to the point event handler so that it can
490                // alter the point size of all points in the scene.
491                peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());
492
493                // create the windows and run the threads.
494                viewer.realize();
495
496                if (doSetViewer) setViewer(viewer, width, height, distance);
497
498                viewerInitialized = true;
499            }
500
501            seh->home();
502
503            // render a frame
504            viewer.frame();
505        }
506    }
507
508    osg::Timer timer;
509    osg::Timer_t start_tick = timer.tick();
510
511
512    osg::ref_ptr<osgDB::ReaderWriter::Options> cacheAllOption = new osgDB::ReaderWriter::Options;
513    cacheAllOption->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL);
514   
515    osgDB::Registry::instance()->setOptions(cacheAllOption.get());
516
517    // read the scene from the list of file specified commandline args.
518    osg::ref_ptr<osg::Node> loadedModel = p3d::readShowFiles(arguments,cacheAllOption.get()); // osgDB::readNodeFiles(arguments, cacheAllOption.get());
519
520
521    osgDB::Registry::instance()->setOptions( 0 );
522
523
524    // if no model has been successfully loaded report failure.
525    if (!loadedModel)
526    {
527        osg::notify(osg::INFO) << arguments.getApplicationName() <<": No data loaded" << std::endl;
528        return 1;
529    }
530
531    osg::Timer_t end_tick = timer.tick();
532
533    osg::notify(osg::INFO) << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
534
535
536    if (loadedModel->getNumDescriptions()>0)
537    {
538        for(unsigned int i=0; i<loadedModel->getNumDescriptions(); ++i)
539        {
540            const std::string& desc = loadedModel->getDescription(i);
541            if (desc=="loop")
542            {
543                osg::notify(osg::NOTICE)<<"Enabling looping"<<std::endl;
544                seh->setLoopPresentation(true);
545            }
546            else if (desc=="auto")
547            {
548                osg::notify(osg::NOTICE)<<"Enabling auto run"<<std::endl;
549                seh->setAutoSteppingActive(true);
550            }
551        }
552    }
553
554
555#if 1
556    // add back in enabling of the GL_ALPHA_TEST to get around the core OSG no longer setting it by default for opaque bins.
557    // the alpha test is required for the volume rendering alpha clipping to work.
558    loadedModel->getOrCreateStateSet()->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
559#endif
560
561
562    // optimize the scene graph, remove rendundent nodes and state etc.
563    osgUtil::Optimizer optimizer;
564    optimizer.optimize(loadedModel.get(), optimizer_options);
565
566    if (!cursorFileName.empty())
567    {
568        osg::ref_ptr<osg::Group> group = new osg::Group;
569        group->addChild(loadedModel.get());
570        group->addChild(createCursorSubgraph(cursorFileName, 0.05f));
571       
572        loadedModel = group.get();
573    }
574
575    // set the scene to render
576    viewer.setSceneData(loadedModel.get());
577
578    if (!viewerInitialized)
579    {
580        // pass the global stateset to the point event handler so that it can
581        // alter the point size of all points in the scene.
582        peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());
583
584        // create the windows and run the threads.
585        viewer.realize();
586
587        if (doSetViewer) setViewer(viewer, width, height, distance);
588
589        viewerInitialized = true;
590    }
591   
592    if (!cursorFileName.empty())
593    {
594        // switch off the cursor
595        osgViewer::Viewer::Windows windows;
596        viewer.getWindows(windows);
597        for(osgViewer::Viewer::Windows::iterator itr = windows.begin();
598            itr != windows.end();
599            ++itr)
600        {
601            (*itr)->useCursor(false);
602        }
603    }
604
605    // pass the model to the slide event handler so it knows which to manipulate.
606    seh->set(loadedModel.get());
607    seh->selectSlide(0);
608
609    seh->home();
610   
611    // osgDB::writeNodeFile(*loadedModel,"saved.osg");
612   
613    osg::Timer_t startOfFrameTick = osg::Timer::instance()->tick();
614    double targetFrameTime = 1.0/targetFrameRate;
615   
616    if (exportName.empty())
617    {
618        // objects for managing the broadcasting and recieving of camera packets.
619        CameraPacket cp;
620        Broadcaster  bc;
621        Receiver     rc;
622        bc.setPort(static_cast<short int>(socketNumber));
623        rc.setPort(static_cast<short int>(socketNumber));
624
625        bool masterKilled = false;
626        DataConverter scratchPad(1024);
627
628        while( !viewer.done() && !masterKilled)
629        {
630            // wait for all cull and draw threads to complete.
631            viewer.advance();
632
633            osg::Timer_t currentTick = osg::Timer::instance()->tick();
634            double deltaTime = osg::Timer::instance()->delta_s(startOfFrameTick, currentTick);
635
636
637            if (deltaTime<targetFrameTime)
638            {
639                OpenThreads::Thread::microSleep(static_cast<unsigned int>((targetFrameTime-deltaTime)*1000000.0));
640            }
641
642            startOfFrameTick =  osg::Timer::instance()->tick();
643
644#if 0           
645            if (kmcb)
646            {
647                double time = kmcb->getTime();
648                viewer.getFrameStamp()->setReferenceTime(time);
649            }
650#endif
651
652#ifdef USE_SDL
653            sdlIntegration.update(viewer);
654#endif
655
656            if (P3DApplicationType==MASTER)
657            {
658                // take camera zero as the guide.
659                osg::Matrix modelview(viewer.getCamera()->getViewMatrix());
660               
661                cp.setPacket(modelview,viewer.getFrameStamp());
662               
663                // cp.readEventQueue(viewer);
664
665                scratchPad.reset();
666                scratchPad.write(cp);
667
668                scratchPad.reset();
669                scratchPad.read(cp);
670
671                bc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);
672               
673                std::cout << "bc.sync()"<<scratchPad._numBytes<<std::endl;
674
675                bc.sync();
676            }
677            else if (P3DApplicationType==SLAVE)
678            {
679                rc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);
680
681                rc.sync();
682               
683                scratchPad.reset();
684                scratchPad.read(cp);
685   
686                // cp.writeEventQueue(viewer);
687
688                if (cp.getMasterKilled())
689                {
690                    std::cout << "Received master killed."<<std::endl;
691                    // break out of while (!done) loop since we've now want to shut down.
692                    masterKilled = true;
693                }
694            }
695
696            // update the scene by traversing it with the the update visitor which will
697            // call all node update callbacks and animations.
698            viewer.eventTraversal();
699
700            // update the scene by traversing it with the the update visitor which will
701            // call all node update callbacks and animations.
702            viewer.updateTraversal();
703
704            if (P3DApplicationType==SLAVE)
705            {
706                osg::Matrix modelview;
707                cp.getModelView(modelview,camera_offset);
708
709                viewer.getCamera()->setViewMatrix(modelview);
710            }
711
712            // fire off the cull and draw traversals of the scene.
713            if(!masterKilled)
714                viewer.renderingTraversals();
715        }
716    }
717    else
718    {
719        ExportHTML::write(seh, viewer, exportName);
720    }
721           
722    return 0;
723}
Note: See TracBrowser for help on using the browser.