]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Create TimeManager subsystem, and collect the time related code out of main.cxx and...
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #include <iostream>
36
37 #include <osg/Camera>
38 #include <osg/GraphicsContext>
39 #include <osgDB/Registry>
40
41 // Class references
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/material/matlib.hxx>
44 #include <simgear/scene/model/animation.hxx>
45 #include <simgear/scene/sky/sky.hxx>
46 #include <simgear/structure/event_mgr.hxx>
47 #include <simgear/props/AtomicChangeListener.hxx>
48 #include <simgear/props/props.hxx>
49 #include <simgear/timing/sg_time.hxx>
50 #include <simgear/math/sg_random.h>
51
52 #include <Time/light.hxx>
53 #include <Include/general.hxx>
54 #include <Aircraft/replay.hxx>
55 #include <Cockpit/cockpit.hxx>
56 #include <Cockpit/hud.hxx>
57 #include <Model/panelnode.hxx>
58 #include <Model/modelmgr.hxx>
59 #include <Model/acmodel.hxx>
60 #include <Scenery/scenery.hxx>
61 #include <Scenery/tilemgr.hxx>
62 #include <Sound/fg_fx.hxx>
63 #include <Sound/beacon.hxx>
64 #include <Sound/morse.hxx>
65 #include <Sound/fg_fx.hxx>
66 #include <ATCDCL/ATCmgr.hxx>
67 #include <Time/TimeManager.hxx>
68 #include <Environment/environment_mgr.hxx>
69 #include <Environment/ephemeris.hxx>
70 #include <GUI/new_gui.hxx>
71 #include <MultiPlayer/multiplaymgr.hxx>
72
73 #include "CameraGroup.hxx"
74 #include "fg_commands.hxx"
75 #include "fg_io.hxx"
76 #include "renderer.hxx"
77 #include "splash.hxx"
78 #include "main.hxx"
79 #include "util.hxx"
80 #include "fg_init.hxx"
81 #include "fg_os.hxx"
82 #include "WindowSystemAdapter.hxx"
83 #include <Main/viewer.hxx>
84
85
86 using namespace flightgear;
87
88 using std::cerr;
89
90 // This is a record containing a bit of global housekeeping information
91 FGGeneral general;
92
93 // Specify our current idle function state.  This is used to run all
94 // our initializations out of the idle callback so that we can get a
95 // splash screen up and running right away.
96 int idle_state = 0;
97
98
99 void fgInitSoundManager();
100 void fgSetNewSoundDevice(const char *);
101
102 // The atexit() function handler should know when the graphical subsystem
103 // is initialized.
104 extern int _bootstrap_OSInit;
105
106 // What should we do when we have nothing else to do?  Let's get ready
107 // for the next move and update the display?
108 static void fgMainLoop( void ) {
109     
110     static SGConstPropertyNode_ptr longitude
111         = fgGetNode("/position/longitude-deg");
112     static SGConstPropertyNode_ptr latitude
113         = fgGetNode("/position/latitude-deg");
114     static SGConstPropertyNode_ptr altitude
115         = fgGetNode("/position/altitude-ft");
116     static SGConstPropertyNode_ptr vn_fps
117         = fgGetNode("/velocities/speed-north-fps");
118     static SGConstPropertyNode_ptr ve_fps
119         = fgGetNode("/velocities/speed-east-fps");
120     static SGConstPropertyNode_ptr vd_fps
121         = fgGetNode("/velocities/speed-down-fps");
122       
123     static SGPropertyNode_ptr frame_signal
124         = fgGetNode("/sim/signals/frame", true);
125
126     frame_signal->fireValueChanged();
127     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
128     
129     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
130     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
131     
132     
133   // update "time"
134     double sim_dt, real_dt;
135     TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
136     // compute simulated time (allowing for pause, warp, etc) and
137     // real elapsed time
138     timeMgr->computeTimeDeltas(sim_dt, real_dt);
139     
140     if (globals->get_warp_delta() != 0) {
141         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
142         l->update( 0.5 );
143     }
144
145     // update magvar model
146     globals->get_mag()->update( longitude->getDoubleValue()
147                                 * SGD_DEGREES_TO_RADIANS,
148                                 latitude->getDoubleValue()
149                                 * SGD_DEGREES_TO_RADIANS,
150                                 altitude->getDoubleValue() * SG_FEET_TO_METER,
151                                 globals->get_time_params()->getJD() );
152
153
154     // Update any multiplayer's network queues, the AIMultiplayer
155     // implementation is an AI model and depends on that
156     globals->get_multiplayer_mgr()->Update();
157
158 #if ENABLE_ATCDCL  
159     // Run ATC subsystem
160     if (fgGetBool("/sim/atc/enabled"))
161         globals->get_ATC_mgr()->update(sim_dt);
162 #endif  
163     
164     globals->get_subsystem_mgr()->update(sim_dt);
165     globals->get_aircraft_model()->update(sim_dt);
166     
167     //
168     // Tile Manager updates - see if we need to load any new scenery tiles.
169     //   this code ties together the fdm, viewer and scenery classes...
170     //   we may want to move this to its own class at some point
171     //
172     double visibility_meters = fgGetDouble("/environment/visibility-m");
173     globals->get_tile_mgr()->prep_ssg_nodes( visibility_meters );
174
175     // update tile manager for view...
176     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
177     SGGeod geodViewPos = SGGeod::fromCart(viewPos);
178     globals->get_tile_mgr()->update(geodViewPos, visibility_meters);
179
180     // run Nasal's settimer() loops right before the view manager
181     globals->get_event_mgr()->update(sim_dt);
182
183     // pick up model coordidnates that Nasal code may have set relative to the
184     // aircraft's
185     globals->get_model_mgr()->update(sim_dt);
186
187     // update the view angle as late as possible, but before sound calculations
188     globals->get_viewmgr()->update(real_dt);
189
190     // Update the sound manager last so it can use the CPU while the GPU
191     // is processing the scenery (doubled the frame-rate for me) -EMH-
192 #ifdef ENABLE_AUDIO_SUPPORT
193     static bool smgr_init = true;
194     static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
195     if (smgr_init == true) {
196         if (sound_working->getBoolValue() == true) {
197             fgInitSoundManager();
198             smgr_init = false;
199         }
200     } else {
201         static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
202         static SGSoundMgr *smgr = globals->get_soundmgr();
203         static bool smgr_enabled = true;
204
205         if (sound_working->getBoolValue() == false) {   // request to reinit
206            smgr->reinit();
207            smgr->resume();
208            sound_working->setBoolValue(true);
209         }
210
211         if (smgr_enabled != sound_enabled->getBoolValue()) {
212             if (smgr_enabled == true) { // request to suspend
213                 smgr->suspend();
214                 smgr_enabled = false;
215             } else {
216                 smgr->resume();
217                 smgr_enabled = true;
218             }
219         }
220
221         if (smgr_enabled == true) {
222             static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
223             smgr->set_volume(volume->getFloatValue());
224             smgr->update(sim_dt);
225         }
226     }
227 #endif
228
229     // END Tile Manager udpates
230     bool scenery_loaded = fgGetBool("sim/sceneryloaded");
231     if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
232         && fgGetBool("sim/fdm-initialized")) {
233         fgSetBool("sim/sceneryloaded",true);
234         if (fgGetBool("/sim/sound/working")) {
235             globals->get_soundmgr()->activate();
236         }
237         globals->get_props()->tie("/sim/sound/devices/name",
238               SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
239     }
240     simgear::AtomicChangeListener::fireChangeListeners();
241     fgRequestRedraw();
242
243     SG_LOG( SG_ALL, SG_DEBUG, "" );
244 }
245
246 void fgInitSoundManager()
247 {
248     SGSoundMgr *smgr = globals->get_soundmgr();
249
250     smgr->bind();
251     smgr->init(fgGetString("/sim/sound/device-name", NULL));
252
253     vector <const char*>devices = smgr->get_available_devices();
254     for (unsigned int i=0; i<devices.size(); i++) {
255         SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
256         p->setStringValue(devices[i]);
257     }
258     devices.clear();
259 }
260
261 void fgSetNewSoundDevice(const char *device)
262 {
263     globals->get_soundmgr()->suspend();
264     globals->get_soundmgr()->stop();
265     globals->get_soundmgr()->init(device);
266     globals->get_soundmgr()->resume();
267 }
268
269 // Operation for querying OpenGL parameters. This must be done in a
270 // valid OpenGL context, potentially in another thread.
271 namespace
272 {
273 struct GeneralInitOperation : public GraphicsContextOperation
274 {
275     GeneralInitOperation()
276         : GraphicsContextOperation(std::string("General init"))
277     {
278     }
279     void run(osg::GraphicsContext* gc)
280     {
281         general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
282         general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
283         general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
284         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVendor() );
285         SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
286         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVersion() );
287
288         GLint tmp;
289         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
290         general.set_glMaxTexSize( tmp );
291         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
292
293         glGetIntegerv( GL_DEPTH_BITS, &tmp );
294         general.set_glDepthBits( tmp );
295         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
296     }
297 };
298
299
300 osg::Node* load_panel(SGPropertyNode *n)
301 {
302     osg::Geode* geode = new osg::Geode;
303     geode->addDrawable(new FGPanelNode(n));
304     return geode;
305 }
306
307 SGPath resolve_path(const std::string& s)
308 {
309   return globals->resolve_maybe_aircraft_path(s);
310 }
311
312 }
313
314 // This is the top level master main function that is registered as
315 // our idle funciton
316
317 // The first few passes take care of initialization things (a couple
318 // per pass) and once everything has been initialized fgMainLoop from
319 // then on.
320
321 static void fgIdleFunction ( void ) {
322     static osg::ref_ptr<GeneralInitOperation> genOp;
323     if ( idle_state == 0 ) {
324         idle_state++;
325         // Pick some window on which to do queries.
326         // XXX Perhaps all this graphics initialization code should be
327         // moved to renderer.cxx?
328         genOp = new GeneralInitOperation;
329         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
330         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
331         osg::GraphicsContext* gc = 0;
332         if (guiCamera)
333             gc = guiCamera->getGraphicsContext();
334         if (gc) {
335             gc->add(genOp.get());
336         } else {
337             wsa->windows[0]->gc->add(genOp.get());
338         }
339         guiStartInit(gc);
340     } else if ( idle_state == 1 ) {
341         if (genOp.valid()) {
342             if (!genOp->isFinished())
343                 return;
344             genOp = 0;
345         }
346         if (!guiFinishInit())
347             return;
348         idle_state++;
349         fgSplashProgress("reading aircraft list");
350
351
352     } else if ( idle_state == 2 ) {
353         idle_state++;
354                 
355         fgSplashProgress("reading airport & navigation data");
356
357
358     } else if ( idle_state == 3 ) {
359         idle_state++;
360         fgInitNav();
361         fgSplashProgress("setting up scenery");
362
363
364     } else if ( idle_state == 4 ) {
365         idle_state++;
366         // based on the requested presets, calculate the true starting
367         // lon, lat
368         fgInitPosition();
369         fgInitTowerLocationListener();
370
371         TimeManager* t = new TimeManager;
372         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
373         t->init(); // need to init now, not during initSubsystems
374         
375         // Do some quick general initializations
376         if( !fgInitGeneral()) {
377             SG_LOG( SG_GENERAL, SG_ALERT,
378                 "General initialization failed ..." );
379             exit(-1);
380         }
381
382         ////////////////////////////////////////////////////////////////////
383         // Initialize the property-based built-in commands
384         ////////////////////////////////////////////////////////////////////
385         fgInitCommands();
386
387
388         ////////////////////////////////////////////////////////////////////
389         // Initialize the material manager
390         ////////////////////////////////////////////////////////////////////
391         globals->set_matlib( new SGMaterialLib );
392         simgear::SGModelLib::init(globals->get_fg_root());
393         simgear::SGModelLib::setPropRoot(globals->get_props());
394         simgear::SGModelLib::setResolveFunc(resolve_path);
395         simgear::SGModelLib::setPanelFunc(load_panel);
396         
397         ////////////////////////////////////////////////////////////////////
398         // Initialize the TG scenery subsystem.
399         ////////////////////////////////////////////////////////////////////
400         globals->set_scenery( new FGScenery );
401         globals->get_scenery()->init();
402         globals->get_scenery()->bind();
403         globals->set_tile_mgr( new FGTileMgr );
404
405
406         ////////////////////////////////////////////////////////////////////
407         // Initialize the general model subsystem.
408         ////////////////////////////////////////////////////////////////////
409         globals->set_model_mgr(new FGModelMgr);
410         globals->get_model_mgr()->init();
411         globals->get_model_mgr()->bind();
412         fgSplashProgress("loading aircraft");
413
414
415     } else if ( idle_state == 5 ) {
416         idle_state++;
417
418         ////////////////////////////////////////////////////////////////////
419         // Initialize the 3D aircraft model subsystem (has a dependency on
420         // the scenery subsystem.)
421         ////////////////////////////////////////////////////////////////////
422         FGAircraftModel* acm = new FGAircraftModel;
423         globals->set_aircraft_model(acm);
424         //globals->add_subsystem("aircraft-model", acm);
425         acm->init();
426         acm->bind();
427
428         ////////////////////////////////////////////////////////////////////
429         // Initialize the view manager subsystem.
430         ////////////////////////////////////////////////////////////////////
431         FGViewMgr *viewmgr = new FGViewMgr;
432         globals->set_viewmgr( viewmgr );
433         viewmgr->init();
434         viewmgr->bind();
435         fgSplashProgress("generating sky elements");
436
437
438     } else if ( idle_state == 6 ) {
439         idle_state++;
440         // Initialize the sky
441
442         Ephemeris* eph = new Ephemeris;
443         globals->add_subsystem("ephemeris", eph);
444         eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
445         eph->bind();
446
447         // TODO: move to environment mgr
448         thesky = new SGSky;
449         SGPath texture_path(globals->get_fg_root());
450         texture_path.append("Textures");
451         texture_path.append("Sky");
452         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
453             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
454             thesky->add_cloud_layer(layer);
455         }
456
457         SGPath sky_tex_path( globals->get_fg_root() );
458         sky_tex_path.append( "Textures" );
459         sky_tex_path.append( "Sky" );
460         thesky->texture_path( sky_tex_path.str() );
461
462         // The sun and moon diameters are scaled down numbers of the
463         // actual diameters. This was needed to fit both the sun and the
464         // moon within the distance to the far clip plane.
465         // Moon diameter:    3,476 kilometers
466         // Sun diameter: 1,390,000 kilometers
467         thesky->build( 80000.0, 80000.0,
468                        463.3, 361.8,
469                        *globals->get_ephem(),
470                        fgGetNode("/environment", true));
471
472         // Initialize MagVar model
473         SGMagVar *magvar = new SGMagVar();
474         globals->set_mag( magvar );
475
476
477                                     // kludge to initialize mag compass
478                                     // (should only be done for in-flight
479                                     // startup)
480         // update magvar model
481         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
482                                     * SGD_DEGREES_TO_RADIANS,
483                                     fgGetDouble("/position/latitude-deg")
484                                     * SGD_DEGREES_TO_RADIANS,
485                                     fgGetDouble("/position/altitude-ft")
486                                     * SG_FEET_TO_METER,
487                                     globals->get_time_params()->getJD() );
488         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
489         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
490         fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
491
492
493         // airport = new ssgBranch;
494         // airport->setName( "Airport Lighting" );
495         // lighting->addKid( airport );
496
497         // build our custom render states
498         fgSplashProgress("initializing subsystems");
499
500
501     } else if ( idle_state == 7 ) {
502         idle_state++;
503         // Initialize audio support
504 #ifdef ENABLE_AUDIO_SUPPORT
505
506         // Start the intro music
507         if ( fgGetBool("/sim/startup/intro-music") ) {
508             SGPath mp3file( globals->get_fg_root() );
509             mp3file.append( "Sounds/intro.mp3" );
510
511             SG_LOG( SG_GENERAL, SG_INFO,
512                 "Starting intro music: " << mp3file.str() );
513
514 # if defined( __CYGWIN__ )
515             string command = "start /m `cygpath -w " + mp3file.str() + "`";
516 # elif defined( _WIN32 )
517             string command = "start /m " + mp3file.str();
518 # else
519             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
520 # endif
521
522             system ( command.c_str() );
523         }
524 #endif
525         // This is the top level init routine which calls all the
526         // other subsystem initialization routines.  If you are adding
527         // a subsystem to flightgear, its initialization call should be
528         // located in this routine.
529         if( !fgInitSubsystems()) {
530             SG_LOG( SG_GENERAL, SG_ALERT,
531                 "Subsystem initialization failed ..." );
532             exit(-1);
533         }
534         fgSplashProgress("setting up time & renderer");
535
536
537     } else if ( idle_state == 8 ) {
538         idle_state = 1000;
539         
540         // setup OpenGL view parameters
541         globals->get_renderer()->init();
542
543         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
544                                          fgGetInt("/sim/startup/ysize") );
545
546         fgSplashProgress("loading scenery objects");
547         int session = fgGetInt("/sim/session",0);
548         session++;
549         fgSetInt("/sim/session",session);
550     }
551
552     if ( idle_state == 1000 ) {
553         // We've finished all our initialization steps, from now on we
554         // run the main loop.
555         fgSetBool("sim/sceneryloaded", false);
556         fgRegisterIdleHandler( fgMainLoop );
557     }
558 }
559
560
561 static void upper_case_property(const char *name)
562 {
563     using namespace simgear;
564     SGPropertyNode *p = fgGetNode(name, false);
565     if (!p) {
566         p = fgGetNode(name, true);
567         p->setStringValue("");
568     } else {
569         props::Type t = p->getType();
570         if (t == props::NONE || t == props::UNSPECIFIED)
571             p->setStringValue("");
572         else
573             assert(t == props::STRING);
574     }
575     p->addChangeListener(new FGMakeUpperCase);
576 }
577
578
579 // Main top level initialization
580 bool fgMainInit( int argc, char **argv ) {
581
582     // set default log levels
583     sglog().setLogLevels( SG_ALL, SG_ALERT );
584
585     string version;
586 #ifdef FLIGHTGEAR_VERSION
587     version = FLIGHTGEAR_VERSION;
588 #else
589     version = "unknown version";
590 #endif
591     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
592             << version );
593     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
594
595     // Allocate global data structures.  This needs to happen before
596     // we parse command line options
597
598     globals = new FGGlobals;
599
600     // seed the random number generator
601     sg_srandom_time();
602
603     FGControls *controls = new FGControls;
604     globals->set_controls( controls );
605
606     string_list *col = new string_list;
607     globals->set_channel_options_list( col );
608
609     fgValidatePath("", false);  // initialize static variables
610     upper_case_property("/sim/presets/airport-id");
611     upper_case_property("/sim/presets/runway");
612     upper_case_property("/sim/tower/airport-id");
613     upper_case_property("/autopilot/route-manager/input");
614
615     // Scan the config file(s) and command line options to see if
616     // fg_root was specified (ignore all other options for now)
617     fgInitFGRoot(argc, argv);
618
619     // Check for the correct base package version
620     static char required_version[] = "2.0.0";
621     string base_version = fgBasePackageVersion();
622     if ( !(base_version == required_version) ) {
623         // tell the operator how to use this application
624
625         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
626         cerr << endl << "Base package check failed ... " \
627              << "Found version " << base_version << " at: " \
628              << globals->get_fg_root() << endl;
629         cerr << "Please upgrade to version: " << required_version << endl;
630 #ifdef _MSC_VER
631         cerr << "Hit a key to continue..." << endl;
632         cin.get();
633 #endif
634         exit(-1);
635     }
636
637     // Load the configuration parameters.  (Command line options
638     // override config file options.  Config file options override
639     // defaults.)
640     if ( !fgInitConfig(argc, argv) ) {
641         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
642         exit(-1);
643     }
644
645     // Initialize the Window/Graphics environment.
646     fgOSInit(&argc, argv);
647     _bootstrap_OSInit++;
648
649     fgRegisterWindowResizeHandler( &FGRenderer::resize );
650     fgRegisterIdleHandler( &fgIdleFunction );
651     fgRegisterDrawHandler( &FGRenderer::update );
652
653     // Initialize plib net interface
654     netInit( &argc, argv );
655
656     // Clouds3D requires an alpha channel
657     fgOSOpenWindow(true /* request stencil buffer */);
658
659     // Initialize the splash screen right away
660     fntInit();
661     fgSplashInit();
662
663     // pass control off to the master event handler
664     fgOSMainLoop();
665
666     // we never actually get here ... but to avoid compiler warnings,
667     // etc.
668     return false;
669 }
670
671