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