]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Merge branch 'next' of git://gitorious.org/fg/flightgear into next
[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
242     SG_LOG( SG_ALL, SG_DEBUG, "" );
243 }
244
245 void fgInitSoundManager()
246 {
247     SGSoundMgr *smgr = globals->get_soundmgr();
248
249     smgr->bind();
250     smgr->init(fgGetString("/sim/sound/device-name", NULL));
251
252     vector <const char*>devices = smgr->get_available_devices();
253     for (unsigned int i=0; i<devices.size(); i++) {
254         SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
255         p->setStringValue(devices[i]);
256     }
257     devices.clear();
258 }
259
260 void fgSetNewSoundDevice(const char *device)
261 {
262     globals->get_soundmgr()->suspend();
263     globals->get_soundmgr()->stop();
264     globals->get_soundmgr()->init(device);
265     globals->get_soundmgr()->resume();
266 }
267
268 // Operation for querying OpenGL parameters. This must be done in a
269 // valid OpenGL context, potentially in another thread.
270 namespace
271 {
272 struct GeneralInitOperation : public GraphicsContextOperation
273 {
274     GeneralInitOperation()
275         : GraphicsContextOperation(std::string("General init"))
276     {
277     }
278     void run(osg::GraphicsContext* gc)
279     {
280         general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
281         general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
282         general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
283         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVendor() );
284         SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
285         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVersion() );
286
287         GLint tmp;
288         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
289         general.set_glMaxTexSize( tmp );
290         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
291
292         glGetIntegerv( GL_DEPTH_BITS, &tmp );
293         general.set_glDepthBits( tmp );
294         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
295     }
296 };
297
298
299 osg::Node* load_panel(SGPropertyNode *n)
300 {
301     osg::Geode* geode = new osg::Geode;
302     geode->addDrawable(new FGPanelNode(n));
303     return geode;
304 }
305
306 SGPath resolve_path(const std::string& s)
307 {
308   return globals->resolve_maybe_aircraft_path(s);
309 }
310
311 }
312
313 // This is the top level master main function that is registered as
314 // our idle funciton
315
316 // The first few passes take care of initialization things (a couple
317 // per pass) and once everything has been initialized fgMainLoop from
318 // then on.
319
320 static void fgIdleFunction ( void ) {
321     static osg::ref_ptr<GeneralInitOperation> genOp;
322     if ( idle_state == 0 ) {
323         idle_state++;
324         // Pick some window on which to do queries.
325         // XXX Perhaps all this graphics initialization code should be
326         // moved to renderer.cxx?
327         genOp = new GeneralInitOperation;
328         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
329         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
330         osg::GraphicsContext* gc = 0;
331         if (guiCamera)
332             gc = guiCamera->getGraphicsContext();
333         if (gc) {
334             gc->add(genOp.get());
335         } else {
336             wsa->windows[0]->gc->add(genOp.get());
337         }
338         guiStartInit(gc);
339     } else if ( idle_state == 1 ) {
340         if (genOp.valid()) {
341             if (!genOp->isFinished())
342                 return;
343             genOp = 0;
344         }
345         if (!guiFinishInit())
346             return;
347         idle_state++;
348         fgSplashProgress("reading aircraft list");
349
350
351     } else if ( idle_state == 2 ) {
352         idle_state++;
353                 
354         fgSplashProgress("reading airport & navigation data");
355
356
357     } else if ( idle_state == 3 ) {
358         idle_state++;
359         fgInitNav();
360         fgSplashProgress("setting up scenery");
361
362
363     } else if ( idle_state == 4 ) {
364         idle_state++;
365         // based on the requested presets, calculate the true starting
366         // lon, lat
367         fgInitPosition();
368         fgInitTowerLocationListener();
369
370         TimeManager* t = new TimeManager;
371         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
372         t->init(); // need to init now, not during initSubsystems
373         
374         // Do some quick general initializations
375         if( !fgInitGeneral()) {
376             SG_LOG( SG_GENERAL, SG_ALERT,
377                 "General initialization failed ..." );
378             exit(-1);
379         }
380
381         ////////////////////////////////////////////////////////////////////
382         // Initialize the property-based built-in commands
383         ////////////////////////////////////////////////////////////////////
384         fgInitCommands();
385
386
387         ////////////////////////////////////////////////////////////////////
388         // Initialize the material manager
389         ////////////////////////////////////////////////////////////////////
390         globals->set_matlib( new SGMaterialLib );
391         simgear::SGModelLib::init(globals->get_fg_root());
392         simgear::SGModelLib::setPropRoot(globals->get_props());
393         simgear::SGModelLib::setPanelFunc(load_panel);
394         
395         ////////////////////////////////////////////////////////////////////
396         // Initialize the TG scenery subsystem.
397         ////////////////////////////////////////////////////////////////////
398         globals->set_scenery( new FGScenery );
399         globals->get_scenery()->init();
400         globals->get_scenery()->bind();
401         globals->set_tile_mgr( new FGTileMgr );
402
403
404         ////////////////////////////////////////////////////////////////////
405         // Initialize the general model subsystem.
406         ////////////////////////////////////////////////////////////////////
407         globals->set_model_mgr(new FGModelMgr);
408         globals->get_model_mgr()->init();
409         globals->get_model_mgr()->bind();
410         fgSplashProgress("loading aircraft");
411
412
413     } else if ( idle_state == 5 ) {
414         idle_state++;
415
416         ////////////////////////////////////////////////////////////////////
417         // Initialize the 3D aircraft model subsystem (has a dependency on
418         // the scenery subsystem.)
419         ////////////////////////////////////////////////////////////////////
420         FGAircraftModel* acm = new FGAircraftModel;
421         globals->set_aircraft_model(acm);
422         //globals->add_subsystem("aircraft-model", acm);
423         acm->init();
424         acm->bind();
425
426         ////////////////////////////////////////////////////////////////////
427         // Initialize the view manager subsystem.
428         ////////////////////////////////////////////////////////////////////
429         FGViewMgr *viewmgr = new FGViewMgr;
430         globals->set_viewmgr( viewmgr );
431         viewmgr->init();
432         viewmgr->bind();
433         fgSplashProgress("generating sky elements");
434
435
436     } else if ( idle_state == 6 ) {
437         idle_state++;
438         // Initialize the sky
439
440         Ephemeris* eph = new Ephemeris;
441         globals->add_subsystem("ephemeris", eph);
442         eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
443         eph->bind();
444
445         // TODO: move to environment mgr
446         thesky = new SGSky;
447         SGPath texture_path(globals->get_fg_root());
448         texture_path.append("Textures");
449         texture_path.append("Sky");
450         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
451             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
452             thesky->add_cloud_layer(layer);
453         }
454
455         SGPath sky_tex_path( globals->get_fg_root() );
456         sky_tex_path.append( "Textures" );
457         sky_tex_path.append( "Sky" );
458         thesky->texture_path( sky_tex_path.str() );
459
460         // The sun and moon diameters are scaled down numbers of the
461         // actual diameters. This was needed to fit both the sun and the
462         // moon within the distance to the far clip plane.
463         // Moon diameter:    3,476 kilometers
464         // Sun diameter: 1,390,000 kilometers
465         thesky->build( 80000.0, 80000.0,
466                        463.3, 361.8,
467                        *globals->get_ephem(),
468                        fgGetNode("/environment", true));
469
470         // Initialize MagVar model
471         SGMagVar *magvar = new SGMagVar();
472         globals->set_mag( magvar );
473
474
475                                     // kludge to initialize mag compass
476                                     // (should only be done for in-flight
477                                     // startup)
478         // update magvar model
479         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
480                                     * SGD_DEGREES_TO_RADIANS,
481                                     fgGetDouble("/position/latitude-deg")
482                                     * SGD_DEGREES_TO_RADIANS,
483                                     fgGetDouble("/position/altitude-ft")
484                                     * SG_FEET_TO_METER,
485                                     globals->get_time_params()->getJD() );
486         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
487         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
488         fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
489
490
491         // airport = new ssgBranch;
492         // airport->setName( "Airport Lighting" );
493         // lighting->addKid( airport );
494
495         // build our custom render states
496         fgSplashProgress("initializing subsystems");
497
498
499     } else if ( idle_state == 7 ) {
500         idle_state++;
501         // Initialize audio support
502 #ifdef ENABLE_AUDIO_SUPPORT
503
504         // Start the intro music
505         if ( fgGetBool("/sim/startup/intro-music") ) {
506             SGPath mp3file( globals->get_fg_root() );
507             mp3file.append( "Sounds/intro.mp3" );
508
509             SG_LOG( SG_GENERAL, SG_INFO,
510                 "Starting intro music: " << mp3file.str() );
511
512 # if defined( __CYGWIN__ )
513             string command = "start /m `cygpath -w " + mp3file.str() + "`";
514 # elif defined( _WIN32 )
515             string command = "start /m " + mp3file.str();
516 # else
517             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
518 # endif
519
520             system ( command.c_str() );
521         }
522 #endif
523         // This is the top level init routine which calls all the
524         // other subsystem initialization routines.  If you are adding
525         // a subsystem to flightgear, its initialization call should be
526         // located in this routine.
527         if( !fgInitSubsystems()) {
528             SG_LOG( SG_GENERAL, SG_ALERT,
529                 "Subsystem initialization failed ..." );
530             exit(-1);
531         }
532         fgSplashProgress("setting up time & renderer");
533
534
535     } else if ( idle_state == 8 ) {
536         idle_state = 1000;
537         
538         // setup OpenGL view parameters
539         globals->get_renderer()->init();
540
541         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
542                                          fgGetInt("/sim/startup/ysize") );
543
544         fgSplashProgress("loading scenery objects");
545         int session = fgGetInt("/sim/session",0);
546         session++;
547         fgSetInt("/sim/session",session);
548     }
549
550     if ( idle_state == 1000 ) {
551         // We've finished all our initialization steps, from now on we
552         // run the main loop.
553         fgSetBool("sim/sceneryloaded", false);
554         fgRegisterIdleHandler( fgMainLoop );
555     }
556 }
557
558
559 static void upper_case_property(const char *name)
560 {
561     using namespace simgear;
562     SGPropertyNode *p = fgGetNode(name, false);
563     if (!p) {
564         p = fgGetNode(name, true);
565         p->setStringValue("");
566     } else {
567         props::Type t = p->getType();
568         if (t == props::NONE || t == props::UNSPECIFIED)
569             p->setStringValue("");
570         else
571             assert(t == props::STRING);
572     }
573     p->addChangeListener(new FGMakeUpperCase);
574 }
575
576
577 // Main top level initialization
578 int fgMainInit( int argc, char **argv ) {
579
580     // set default log levels
581     sglog().setLogLevels( SG_ALL, SG_ALERT );
582
583     string version;
584 #ifdef FLIGHTGEAR_VERSION
585     version = FLIGHTGEAR_VERSION;
586 #else
587     version = "unknown version";
588 #endif
589     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
590             << version );
591     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
592
593     // Allocate global data structures.  This needs to happen before
594     // we parse command line options
595
596     globals = new FGGlobals;
597
598     // seed the random number generator
599     sg_srandom_time();
600
601     FGControls *controls = new FGControls;
602     globals->set_controls( controls );
603
604     string_list *col = new string_list;
605     globals->set_channel_options_list( col );
606
607     fgValidatePath("", false);  // initialize static variables
608     upper_case_property("/sim/presets/airport-id");
609     upper_case_property("/sim/presets/runway");
610     upper_case_property("/sim/tower/airport-id");
611     upper_case_property("/autopilot/route-manager/input");
612
613     // Scan the config file(s) and command line options to see if
614     // fg_root was specified (ignore all other options for now)
615     fgInitFGRoot(argc, argv);
616
617     // Check for the correct base package version
618     static char required_version[] = "2.0.0";
619     string base_version = fgBasePackageVersion();
620     if ( !(base_version == required_version) ) {
621         // tell the operator how to use this application
622
623         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
624         cerr << endl << "Base package check failed ... " \
625              << "Found version " << base_version << " at: " \
626              << globals->get_fg_root() << endl;
627         cerr << "Please upgrade to version: " << required_version << endl;
628 #ifdef _MSC_VER
629         cerr << "Hit a key to continue..." << endl;
630         cin.get();
631 #endif
632         exit(-1);
633     }
634
635     // Load the configuration parameters.  (Command line options
636     // override config file options.  Config file options override
637     // defaults.)
638     if ( !fgInitConfig(argc, argv) ) {
639         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
640         exit(-1);
641     }
642
643     // Initialize the Window/Graphics environment.
644     fgOSInit(&argc, argv);
645     _bootstrap_OSInit++;
646
647     fgRegisterWindowResizeHandler( &FGRenderer::resize );
648     fgRegisterIdleHandler( &fgIdleFunction );
649     fgRegisterDrawHandler( &FGRenderer::update );
650
651     // Initialize plib net interface
652     netInit( &argc, argv );
653
654     // Clouds3D requires an alpha channel
655     fgOSOpenWindow(true /* request stencil buffer */);
656
657     // Initialize the splash screen right away
658     fntInit();
659     fgSplashInit();
660
661     // pass control off to the master event handler
662     int result = fgOSMainLoop();
663     
664     // clean up here; ensure we null globals to avoid
665     // confusing the atexit() handler
666     delete globals;
667     globals = NULL;
668     
669     return result;
670 }
671
672