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